Skip to Content

Retries and replay

Inspect delivery history, replay an event without changing its identity, and prune expired history on your schedule.

Retries follow the retry policy. Two things look like failures but are not receiver failures:

  • Paused endpoint. The delivery waits until resume and then gets a full retry window. That includes endpoints the worker paused automatically.
  • Provider lookup failure. The delivery is deferred without consuming an attempt, and the error goes to the worker's onError.

History and replay are server operations on the client for the endpoint's scope. They are not exposed as Better Auth routes.

Inspect deliveries

import { webhooks } from './webhooks.js'

const organization = webhooks.forScope({ type: 'organization', id: organizationId })

const page = await organization.deliveries.list({ eventId: publication.eventId, limit: 25 })
for (const item of page.items) {
  const detail = await organization.deliveries.get(item.id)
  console.log(detail.status, detail.lastStatus, detail.attempts.length)
}

Filter by eventId, endpointId, or status. Results are newest first; pass page.nextCursor as before for the next page. get() includes every attempt with its status code, captured response body (up to maxResponseBytes), and error. Payloads and response bodies can contain user data, so treat history as sensitive.

Replay

After fixing the cause, replay the original delivery:

const detail = await organization.deliveries.get(deliveryId)
if (detail.replayOf === null && ['succeeded', 'failed'].includes(detail.status)) {
  const replay = await organization.deliveries.replay(detail.id)
}
  • Only original succeeded or failed deliveries are eligible. A replay cannot be replayed.
  • One pending or in-flight replay per original at a time, otherwise REPLAY_IN_PROGRESS.
  • The endpoint must be active and the event not yet pruned.
  • The replay gets a new delivery ID and retry budget, the same event ID and body, and the endpoint's current URL and secrets. A worker still has to send it.

Because the event ID is unchanged, a deduplicating receiver ignores a replay of an event it already processed.

Bulk replay

When a receiver lost many events, for example after a bad deploy, replay them in pages with replayMany(). It takes the endpoint, an optional status (failed by default), a createdAt range, a page size up to 1,000, and a cursor. The reference lists every field.

Each call examines one page of the endpoint's original deliveries with that status, newest first, and replays every eligible one in a single transaction. The rules match replay():

  • Only originals are examined. A replay is never replayed again.
  • The endpoint must be active: a paused endpoint is INVALID_STATE, and a deleted or unknown one is NOT_FOUND. Nothing is replayed in either case.
  • A delivery whose event is outside retention, or that already has a pending or in-flight replay, is counted in skipped instead of failing the call.

Loop until nextCursor is null:

let before: string | undefined
do {
  const page = await organization.deliveries.replayMany({ endpointId, since, before })
  console.log(page.replayed, page.skipped)
  before = page.nextCursor ?? undefined
} while (before)

Recover failed deliveries

Failed deliveries are already kept as history, so there is no separate list to manage. After the receiver is fixed, look at what failed, then replay it:

const failed = await organization.deliveries.list({ endpointId, status: 'failed' })
// Inspect failed.items, then replay every page that failed since the incident started.
let before: string | undefined
do {
  const page = await organization.deliveries.replayMany({
    endpointId,
    since: incidentStart,
    before,
  })
  before = page.nextCursor ?? undefined
} while (before)

Each replay gets a new delivery ID and retry budget and keeps the event ID, as a single replay does.

Clean up history

Events are kept for seven days by default (retentionMs), then become eligible for deletion. Nothing deletes them automatically: schedule a cleanup job that calls prune().

const removed = await webhooks.worker.prune() // at most 100 events per call

prune() deletes up to 100 expired events with their deliveries and attempts. Call it in a loop until it returns zero or your time budget runs out. The package ships a bounded cleanup entrypoint that runs up to 20 batches or 30 seconds, then exits:

examples/operations/cleanup.ts
import { createWebhooks } from 'good-webhooks'
import { Pool } from 'pg'
import { errorDetails, readOperationsConfig } from './config.ts'

const stop = new AbortController()
let pool: Pool | undefined
let failed = false
let phase = 'configuration'
let summary: { batches: number; deleted: number; reason: string } | undefined
const requestStop = () => stop.abort()
const fail = (error: unknown, at: string) => {
  failed = true
  process.exitCode = 1
  console.error(
    JSON.stringify({ event: 'webhooks.cleanup.failed', phase: at, ...errorDetails(error) }),
  )
  stop.abort()
}

process.on('SIGTERM', requestStop)
process.on('SIGINT', requestStop)

try {
  const config = readOperationsConfig('cleanup')
  pool = new Pool(config.database)
  pool.on('error', (error) => fail(error, 'pool'))
  const clientError = (error: Error) => fail(error, 'database')
  pool.on('acquire', (client) => client.on('error', clientError))
  pool.on('release', (_error, client) => client.off('error', clientError))
  const webhooks = createWebhooks({ database: pool, ...config.webhooks })
  phase = 'startup'
  await webhooks.check()
  phase = 'prune'
  const deadline = performance.now() + config.cleanupMaxDurationMs
  let batches = 0
  let deleted = 0
  let reason = 'batch_budget'
  while (batches < config.cleanupMaxBatches) {
    if (stop.signal.aborted) {
      reason = 'signal'
      break
    }
    if (performance.now() >= deadline) {
      reason = 'time_budget'
      break
    }
    const count = await webhooks.worker.prune()
    batches += 1
    deleted += count
    // A short batch can reflect contention. Continue until zero progress or a budget ends.
    if (count === 0) {
      reason = 'no_progress'
      break
    }
  }
  summary = { batches, deleted, reason }
  if (reason === 'batch_budget' || reason === 'time_budget') {
    console.warn(JSON.stringify({ event: 'webhooks.cleanup.budget_exhausted', ...summary }))
  }
} catch (error) {
  fail(error, phase)
} finally {
  stop.abort()
  try {
    await pool?.end()
  } catch (error) {
    fail(error, 'close')
  }
  process.off('SIGTERM', requestStop)
  process.off('SIGINT', requestStop)
  if (!failed && summary)
    console.log(JSON.stringify({ event: 'webhooks.cleanup.finished', ...summary }))
}

It uses the worker's configuration plus WEBHOOK_CLEANUP_MAX_BATCHES and WEBHOOK_CLEANUP_MAX_DURATION_MS, and logs webhooks.cleanup.finished with the counts and stop reason. Twenty batches per minute remove at most 2,000 events per minute; pick a cadence faster than history expires, avoid overlapping runs, and alert on repeated webhooks.cleanup.budget_exhausted.

A pruned event can no longer be replayed, and its idempotency key can be accepted again. Cleanup covers every scope in its delivery database and schema, and never touches Better Auth records or receiver receipts.

On this page