Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/orphans-keys-defer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"txob": minor
---

Fix three ways one bad delivery could stall processing, and make the documented `defer` opt-out real:

- **Deleted events:** a pending delivery whose event was deleted (e.g. by a retention job; only Postgres cascades) crashed every MongoDB processor through an unhandled rejection, wedged the whole Redis claim batch with climbing attempts, and was claimed again forever on DynamoDB. These stores now mark such deliveries dead with `last_error` "event '...' not found", and the processor marks dead any delivery a store returns without its event and no longer lets an unexpected error escape as an unhandled rejection.
- **`perKey` keys:** a key function returning `undefined`, which its type allows, blocked every handler of the event forever. `undefined` now means no key, like `null`.
- **Fan-out errors:** a `priority`, `perKey` key or `defer` function that throws or returns an invalid value still keeps the event unfanned, but only for the failing handler's `retry.maxAttempts` fan-out attempts; then its delivery is created dead with the error and the event's other handlers run. `TxOBNewDelivery` gains an optional `error` that stores must honor (custom stores: see MIGRATING.md).
- **`defer` functions** are now called for events published with `defer` and can override it, as the docs said; returning `null`/`undefined` keeps the publisher's `defer_until`. **Behavior change:** a `defer` function that returns a value for such events used to be ignored and now wins. Static `defer` values are still overridden by `publish`.
5 changes: 5 additions & 0 deletions MIGRATING.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
- **Defaults and transforms run at delivery**, once per delivery. Make them deterministic: compute IDs and timestamps before publishing instead of in `.default()` or `.transform()`.
- **The memory store keeps event data as JSON**, like the Postgres, Redis and DynamoDB stores, so tests catch the cases above.
- **Custom stores:** optionally implement `roundTripData(data)` to return event data as the store will read it back. Without it, `publish` validates data as given, as before.
- **`defer` functions decide for themselves.** A handler's `defer` function is now called for events published with `defer` too, and a non-null result overrides the publisher's `defer_until`. Returning `null` or `undefined` keeps `defer_until`, as before. Static `defer` values are still overridden by `publish`. If you have a `defer` function that always returns a value and want publish-time defers to win, return `null` when `event.defer_until` is set.
- **A `perKey` key of `undefined` means no key**, like `null` (it used to block the event).
- **Fan-out errors are capped.** A `priority`, `perKey` key or `defer` function that throws or returns an invalid value keeps the event unfanned, as before, but only for the failing handler's `retry.maxAttempts` fan-out attempts. Then that delivery is created dead, with the error in `last_error`, and the event's other handlers run. `onDeliveryDead` isn't called for it.
- **Deliveries whose event was deleted** are marked dead (`last_error` "event '...' not found") on MongoDB, Redis and DynamoDB instead of crashing the processor (MongoDB) or being claimed again forever (Redis, DynamoDB). On Postgres the foreign key already deletes them with the event.
- **Custom stores:** `TxOBNewDelivery` gains an optional `error`. When `completeFanout` gets a delivery with `error`, create it dead with that `last_error`, and never claim it. A claimed delivery whose event no longer exists should be marked dead in the store (with `eventMissingError(eventId)` as its error) rather than returned; if a store does return one without its `event`, the processor marks it dead. The contract in `test/contract.ts` covers both.

# Migrating from 0.5 to 0.6

Expand Down
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ Each handler is either a function or a config object:

- **Concurrency, per-key concurrency and rate limits are global.** `concurrency: 5` means at most 5 deliveries of the handler run at once across all processors. Running deliveries are counted by their live leases, so a processor that crashes keeps holding its share until its leases expire (at most `leaseMs`).
- **Claims for a limited handler are serialized** (a transaction-scoped advisory lock on Postgres, a short-lived lock document on MongoDB). Claims take milliseconds, but if one handler sees very high claim rates, prefer a higher `concurrency` on the processor over many tiny claims.
- **`priority`, the `perKey` key and `defer` are computed at fan-out** and stored with the delivery, so they're evaluated once per event, not per attempt.
- **`priority`, the `perKey` key and `defer` are computed at fan-out** and stored with the delivery, so they're evaluated once per event, not per attempt. A key of `null` or `undefined` means the delivery has no key. If one of these functions throws or returns an invalid value, the event stays unfanned and is retried when its fan-out lease expires; once that has happened `retry.maxAttempts` times, the failing handler's delivery is created `dead` with the error as `last_error` (without calling `onDeliveryDead`), and the event's other handlers get their deliveries.
- **`timeoutMs` cancels the handler's context.** When it elapses, the `signal` passed to the handler is aborted with a `TxOBTimeoutError` reason. Honoring it is up to the handler: pass the signal to `fetch`, database drivers and so on, or check `signal.aborted`. Whatever the handler then does decides the outcome. If it throws, the attempt fails and is retried; if it finishes successfully anyway, the delivery is completed. The lease stays renewed while the handler runs.
- **Process-wide defaults** go in `handlerDefaults: { retry, timeoutMs }`.

Expand All @@ -268,14 +268,21 @@ OrderPlaced: {
defer: (event) => (event.data.reminderAt ? { until: event.data.reminderAt } : { delayMs: 86_400_000 }),
handler: async (event) => {},
},
// Static defer (or none): follows a publish-time defer
notifyWarehouse: { defer: { delayMs: 60_000 }, handler: async (event) => {} },
// Opts out of a publish-time defer
audit: {
defer: (event) => (event.defer_until ? { delayMs: 0 } : null),
handler: async (event) => {},
},
},

// Publish-time override: every handler of this event waits 10 minutes
// Publish-time override: notifyWarehouse waits 10 minutes; defer functions decide for themselves
await outbox.publish(tx, "OrderPlaced", data, { defer: { delayMs: 600_000 } });
```

- **Resolved once, to a timestamp.** `publish` resolves its `defer` immediately and stores it on the event as `defer_until`. The processor resolves a handler's `defer` at fan-out, so a change to it applies to events fanned out afterwards. Either way the result is the delivery's `run_after`. `delayMs` counts from `created_at`, not from fan-out, so a processor that was down for an hour doesn't push "in 5 minutes" to "in 65 minutes", and repeated fan-outs of the same event agree.
- **The publish-time `defer` wins** over the handler's for every handler of that event. The resolved time is available to handler `defer` functions and handlers as `event.defer_until`, so a handler can opt out of honoring it.
- **The publish-time `defer` wins over a static one.** It applies to every handler of the event whose `defer` is a value or unset. A `defer` _function_ is called with the event, `event.defer_until` included, and decides: whatever it returns is used, and returning `null` or `undefined` keeps the publisher's `defer_until`. So a handler can opt out (`{ delayMs: 0 }` runs it right away) or wait longer. Handlers see `event.defer_until` too.
- **Due deliveries are picked up promptly.** The processor that fanned the event out polls when the earliest deferred delivery is due; beyond `pollingIntervalMs`, the regular poll finds it.
- **Priority still applies.** A deferred delivery competes with everything else that is due once its time comes.

Expand Down Expand Up @@ -506,7 +513,7 @@ const processor = createEventProcessor({

- **Requires a replica set or sharded cluster.** Atomic publishing and `onDeliveryDead` use multi-document transactions, and wakeups use change streams. A standalone server can run as a single-node replica set.
- **Timestamps come from the processors' clocks.** Keep them synchronized (e.g. NTP); skew well below `leaseMs` is harmless.
- **Retention:** deleting an event does not cascade. Delete its deliveries (`{ event_id }`) along with it.
- **Retention:** deleting an event does not cascade. Delete its deliveries (`{ event_id }`) along with it, and only once none of them is `pending`. A pending delivery whose event is gone is marked dead (`last_error` "event '...' not found") when it is next claimed, without running its handler.

## Redis and Valkey

Expand Down Expand Up @@ -543,7 +550,7 @@ const processor = createEventProcessor({
- **Durability** is whatever your persistence settings give you. For an outbox, use AOF (`appendfsync always` for no loss, `everysec` to risk up to a second) and `maxmemory-policy noeviction` so txob's keys are never evicted.
- **Cluster:** all of txob's keys share the `{txob}` hash tag, so they live in one slot. To publish in the same `MULTI` as your writes, your keys must use the same hash tag. Cluster mode isn't covered by the test suite yet.
- **ORMs:** Redis OM's `repository.save` can't join a `MULTI`, so writes made through it can't be published atomically. Write those keys with the client on the same `MULTI` instead.
- **Retention:** completed deliveries keep their hash. Prune `{txob}:d:*`, `{txob}:e:*` and their entries in the `{txob}:deliveries` / `{txob}:events` sorted sets on a schedule.
- **Retention:** completed deliveries keep their hash. Prune `{txob}:d:*`, `{txob}:e:*` and their entries in the `{txob}:deliveries` / `{txob}:events` sorted sets on a schedule, removing an event only once none of its deliveries is `pending`. A pending delivery whose event is gone is marked dead when it is next claimed, without running its handler.

## DynamoDB

Expand Down Expand Up @@ -625,7 +632,7 @@ await client.send(
- **Per-key limits:** keys at their limit are filtered out of claim queries. If one key's backlog is larger than a claim reads (a few thousand deliveries), each claim continues where the last one stopped, so other keys at the same priority may wait a few polls but are never starved.
- **Transactions** hold at most 100 items, and the event takes one of them. `onDeliveryDead` writes join the transaction that marks the delivery dead, so they share that limit.
- **Priorities** must be 32-bit integers. Timestamps come from the processors' clocks, so keep them synchronized.
- **Retention:** add a TTL attribute in your own retention job, or delete completed `d#` and `e#` items on a schedule.
- **Retention:** add a TTL attribute in your own retention job, or delete completed `d#` and `e#` items on a schedule. Remove an event only once none of its deliveries is `pending`; a pending delivery whose event is gone is marked dead when it is next claimed, without running its handler.

## Testing

Expand Down
120 changes: 82 additions & 38 deletions src/dynamodb/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ import {
type TransactWriteCommandInput,
} from "@aws-sdk/lib-dynamodb";
import { jsonRoundTrip } from "../json.js";
import type { TxOBHandlerSlot, TxOBNewDelivery, TxOBStore } from "../store.js";
import type { TxOBDelivery, TxOBEvent } from "../types.js";
import {
eventMissingError,
type TxOBHandlerSlot,
type TxOBNewDelivery,
type TxOBStore,
} from "../store.js";
import type { TxOBDelivery, TxOBEvent, TxOBSerializedError } from "../types.js";
import {
defaultTableName,
fanoutIndex,
Expand Down Expand Up @@ -260,6 +265,28 @@ export const createDynamoStore = (
return transact(items);
};

/** Marks a delivery dead, fenced by its lease token. */
const markDead = (
d: TxOBDelivery,
error: TxOBSerializedError,
extra: DynamoTransactItems = [],
): Promise<boolean> =>
fenced(
d,
{
UpdateExpression:
"SET #status = :dead, completed_at = :now, last_error = :error REMOVE lease_token, queue_pk, queue_sk",
ExpressionAttributeNames: { "#status": "status" },
ExpressionAttributeValues: {
":dead": "dead",
":now": Date.now(),
":error": JSON.stringify(error),
},
},
releaseHolder(d),
extra,
);

/** Due deliveries of a handler in claim order, skipping keys in `exclude`. */
const queryQueue = async (
slot: TxOBHandlerSlot,
Expand Down Expand Up @@ -644,7 +671,8 @@ export const createDynamoStore = (
string,
{ d: TxOBNewDelivery; set: Set<number> }
>();
for (const d of deliveries) {
// Dead deliveries are in no queue partition
for (const d of deliveries.filter((d) => !d.error)) {
if (
!Number.isInteger(d.priority) ||
Math.abs(d.priority) > maxPriority
Expand All @@ -671,7 +699,7 @@ export const createDynamoStore = (
),
);
await Promise.all(
deliveries.map(async ({ run_after, ...d }) => {
deliveries.map(async ({ run_after, error, ...d }) => {
const id = deliveryId(d);
const runAfter = run_after?.getTime() ?? now;
try {
Expand All @@ -681,12 +709,21 @@ export const createDynamoStore = (
Item: {
pk: `d#${id}`,
...d,
status: "pending",
attempts: 0,
run_after: runAfter,
created_at: now,
queue_pk: queuePk(d.event_type, d.handler, d.priority),
queue_sk: queueSk(runAfter, id),
...(error
? {
// Its settings couldn't be computed: dead, and never claimed
status: "dead",
last_error: JSON.stringify(error),
completed_at: now,
}
: {
status: "pending",
queue_pk: queuePk(d.event_type, d.handler, d.priority),
queue_sk: queueSk(runAfter, id),
}),
},
ConditionExpression: "attribute_not_exists(pk)",
}),
Expand Down Expand Up @@ -752,19 +789,33 @@ export const createDynamoStore = (

const flat = leased.flat();
const events = await getEvents(flat.map(({ item }) => item.event_id));
const toDelivery = ({ item, token }: (typeof flat)[number]) => ({
event_id: item.event_id,
event_type: item.event_type,
handler: item.handler,
attempts: item.attempts + 1,
priority: item.priority,
concurrency_key: item.concurrency_key ?? null,
lease_token: token,
});
// A delivery whose event was deleted while it was pending has nothing to run
await Promise.all(
flat
.filter(({ item }) => !events.has(item.event_id))
.map((leasedItem) =>
markDead(
toDelivery(leasedItem) as TxOBDelivery,
eventMissingError(leasedItem.item.event_id),
),
),
);
return flat
.filter(({ item }) => events.has(item.event_id))
.sort((a, b) => (claimOrder(a.item) < claimOrder(b.item) ? -1 : 1))
.map(
({ item, token }): TxOBDelivery => ({
event_id: item.event_id,
event_type: item.event_type,
handler: item.handler,
attempts: item.attempts + 1,
priority: item.priority,
concurrency_key: item.concurrency_key ?? null,
lease_token: token,
event: events.get(item.event_id)!,
(leasedItem): TxOBDelivery => ({
...toDelivery(leasedItem),
event: events.get(leasedItem.item.event_id)!,
}),
);
},
Expand Down Expand Up @@ -799,28 +850,21 @@ export const createDynamoStore = (
if (current?.lease_token !== d.lease_token) return false;
await failOpts.within(extra);
}
const error = JSON.stringify(failure.error);
const input = failure.run_after
? {
UpdateExpression:
"SET run_after = :run_after, queue_sk = :sk, last_error = :error REMOVE lease_token",
ExpressionAttributeValues: {
":run_after": failure.run_after.getTime(),
":sk": queueSk(failure.run_after.getTime(), deliveryId(d)),
":error": error,
},
}
: {
UpdateExpression:
"SET #status = :dead, completed_at = :now, last_error = :error REMOVE lease_token, queue_pk, queue_sk",
ExpressionAttributeNames: { "#status": "status" },
ExpressionAttributeValues: {
":dead": "dead",
":now": Date.now(),
":error": error,
},
};
return fenced(d, input, releaseHolder(d), extra);
if (!failure.run_after) return markDead(d, failure.error, extra);
return fenced(
d,
{
UpdateExpression:
"SET run_after = :run_after, queue_sk = :sk, last_error = :error REMOVE lease_token",
ExpressionAttributeValues: {
":run_after": failure.run_after.getTime(),
":sk": queueSk(failure.run_after.getTime(), deliveryId(d)),
":error": JSON.stringify(failure.error),
},
},
releaseHolder(d),
extra,
);
},

extendLeases: async (deliveries, { leaseMs }) => {
Expand Down
19 changes: 15 additions & 4 deletions src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ export type TxOBBackoffContext<TEvent> = {
};

export type TxOBRetryConfig<TEvent> = {
/** Total attempts before the delivery is marked dead. Default: 5. */
/**
* Total attempts before the delivery is marked dead. Default: 5. Also the number of fan-out
* attempts after which a delivery whose priority, concurrency key or defer can't be computed
* is created dead, so it doesn't hold up the event's other handlers.
*/
maxAttempts?: number;
/** Delay before the next attempt, in ms or as a date. Default: exponential, 1s doubling up to 60s. */
backoff?: (ctx: TxOBBackoffContext<TEvent>) => number | Date;
Expand All @@ -46,6 +50,7 @@ export type TxOBConcurrencyConfig<TEvent> = {
* when the event is fanned out, so deliveries for different keys never block each other.
*/
perKey?: {
/** `null` or `undefined` means no key: the delivery isn't limited per key. */
key: (event: TEvent) => string | null | undefined;
limit: number;
};
Expand All @@ -72,8 +77,10 @@ export type TxOBHandlerConfig<TEvent> = {
priority?: number | ((event: TEvent) => number);
/**
* Delay before deliveries of this handler become claimable. `delayMs` counts from the
* event's `created_at`. Resolved when the event is fanned out, and overridden by a `defer`
* passed to `publish`. A function receives the event (including its `defer_until`).
* event's `created_at`. Resolved when the event is fanned out. A static value is overridden by
* a `defer` passed to `publish`. A function receives the event, including the publisher's
* `defer_until`, and decides: its result is used, and returning `null` or `undefined` keeps
* `defer_until` (or no delay if there is none).
*/
defer?: TxOBDefer | ((event: TEvent) => TxOBDefer | null | undefined);
};
Expand Down Expand Up @@ -255,7 +262,11 @@ export const compileHandlerMap = (
backoff: retry.backoff ?? defaultBackoff,
timeoutMs,
priority: typeof priority === "function" ? priority : () => priority,
defer: typeof defer === "function" ? defer : () => defer,
defer:
typeof defer === "function"
? defer
: // A publish-time defer overrides a static one
(event) => (event.defer_until ? null : defer),
});
}
compiled.set(eventType, compiledHandlers);
Expand Down
Loading
Loading