Field Notes
    Preparing search index...

    Module @fieldnotes/sync-redis

    @fieldnotes/sync-redis

    A HubBackend that persists Field Notes relay room state in Redis — state survives relay restarts and is shared across relay instances.

    pnpm add @fieldnotes/sync-redis
    # plus your Redis client of choice, e.g.:
    pnpm add redis # node-redis v4
    # or
    pnpm add ioredis

    @fieldnotes/sync-redis has no Redis dependency of its own — you inject a client that satisfies a minimal RedisHashClient interface (hGetAll / hGet / hSet / hDel / del / eval). Element writes run as Lua scripts through eval (or scriptLoad/evalSha when present).

    node-redis v4's client already matches RedisHashClient, so you can pass it straight through:

    import { createClient } from 'redis';
    import { createSyncServer } from '@fieldnotes/sync-server';
    import { RedisHubBackend } from '@fieldnotes/sync-redis';

    const client = createClient({ url: process.env.REDIS_URL });
    await client.connect();
    createSyncServer({ port: 8080, backend: new RedisHubBackend(client) });

    ioredis uses lowercased method names, so wrap it in a small adapter:

    import Redis from 'ioredis';
    import { RedisHubBackend } from '@fieldnotes/sync-redis';

    const io = new Redis(process.env.REDIS_URL);
    const client = {
    hGetAll: (k: string) => io.hgetall(k),
    hGet: (k: string, f: string) => io.hget(k, f),
    hSet: (k: string, f: string, v: string) => io.hset(k, f, v),
    hDel: (k: string, f: string) => io.hdel(k, f),
    del: (k: string) => io.del(k),
    expire: (k: string, seconds: number) => io.expire(k, seconds),
    eval: (script: string, options: { keys: string[]; arguments: string[] }) =>
    io.eval(script, options.keys.length, ...options.keys, ...options.arguments),
    };
    const backend = new RedisHubBackend(client);

    Each room is stored as a Redis HASH at {keyPrefix}{room} (default prefix fieldnotes:room:):

    • field = element id
    • value = JSON.stringify(element)

    Removed elements move to the {keyPrefix}{room}:tombstones hash (field = id, value = JSON { id, version, editor, removedAt, ownerId?, removedBy?, audience? }). One Lua script checks the expected version and writes both hashes, so concurrent writes from several relay instances never overwrite a newer element. Tombstones are dropped tombstoneRetentionMs after removal (default 7 days) when a snapshot is read:

    new RedisHubBackend(client, { tombstoneRetentionMs: 24 * 60 * 60 * 1000 });
    

    Rooms written before 0.14 hold elements with zIndex and no index. On first access in each process the backend gives them fractional keys with assignLegacyOrder, in HGETALL order (the order a joining pre-0.14 client saw), and writes only fields that still lack index. No manual step is needed. HGETALL returns insertion order only for small (listpack-encoded) hashes; larger rooms keep Redis' hash order. Upgrade every relay instance and client at once (sync protocol 3).

    Backend plugins own any additional key schemas and atomic scripts. For fog, pass createFogBackendPlugin() from @fieldnotes/vtt/redis; it owns ${key}:fog:meta and ${key}:fog:tiles and requires the node-redis-compatible eval(script, { keys, arguments }) shape shown above.

    node-redis v4 conforms to RedisHashClient directly (it has hGet); RedisHubBackend.getRecord(room, id) (via HGET) reads the element or tombstone each write is checked against. The plugin key prefix tombstones is reserved.

    The prefix is configurable:

    new RedisHubBackend(client, { keyPrefix: 'myapp:room:' });
    
    import { createFogBackendPlugin } from '@fieldnotes/vtt/redis';

    new RedisHubBackend(client, { plugins: [createFogBackendPlugin()] });

    Pass ttlSeconds to expire abandoned rooms:

    new RedisHubBackend(client, { ttlSeconds: 7 * 24 * 60 * 60, plugins: [createFogBackendPlugin()] });
    

    Every element or layer write, every room snapshot (each join) and every fog write refreshes EXPIRE on the room's hash, :layers and :tombstones hashes and plugin keys. A room with no writes and no joins for ttlSeconds is deleted, so pick a value well above the longest pause between sessions. The client needs expire(key, seconds); node-redis v4 has it.

    Persistence and shared state work with any number of relay instances — every instance reads and writes the same Redis, so room state survives restarts and is visible to all of them.

    For clients connected to different relay instances to see each other's live ops, you also need cross-instance fan-out (Redis pub/sub) — available via RedisHubFanout (below). A single relay instance is fully live on its own.

    RedisHubFanout is a HubFanout (from @fieldnotes/sync-server) over Redis pub/sub: each relay instance publishes its live ops to a single channel and every other instance forwards them to its local connections. Like the backend, it has no Redis dependency of its own — you inject two connections via the RedisPublisher / RedisSubscriber seams.

    publish() resolves only after Redis acknowledges the command. If Redis rejects it, the fanout invokes the optional onError observer and rethrows so SyncHub can surface the failed durable mutation publication. Do not discard the returned promise when publishing directly.

    The subscriber MUST be a dedicated connection. Redis forbids any other command on a connection that is in subscribe mode, so publish and subscribe cannot share one connection — that is why RedisHubFanout takes two.

    import { createClient } from 'redis';
    import { createSyncServer } from '@fieldnotes/sync-server';
    import { RedisHubBackend, RedisHubFanout } from '@fieldnotes/sync-redis';

    const hash = createClient({ url: process.env.REDIS_URL });
    await hash.connect(); // HASH backend (persistence)

    const publisher = createClient({ url: process.env.REDIS_URL });
    await publisher.connect();
    const subscriber = publisher.duplicate();
    await subscriber.connect(); // DEDICATED subscriber — a subscriber connection cannot also publish

    createSyncServer({
    port: 8080,
    backend: new RedisHubBackend(hash),
    fanout: new RedisHubFanout(publisher, subscriber),
    });

    ioredis lowercases publish/subscribe and delivers messages via a 'message' event, so wrap each client:

    import Redis from 'ioredis';
    import { RedisHubFanout } from '@fieldnotes/sync-redis';

    const pubIo = new Redis(process.env.REDIS_URL); // publish connection
    const subIo = new Redis(process.env.REDIS_URL); // SECOND, dedicated subscriber connection

    const publisher = { publish: (c: string, m: string) => pubIo.publish(c, m) };
    const subscriber = {
    subscribe: (channel: string, listener: (m: string) => void) => {
    subIo.on('message', (ch, msg) => {
    if (ch === channel) listener(msg);
    });
    return subIo.subscribe(channel);
    },
    };

    const fanout = new RedisHubFanout(publisher, subscriber);

    All instances must share one channel (default fieldnotes:fanout, configurable):

    new RedisHubFanout(publisher, subscriber, { channel: 'myapp:fanout' });
    

    Multi-instance live sync requires both a shared fanout and a shared backend (both Redis). The fanout forwards live ops; the shared backend keeps snapshots consistent. A shared fanout without a shared backend leaves a new joiner's snapshot stale — it would catch up from whichever instance it happened to hit, missing edits applied elsewhere. Pair RedisHubFanout with RedisHubBackend for full multi-instance real-time sync.

    src/redis-fog.integration.test.ts runs the fog Lua scripts against a real server instead of a fake, so it is skipped unless REDIS_URL is set. Point it at a scratch Redis — the suite writes under a random fieldnotes-it:<uuid>:room: key prefix and deletes those keys afterwards, but it does use KEYS, so do not aim it at a production instance:

    REDIS_URL=redis://localhost:6379 pnpm --filter @fieldnotes/sync-redis test
    
    RedisHubBackend
    RedisHubFanout
    BackendPluginContext
    BackendSyncPlugin
    RedisHashClient
    RedisHubBackendOptions
    RedisHubFanoutOptions
    RedisPublisher
    RedisSubscriber
    ScriptRunOptions
    ScriptRunner
    createScriptRunner
    encodeRoomKey