@nodii/outbox-dispatcher
v0.17.0
Published
Pattern 3 producer-side outbox drainer for the Nodii microservice stack — defineDispatcher + startDispatcher + single-active SET-NX-EX lease (D209) + FOR UPDATE SKIP LOCKED drain + XADD to Redis Streams + currentHwm + 24h-unpublished ops-alert sweep (D401
Readme
@nodii/outbox-dispatcher
Producer-side Pattern-3 outbox drainer for the Nodii microservice stack —
the symmetric peer of @nodii/replica-consumer (the
consumer side). Drains a service's <service>_outbox table to Redis Streams
via XADD, with single-active-worker leasing, a retry-backoff cap, a
24h-unpublished ops-alert sweep (D401 — no publish-side DLQ), HWM
exposure for snapshot live-stitch, lag/depth metrics, and graceful drain.
Spec: planning hub feature_doc serviceId=nodii-libs docKey=outbox-dispatcher.
Implements 01-communication-doctrine § 9.2 (drainer, softened by D209:
SET-NX-EX lease is canonical, BullMQ optional) + 09-replication-doctrine
§ 2.4 (XADD envelope) + § 7 (snapshot HWM cursor).
Quick start
import { defineDispatcher, startDispatcher } from "@nodii/outbox-dispatcher";
const dispatcher = defineDispatcher({
serviceName: "nodii-tenant-service",
outboxTable: "outbox", // 09-replication § 2.2
streamFor: (row) => `tenant.${row.topic.split(".")[1]}`,
leaseKey: "lock:outbox:tenant-service", // D209 SET-NX-EX
leaseTtlMs: 30_000, // renew at ttl/2
pollMs: 500, // § 9.2
batchSize: 50, // § 9.2
publishMaxAttempts: 8, // retry-backoff cap (D401: never deletes/DLQs)
drainDeadlineSeconds: 30, // graceful drain
});
const handle = await startDispatcher([dispatcher], { pgPool, redis, telemetry });
// snapshot RPC handler at freeze:
const hwm = handle.currentHwm("tenant.user_membership"); // → "1748100000000-0"Writing a row (COMM-24.3)
writeOutboxEvent(tx, outboxTable, input) inserts one row in the caller's
business transaction and returns the minted eventId.
aggregateIdis free text, not a UUID (notifywrites<requestId>:<channel>,usagewrites its idempotency id). The table column isTEXT.tenantIdis optional. When present it is written to the nullabletenant_idcolumn, and the service's tenant RLS checks it against the transaction's tenant. When absent the INSERT does not nametenant_id, so a service's payload-tenant trigger can fill it frompayload.tenant_id, and a table without the column keeps working.tenantIdmust be a standard hyphenated UUID (any case) and is bound in lower case; anything else throwsInvalidOutboxTenantbefore the INSERT.- The payload's owning tenant is compared as it will be stored in the JSON
payload:
payload.scope_tenant_idwhen it is present and not null, elsepayload.tenant_id(AUDIT-134; COMM-26, S08-3). A Nodii-sent request, such as an@nodii/notifyrequest, names the recipient intenant_idand the owner inscope_tenant_id. Such a payload'stenant_idis not checked. - A payload with a non-null
scope_tenant_idand notenantIdis recorded under thatscope_tenant_id: the INSERT namestenant_id, so a payload-tenant trigger cannot store the row under the recipient (P-8). Thatscope_tenant_idmust be a standard hyphenated UUID, else the write throwsInvalidOutboxTenant. - A
tenantIdthat disagrees with that field throwsOutboxTenantMismatchbefore the INSERT; the message names the field. - The published envelope (COMM-24.1) carries no tenant. Consumers that need the
tenant read
payload.tenant_id, so keep it in the payload alongsidetenantId.
The migration adds tenant_id UUID NULL with ADD COLUMN IF NOT EXISTS and
never rewrites an existing column in place.
Caller event id and write-once (LIBS-35)
eventIdis optional. A producer with a durable business key passes it, and it is stored and returned verbatim (free text; the column isTEXT). An empty string (or a non-string from untyped JS) throwsInvalidOutboxEventId. When absent a UUIDv7 is minted, as before.writeOutboxEventOnce(tx, outboxTable, input)is the same write withON CONFLICT DO NOTHING. It returns{ eventId, inserted: true }when the row was written, and{ eventId: null, inserted: false }when it conflicted with a unique index and was skipped. The id is null because no row carries it (the conflict may be on another index); the existing row is left as it was.- The statement names no conflict target, so it skips on any unique index:
an
event_idindex (pair it with a stableeventId), or a service's own partial index such as onehr.attendance.day_started.v1per tenant and aggregate. Scope anevent_idindex by tenant,(tenant_id, event_id): a global one lets one tenant's id silently skip another tenant's write. The library migration adds no unique index onevent_id; on a table with no unique index nothing conflicts, so every call inserts. - Do not use write-once on a table whose integrity index must fail loudly.
Because it suppresses a conflict on any unique index, a service such as
billing, whose version index (BIL-REP-6) must raise on a duplicate, must use
writeOutboxEvent. The default keeps every conflict an error. - Pass the open business transaction, and an executor that reports the
affected-row count as
count(postgres.js and Bun SQL do). Without a count the call throws rather than guess, after the INSERT has run: the row is undone only when that transaction rolls back. On a pool or autocommit executor it is already committed. writeOutboxEventitself is unchanged: a duplicate under a unique index still throws.
Telemetry envelope (LIBS-35)
telemetryEnvelopeis optional: a JSON object, written to thetelemetry_envelopecolumn. The drainer folds it into the published event aspayload._telemetry, replacing any_telemetrythe payload carries.- The stored payload stays as the caller gave it, so a second reader of the
outbox (ticketing's outbound webhook fan-out) never sees the context. Do not
also write
payload._telemetryyourself. - Anything but an object (an array, a string, a number) throws
InvalidOutboxTelemetryEnvelopebefore the INSERT. When absent the INSERT does not name the column, exactly as before. - A
Dateinside it is written byDate.toJSON("2026-11-03T12:00:00.000Z"). Python and Go write a datetime in the same form, so every port stores the same bytes.
Aggregate-kind registry (S03-5, TKT-INT-14, S07-48)
A producer owns the kinds it emits. Declare them once and pass the registry to every write; an unregistered kind is refused before the INSERT, so a kind can never come from topic text.
export const TICKETING_KINDS = defineAggregateKinds("ticketing", [
"NotificationRequest",
"Queue",
"Ticket",
]);
await writeOutboxEvent(tx, "ticketing_outbox", input, { kinds: TICKETING_KINDS });- Kinds must be singular PascalCase (
^[A-Z][A-Za-z0-9]*$) and unique, and the service name lowercase; otherwisedefineAggregateKindsthrowsInvalidAggregateKind. - A write whose
aggregateKindis not registered throwsUnregisteredAggregateKind(writeOutboxEventandwriteOutboxEventOnce). registry.toDocument()is canonical JSON,{"aggregate_kinds":[...],"service":"..."}with sorted kinds, byte-equal in TS, Python and Go. Export the registry (or its document) from the producer's own package so consumers pin the version they read (S07-48).
Drain sequence (§ 5.2)
acquire-lease (D209) → SELECT … FOR UPDATE SKIP LOCKED → XADD canonical
envelope → UPDATE … SET dispatched_at = now(), stream_id = … → release.
At-least-once: the consumer dedupes on event_id via consumed_events.
Rows with dispatched_at IS NOT NULL are never re-claimed (idempotent
re-XADD on restart).
Round-robin across tenants (COMM-47)
Each pass takes the oldest due row of every tenant (by occurred_at, then
table order) before the second row of any tenant, so one tenant's backlog cannot delay
the others. Within a tenant, rows keep occurred_at order; rows with a NULL
tenant_id take their turns as one group. Each turn goes round the tenants in
byte order of their id and starts after the tenant the last pass ended on, so
when there are more pending tenants than batchSize, the ones a pass did not
reach go first on the next, however old the others' rows are. The runner keeps
that position in memory; a restart starts the rotation again.
Rows with the same occurred_at (rows written in one transaction always share
it) go in table order (ctid), on both claims and in the unpublished sweep. For
fresh rows that is the order they were written while they fit on the page
Postgres is filling. Postgres does not promise it: once vacuum has freed space
in the table, a later row of the same transaction can land on an earlier page
and go first. A row whose publish failed is
the exception: recording the failure rewrites the row, which gives it a new
ctid, so on its retry it can go after rows it was written before. A producer
that needs strict order within one aggregate opts in to orderPerAggregate
(DEC-0428), which orders by version; this tie-break does not promise it.
The claim reads the migration's
idx_pending_tenant_<table> index on (tenant_id, occurred_at, id) WHERE
dispatched_at IS NULL: one probe per pending tenant and at most batchSize
rows per tenant, so its cost follows the number of pending tenants, not the
backlog. On a large live table, build that index first with
buildPendingTenantIndexSql(table) (CONCURRENTLY, outside a transaction).
An outbox table without a tenant_id column is claimed in plain
occurred_at, ctid order, and the runner logs one warning; run the library migration to add the
column. The runner checks again each pass until it finds the column, then
switches to the round-robin claim without a restart.
Per-aggregate order (orderPerAggregate)
COMM-47 keeps occurred_at order within a tenant by default. A producer may opt
in to version order within each aggregate (DEC-0428). With
orderPerAggregate: true the claim skips a row while an earlier unpublished
row of the same (tenant_id, aggregate_kind, aggregate_id) exists, earlier
meaning a lower (source_entity_version, id). The order does not depend on
occurred_at, which can be out of step with the real order.
- A failed row holds back only the later rows of its own aggregate. Other aggregates keep publishing.
- A row past
publishMaxAttemptsholds its aggregate until it is repaired; the 24-hour sweep alerts on it. The held rows behind it are unpublished too, so the sweep alerts on them as they age. - The producer must bump the aggregate's version in the same transaction as the outbox row, holding the aggregate's row lock (S03-11). Then versions commit in order. The check sees only committed rows: if version 2 committed before version 1, version 2 could publish first.
- Consecutive rows, consecutive versions. An aggregate's consecutive
outbox rows must carry consecutive versions. A version bump that writes no
outbox row reads as a gap: the next row waits
aggregateGapWaitMsand alerts. A producer whose versions skip should not opt in. - Bounded gap wait. When the aggregate's latest earlier row is more than
one version below the row, a version is missing. The row waits
aggregateGapWaitMs(default 60000, at most 86400000; 0 publishes at once), counted from the later of the earlier row's publish time and the row's ownoccurred_at. So an aggregate that was idle for longer than the wait still waits for a newly written row. A producer that setsoccurred_atin the past shortens the wait. A row whoseoccurred_atis more than the wait in the future does not wait at all, so no row waits longer than twice the wait. Then it publishes,outbox.aggregate_version_gaps{service, topic, aggregate_kind}counts it and a warning names the aggregate and both versions. A missing version holds only its own aggregate, and never for longer than twice the wait. A row with no earlier row in the table (the aggregate's first, or its history deleted) never waits. A missing version that commits after a later one has published publishes too (it is not held), and alerts the same way.aggregateGapWaitMswithoutorderPerAggregateis refused, also on a hand-built dispatcher at start. - With
excludeTopicPrefixestoo, an excluded row never holds back its aggregate: the dispatcher never claims it, so the earlier-row check skips it. Its version still counts for the gap check. Its own handler publishes it, so an excluded row that is already published is never taken as a late commit of a later version. - The ordered claim takes candidates round-robin across tenants (COMM-47),
like the default claim: each tenant's oldest candidate, then each tenant's
next one, so a tenant with a large backlog cannot delay the others. It
continues the same tenant rotation, starting after the tenant the last pass
ended on, and never falls back to the plain
occurred_atclaim. - Each pass publishes at most one row per aggregate, and the loop drains again
at once while rows are published. The default (
false) claim is the round-robin claim above, unchanged by this option. - Cost. Each ordered pass probes the pending index once per due pending
row to find each aggregate's earliest row. The previous-row lookup and the
gap wait then run once per aggregate, and the later-row gap check only on the
claimed rows. So a pass costs about one cheap index probe per pending row, and
draining a backlog of P rows over A pending aggregates takes about
P² / min(batchSize, A) probes in all, since each pass publishes at most one
row per aggregate: about P² when one aggregate holds the whole backlog. The candidates are not capped on purpose: a cap on the
oldest rows would let one aggregate's or one tenant's backlog fill the window
and hold back every other aggregate, which is what this option exists to
prevent. Opt in only where per-aggregate order is needed, and keep
batchSizelarge enough for the number of aggregates that are usually pending. - Rows of one aggregate with the same version publish in
idorder (COMM-47).writeOutboxEventmints UUIDv7 ids, which sort in write order; a producer that inserts its own ids should use UUIDv7 too. - The ordered claim reads the aggregate's earlier and later rows, published or
not. A table that opts in should add the two indexes
buildOrderPerAggregateIndexSql(table)returns (Pythonbuild_order_per_aggregate_index_sql, GoBuildOrderPerAggregateIndexSQL), one statement at a time outside a transaction:idx_aggregate_order_<table>on(aggregate_kind, aggregate_id, source_entity_version, id)andidx_aggregate_pending_<table>on the same columnsWHERE dispatched_at IS NULL, bothCONCURRENTLY. The tenant is a filter:IS NOT DISTINCT FROMcannot seek a btree index. WithorderPerAggregate, a table name longer than 41 bytes (UTF-8) is refused (InvalidDispatcherConfig), because Postgres would cut the index names to 63 bytes. A runner started withorderPerAggregateon a table where either is missing, on another table or invalid (a failedCONCURRENTLYbuild leaves one) logs one warning naming the statements; it still runs.
Per-stream MAXLEN (streamMaxLenFor)
streamMaxLenFor(stream) returns the MAXLEN for one destination stream: a
whole number trims it to MAXLEN ~ n (0 leaves it untrimmed), undefined or
null uses streamMaxLenApprox. One dispatcher can then keep a short stream
next to long ones:
defineDispatcher({
serviceName: "auth",
streamFor,
streamMaxLenFor: (s) => (s === "auth.audit_event" ? 10_000 : undefined),
});Any other return value fails that row's publish, recorded on the row like any
publish failure. ~ trims whole stream nodes, so a stream keeps at least the
given length, not exactly it.
Excluded topics (excludeTopicPrefixes)
excludeTopicPrefixes lists topic prefixes the dispatcher never claims or
publishes (default none). A row whose topic starts with one of them stays in
the outbox for the service's own handlers, for example hr's private
hr.internal. topics:
defineDispatcher({ serviceName: "hr", streamFor, excludeTopicPrefixes: ["hr.internal."] });The match is a plain prefix (starts_with), so hr.internal. does not match
hr.internal_audit.. Each row's dispatch state has one writer (P-11): the
dispatcher never claims or writes an excluded row, so the service's own
handler is that row's only writer and marks it done when it finishes (hr's
handlers do so today). The 24-hour unpublished sweep and the outbox.depth
gauge only read, and they still cover excluded rows, so a row its handler
never finishes raises the same alert as any other (LIB-EVT-6). An empty or
non-string prefix is refused at define. With no prefixes the claim SQL is
unchanged.
XADD envelope — consumer contract
The XADD output is byte-identical to what @nodii/replica-consumer reads:
a single Redis-Streams field named event carrying
JSON.stringify({ event_id, topic, aggregate_kind, aggregate_id,
entity_version, payload, stream_id, committed_at }). The outbox column
source_entity_version maps to the envelope key entity_version; the producer
telemetry_envelope is folded into payload._telemetry. The contract test
(tests/contract.test.ts) drives this output back through the consumer's read
path to prove round-trip. (The feature_doc § 5.2 lists individual XADD fields +
source_entity_version; the shipped consumer reads a single JSON event
field keyed entity_version — the consumer's read path is the binding
contract per the feature_doc's own statement; drift filed.)
Publish failures + the 24h-unpublished sweep (D401)
There is no publish-side DLQ. Per locked decision D401
(01-comms § 9.2 / 09-replication § 2.5), a failed XADD only increments
publish_attempts + records last_error on the outbox row — the row is
never deleted and never moved to a <service>_outbox_dlq table, so the
at-least-once / replay-from-outbox invariant holds for financial + business
events. publishMaxAttempts caps retry backoff only (the claim query stops
re-claiming a row once publish_attempts reaches it); it never affects row
lifecycle.
Liveness is surfaced by a per-service 24h-unpublished sweep. Schedule
sweepUnpublishedOutbox (e.g. hourly) — it selects rows un-dispatched past a
threshold (default 24h) and raises an M17 page-tier ops alert
(outbox.unpublished_alert, severity=page) carrying outbox_id, topic,
event_id, publish_attempts, last_error, age:
import { sweepUnpublishedOutbox } from "@nodii/outbox-dispatcher";
// in your scheduler (BullMQ per 01 § 9.3, or your existing cron):
await sweepUnpublishedOutbox({ pool: pgPool, dispatcher, telemetry });This is distinct from the subscriber-side replication_dlq (09 § 8.1), which
handles consume-side poison applies and is unaffected.
Retention: prune published rows, bound streams by age (RETENTION-FIX-4, LIBS-72)
Outbox payloads can hold personal data, and nothing else ever deletes a published row. Wire the prune job once in your worker process and run its handler daily:
import { makeOutboxPruneJob } from "@nodii/outbox-dispatcher";
const dispatcher = defineDispatcher({ serviceName: "tenant", streamFor /* , orderPerAggregate */ });
worker.schedule(makeOutboxPruneJob({ dispatcher, pool: ownerSql, redis }));
// { name: "tenant.outbox-prune", intervalMs: 86_400_000, pool: "owner", handler }Passing the dispatcher gives the job its serviceName, outboxTable and
orderPerAggregate; each can also be given on its own.
Python: make_outbox_prune_job(dispatcher=dispatcher, pool=owner_pool, redis=redis).
Go: outbox.MakeOutboxPruneJob(outbox.OutboxPruneJobConfig{Dispatcher: &d, Pool: ownerPool, Redis: redisClient}).
Each run:
- Deletes published rows whose
dispatched_atis older thanretentionMs(default 30 days, operator ruling of 20 Nov 2026),batchSize(1,000) rows perDELETE, until aDELETEremoves nothing (a short batch is not the end:SKIP LOCKEDmay have passed over rows a drain holds), at mostmaxBatchesPerRun(1,000) statements. - With
orderPerAggregate, keeps each aggregate's latest published row. The ordered claim reads the aggregate's previous row to detect a version gap; if the prune removed the aggregate's whole history, a v7 committing before v6 would publish at once. So a row is deleted only while a newer published row of its aggregate exists, and the kept latest row, once past the retention, is scrubbed (payload = '{}', trace, telemetry and error columns NULL): its version survives, its personal data does not (outbox.prune.scrubbed_rows). WithoutorderPerAggregateevery aged published row goes, so one-shot aggregates do not pile up. As a fail-safe, a table that carries the aggregate-order index (idx_aggregate_order_<table>, frombuildOrderPerAggregateIndexSql) is treated as ordered even when the job was built fromserviceNamerather than thedispatcher. - Never deletes an unpublished row (
dispatched_at IS NULL), however old and however often its publish failed. D401 keeps it as the source of truth; once repaired it publishes, and it is deleted 30 days after that. - Trims the streams you list, and only those, to
XTRIM <stream> MINID ~ <now - 14 days>(per-streamretentionMs, default 14 days). Trimming is opt-in per stream: a new consumer group, or one whose cursor points at a trimmed entry, starts mid-stream, so list a stream only when every consumer group on it can hydrate from a snapshot on cold start (or starts at$by design). Streams whose consumers replay from0with no snapshot stay unlisted. The trim is approximate (~): Redis removes whole macro nodes only, so a few entries a little older than the bound can remain until a later run. - Never trims past an entry a consumer group still needs: the trim point is
held at each group's lowest pending id, else its last-delivered id. A group
that stopped reading holds its stream back; the job logs the group and sets
outbox.stream_trim.held_back{service,stream}to 1. PassrespectConsumerGroups: falseonly for a stream whose groups are disposable.
makeOutboxPruneJob({
serviceName: "tenant",
pool: ownerSql,
redis,
streams: [
"tenant.custom_domain", // 14 days
{ stream: "tenant.role", retentionMs: 30 * 86_400_000 },
],
});One replica runs at a time, under the fenced lease
nodii:lease:<service>:outbox-prune (LIB-EVT-20). The fence is checked before
every DELETE batch and every XTRIM; a run whose lease is taken stops and
returns leaseLost: true. A replica that finds the lease held returns
ran: false. A failed run (a lease-backend outage at acquire, a database
error) is counted as outcome=error with the rows it already deleted, then
thrown, so nothing is deleted blind. A run is complete only when the DELETE
loop ended on an empty batch and every listed stream's trim finished within
its call budget. The DELETE bypasses tenant RLS, so pass the owner pool.
If row level security still applies to that role on the outbox (the table has
FORCE ROW LEVEL SECURITY, or the role is not the owner) and no permissive
USING (true) policy opens the table to it, the DELETE would see no rows;
the run fails with OutboxPruneRowSecurityError (Go
ErrOutboxPruneRowSecurity) instead of reporting itself complete. Run it as
the owner on a table without FORCE, as a BYPASSRLS role, or with a policy
such as db-rls's FOR ALL TO nodii_owner USING (true). The check asks for
USING (true) on SELECT, UPDATE and DELETE on every run, ordered or not,
so separate FOR SELECT and FOR DELETE policies with no FOR UPDATE one are
refused.
The event-id dedupe window becomes the outbox retention.
writeOutboxEventOnce skips a write whose event_id conflicts with a row
still in the table. Once the prune deletes the published row (30 days after
publish by default), a retried command with the same event_id inserts again
and is published again. A caller that needs a longer dedupe window must keep
its own idempotency record (for example @nodii/idempotency) or raise
retentionMs to cover it. The same goes for consumers: a consumer that dedupes
on outbox event ids (consumed_events) should keep those records at least as
long as the outbox retention, or a re-published event is processed again.
The job writes no audit event (AUDT-49). It reports through logs and metrics:
outbox.prune.runs{service,outcome} (complete / partial / lease_lost /
skipped / error), outbox.prune.deleted_rows{service,table},
outbox.prune.scrubbed_rows{service,table},
outbox.stream_trim.entries{service,stream},
outbox.stream_trim.held_back{service,stream} and
outbox.stream_trim.errors{service,stream}.
The library owns only your outbox table. saga_outbox belongs to
@nodii/saga and replication_dlq to @nodii/replica-consumer; neither is
pruned here. For a large outbox, add the prune's index once, outside a transaction
(it is built CONCURRENTLY, so producers' INSERTs are never blocked); the
prune works without it, scanning the table per batch, and the job logs a
warning naming the index when it is missing:
await sql.unsafe(buildPruneIndexSql("outbox"));
// CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_prune_outbox" ON "outbox" (dispatched_at) WHERE dispatched_at IS NOT NULLPython build_prune_index_sql, Go BuildPruneIndexSQL. It is not in the
table migration, because a plain CREATE INDEX there would lock an existing
outbox against writes while it builds. If a concurrent build fails (cancelled, lock
timeout), Postgres leaves an INVALID idx_prune_<table> that IF NOT EXISTS
then skips: check SELECT indisvalid FROM pg_index WHERE indexrelid =
'idx_prune_outbox'::regclass, and if it is false run DROP INDEX CONCURRENTLY
IF EXISTS "idx_prune_outbox" and build it again.
A stream whose trim fails (a non-stream key under the name, a Redis error) is
returned with error, counted in outbox.stream_trim.errors{service,stream},
and does not stop the next stream or the run's report.
Metrics (§ 5.6)
outbox.depth{topic} · outbox.lag_seconds{topic} · outbox.dispatch_rate{topic}
· outbox.publish_failures{topic,reason} · outbox.hwm{stream} ·
outbox.lease_renewals{result}. D401 sweep:
outbox.unpublished_over_threshold{service} (gauge) ·
outbox.unpublished_alert{topic,service,severity=page} (the M17 alert).
migrate-gen (§ 5.8)
bunx @nodii/outbox-dispatcher migrate-gen --service nodii-tenant-service [--out-dir .]Emits the <service>_outbox table DDL (D401: no publish-side DLQ table) + a
src/outbox/boot.ts skeleton.
Optional @nodii/db-rls (08-rls § 4)
Pass tenantId on the dispatcher + a dbRls handle at startDispatcher and
the drain SELECT runs inside withSystemContext({ tenantId }). Without it,
the raw pool is used (platform-tenant outbox only).
