Delivery
Publication, delivery history, worker execution, and PostgreSQL sender options.
good-webhooks/delivery is the PostgreSQL sender: it publishes events, records deliveries, and runs workers against any endpoint source.
import { createDelivery } from 'good-webhooks/delivery'
import type {
AttemptEvent,
DeliveryEngine,
DeliveryHooks,
DeliveryOptions,
DeliveryStats,
DescribeEventsOptions,
EndpointHealthOptions,
EndpointPausedEvent,
EndpointSource,
EndpointResolution,
EventDescription,
ManagementScope,
} from 'good-webhooks/delivery'Shared event, database, query, and result types come from good-webhooks. Every method on this page is also on the createWebhooks() client.
createDelivery
createDelivery<const E extends EventDefinitions>(options: DeliveryOptions<E>): DeliveryEngine<E>import { createDelivery } from 'good-webhooks/delivery'
import { createPostgresManagement } from 'good-webhooks/management/postgres'
import { Pool } from 'pg'
import { z } from 'zod'
const database = new Pool({ connectionString: process.env.DATABASE_URL })
const events = {
'invoice.paid': z.object({ invoiceId: z.string(), amount: z.number().int() }),
}
const management = createPostgresManagement({
database,
eventTypes: Object.keys(events),
encryptionKey: process.env.WEBHOOK_ENCRYPTION_KEY!,
})
export const delivery = createDelivery({ database, events, source: management.source })Any EndpointSource works as source, including Better Auth management. The constructor starts no work.
| Option | Default |
|---|---|
database | Required |
events | Required |
source | Required |
schema | 'public' |
retry.delaysMs | Seven delays |
retry.maxAgeMs | 172800000 |
retry.respectRetryAfter | true |
endpointHealth | On |
hooks | None |
retentionMs | 604800000 |
allowLocalhost | false |
delivery | See below |
database: a PostgreSQL executor withquery()andconnect().pg.Poolsatisfies this shape.- A checked-out client has
query()andrelease().
- A checked-out client has
events: a nonempty map of event names to Standard Schema validators.source: a trustedEndpointSourcewithmatchRecipientsandresolveEndpoint.schema: the PostgreSQL schema containing delivery tables.retry.delaysMs: at most 20 integer delays, each from 1 through 86,400,000 ms. An empty array disables retries.- The default is
[5000, 300000, 1800000, 7200000, 18000000, 36000000, 36000000].
- The default is
retry.maxAgeMs: the retry window, from 100 through 2,592,000,000 ms. It counts from creation or from the first attempt after a pause.- The default (48 hours) fits the default schedule with jitter.
retry.respectRetryAfter: wait at least as long as a429or503response'sRetry-Afterasks. See attempt outcomes.endpointHealth: automatic pauses, orfalseto turn them off. See automatic pauses.hooks: callbacks after each recorded outcome. See hooks.retentionMs: event retention from 1,000 through 31,536,000,000 ms. Must be at leastretry.maxAgeMs.allowLocalhost: permits HTTP loopback destinations for development. Other private addresses stay forbidden.delivery: per-attempt and per-batch limits. The delivery object lists each default.
Event names match ^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,119}$. The constructor validates each event's Standard Schema interface. Any invalid option throws INVALID_CONFIG. Delivery guarantees explains how retry plays out.
The delivery object
The delivery object has the following fields. This table is generated from the public DeliveryOptions type.
Prop
Type
| Field | Default | Limits |
|---|---|---|
timeoutMs | 10000 | Integer from 10 through 120,000 ms. |
concurrency | 10 | Integer from 1 through 100 claims per batch. |
leaseMs | 60000 | Integer from 100 through 3,600,000 ms, at least twice timeoutMs. |
maxResponseBytes | 4096 | Integer from 0 through 65,536 captured response bytes. |
publish
publish(input: PublishInput<E>, options?: PublishOptions): Promise<PublishResult>import { delivery } from './delivery.js'
const { eventId, deliveryCount, duplicate } = await delivery.publish({
type: 'invoice.paid',
data: { invoiceId: 'inv_123', amount: 4200 },
idempotencyKey: 'invoice.paid:inv_123',
})input.type: a configured event name.input.data: the event validator's input type. The validator runs before anything is stored.idempotencyKey: a nonblank string of at most 200 characters without null bytes. Unique within a scope while the event is retained.options.transaction: an optional PostgreSQL client inside an activeBEGINtransaction. It must access the configured delivery tables.result.eventId: the accepted event UUID.result.deliveryCount: the number of original deliveries created for the accepted recipient set, including paused recipients. Can be zero.result.duplicate:truewhen the same key already identifies the same event type and validated payload.
The stored body is { id, type, occurredAt, data }. id is the event UUID and occurredAt is an ISO timestamp assigned during publication.
The event and its original deliveries commit atomically within delivery storage. A caller-owned transaction stays uncommitted when publish returns. The transaction and recipient guarantees also apply to duplicate publication. The publish guide shows idempotency keys and transactions in context.
INVALID_INPUT: unknown event type, payload rejected by the validator, payload outside the JSON limits, or an invalid key.IDEMPOTENCY_CONFLICT: the key already identifies a different event type or payload in this scope.TRANSACTION_REQUIRED:options.transactionhas no active transaction.- Other errors: validator-thrown errors, source failures, and database failures propagate unchanged.
deliveries
deliveries.list(query?: DeliveryQuery): Promise<Page<Delivery>>
deliveries.get(id: string): Promise<DeliveryDetail>
deliveries.replay(id: string): Promise<Delivery>
deliveries.replayMany(input: ReplayManyInput): Promise<ReplayManyResult>
deliveries.stats(): Promise<DeliveryStats>import { delivery } from './delivery.js'
const page = await delivery.deliveries.list({ status: 'failed', limit: 25 })
const detail = await delivery.deliveries.get(page.items[0]!.id)
if (detail.replayOf === null) await delivery.deliveries.replay(detail.id)list
DeliveryQuery field | Contract |
|---|---|
endpointId | Only deliveries to this endpoint. |
eventId | Only deliveries of this event ID. |
status | One delivery status. |
limit | Integer from 1 through 100. Default 25. |
before | Exclusive delivery-ID cursor. Pass the previous nextCursor. |
list returns newest delivery IDs first. The result is { items, nextCursor }; nextCursor: null marks the final page. Invalid query values throw INVALID_INPUT.
An eventId follows the receiver's webhook-id rule: 1 to 255 printable ASCII characters without dots or commas. A valid ID that is not a UUID returns an empty page, because no event in this store has it.
get
get returns the delivery with its attempts array in attempt-number order. Delivery IDs are positive PostgreSQL bigint strings. A missing record in the selected scope produces NOT_FOUND.
replay
replay sends the original event to the same endpoint again as a new delivery. It keeps the event ID and body and gets a new delivery ID and retry budget. See retries and replay.
NOT_FOUND: no delivery with this ID in the selected scope.INVALID_STATE: the endpoint is not active, the delivery is a replay or notsucceededorfailed, or the event is outside retention.REPLAY_IN_PROGRESS: the original delivery already has a pending or in-flight replay.
replayMany
replayMany replays one page of an endpoint's original deliveries in one transaction, newest delivery IDs first. Each eligible delivery follows replay's rules, and an ineligible one is skipped instead of failing the call. See bulk replay.
ReplayManyInput has these fields:
endpointId: required. Only original deliveries to this endpoint. Replays are never examined.status:'failed'(default) or'succeeded'.since: aDate. Only deliveries withcreatedAtat or after it.until: aDate, not earlier thansince. Only deliveries withcreatedAtbefore it.limit: deliveries examined per call, from 1 through 1,000. Default 100.before: an exclusive delivery-ID cursor. Pass the previousnextCursor.
ReplayManyResult has these fields:
replayed: new replay deliveries created.skipped: examined deliveries whose event is outside retention or that already have a pending or in-flight replay.nextCursor: the last examined delivery ID when more remain, ornull.
| Error | When |
|---|---|
INVALID_INPUT | A missing or invalid field, an unknown status, or since later than until. |
NOT_FOUND | The endpoint is deleted or unknown in the selected scope. |
INVALID_STATE | The endpoint is paused. |
stats
stats summarizes the selected scope's retained deliveries for a status page or a backlog alert. The root client reports the application scope, and forScope(scope).deliveries.stats() reports that scope. There is no variant across scopes.
import { delivery } from './delivery.js'
const { deliveries, oldestPendingAgeMs, attemptsLastHour } = await delivery.deliveries.stats()
// deliveries: { pending: 12, in_flight: 2, succeeded: 4810, failed: 3, cancelled: 0 }
// oldestPendingAgeMs: 95000, or null when nothing is pending
// attemptsLastHour: { started: 2, succeeded: 140, retry: 6, failed: 1, abandoned: 0 }DeliveryStats field | Meaning |
|---|---|
deliveries | Retained deliveries by status |
oldestPendingAgeMs | Age of the oldest pending delivery |
attemptsLastHour | Attempts in the last hour by outcome |
Every status and outcome key is present, 0 when none. oldestPendingAgeMs is in milliseconds from the database clock, and null when nothing is pending. In attemptsLastHour, started counts attempts not yet finished or recovered.
pending includes deliveries waiting for a retry and deliveries queued behind a paused endpoint. Replays count as deliveries. Deliveries and attempts come from two separate reads, so they can disagree slightly under load.
Cost. stats runs two queries without a transaction. The deliveries query reads every retained delivery of the scope. PostgreSQL reads the scope through its index when the scope is a small share of the table. When the scope holds most of the table, it scans the whole deliveries table instead. That is the usual case for an app that only uses application scope. The last-hour filter on attempts has no index. So the attempts query either reads every retained attempt of the scope through the deliveries index, or scans the whole attempts table when that is cheaper. As an order of magnitude, not a promise: with about 100,000 deliveries and 150,000 attempts in one scope, each query took tens of milliseconds on a local machine. Cost grows with retention, and prune() bounds it. Call it from a status page or a periodic check, not on every request.
Delivery and attempt records
| Delivery field | Type or meaning |
|---|---|
id | String identifier. |
endpointId | String identifier. |
eventId | String identifier. |
eventType | The event's type, such as 'invoice.paid'. |
status | One of five states |
attemptCount | Number of recorded attempts. |
nextAttemptAt | Date. |
createdAt | Date. |
replayOf | Original delivery ID, or null. |
lastError | Last error text, or null. |
lastStatus | Last HTTP status, or null. |
attempts | Attempt[], on DeliveryDetail only |
| Attempt field | Type or meaning |
|---|---|
number | Attempt number, starting at 1. |
startedAt | Date. |
finishedAt | Date, or null while the attempt runs. |
outcome | One of five outcomes |
responseStatus | HTTP status, or null. |
responseBody | Captured response text bounded by maxResponseBytes, or null. |
error | Error text, or null. |
status:'pending','in_flight','succeeded','failed', or'cancelled'.attempts: present only onDeliveryDetail, the result ofget.outcome:'started','succeeded','retry','failed', or'abandoned'.
deliverySettings
deliverySettings.get(endpointId: string): Promise<{ maxInFlight: number }>
deliverySettings.set(endpointId: string, settings: { maxInFlight: number }): Promise<{ maxInFlight: number }>import { delivery } from './delivery.js'
const endpointId = 'ENDPOINT_ID' // From endpoints.create()
await delivery.deliverySettings.set(endpointId, { maxInFlight: 4 })| Setting | Default | Limits |
|---|---|---|
maxInFlight | 2 | Integer from 1 through 50. |
Stores sender-owned concurrency settings separately from endpoint records. Active and paused endpoints accept settings. Missing or deleted endpoints produce NOT_FOUND. An out-of-range value produces INVALID_INPUT.
These settings apply to all workers sharing the same delivery database and schema. They are distinct from the delivery.concurrency limit on each batch.
worker
worker.runOnce(options?: {
signal?: AbortSignal
shutdownGraceMs?: number
}): Promise<WorkerResult>
worker.run(options: {
signal: AbortSignal
onError?: (error: unknown) => void
pollIntervalMs?: number
shutdownGraceMs?: number
}): Promise<void>
worker.prune(): Promise<number>import { delivery } from './delivery.js'
const stop = new AbortController()
process.once('SIGTERM', () => stop.abort())
await delivery.worker.run({
signal: stop.signal,
onError: (error) => console.error('Webhook worker batch failed', error),
})| Option | Applies to | Default |
|---|---|---|
signal | run (required), runOnce | None |
onError | run | None |
pollIntervalMs | run | 1000 |
shutdownGraceMs | run, runOnce | 30000 |
signal: abort to stop. An already-aborted signal returns without database work.onError: called with an internal batch failure. Without it, the failure stopsrun.pollIntervalMs: an integer from 10 through 60,000 ms. The wait after an empty batch.shutdownGraceMs: an integer from 0 through 2,147,483,647 ms. Time for prepared attempts to finish after abort.
All worker methods cover every scope in the configured delivery database and schema. Workers own neither the host's process signal handlers nor its database pool. The workers guide shows a supervised process.
runOnce
runOnce recovers expired leases and processes one bounded batch. It does not drain the queue. Its WorkerResult contains these counts:
| Count | Meaning |
|---|---|
claimed | Deliveries claimed in this batch. |
succeeded | Attempts that got a 2xx. |
retried | Attempts that failed and were scheduled for a retry. |
failed | Attempts that failed permanently or used up their retries. |
stale | Attempts whose claim no longer owns completion. |
run
run processes batches until its signal aborts. After a batch that completed at least one attempt, the next batch starts immediately; empty and stale-only batches wait pollIntervalMs. Without onError, an internal batch failure stops run. With it, the loop awaits the callback, waits pollIntervalMs, and continues; a callback that throws stops the loop.
Attempt outcomes
| Response | Attempt outcome |
|---|---|
2xx | succeeded |
410 | failed, no retry |
| Any other status | retry or failed |
| Network error | retry or failed |
| Unsafe address | failed, no retry |
| Stopped mid-request | abandoned |
- Any other status: includes
3xxand4xx. The outcome isretrywhile retries remain, otherwisefailed.- Redirects are never followed.
- Network error: a network, DNS, or timeout error. The outcome is
retrywhile retries remain, otherwisefailed. - Unsafe address: the URL resolves to an unsafe address at send time.
- Stopped mid-request: the worker stopped or the lease expired mid-request. The delivery retries if budget remains.
Each retry waits its configured delay plus up to 20% random jitter. When a 429 or 503 response carries a Retry-After header (seconds or an HTTP date) that asks for longer, the retry waits at least that long, plus the same jitter, unless retry.respectRetryAfter is false. The worker doesn't schedule a retry that would land after the retry window ends, so the delivery fails. The window is retry.maxAgeMs, counted from the delivery's creation, or from its first attempt after the endpoint was paused.
Automatic pauses
The worker pauses an endpoint when every attempt to it has failed for endpointHealth.pauseAfterMs, or as soon as it answers 410 Gone. The endpoint's pauseReason becomes 'failing' or 'gone', its queued deliveries wait, and its owner resumes it like any paused endpoint.
endpointHealth field | Default |
|---|---|
pauseAfterMs | 432000000 |
pauseOnGone | true |
pauseAfterMs is five days by default and takes an integer from 60,000 through 2,592,000,000 ms. pauseOnGone pauses on the first 410 response instead of waiting the period.
- Every attempt without a
2xxcounts as a failure, including timeouts, DNS errors, and unsafe addresses.abandonedattempts don't count. - A success, a resume, or any change to the endpoint starts a new period. The pause applies only if the endpoint hasn't changed since the worker counted the failures. Both rely on the source's
revision. With a source that reports none, only a success starts a new period. - Pausing needs an endpoint source with
pause(). The built-in PostgreSQL and Better Auth providers have it.run()andrunOnce()throwINVALID_CONFIGfor a source without it unlessendpointHealthisfalse. An engine that only publishes never needs it.
Hooks
export const delivery = createDelivery({
database,
events,
source: management.source,
// metrics and notifyOwner stand for your own code.
hooks: {
onAttempt: ({ outcome, responseStatus, durationMs }) =>
metrics.record('webhook.attempt', durationMs, { outcome, status: responseStatus }),
onEndpointPaused: ({ scope, endpointId, reason }) => notifyOwner(scope, endpointId, reason),
},
})onAttempt: called with anAttemptEventonce per recorded attempt.AttemptEventhasscope,endpointId,deliveryId,eventId,eventType,attempt,outcome,responseStatus,error, anddurationMs.
onEndpointPaused: called with anEndpointPausedEventonce per automatic pause. Manual pauses don't call it.EndpointPausedEventhasscope,endpointId, andreason('failing'or'gone').
The worker awaits each hook after it commits the outcome. Hook errors join the batch errors, and a crash between the commit and the call skips the hook. The hooks guide shows both hooks in use and explains how they run.
prune
prune deletes at most 100 expired events and their dependent deliveries and attempts per call. It returns the number of removed events. Live leases or contended locks can defer deletion. It does not run automatically. See clean up history.
Worker errors
INVALID_INPUT:pollIntervalMsorshutdownGraceMsis out of range.INVALID_CONFIG: automatic pauses are on and the endpoint source has nopause().INVALID_STATE: this instance already has an activerunloop or batch.AggregateError: internal failures in a batch, including hook and pause errors. Thrown after all sibling attempts settle.
check and forScope
check(): Promise<void>
forScope(scope: Scope): Pick<DeliveryEngine<E>, 'publish' | 'deliveries' | 'deliverySettings'>import { delivery } from './delivery.js'
await delivery.check()
const organization = delivery.forScope({ type: 'organization', id: 'org_123' })
await organization.deliveries.list()check() verifies delivery schema version 7 and throws SCHEMA_MISMATCH otherwise, naming the SQL to apply. It never applies migrations and does not check management storage.
forScope(scope) returns publish, deliveries, and deliverySettings bound to one named scope. An invalid scope throws INVALID_INPUT. The root methods use application scope. Scope selection does not authorize access. See scopes.
describeEvents
describeEvents(options?) returns the configured event names with the JSON Schema of each payload, for a receiver-facing catalog. The core reference documents it.