# Coordination (https://lazy-layers-cache.vercel.app/docs/reference/coordination)

> lazy-layers-cache/coordination: shared keys, locks, counters, rate limits, a shared cache tier and invalidation buses without Redis.



```ts
import {
  durableObjectCoordination, mongoCoordination, localCoordination,
  createCoordinationObject, createCoordinationCore, memoryCoordinationStorage, sqliteCoordinationStorage,
  consumeRateLimit, RemoteCacheStore, BroadcastEventBus, MongoChangeStreamEventBus,
} from 'lazy-layers-cache/coordination'
```

Available in ESM and CommonJS from 0.7.0. The entry point loads no Redis, NATS, RabbitMQ or native codec code. For when to use which backend, see [Without Redis](/docs/setups/coordination).

## The Coordination API [#the-coordination-api]

Every backend returns an object with this interface. All methods are asynchronous and atomic.

```ts
interface Coordination {
  readonly backend: string // 'durable-objects' | 'mongo' | 'memory'
  get(key: string): Promise<string | null>
  mget(keys: string[]): Promise<(string | null)[]>
  set(key: string, value: string, options?: { ttlMs?: number; ifAbsent?: boolean }): Promise<boolean>
  del(keys: string[]): Promise<number>
  delIfEquals(key: string, value: string): Promise<boolean>
  incr(key: string, options?: { by?: number; ttlMs?: number }): Promise<{ value: number; expiresAt: number | null }>
  pttl(key: string): Promise<number>
  ping(): Promise<boolean>
  cacheTier(): CoordinationCacheTier | null
}
```

| Method        | Behavior                                                                                                                                                                                      |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get`         | The value, or `null` when the key is missing or expired.                                                                                                                                      |
| `mget`        | Values in key order; `null` for misses. On Durable Objects: one call per object holding some of the keys.                                                                                     |
| `set`         | Writes the value. With `ttlMs` the key expires; without it, it never does. With `ifAbsent: true` it writes only if the key does not exist and returns `false` otherwise (a lock).             |
| `del`         | Deletes keys; returns how many existed (expired keys do not count).                                                                                                                           |
| `delIfEquals` | Deletes the key only while it holds `value`. Use it to release a lock you own.                                                                                                                |
| `incr`        | Adds `by` (default 1, a safe integer) to an integer key. A missing or expired key starts at 0 and takes `ttlMs` as its expiry; an existing key keeps its expiry. Rejects a non-integer value. |
| `pttl`        | Milliseconds until expiry; `-1` for no expiry, `-2` for missing.                                                                                                                              |
| `ping`        | `true` when the backend answers (every shard on Durable Objects).                                                                                                                             |
| `cacheTier`   | The shared byte cache (Durable Objects and memory), or `null` (MongoDB).                                                                                                                      |

Values are strings. Store JSON with `JSON.stringify` when you need structure.

## Backends [#backends]

### durableObjectCoordination(options) [#durableobjectcoordinationoptions]

<ParamField path="namespace" type="DurableObjectNamespace">
  The binding of a class that answers `exec(op, args)` with [`createCoordinationObject`](#createcoordinationobjectctx-options).
</ParamField>

<ParamField path="shards" type="number" default="4">
  Number of objects keys are spread over (`hash(key) % shards`). Keep it fixed once keys exist.
</ParamField>

<ParamField path="locationHint" type="string">
  Passed to `namespace.get()`; put the objects near the callers (for example `apac`).
</ParamField>

<ParamField path="objectName" type="(index: number) => string" default="index => `coordinator-${index}`">
  Object names per shard.
</ParamField>

Reads (`get`, `mget`, `pttl`, cache reads, `ping`) are retried once after a retryable Durable Object error. Writes are not retried, because a failed write may still have been applied.

### createCoordinationObject(ctx, options) [#createcoordinationobjectctx-options]

The inside of the Durable Object class. Keys are stored in `ctx.storage.sql` (a SQLite-backed class is required). An alarm removes expired keys every `cleanupIntervalMs` while any key can expire.

<ParamField path="cacheBytes" type="number" default="33554432">
  Byte budget of this object's in-memory cache tier (LRU).
</ParamField>

<ParamField path="cleanupIntervalMs" type="number" default="600000">
  How often expired keys are removed.
</ParamField>

<ParamField path="table" type="string" default="lazy_layers_coordination">
  SQLite table name.
</ParamField>

Returns `{ core, exec(op, args), alarm() }`. `exec` accepts only the coordination operations; anything else is rejected.

### mongoCoordination(options) [#mongocoordinationoptions]

<ParamField path="collection" type="() => Collection">
  The collection of `{ _id: key, v, exp }` documents. Called on every operation, so it may throw while the database is not connected. Create a TTL index: `createIndex({ exp: 1 }, { expireAfterSeconds: 0 })`.
</ParamField>

<ParamField path="now" type="() => number" default="Date.now">
  Clock, for tests.
</ParamField>

Locks use a conditional upsert (a live key makes the insert collide on `_id`). Counters use one pipeline `findOneAndUpdate`; concurrent first increments of the same key are retried. There is no cache tier.

### localCoordination(core) · createCoordinationCore(storage, options) [#localcoordinationcore--createcoordinationcorestorage-options]

`createCoordinationCore` is the synchronous engine every backend shares. `localCoordination` wraps it as an asynchronous `Coordination` for one process or for tests. Storage adapters: `memoryCoordinationStorage()` and `sqliteCoordinationStorage(sql, table?)`.

## consumeRateLimit(coordination, key, options) [#consumeratelimitcoordination-key-options]

Fixed-window rate limiting with one atomic increment per call.

```ts
const result = await consumeRateLimit(coordination, `rl:login:${ip}`, { limit: 5, windowMs: 60_000 })
// { allowed, count, limit, remaining, resetAt }
```

<ParamField path="limit" type="number">
  Requests allowed per window.
</ParamField>

<ParamField path="windowMs" type="number">
  Window length; the first request starts the window.
</ParamField>

<ParamField path="cost" type="number" default="1">
  How much this request counts.
</ParamField>

## RemoteCacheStore [#remotecachestore]

A [`CacheStore`](/docs/reference/stores) on a `CoordinationCacheTier`, for `LazyLayersCache`'s `l2`. Values use the portable serializer, as the Cloudflare KV stores do.

```ts
new RemoteCacheStore(coordination.cacheTier(), { ttlMs: 30_000 })
```

## Event buses [#event-buses]

Both implement the [`EventBus`](/docs/reference/event-buses) contract, report `subscribed` / `disconnected` through `onStatus`, and deliver at most once. An event that cannot be decoded makes LazyLayers reconcile L1.

### BroadcastEventBus [#broadcasteventbus]

```ts
new BroadcastEventBus({ send: (payload: Uint8Array) => Promise<void>, transport?: string })
```

`publish(event)` encodes the event and calls `send(payload)`. Your transport delivers the bytes to the other instances, which call `bus.deliver(payload)`. Durable Object RPC between shards is the intended transport.

### MongoChangeStreamEventBus [#mongochangestreameventbus]

```ts
new MongoChangeStreamEventBus({ collection, ready?, source?, retry?, onError? })
```

`publish(event)` inserts `{ payload, source, at }`. Every instance watches the collection and receives the other instances' events. Give the collection a TTL index on `at`.

<ParamField path="ready" type="() => Promise<unknown>">
  Resolves when the database is connected; the stream starts after it.
</ParamField>

<ParamField path="retry" type="{ minDelayMs?, maxDelayMs? }" default="{ minDelayMs: 500, maxDelayMs: 30000 }">
  Backoff for reopening the stream after an error.
</ParamField>

Needs a replica set. On a standalone server it reports `disconnected` once and stops retrying.
