Packages / Events / Redisexperimental

Redis

Redis Streams transport for @miiajs/messaging - consumer groups, PEL-backed retry, auto-DLQ.

@miiajs/messaging-redis is the production transport for @miiajs/messaging. It implements the same MessageTransport interface as the in-memory default, so user code does not change - only the transport factory passed to MessagingModule.configure. Reach for it as soon as you need persistence, multi-replica deployments, or crash recovery.

Under the hood it uses Redis Streams with consumer groups, the group's own pending entries list (PEL) as the retry queue, and atomic Lua scripts for the nack and DLQ transitions.

Installation

bun add @miiajs/messaging-redis ioredis

ioredis is a peer dependency - install it explicitly so your app pins the version. The transport requires ioredis@^6.

Redis 7.2 is the supported minimum, and Valkey works too. onInit() reads the server version with HELLO and logs one warning on anything older - the transport still starts, but older servers are not tested. When HELLO is denied (an ACL that leaves it out, or a proxy that does not know the command), the check is skipped with a warning instead. The package's own test suite runs against Redis 7.2, 7.4 and 8, and Valkey 9.

Redis Cluster is not supported. client takes an ioredis Redis, not a Cluster, and a message that runs out of retries moves to the DLQ through one Lua script over two keys - the topic's stream and ${topic}.dlq - which Cluster rejects with CROSSSLOT unless both hash to the same slot.

Setup

typescript
import { Module } from '@miiajs/core'
import { MessagingModule } from '@miiajs/messaging'
import { redisStreamsTransport } from '@miiajs/messaging-redis'

@Module({
  imports: [
    MessagingModule.configure({
      transport: redisStreamsTransport({
        url: 'redis://localhost:6379',
      }),
    }),
  ],
})
class AppModule {}

With ConfigService for env-driven URLs:

typescript
import { ConfigService } from '@miiajs/config'

MessagingModule.configure((resolve) => ({
  transport: redisStreamsTransport({
    url: resolve(ConfigService).getOrThrow('REDIS_URL'),
    retry: { maxAttempts: 10 },
  }),
}))

Everything else from the Overview page - event contracts, @On, groups, retry/DLQ, MessageBus.publish - works identically. Each entry stores the envelope as JSON and a handler gets JSON.parse of it, so write event schemas for the JSON form (z.coerce.date(), not z.date()) - see Schemas describe the JSON form.

redisStreamsTransport options

OptionTypeDefaultDescription
urlstring-Redis URL. Mutually exclusive with client.
clientRedis-Pre-built ioredis instance. The transport does not call connect() or quit() on a user-supplied client - see Pre-built ioredis client.
retryPartial<RetryConfig>DEFAULT_RETRYOverride individual retry fields (maxAttempts, backoffMs, backoffMultiplier, dlq).
retryIntervalMsnumber1000Housekeeping cadence: one XPENDING ... IDLE <horizon> sweep per (topic, group) per tick, then claim and redeliver. A parked retry only fires on a tick, so this is both the granularity of backoff timing and, together with the horizon, the granularity of crash detection.
minIdleMsnumber60000Floor for the retry horizon. The horizon is max(minIdleMs, every backoff level), so lowering this below your largest backoff changes nothing.
blockMsnumber5000XREADGROUP BLOCK timeout. Governs idle Redis traffic and the retry cadence after a transient connection error - new messages wake the blocked read immediately, publish latency is unaffected thanks to the connection model, and onShutdown() disconnects the socket rather than waiting the block out.
socketTimeoutMsnumber10000How long a connection may stay silent with a command outstanding before it is dropped and reconnected - its commands are resent. Lanes get blockMs on top, and none with blockMs: 0. Bounds connecting too. 0 disables. Not applied to a client you pass. See Stalled connections.
drainTimeoutMsnumber5000One budget covering the running housekeeping pass and the in-flight handlers, before onShutdown() gives up on them. 0 skips the drain. See Graceful drain.
consumerNamestring${hostname}:${pid}:${rand8}Override for the auto-generated consumer name. Useful for diagnostics.

Connection model

The transport keeps one publisher client for XADD, XACK, all Lua commands (parkRetry / moveToDlq), XGROUP CREATE (and the TIME read before it for an initialPosition window), the XINFO GROUPS read on every subscribe(), SET / EXISTS on liveness keys, the housekeeping sweep, the heartbeat and HELLO (the startup version read). Every subscribe() call additionally creates its own duplicated client per lane via pubClient.duplicate({ lazyConnect: true, socketTimeout }) and runs its blocking XREADGROUP loop on it.

┌─────────────────────────────────────────────────────┐
│ pubClient            (1 socket)                     │
│   ├─ XADD            (publish)                      │
│   ├─ XACK            (per-message ack)              │
│   ├─ Lua scripts     (parkRetry, moveToDlq)         │
│   ├─ XPENDING/XCLAIM (housekeeping sweep)           │
│   ├─ XCLAIM JUSTID   (heartbeat)                    │
│   ├─ XGROUP/TIME     (group creation on subscribe)  │
│   ├─ XINFO GROUPS    (group position, orphan scan)  │
│   ├─ SET/EXISTS      (broadcast liveness keys)      │
│   └─ HELLO           (startup version read)         │
├─────────────────────────────────────────────────────┤
│ subClient #1         (1 socket per lane)            │
│   └─ XREADGROUP BLOCK <ms>                          │
│ subClient #2                                        │
│   └─ XREADGROUP BLOCK <ms>                          │
│ ...                                                 │
└─────────────────────────────────────────────────────┘

Why split the connection: ioredis serializes commands on a single TCP socket, and XREADGROUP ... BLOCK <ms> holds the socket until data arrives or the timeout fires. Sharing one connection for publishing and blocking subscribers would queue every XADD behind the in-flight BLOCK, with publish latency growing linearly in subscriber count. Per-subscribe duplicates make publish latency constant (≈ network RTT), regardless of how many topics × groups you subscribe to. This is the same pattern BullMQ uses for its workers.

Connection count: 1 (publisher) + Σ handlers × max(1, sliding lane count). Each @On is its own subscription, so handler count is the multiplier - batch handlers add one connection each, sliding handlers add concurrency connections each. Earlier versions collapsed several @On sharing a (topic, group) pair into a single subscription; each is now its own, trading connection budget for delivery isolation. Replicas multiply this by replica count, but consumers within an auto-derived group share that group's broker round-robin (replicas don't multiply broker-side group count - just consumer count within each group). redisIdempotencyStore keeps its own client and adds to the count separately. SubClients are owned by the transport regardless of ownsClient - the ownsClient flag only governs the user-supplied parent client; duplicates are always created and closed by us. Lua scripts are registered per instance on the parent client only; lane clients never run anything but XREADGROUP, so they do not need them.

Stalled connections

A connection that stops answering - a half-open socket after a network partition, a proxy that accepted and went silent - is dropped once it has been silent for socketTimeoutMs (default 10s) with a command outstanding, then reconnected, and its commands are resent. A lane's XREADGROUP BLOCK is silent by design, so a lane's timeout is blockMs + socketTimeoutMs, and a lane under blockMs: 0, which blocks forever, gets none. Connecting is bounded the same way - the publisher's startup in the url form by socketTimeoutMs, a lane's by blockMs + socketTimeoutMs, not at all with blockMs: 0 - and a connect that fails throws Could not connect to Redis: <cause> from onInit() or subscribe() instead of leaving the client reconnecting in the background. 0 turns the timeout off.

What it costs:

  • A long event-loop stall looks the same. A stall longer than the timeout with a command in flight drops a healthy socket too.
  • A resent XADD can append twice. When the entry was written but the reply was lost, the resend writes it again - publishing is at-least-once, and @Idempotent covers consumers.
  • A resent sweep XCLAIM costs an attempt and a horizon. When the claim landed but its reply was lost, the resend finds the entry no longer idle and claims nothing; the entry comes back on a sweep one horizon later, its delivery count one higher.
  • An entry handed to a lane that went silent waits for the sweep. Redis may deliver an entry to a socket that has stopped forwarding; it stays pending and returns through the housekeeping sweep after the horizon - late, not lost.

Broadcast group lifecycle

Each handler with broadcast: true derives its consumer group as <base>__<hostname>_<pid>_<token>, with a random token per process, so replicas that share hostname and pid (host-network containers that all run as pid 1) still get a group each. On graceful shutdown the transport's onDestroy() runs XGROUP DESTROY on every broadcast group it subscribed to, including ones unsubscribed earlier, so they don't leak.

Ungraceful exits (process crash, OOM kill) are covered by a liveness key. A process with broadcast subscriptions keeps miia:messaging:alive:<hostname>_<pid>_<token>, written with PX 30000 and refreshed every 10s. The transport reads that owner off each broadcast group's name, so a group subscribed directly under a name without the suffix gets no key and no orphan cleanup. The key is never deleted - it expires 30s after the last refresh. On every broadcast subscribe, and once more about 40s later, the transport scans XINFO GROUPS and destroys any <base>__* group of the same handler, from any host, whose owner's key has expired. Orphans of crashed replicas go away shortly after a replacement starts, whatever host it lands on, and live siblings on one host (a PM2 cluster, several workers per container) are left alone. The second pass is for a predecessor that crashed just before its replacement started, while its key was still alive.

Caveats:

  • A process that cannot refresh its key for 30s looks dead. An event loop wedged that long, Redis unreachable that long, or a key evicted under memory pressure (volatile-* policies evict keys with a TTL first) can cost it its group to a sibling that starts meanwhile. Its lanes then recreate the group (see NOGROUP recovery).
  • The match is by name shape. A group of the form <base>__<host>_<pid>_<token>, or <base>__<host>_<pid> as releases before the token named them, that is not this handler's broadcast group and has no liveness key is removed too.
  • ACL. The publisher client needs SET and EXISTS on ~miia:messaging:alive:*. When SET is denied, the transport logs one warning and turns off liveness and orphan cleanup: without a key of its own, other processes' keys tell it nothing reliable.
  • Rolling upgrade from < 0.8. Older replicas write no liveness key, so new replicas remove their broadcast groups on start, and the old replicas, which cannot recreate a group, stop receiving broadcasts until they are replaced.

Dispatch modes

Redis Streams supports both dispatch modes - 'batch' (default) and 'sliding'. The choice trades latency under variable handler runtimes against the number of Redis connections held open.

Batch (default)

A single consumer loop reads up to concurrency messages per XREADGROUP COUNT=concurrency call, runs them through Promise.allSettled, then reads again. That allSettled is the head-of-line barrier, accepted deliberately: the slowest handler in a batch holds back the next read.

subscription (1 connection)
  └─ XREADGROUP COUNT=4 BLOCK 5000  ──► [m0, m1, m2, m3]  ──► allSettled
                                                              │
                                                              └──► next XREADGROUP

Best for high-throughput uniform workloads where per-message variance is small. One connection per subscription regardless of concurrency.

Sliding

concurrency parallel lanes, each on its own duplicated Redis connection running XREADGROUP COUNT 1 with a unique consumer name suffix :laneN. Redis distributes pending entries across the lanes (since they all join the same group), so each lane only ever holds one in-flight message and the batch barrier degenerates to a single message. A slow message on lane 0 does not block lanes 1-N.

subscription (4 connections, mode='sliding', concurrency=4)
  ├─ XREADGROUP COUNT=1 (consumer :lane0)  ──► m0  ──► next read
  ├─ XREADGROUP COUNT=1 (consumer :lane1)  ──► m1  ──► next read
  ├─ XREADGROUP COUNT=1 (consumer :lane2)  ──► m2  ──► next read
  └─ XREADGROUP COUNT=1 (consumer :lane3)  ──► m3  ──► next read

Best when handler runtimes vary and you cannot tolerate one slow message stalling the others. Mirrors the BullMQ worker pattern.

Picking a mode

BatchSliding
Connection budget per subscription1concurrency
Behavior under runtime skewhead-of-line blockingindependent lanes
Best fituniform workloads, high message volumemixed workloads, latency-sensitive paths
typescript
MessagingModule.configure({
  transport: redisStreamsTransport({ url: process.env.REDIS_URL! }),
  dispatch: { mode: 'sliding', concurrency: 4 }, // bus default
})

@On(OrderPlaced, { mode: 'sliding', concurrency: 8 }) // per-handler override
async onOrder(order: OrderPlaced) { ... }

Lane consumer names show up in XINFO CONSUMERS <stream> <group> as ${baseConsumer}:lane0, ${baseConsumer}:lane1 etc, which makes lane-level diagnostics straightforward. Redeliveries from the housekeeping sweep do not use a lane - they run under ${baseConsumer}:retry and are capped by the subscription's concurrency, so a large batch of abandoned entries cannot run more handlers at once than a normal read would.

Consumer groups and deployment

Consumer groups are how Redis Streams maps logical roles to running replicas. The deployment story is straightforward:

  • One consumer group per logical role. email-workers, analytics, audit-log - pick names that describe the job, not the host.
  • Every replica of the same role joins the same group. Redis automatically load-balances messages across consumers within a group, so adding replicas scales throughput linearly until a single message is no longer the bottleneck.
  • Fan-out across groups is automatic. Two @On(UserCreated, { group: 'email-workers' }) handlers in one app + two @On(UserCreated, { group: 'analytics' }) handlers in a different app = both groups receive every message, independently.

The most common misconfig is mixing up consumer names and group names. Group names are shared across replicas (that's what enables load balancing). Consumer names must be unique per replica - the transport defaults to hostname:pid:rand8 which is safe by construction; only override consumerName if you have a reason. See Subscriptions and fan-out on the Overview page for the full mental model.

Retry mechanics

The group's pending entries list is the retry queue. A nack acks nothing and re-publishes nothing: the entry stays pending in the PEL of the group that read it, and resurfaces one backoff later for that group only.

XADD ──► XREADGROUP '>' ──► handler ──► ack ──► XACK  (done)
                              │
        attempts left         ├──► XCLAIM ... IDLE <horizon - backoff> JUSTID
                              │       (still pending in THIS group's PEL)
                              │                     │
                              │                     ▼  every retryIntervalMs
                              │     XPENDING ... IDLE <horizon> ──► XCLAIM ──► handler
                              │
        budget spent / reject └──► XACK + XADD <topic>.dlq   (one Lua step)

Step by step:

  1. XADD <topic> writes the envelope as a stream entry.
  2. A consumer reads via XREADGROUP GROUP <group> <consumer> COUNT <n> BLOCK <ms> STREAMS <topic> >. > only ever yields entries never delivered to this group, so the delivery count is 1 and so is meta.attempt.
  3. On ack: a single XACK <topic> <group> <id> removes the entry from the PEL. Nothing else happens.
  4. On nack with attempts left, the parkRetry Lua script runs XCLAIM <topic> <group> <consumer> 0 <id> IDLE <horizon - backoff> JUSTID. No XACK, no XADD. JUSTID skips the payload in the reply and does not increment the delivery count - parking is not a delivery. The entry now reports horizon - backoff ms of idle time, so it crosses the horizon exactly one backoff later. The script is gated on this consumer still owning the entry, so a process whose heartbeat lapsed cannot steal back an entry another replica has legitimately reclaimed.
  5. Every retryIntervalMs, the housekeeping pass sweeps each subscribed (topic, group): XPENDING <topic> <group> IDLE <horizon> - + <count>, paged with an exclusive (<id> cursor, skipping entries this process is still handling. Each match is claimed with XCLAIM ... <horizon> and redelivered. The claim is the mutual exclusion: it resets idle to zero, so a concurrent pass on another replica gets an empty reply instead of a second delivery.
  6. On nack with the budget spent (attempt >= maxAttempts), the moveToDlq Lua script runs XACK on the original entry plus XADD <topic>.dlq with meta.lastError filled in. The XACK return value gates the XADD, so two replicas reaching the same exhausted entry in one window write exactly one DLQ record. With retry: { dlq: false } the entry is acked and the failure logged instead. A record that is itself a dead-letter record and exhausts again takes that same path: it is acked and logged at error rather than nested into <topic>.dlq.dlq, a stream nothing reads and nothing trims. Detection is the meta.lastError marker the transport writes on the move, not the topic name, so an ordinary topic you happened to call billing.dlq still gets a real dead-letter record.
  7. On reject - what the bus returns for a payload that fails the event's schema - the entry takes the same moveToDlq step on the delivery that returned it, however many attempts are left: no parkRetry, no retry from the PEL. The dead letter's meta.attempt is that delivery's, 1 for a fresh entry. With retry: { dlq: false } the entry is acked and the drop logged as rejected without retry.

Both transitions use Lua scripts (registered via ioredis defineCommand and cached server-side via EVALSHA) because each couples two Redis operations that must succeed or fail together, and because both decisions are reachable by several replicas at once.

XCLAIM bumps the delivery count by exactly one, and the post-claim count equals the number of times the handler has run. That is the invariant behind meta.attempt: the attempt number a redelivery carries is the pre-claim delivery count plus one. The one exception is a record read off a <topic>.dlq stream, whose meta.attempt describes the death of the original message and is left alone - reading a DLQ record can never look like a fresh exhaustion.

Why the PEL and not a scheduler queue

The previous design acked the entry and re-published it with XADD. Every consumer group on a topic sees an XADD, and each @On handler derives its own group, so multi-group topics are the norm rather than the exception - which made one handler's retry a duplicate delivery for every other handler on that topic. Keeping the retry pending in its own group's PEL and redelivering only through that group's XCLAIM is what makes multi-group topics safe. The suite pins this as a regression test: a retry in one consumer group is never redelivered to another group on the same topic.

The horizon

The horizon is the idle threshold at which a pending entry counts as due:

horizon = max(minIdleMs, every backoff level below maxAttempts)
  • A backoff is expressed as IDLE horizon - backoff, so the horizon has to cover every level. Redis clamps a deadline in the future to now, so a level larger than the horizon would silently collapse into an immediate retry.
  • It is the max() of all levels, not the last one: backoffMultiplier below 1 is legal and unvalidated upstream, which makes the last level the smallest.
  • Levels stop one short of maxAttempts - that attempt is dead-lettered, never parked.
  • Idle time is measured by Redis's own clock. Sending an absolute deadline instead would fold a few seconds of clock skew between the app and Redis either into a near-zero backoff or into a full horizon.
  • Because the horizon is a max(), lowering minIdleMs below your largest backoff level changes nothing.

The heartbeat

Every horizon / 2 (floor 50ms), the transport sends one XCLAIM <topic> <group> <consumer> 0 <ids...> IDLE 0 JUSTID per (topic, group, consumer) covering every entry it is still handling, batched at 100 ids per call. Resetting idle to zero is what frees a handler from having to finish inside the horizon - without it, a handler that runs longer than the horizon would have its own entry swept out from under it and redelivered on another replica. It is the same mechanism as BullMQ's lockDuration / lockRenewTime.

Crash recovery

Retry and crash recovery are one mechanism. To the housekeeping sweep, a retry whose backoff has elapsed and an entry whose consumer died are indistinguishable - both are pending entries idle past the horizon, and both are claimed and redelivered by the same code. There is no separate reclaim path that can be forgotten and no second counter to keep in sync, so the backoff tests and the dead-consumer tests in the suite exercise the same sweep.

Worst-case detection latency after a consumer dies:

horizon + retryIntervalMs   =   60s + 1s with the defaults

Shorten retryIntervalMs for faster reaction (the cost is one PEL scan per (topic, group) per tick), and minIdleMs only if it is currently above your largest backoff level - the horizon is a max(), so below that point it has no effect.

The attempt counter of record is the PEL delivery count, which Redis maintains. Three consequences:

  • It survives the process. A replica that dies mid-handler does not reset or lose the count, which is what makes a crashed delivery resume the retry sequence rather than restart it.
  • There is exactly one counter, shared by business failures and crashes. A SIGKILL in the middle of a handler costs an attempt. Graceful shutdown drains the handler first, so this only bites on hard kills.
  • An abandoned entry whose delivery count already reached maxAttempts goes straight to the DLQ with a synthetic error - Abandoned on <topic> after N delivery attempt(s) without ack or retry - because nobody was alive to report the real one. That check runs before the claim, so a poison message that kills the process does not earn an extra attempt beyond maxAttempts.

Initial position

subscribe() creates the group with XGROUP CREATE ... MKSTREAM, and the subscription's initialPosition picks the start id:

initialPositionStart idA new group reads
'latest' (default)$entries added after the group is created
'earliest'0the whole stream
{ since: ms }<TIME - since>-0entries from the last since ms, then everything after
  • The window is measured on the Redis clock. Stream ids carry the server's time, so the transport reads TIME rather than trusting the process clock. Only when TIME is denied (an ACL that leaves it out, or a proxy that does not know the command) does it fall back to the process clock, with one warning per transport - that assumes clock skew far below since. The warning means TIME was denied, not that a window was measured: TIME runs before every { since } XGROUP CREATE, including the ones that find the group already there.
  • An existing group is never moved. XGROUP CREATE answers BUSYGROUP for a group that exists, and the transport leaves it where it is, whatever position is asked for. Actual creation logs Created consumer group <group> on <topic> at <id>, and so does a recreation after NOGROUP; no such line means the group was already there. Broadcast groups are created at $ regardless of the position and without the line - a broadcast group recovered after NOGROUP is created at the position this process knows for it.
  • Lag can read as nil. XINFO GROUPS reports entries-read as nil for a group created at an arbitrary id, and lag may stay nil until the group catches up with the end of the stream. Treat nil as unknown, not as zero, in monitoring.
  • 'earliest' is the whole stream because the transport never trims - every entry ever published to the topic. A since that reaches back past the start of the Redis clock's epoch starts at 0 and behaves the same way.

Stream retention

Trimmed entries are gone for a new group too: 'earliest' and { since } can only replay what the stream still holds.

Operational notes

  • XPENDING ... IDLE scans the whole PEL. The IDLE filter is applied after the range walk and does not consume COUNT, so the scan is proportional to PEL size, once per (topic, group) per tick. Measured: 20k pending entries with zero matches costs about 3ms. Not a cliff, but it is why retryIntervalMs and PEL depth interact.
  • Manual Redis commands drift the attempt counter. An operator-issued XCLAIM burns an attempt. XREADGROUP ... 0 both increments the count and resets idle, which pushes every parked retry on that group out by a full horizon. XGROUP SETID ... 0 resets the counters outright.
  • Renaming a handler orphans its parked retries. The consumer group name is derived from the class of the handler instance and the method (and the app name, when set), so renaming any of them - or introducing appName - creates a new group. Retries parked under the old group become unreachable: housekeeping only sweeps groups this process is actually subscribed to. Drain the old deployment before renaming, or clean the old group up by hand. The new group starts at the handler's initialPosition, so with 'latest' the entries published between the old deployment stopping and the new one starting are not delivered to it. { since } covers that gap at the cost of replaying entries the old group already handled - the default @Idempotent key contains the class and method name, so it does not dedupe across a rename.
  • NOGROUP recovery. When the group or the stream disappears under a running consumer - Redis restarted without persistence, FLUSHALL, the key evicted, a manual DEL or XGROUP DESTROY, or a sibling's orphan cleanup that took this process for dead - the lane recreates the group and keeps reading. It recreates it at the highest position this process knows for that group: where the group stood when this process subscribed, or the last entry it has read since. The subscription's initialPosition applies only when that is unknown (XINFO GROUPS failed at subscribe, which logs a warning).
    • When it notices. At once after an XGROUP DESTROY or a deletion (DEL, FLUSHALL, eviction).
    • Expect a few error lines. The lane (Consumer group <group> on <topic> is gone, recreating it), the retry sweep and the heartbeat each report on their own channel. recovered after N lines come from the sweep and heartbeat channels; the lane's channel usually counts one failure and prints none.
    • Duplicates. Entries other replicas consumed past this replica's known position are delivered again. @Idempotent covers them.
    • One edge after a wipe. A recreated stream numbers its ids from <ms>-0 again, so an entry added in the same millisecond as the last one this process read gets an id at or below the known position and is skipped - as are entries stamped by a Redis that comes back on a host whose clock is behind.
    • Deleting on purpose does not stick. MKSTREAM brings back a stream deleted under live consumers, and a group deleted under live consumers comes back. Stop the consumers first; to move a group, use XGROUP SETID.
    • Entries in flight at that moment lose their retry state. A nack before the group is back fails (Delivery failed), a nack after it finds no PEL entry (no longer pending), and a nack on the last attempt is dropped without a DLQ record. Retries parked in a destroyed group's PEL are gone.

Graceful drain

onShutdown() waits up to drainTimeoutMs for in-flight handlers to finish; onDestroy(), which the app runs only after every provider's onShutdown(), closes the Redis client. Without drain, a SIGTERM mid-handler aborts the consumer loop and quits the client while a handler is still running - the message stays un-acked, another replica's housekeeping pass picks it up once it crosses the horizon, and the work is done twice.

Shutdown order. In onShutdown(): abort each subscription → disconnect each subClient (forces in-flight XREADGROUP BLOCK to throw Connection is closed, the consumer loop sees the abort flag and exits cleanly) → await the running housekeeping pass and every in-flight handler so they finish their final XACK / Lua calls through the still-alive pubClient. In onDestroy(): stop the heartbeat and the liveness-key refresh → XGROUP DESTROY for broadcast groups → quit pubClient (only when the transport owns it). Once onShutdown() has started, subscribe() rejects - and so does a subscribe() still in progress when it starts, after closing the lanes it had opened. Calling onDestroy() alone, as tests do, runs the drain first.

Two details of that order matter:

  • One budget, not two. drainTimeoutMs covers the running housekeeping pass and the handlers it started. A slow pass does not buy its own redeliveries a second timeout.
  • The heartbeat stops last. It keeps running through the drain, and between the two phases, so a handler that is still finishing keeps its entry invisible to other replicas; stopping it first would expose those entries to the horizon early. The liveness-key refresh stops with it, so a long drain cannot let the key expire and hand this process's broadcast groups to a starting sibling's orphan cleanup.

A handler that misses the drain window is not lost: its entry stays in the PEL and any replica redelivers it once it crosses the horizon. drainTimeoutMs sizes duplicate work, not loss.

DLQ writes during drain are safe - the moveToDlq Lua script is awaited synchronously inside the tracked processMessage promise, so the XADD to <topic>.dlq completes before the drain promise resolves.

redisIdempotencyStore

Production-ready IdempotencyStore backed by Redis. Pair with any MessageTransport (Redis Streams, NATS, in-memory, etc.) - the store is transport-agnostic.

typescript
import { Module } from '@miiajs/core'
import { MessagingModule } from '@miiajs/messaging'
import { redisIdempotencyStore, redisStreamsTransport } from '@miiajs/messaging-redis'

@Module({
  imports: [
    MessagingModule.configure({
      transport: redisStreamsTransport({ url: 'redis://localhost:6379' }),
      idempotency: redisIdempotencyStore({
        url: 'redis://localhost:6379',
        keyPrefix: 'orders-svc:idem:',
      }),
    }),
  ],
})
class AppModule {}

claim() is SET <prefix><id> 1 NX EX <ttl> - atomic, so concurrent claims for the same id produce exactly one true. release() is DEL <prefix><id>. Keys auto-expire after the TTL passed to @Idempotent.

OptionTypeDefaultDescription
urlstring-Redis URL. Mutually exclusive with client.
clientRedis-Pre-built ioredis instance. The store does not call connect() or quit() on a user-supplied client, nor add an error listener to it.
keyPrefixstring'miia:idem:'Key prefix in Redis. Set a per-service prefix when multiple services share a Redis instance so claims do not collide across services.
socketTimeoutMsnumber10000url form only. How long the connection may stay silent with a command outstanding before it is dropped and reconnected - its commands are resent. Without it, a half-open connection stalls every @Idempotent handler. 0 disables.

With url, the store logs the first connection error of an outage, and a recovery line with the error count once the connection is back after more than one.

Pre-built ioredis client

When you want to share a connection with other parts of your app - caching, rate limiting, session storage - pass a pre-built Redis instance instead of a URL:

typescript
import { Redis } from 'ioredis'
import { redisStreamsTransport } from '@miiajs/messaging-redis'

const client = new Redis(process.env.REDIS_URL!)

MessagingModule.configure({
  transport: redisStreamsTransport({ client }),
})

Keep the default replyMapping - a client created with replyMapping: 'resp3' is rejected. Behind a proxy that refuses HELLO 3, build the client with protocol: 2.

The transport tracks an ownsClient flag internally:

  • url form: the transport creates the ioredis instance, calls connect() in onInit, and quit() in onDestroy. It owns the lifecycle of the parent client.
  • client form: the transport never calls connect() or quit() on your client. Your code owns the lifecycle. Initialise the connection before the app starts, and tear it down after app.destroy() returns.

In both cases, the transport calls client.duplicate({ lazyConnect: true, socketTimeout: blockMs + socketTimeoutMs }) for every subscribe() to spin up a dedicated blocking client (see Connection model). Those duplicates are owned by the transport regardless of ownsClient - they are created and closed by us, never by your code. The ownsClient flag only governs the parent.

Connection errors of the clients the transport creates - the url form's client and every lane - go through the transport's logger: one Redis connection error line when the failures start, then at most one a minute unless the cause changes, and a Redis connection recovered line when they stop, with the count after more than one. The transport adds no error listener and no socketTimeout to your client: set both yourself, or ioredis prints each of its connection errors as [ioredis] Unhandled error event and a connection that goes silent hangs its commands. Lanes get both from the transport, their own socketTimeout in place of any your client carries.

This split exists so you can multiplex the parent connection across multiple subsystems (idempotency store, cache, rate limiter) without the transport reaching in and quitting it out from under you, while still getting per-subscribe blocking isolation for free.

Testing

Integration tests need a real Redis - ioredis-mock and similar libraries do not implement Streams faithfully enough for retry/DLQ semantics. The pattern used by the package's own test suite is to skip when REDIS_TEST_URL is unset:

typescript
import { describe, it, expect } from 'bun:test'
import { Redis } from 'ioredis'
import { RedisStreamsTransport } from '@miiajs/messaging-redis'
import { randomUUID } from 'node:crypto'

const REDIS_URL = process.env.REDIS_TEST_URL
const d = REDIS_URL ? describe : describe.skip

d('my events integration', () => {
  it('delivers across consumers', async () => {
    const transport = new RedisStreamsTransport({
      url: REDIS_URL!,
      retry: { backoffMs: 50 },
      blockMs: 200,
    })
    await transport.onInit()
    // ... use transport ...
    await transport.onDestroy()
  })
})

Two operational tips:

  • Always use unique topic names per test (UUID suffix is enough). Cross-test pollution from a leftover stream is the #1 source of flaky retry/DLQ assertions. With initialPosition: 'earliest' or { since }, a suite that reuses a fixed topic with fresh group names also picks up whatever earlier runs left in the stream.
  • Lower blockMs to 200ms in tests so unsubscribe() and onDestroy() return promptly instead of waiting for the default 5s XREADGROUP BLOCK to time out.

Provisioning the Redis instance itself - local container, managed service, in-cluster pod - is up to you; the transport only needs a reachable URL exported as REDIS_TEST_URL before the suite runs.

Exports

typescript
import {
  RedisIdempotencyStore,
  redisIdempotencyStore,
  RedisStreamsTransport,
  redisStreamsTransport,
  type RedisIdempotencyStoreOptions,
  type RedisStreamsTransportOptions,
} from '@miiajs/messaging-redis'
Edit this page on GitHub