Skip to Content

Outbox

Work that follows something the library did, kept until it is done

A hook that runs after the library's write is the usual place to do your side of it: write your own row for a new account, tell another service a session ended. When that work fails, the two sides are apart. The account exists and your row does not, and the hook cannot say so: throwing would tell the person their sign-up failed when it did not.

The outbox plugin gives that work somewhere to wait. You record an event, a handler does the work, and a failure is tried again later, after the response, without failing the request.

Installation

Add the plugin to your auth config

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { outbox } from "@entro314labs/entro-auth/plugins"; 

export const auth = entroAuth({
    // ... other auth config
    plugins: [
        outbox({ 
            handlers: { 
                "member.added": async ({ key, payload }) => { 
                    await mirrorMember(payload.memberId as string, key); 
                }, 
            }, 
        }), 
    ],
});

Migrate the database

Run the migration or generate the schema to add the outboxEvent table.

npx @entro314labs/entro-auth-cli@latest migrate

See the Schema section to add the table by hand.

Recording an Event

auth.api.enqueueOutboxEvent records one. It has no HTTP route: only your server code can call it. Call it from the hook where you would have done the work:

auth.ts
organization({
    organizationHooks: {
        afterAddMember: async ({ member }) => {
            try {
                await auth.api.enqueueOutboxEvent({
                    body: {
                        topic: "member.added",
                        key: `member:${member.id}:added`,
                        payload: { memberId: member.id },
                    },
                })
            } catch (error) {
                // The member is already added: do not fail the request for it.
                console.error("could not record member.added", error)
            }
        },
    },
})

The same shape works in databaseHooks.*.after, for a new account or a deleted one.

  • topic names the handler.
  • key is what makes a repeat harmless. Recording the same key twice records one event, and the handler is given the key to deduplicate its own write by. Without one, a random key is made.
  • payload should hold ids, not copies of rows, and never a token. By the time the handler runs, or runs again, the row may have changed: read it then.

Catch a failed enqueueOutboxEvent inside an after hook, as above. The library's write has already happened, and an error thrown from there fails the request for something that succeeded.

Delivery

An event is handed to its handler right after it is recorded: after the response where advanced.backgroundTasks has a handler (waitUntil on a serverless platform), and before it otherwise. Either way a handler that throws does not fail the request. The error is logged and kept on the event, and the event is tried again: 30 seconds after the first failure, then 1 minute, 2, 4, up to an hour apart, eight attempts in all by default.

Retries need something to run them. Call deliverOutbox on a schedule:

cron.ts
const { delivered, failed, remaining } = await auth.api.deliverOutbox({
    body: { limit: 50 },
})

It tries the events that are due, and removes delivered ones that have been kept long enough. Recording a new event also tries a few that were waiting, so retries move without a schedule on a busy site, but do not rely on that alone.

An event that failed its last attempt stays in the table with the status failed and its last error, for you to look at. Nothing retries it again.

What It Promises, and What It Does Not

  • At least once. A handler can run twice for one event: when it succeeded and the process died before saying so, or when two attempts overlap after a long handler. Make it safe to repeat, with the key.
  • No order. Events for the same thing can arrive out of order or after a later one. A handler that reads the current state is right either way; one that applies what the payload said is not.
  • Recorded with the library's write only inside the library's transaction. Where the library runs a transaction and you record from within it, the event is committed or rolled back with it, and delivered only after it commits. From an after hook the write has already committed, so a process that dies between the two loses the event. A transaction of your own, on your own database client, is a different connection: the event is not part of it.
  • A key is refused as a duplicate only while its event exists. Delivered events are removed after keepDeliveredFor.
  • Without a database there is nowhere to keep an event. The handler is called once, as a hook would have been, and the plugin says so when the server starts.

With Account Events

When this plugin is configured, the account events plugin delivers through it: a delivery the receiver does not take is tried again, under the same webhook-id, signed anew each time.

Options

handlers: Record<string, (event) => Promise<void>> - The work for each topic. The event is { id, topic, key, payload, attempt }.

maxAttempts: number - How many times an event is tried before it is left as failed. Default: 8.

retryAfter: (attempt: number) => number - Seconds to wait after a failed attempt, given the number of the attempt that failed. Default: 30 seconds after the first, doubling, at most an hour.

keepDeliveredFor: number - Seconds a delivered event is kept. Default: 7 days.

Schema

Table name: outboxEvent

Table
Field
Type
Attributes
Description
id
string
PK
Unique identifier for each event
topic
string
-
Which handler the event is for
key
string
UQ
The idempotency key; unique
payload
string
-
JSON the handler is given
status
string
-
pending, delivered or failed
attempts
number
-
How many attempts have been made
nextAttemptAt
Date
-
The event is not tried before this time
lastError ?
string
-
The last failure's message
deliveredAt ?
Date
-
When a handler finished without an error
createdAt
Date
-
When the event was recorded

On this page