Without Redis
Run several instances without Redis: locks, counters, rate limits, a shared L2 and cache invalidation on Cloudflare Durable Objects or MongoDB.
To run several instances without Redis, use lazy-layers-cache/coordination. On Cloudflare Workers it keeps locks, counters, rate limits and a shared L2 cache tier in Durable Objects, and invalidates peers over Durable Object RPC. On Node.js it keeps the same state in a MongoDB collection and invalidates peers over change streams.
Several instances of an app need shared state the cache alone does not give: a lock so only one instance runs a job, a revocation list for logged-out tokens, login rate limits, and a way to tell the other instances' L1 caches about a delete. Redis is the usual answer. The lazy-layers-cache/coordination entry point (added in 0.7, unchanged in 8.0) gives the same building blocks on what you may already run:
| You run on | Shared keys, locks, counters, rate limits | Shared L2 | Cache invalidation between instances |
|---|---|---|---|
| Cloudflare Workers | Durable Objects (SQLite storage) | Durable Object cache tier | Durable Object RPC (BroadcastEventBus) |
| Node.js with MongoDB (servers, serverless) | MongoDB collection | none (L1 per instance) | MongoDB change streams (MongoChangeStreamEventBus) |
| One process, tests | memory | — | — |
The entry point loads no Redis, NATS, RabbitMQ or native compression code, so it bundles for Workers as is. Nothing in the existing API changed: code that uses Redis keeps working.
The Durable Object backend needs no extra service and no add-on. SQLite-backed Durable Objects are part of the Workers plans; see Cloudflare's pricing for requests, duration and storage.
What you get
All three backends answer the same asynchronous API (see the reference):
await coordination.set('reset:abc', adminId, { ttlMs: 5 * 60_000 }) // a value that expires
await coordination.set('lock:job', workerId, { ifAbsent: true, ttlMs: 30_000 }) // true for one caller only
await coordination.delIfEquals('lock:job', workerId) // release only your own lock
await coordination.incr('stats:version:42') // atomic counter
await consumeRateLimit(coordination, `rl:login:${ip}`, { limit: 5, windowMs: 60_000 })Every operation is atomic. On Durable Objects each key belongs to one object, and an object runs one operation at a time. On MongoDB each operation is one atomic command.
Cloudflare Workers
Export a coordination Durable Object and bind it. The class is a thin wrapper, so the package does not need to import cloudflare:workers:
import { DurableObject } from 'cloudflare:workers'
import { createCoordinationObject, durableObjectCoordination, consumeRateLimit } from 'lazy-layers-cache/coordination'
export class Coordinator extends DurableObject {
constructor(ctx, env) {
super(ctx, env)
this.handler = createCoordinationObject(ctx) // keys in SQLite, cache tier in memory
}
exec(op, args) { return this.handler.exec(op, args) }
alarm() { return this.handler.alarm() } // removes expired keys
}
export default {
async fetch(request, env) {
const coordination = durableObjectCoordination({ namespace: env.COORDINATOR, shards: 4 })
const ip = request.headers.get('cf-connecting-ip') ?? 'unknown'
const limit = await consumeRateLimit(coordination, `rl:login:${ip}`, { limit: 5, windowMs: 60_000 })
if (!limit.allowed) return new Response('Too many attempts', { status: 429 })
// …
},
}{
"durable_objects": { "bindings": [{ "name": "COORDINATOR", "class_name": "Coordinator" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Coordinator"] }]
}Keys are spread over shards objects by a stable hash. Keep shards fixed once keys exist: a different count moves keys to other objects, so existing locks and revocations would no longer be found. Each object handles its keys one operation at a time, so add shards for more throughput (each busy object is billed for its active time).
A full example, including a test that runs it in the Workers runtime, is in examples/cloudflare-durable-object-coordination (npm run cloudflare:coordination:verify).
Shared L2 and invalidation between Workers
If your app runs LazyLayersCache inside Durable Objects (for example one object per API shard), give it the coordination cache tier as L2 and broadcast invalidations to the other shards:
import { LazyLayersCache, MemoryStore } from 'lazy-layers-cache/cache'
import { BroadcastEventBus, RemoteCacheStore } from 'lazy-layers-cache/coordination'
const bus = new BroadcastEventBus({
send: async (payload) => {
await Promise.all(peerShards.map((peer) => peer.cacheEvent(payload))) // RPC to the other shards
},
})
const cache = new LazyLayersCache({
l1: new MemoryStore({ ttlMs: 30_000 }),
l2: new RemoteCacheStore(coordination.cacheTier()),
eventBus: bus,
})
// In the shard class: cacheEvent(payload) { return bus.deliver(payload) }The cache tier lives in the coordination objects' memory (LRU, 32 MiB per object by default). It is strongly consistent: after a delete, the next read anywhere misses. Losing it (an object restarts) only costs reloads from your origin.
Workers bundles that import lazy-layers-cache/cache (the full LazyLayersCache) must alias the optional native codecs (lz4-napi, snappy) to a stub and set CACHE_COMPRESSION=gzip. The coordination and cloudflare entry points need neither.
Node.js with MongoDB
Use one collection for keys and one for cache events. Every process and serverless instance shares them:
import { mongoCoordination, MongoChangeStreamEventBus } from 'lazy-layers-cache/coordination'
const keys = db.collection('coordination')
await keys.createIndex({ exp: 1 }, { expireAfterSeconds: 0 }) // removes expired keys
const coordination = mongoCoordination({ collection: () => keys })
const events = db.collection('cache_events')
await events.createIndex({ at: 1 }, { expireAfterSeconds: 3600 })
const bus = new MongoChangeStreamEventBus({ collection: () => events })
const cache = new LazyLayersCache({ eventBus: bus /* l1, ttlMs, … */ })collection is a function so it can throw while the database is down: calls then fail fast instead of queueing. Expired keys read as absent right away, before MongoDB's TTL monitor (which runs about once a minute) deletes them.
Change streams need a replica set. MongoDB Atlas and most production deployments are one. While the stream is not open, the bus reports disconnected. LazyLayers then stops trusting L1 and reconciles it when the stream is back, so a missed event cannot leave stale data in L1. On a standalone server the bus stays disconnected and does not retry, so L1 is bypassed.
Choosing between them
| Durable Objects | MongoDB | |
|---|---|---|
| Latency per operation | an RPC to the object (same location: a few ms) | a database round trip |
| Throughput | per object, scales with shards | your MongoDB cluster |
| Shared L2 | yes (cache tier) | no: keep cache traffic off the database |
| Survives restarts | keys yes (SQLite); cache tier no | yes |
| Extra infrastructure | none on Workers | none if you already run MongoDB |
Cloudflare KV is not a substitute for these. KV has no atomic set-if-absent, accepts about one write per second per key, and can serve a value up to 60 seconds old after a write elsewhere. That rules out locks, counters, rate limits and token revocation; KV remains a good read-heavy shared L2.
Limits
- A lock is a lease: it expires after
ttlMseven if its owner is still working. Release it withdelIfEqualsso a late owner cannot free someone else's lock. - Rate limits use fixed windows: a burst at the end of one window and the start of the next can reach twice the limit in a short span.
BroadcastEventBusandMongoChangeStreamEventBusdeliver at most once. An undecodable event or a stream gap makes LazyLayers reconcile L1; a peer that is unreachable when an event is sent keeps its L1 until the entry expires.- An explicit
cache.set()updates the local L1 and L2 only. Peers learn aboutgetOrSetfills and about deletes, as with the other buses.
Questions
Is there a shared L2 cache with MongoDB?
No. With MongoDB each instance keeps its own L1, and change streams carry invalidations between them. The Durable Object backend does provide a shared cache tier.
Does the coordination entry point work in Cloudflare Workers?
Yes. It loads no Redis, NATS, RabbitMQ or native compression code, so it bundles for Workers as it is, and every operation is atomic.