Aviary
Packages

@dudousxd/nestjs-agent-transport-redis

RedisTokenStreamSink — a TokenStreamSink over Redis for multi-replica deployments, so a token stream started on one pod is subscribable and resumable from any other.

The default TokenStreamSink (InProcessTokenStreamSink) buffers a run's tokens in the process that started it — reconnect from a different pod and there's nothing to replay. -transport-redis implements the same TokenStreamSink SPI over Redis, so any replica can subscribe to any run's stream.

pnpm add @dudousxd/nestjs-agent-transport-redis

Minimal example

import { RedisTokenStreamSink } from '@dudousxd/nestjs-agent-transport-redis';
import { AgentModule, HeaderActorResolver } from '@dudousxd/nestjs-agent';

@Module({
  imports: [
    AgentModule.forRoot({
      model: myModelProvider,
      actorResolver: new HeaderActorResolver(),
      // myRedisClient: a RedisStreamClient (see below); options: { keyPrefix?: string; ttlSeconds?: number }
      sink: new RedisTokenStreamSink(myRedisClient), // shared across every replica
    }),
  ],
})
export class AppModule {}

RedisStreamClient — bring your own driver

The package takes zero dependency on ioredis or node-redis — it depends on a small interface, RedisStreamClient, that your app implements over whichever client it already runs:

interface RedisStreamClient {
  rpush(key: string, value: string): Promise<number | void>; // resolve to the new length (RPUSH's reply)
  lrange(key: string, start: number, stop: number): Promise<string[]>;
  set(key: string, value: string): Promise<void>;
  get(key: string): Promise<string | null>;
  publish(channel: string, message: string): Promise<void>;
  subscribe(channel: string, onMessage: (message: string) => void): Promise<() => Promise<void>>;
  del(...keys: string[]): Promise<void>;
  expire(key: string, seconds: number): Promise<void>;
}

rpush should resolve to the list's new length, which is what RPUSH replies and what ioredis and node-redis resolve to as is. The sink numbers frames with it so it can carry them in the PUBLISH (see What a token costs). An adapter whose rpush resolves to nothing still works: it publishes bare wakes and subscribers read the list on each one, at the cost from before.

A run's :chunks and :state keys expire ttlSeconds (default 3600) after the run's last write. While the run streams, the TTL is armed on its first write and re-armed at most once a minute (every quarter TTL, if that is shorter), each time for ttlSeconds plus that period, so the keys outlive the last write by at least ttlSeconds and a run whose writer died is gone at most a minute later. When the run ends or fails, both keys get exactly ttlSeconds. ttlSeconds: 0 keeps them until close(). An adapter without expire still streams, but its keys never expire.

A subscribed Redis connection can't run other commands, so most drivers need a dedicated connection for subscribe — the sink only calls it from subscribe():

// adapting ioredis: one command connection, one subscriber connection
import Redis from 'ioredis';
import type { RedisStreamClient } from '@dudousxd/nestjs-agent-transport-redis';

function ioredisStreamClient(redis: Redis, sub: Redis): RedisStreamClient {
  return {
    rpush: (key, value) => redis.rpush(key, value), // resolves to the length
    lrange: (key, start, stop) => redis.lrange(key, start, stop),
    set: async (key, value) => { await redis.set(key, value); },
    get: (key) => redis.get(key),
    publish: async (channel, message) => { await redis.publish(channel, message); },
    subscribe: async (channel, onMessage) => {
      const listener = (ch: string, message: string) => { if (ch === channel) onMessage(message); };
      sub.on('message', listener);
      await sub.subscribe(channel);
      return async () => {
        sub.off('message', listener);
        await sub.unsubscribe(channel);
      };
    },
    del: async (...keys) => { await redis.del(...keys); },
    expire: async (key, seconds) => { await redis.expire(key, seconds); },
  };
}

No driver dependency, on purpose

Requiring your app to adopt a specific Redis client just to stream tokens would be the wrong trade. RedisStreamClient is the seam: implement its eight methods over whichever client (ioredis, node-redis, a cluster client) your app already runs, and RedisTokenStreamSink never needs to know which one.

How it's keyed

Per run (keyPrefix defaults to agent:stream):

StructureKeyPurpose
LIST<prefix>:<runId>:chunksEvery chunk (base64) appended in order — what a late subscriber replays before following live.
pub/sub channel<prefix>:<runId>Each append's frames with their list index ({"seq":n,"frames":[…]}), published after the append, plus end and close — what live subscribers follow.
terminal marker<prefix>:<runId>:state{ t: 'end' } or { t: 'fail', error }, set when the run ends — a reconnect after completion sees the ending instead of hanging on an empty subscribe.

Both keys expire ttlSeconds after the run's last write (see above); close(runId) deletes them at once.

What a token costs

Consecutive text frames are gathered while the previous send is still on the wire and go out as one text chunk: one RPUSH, then one PUBLISH that carries the chunk and its list index. No timer is involved, so a model streaming faster than a Redis round trip costs one send per burst, and a slow stream still goes out a token at a time with no added latency. The PUBLISH waits for the RPUSH, so the list always holds what was published. Non-text frames keep their place between the gathered text around them.

That is about 2 commands per streamed frame, whatever the number of subscribers: measured with a real Redis at 400 tokens 20 ms apart, 2.02 per frame with one subscriber and 2.04 with three, where re-arming the TTL on every frame and having each subscriber LRANGE on every wake cost 4.02 and 6.04. Chunks over 64 KiB are published as a bare wake instead, and subscribers read them from the list. Writers opened for the same run in one process share what they gather, so a delegated run's text and its parent's next frame keep the order they were written in, and flush() writes whatever is gathered without ending the stream.

A gathered send that fails is raised by the writer's next write, flush, end or fail, not by the write that gathered it.

A subscriber subscribes first, then reads the list with LRANGE to catch up — so a late subscriber or a reconnect gets the whole history — and from there appends the frames each PUBLISH carries. Frames it already has (published while it was catching up) are skipped by their index. It goes back to LRANGE only when a published index skips past what it has (a gap: another writer's append published out of order, or a lost message), when a message carries no frames, and when the run ends. It reads the terminal marker only when it attaches and once an end message arrives; after seeing the ending it reads the list once more, so chunks appended just before the marker are not lost. Every subscriber numbers frames by their place in the same stored list, so SSE frame ids and ?after= cursors are the same on every replica.

During a rolling deploy the two versions mix: a subscriber from before this scheme treats the frame-carrying PUBLISH as a wake and reads the list as it always did, and a subscriber of this version treats the old writer's bare chunk wake as a gap and reads the list. Both see every frame, in order, once.

A subscription passed { signal } (the chat routes pass one that aborts when the client disconnects) unsubscribes from the channel as soon as it aborts, even on a run that never writes again.

A subscriber also stops, as if the run had ended, once the run is gone: close() deleted its keys, or ttlSeconds passed with nothing written — by then the keys have expired, whether the run crashed, is parked past its TTL, or never started. A run that writes again before a full TTL passes is still followed, and a subscriber whose wake-up was lost picks the chunks up from the list instead of ending. Under ttlSeconds: 0 only close() ends a silent run's subscribers.

A run that ended in failure re-raises as AgentStreamError (from @dudousxd/nestjs-agent-core) on the subscriber side rather than silently closing, so a reconnecting client can tell "the run is done" from "the run failed" the same way it would against the in-process sink.

Exports

ExportKindPurpose
RedisTokenStreamSinkclass (TokenStreamSink)new RedisTokenStreamSink(client, options?); open / subscribe(runId, { signal }?) / close, backed by the LIST + pub/sub + marker scheme above
RedisTokenStreamSinkOptionstype{ keyPrefix?: string; ttlSeconds?: number } — defaults agent:stream and 3600
RedisStreamClienttypeThe eight-method seam your app implements over its own Redis driver
RedisChannelStoreclass (ChannelStore)new RedisChannelStore(client, { prefix? }) — the state of text channels (message ids, questions, relayed outcomes) shared by every replica: SET … PX … NX claims, GET, DEL. Pass it as AgentChannelsModule.forRoot({ store })
RedisChannelClienttypeThe three commands it uses (set with PX/NX, get, del) — an ioredis client has them as is
RedisConsoleApprovalClientclass (AgentApprovalPort)new RedisConsoleApprovalClient(client, { keyPrefix?, timeoutMs? }) — on a federated console's hub: sends approve/reject to an app over its Redis and waits for the app's answer
RedisConsoleActionResponderclassnew RedisConsoleActionResponder(client, approvals, { keyPrefix? }) — on the app: executes those requests through the app's own approval port, one replica per request
ConsoleActionErrorclassWhat the client rejects with: the app's status (404, 409, …), or 504 without an answer
RedisConsolePubSub / RedisConsoleResponderClienttypespublish + subscribe; the responder's adds claim (SET … NX EX)

When to use it

Reach for this package the moment your app runs more than one replica behind a load balancer (or serverless instances that don't share process memory) and you want GET /agent/chat/:runId/stream to work no matter which instance handles the reconnect. Single-replica deployments — most local dev, many small production deployments — are fine on the default InProcessTokenStreamSink and don't need this package at all.

Several replicas, no Redis

If you already run a SQL store, DrizzleTokenStreamSink(db) (-store-drizzle) and MikroOrmTokenStreamSink(em) (-store-mikro-orm) — both built on core's SqlTokenStreamSink — keep frames in an agent_stream_frame table that every replica polls. Coalesced text rows, a TTL (ttlSeconds, default 1h) with auto-purge, and polling latency (pollIntervalMs, default 250ms) instead of pub/sub push.

durable: true dispatches the turn's long steps

Under AgentModule.forRoot({ durable: true, ... }) the model call and each tool execution run as routed durable steps, so they can execute on a different worker process than the one that opened the stream — this is true even in a "single replica" web app paired with a separate durable worker pool, not just multi-pod fleets. A cross-process sink like RedisTokenStreamSink is required whenever the process that streams a chunk may differ from the one a client reconnects through; a boot warning fires when durable is on with the default in-process sink.

  • Architecture — the control plane / data plane split this sink lives on
  • Frontend — resumeRunId and reconnecting a dropped SSE stream

On this page