Caching & Performance
How SonicJS delivers sub-50ms API responses globally β and the three-tier cache that keeps them there.
See It Live
The SonicJS Speed Demo races SonicJS (Cloudflare Workers + D1 + KV edge cache) against Payload CMS (Cloudflare Workers + D1, no cache) across 50,000 employee records β same runtime, same database engine, so the only variable is the caching layer. Filter by department or region and watch the response timers update in real time.
The demo shows the single-user latency advantage, but that's just the tip of the iceberg. The real benefit emerges at scale: when thousands of requests hit the same query simultaneously, every one is served from KV in parallel with zero database contention. An uncached backend serializes those hits against D1. The gap doesn't just hold under load β it widens.
We're adding k6 load tests that will drive sustained concurrent traffic at both backends and publish the full results β throughput, p95/p99 latency, and error rates β along with all source code so you can reproduce the benchmark on your own Cloudflare account.

Live benchmark: SonicJS Edge (47ms) vs Payload CMS (211ms) β try it yourself β
Why SonicJS is Fast
Most CMS platforms run on a single server in a single region. Your users in London wait for a round-trip to us-east-1. Your users everywhere wait for a cold boot after the process sat idle.
SonicJS avoids both problems by design.
No Cold Starts: V8 Isolates
Traditional Node.js servers boot a full process β load modules, connect to databases, initialize the runtime. That takes 500β2000ms. When traffic is light and a process goes idle, you pay that cost on the next request.
Cloudflare Workers run as V8 isolates: lightweight JavaScript contexts that start in microseconds. There's no process to boot, no module graph to initialize. The first request to a fresh isolate still runs the SonicJS bootstrap middleware, but it's checking a flag and running migrations β not starting a server. Cold start in practice: 0β5ms.
Global by Default: 300+ Edge Locations
A Node.js CMS has one home. When a request comes from the wrong continent, it travels to that server and back β 300β800ms of pure latency that no amount of code optimization can fix.
Workers run in 300+ Cloudflare cities worldwide. Every request is handled from somewhere close to the user. Cross-region latency drops from 300β800ms to 30β60ms.
The Three-Tier Cache
Even at the edge, database reads take time. SonicJS intercepts every content query through a three-tier cache before it ever touches D1 β so most requests never hit the database at all.
Tier 1: Memory
Per-isolate in-memory store. Sub-millisecond reads. 50MB limit with LRU eviction.
Tier 2: KV
Cloudflare KV β globally distributed, survives isolate recycling. 10β50ms reads.
Tier 3: D1
SQLite source of truth. Only reached on a full cache miss. Results populate both upper tiers.
Three-Tier Cache
Tier 1 β In-Memory Cache
Each Cloudflare Worker isolate keeps a local in-memory store. Reads are synchronous and return in under a millisecond. The store has a 50MB ceiling with LRU eviction β the least-recently-used entries are dropped when space runs short.
The tradeoff: memory is per-isolate. If Cloudflare routes two consecutive requests to different isolates (which happens), they each have their own memory store. That's why KV exists.
Tier 2 β Cloudflare KV
KV is a globally-replicated key-value store. When an isolate has a memory miss, it checks KV next. A KV hit costs 10β50ms β fast, and it populates the memory tier so subsequent requests in the same isolate are free.
KV is eventually consistent: writes propagate globally within seconds. For CMS content β articles, media metadata, collection schema β eventual consistency is fine. For session data, SonicJS skips the KV tier and keeps sessions memory-only.
Tier 3 β D1 Database
D1 is SQLite at the edge. It's the source of truth. SonicJS only reaches D1 when both memory and KV miss. On a D1 hit, the result is written back to KV and memory before returning to the caller, so the next request finds it in cache.
Cache Flow
Incoming request
β
Memory cache? ββββ hit βββ return (<1ms)
β miss
KV cache? ββββββhit βββ populate memory β return (10β50ms)
β miss
D1 database βββββββββββ populate KV + memory β return (50β200ms)
The measured impact on a typical content API endpoint:
| Scenario | Response time |
|---|---|
| Memory hit | < 1ms |
| KV hit | 10β50ms |
| D1 hit (cold) | 50β200ms |
| No cache (baseline) | 100β500ms |
Default TTLs
SonicJS ships with per-namespace cache configurations tuned to how often each data type changes.
| Namespace | TTL | KV enabled | Notes |
|---|---|---|---|
content | 1 hour | β | Published articles, pages |
config | 2 hours | β | Plugin config, system settings |
collection | 2 hours | β | Schema definitions |
media | 1 hour | β | File metadata |
user | 15 minutes | β | User records, roles |
api | 5 minutes | β | API endpoint responses |
session | 30 minutes | β | Auth sessions (memory only) |
TTLs are maximums, not guarantees
A cached entry lives up to its TTL β but event-driven invalidation clears it immediately when the underlying data changes. A content update fires content.update, which deletes the specific item cache and invalidates all list caches before the response returns.
Cache Invalidation
SonicJS uses an event-driven invalidation model. Every write operation emits a typed event; the cache service subscribes and clears the relevant keys immediately.
Automatic Invalidation Events
// Content events β invalidate content namespace
'content.create' β invalidate('content:*')
'content.update' β delete specific item + invalidate('content:list:*')
'content.delete' β delete specific item + invalidate('content:*')
'content.publish' β invalidate('content:*')
// User events
'user.update' β invalidate specific user key
'user.delete' β invalidate specific user key
// Config events
'config.update' β invalidate('config:*')
'plugin.activate' β invalidate('config:*') + invalidate('collection:*')
You don't need to call invalidation manually in most cases. When you write a document via the SonicJS API, the event fires automatically and the cache is cleared before the response goes back to the client.
Manual Invalidation
If you need to clear cache entries from your own plugin code:
Manual Cache Invalidation
import { getCacheService } from 'sonicjs/services/cache'
const cache = getCacheService({ ttl: 3600, keyPrefix: 'myPlugin' })
// Delete a specific key
await cache.delete('myPlugin:item:abc123')
// Invalidate by pattern (clears all matching keys)
await cache.invalidate('myPlugin:list:*')
// Clear everything in this namespace
await cache.clear()
Using the Cache API
getOrSet β the most common pattern
getOrSet Pattern
import { getCacheService } from 'sonicjs/services/cache'
const cache = getCacheService({
ttl: 300, // 5 minutes
keyPrefix: 'api',
})
app.get('/api/posts', async (c) => {
const key = cache.generateKey('list', 'all')
const posts = await cache.getOrSet(key, async () => {
// Only runs on a cache miss
return db.prepare('SELECT * FROM posts ORDER BY createdAt DESC').all()
})
return c.json({ data: posts })
})
Reading cache source (for debugging)
Inspecting Cache Source
const result = await cache.getWithSource<Post[]>(key)
if (result.hit) {
console.log(`Cache hit from: ${result.source}`) // 'memory' | 'kv'
return c.json({ data: result.data, _cacheSource: result.source })
}
// Miss β fetch from DB, populate cache
const posts = await fetchFromDB()
await cache.set(key, posts)
return c.json({ data: posts, _cacheSource: 'db' })
Generating consistent cache keys
Cache Key Generation
// Format: {namespace}:{type}:{identifier}
const key = cache.generateKey('item', documentId)
// β 'api:item:abc123'
// For complex queries, hash the params
import { hashQueryParams } from 'sonicjs/plugins/cache/services/cache-config'
const queryHash = hashQueryParams({ page: 1, limit: 20, status: 'published' })
const key = cache.generateKey('list', queryHash)
Admin Dashboard
The cache admin panel at /admin/cache shows live stats across all namespaces: hit rates, entry counts, memory usage, and per-namespace breakdowns. You can flush individual namespaces or clear everything from there without touching code.
The dashboard reads from the same singleton that your route code writes to β so the numbers are accurate, not estimates.
Configuration
Enabling / disabling tiers
Both tiers are on by default. You can disable KV for namespaces that don't need global consistency (e.g. session data, transient locks):
Custom Cache Config
import { getCacheService } from 'sonicjs/services/cache'
// Memory-only namespace (no KV write)
const sessionCache = getCacheService({
ttl: 1800,
keyPrefix: 'session',
})
// Longer-lived content with KV
const contentCache = getCacheService({
ttl: 3600,
keyPrefix: 'content',
})
Cache versioning
Each namespace carries a version string (v1 by default). Bumping the version busts all entries in that namespace β useful after a schema change where old cache shapes are incompatible with new code:
Cache Key with Version
import { generateCacheKey } from 'sonicjs/plugins/cache/services/cache-config'
// Produces: content:item:abc123:v2
const key = generateCacheKey('content', 'item', documentId, 'v2')
Cache warming
After a cold deploy or a full cache flush, the first requests to each route rebuild the cache. For high-traffic production sites, consider running cache-warming scripts against your critical endpoints immediately after deploy to avoid a thundering herd on the first real request.