--- title: "Idempotency" description: "Make Beignet commands, webhooks, and jobs safe to retry with scoped keys, payload fingerprints, and durable reservations." url: "https://www.beignetjs.com/idempotency" markdown_url: "https://www.beignetjs.com/markdown/idempotency.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Idempotency Idempotency makes retryable work safe. Use it when the same logical command may arrive more than once: a user double-submits a form, a mobile client retries a request, a webhook provider redelivers an event, or a job provider retries background work. Beignet enforces idempotency at the HTTP boundary the same way it enforces rate limits: contracts declare the requirement, `createIdempotencyHooks(...)` enforces it, and `IdempotencyPort` decides where reservations live. `runIdempotently(...)` remains the workflow-level primitive for non-HTTP work. ```bash bun add @beignet/core ``` ## Contract metadata Declare the requirement on the contract: ```typescript export const createAppointment = appointments .post("/") .headers( z.object({ "idempotency-key": z.string().min(1), }), ) .body(CreateAppointmentRequest) .meta({ idempotency: { required: true, header: "idempotency-key", scope: "actor-tenant", ttlSec: 60 * 60 * 24, }, }) .errors({ IdempotencyConflict: errors.IdempotencyConflict, IdempotencyInProgress: errors.IdempotencyInProgress, }) .responses({ 201: AppointmentResponse }); ``` The optional `headers` schema documents the key for OpenAPI and typed clients and rejects requests without it during request validation. The `.errors(...)` declarations reuse Beignet's `httpErrors.IdempotencyConflict` and `httpErrors.IdempotencyInProgress` catalog entries so clients see the declared `409` responses. ## Typed clients send keys automatically Beignet clients read the same contract metadata. When a contract declares `idempotency`, every call attaches a generated UUID to the metadata header (`meta.header`, default `idempotency-key`), so components never build keys by hand: ```typescript const createAppointmentEndpoint = apiClient.endpoint(createAppointment); // This call gets a generated idempotency-key header. await createAppointmentEndpoint.call({ body }); ``` The generated key is injected before request header validation runs, and the header becomes optional in the call types. To take control of the key, pass `idempotencyKey` as a call option for retry-with-same-key flows, or pass the header explicitly in `headers` — an explicit header always wins over generation. Each direct `call(...)` invocation gets a new generated key. If application code catches a timeout or network error and calls the endpoint again, that is a new invocation with a new key. Generate one key outside the retry loop and pass it as `idempotencyKey` on every attempt when those calls represent one logical command. Separate calls — including double-clicks — intentionally remain separate unless the app supplies the same key. `required: true` on the contract remains the server-side backstop: clients that are not Beignet clients — curl, mobile apps, third-party integrations — still get a framework-owned `400` when the key is missing. React Query mutations keep the generated key stable across TanStack retry attempts. See [React Query](https://www.beignetjs.com/markdown/react-query.md) for the details. ## Hook wiring Install the built-in hook where the server is composed: ```typescript import { createIdempotencyHooks } from "@beignet/core/server"; import { createNextServer, createNextServerLoader } from "@beignet/next"; export const getServer = createNextServerLoader(() => createNextServer({ ports: initialPorts, hooks: [createIdempotencyHooks()], // ... }), ); ``` The hook reads `contract.metadata.idempotency` and enforces it with `ctx.ports.idempotency`. After request parsing and route hook identity resolution it reserves `{ namespace: "http.", key, scope, fingerprint }`, where the fingerprint hashes the parsed `{ path, query, body }`. A completed matching reservation short-circuits the handler and replays the stored response with an `idempotency-replayed: true` header. On success it stores final route-owned 2xx responses after the response-validation phase for replay; on framework-owned responses, errors, non-2xx responses, and native `Response` streams it releases the reservation so a retry re-executes. Routes without idempotency metadata pass through untouched. ## Scopes `meta.scope` controls who may replay a stored result: | Scope | Default scope value | | -------------- | ------------------------------------------------------------------------------ | | omitted | `{ actorId: ctx.actor?.id }`, plus `tenantId` when `ctx.tenant?.id` is present | | `global` | `"global"` | | `actor` | `{ actorId: ctx.actor?.id }` | | `tenant` | `{ tenantId: ctx.tenant?.id }` | | `actor-tenant` | `{ actorId: ctx.actor?.id, tenantId: ctx.tenant?.id }` | Omitting `meta.scope` binds the key to the actor, includes the current tenant when one is present, and fails closed when `ctx.actor.id` is missing. Choose `global` explicitly only for a public operation whose callers should share one key namespace. Otherwise, scope keys to the boundary that owns the operation so one actor or tenant can never replay another's result. ## Error semantics | Reservation | Response | | ------------ | --------------------------------------------------------------- | | `reserved` | Handler runs; final route-owned 2xx result is stored for replay | | `replay` | Stored response + `idempotency-replayed: true` | | `inProgress` | `409` with code `IDEMPOTENCY_IN_PROGRESS` | | `conflict` | `409` with code `IDEMPOTENCY_CONFLICT` | The server maps the `IdempotencyConflictError` and `IdempotencyInProgressError` primitives to framework-owned `409` envelopes — including from use cases that call `runIdempotently(...)` directly, so apps do not need to re-map the primitive errors to their own catalog entries. ## Customization Override the namespace, scope, or fingerprint input when defaults do not fit: ```typescript createIdempotencyHooks({ namespace: ({ contract }) => `api.${contract.name}`, scope: ({ ctx, meta }) => ({ tenantId: ctx.tenant?.id, plan: ctx.tenant?.metadata?.plan, }), fingerprintInput: ({ body }) => body, }); ``` Use `fingerprintInput` when request metadata such as tracing headers or pagination noise should not define the logical command. ## Workflow-level idempotency Use `runIdempotently(...)` inside a use case, job, listener, webhook handler, or schedule when the retried work does not arrive over HTTP, or when the workflow itself owns retry safety: ```typescript import { createIdempotencyFingerprint, runIdempotently, } from "@beignet/core/idempotency"; export const importAppointments = useCase .command("appointments.import") .input(ImportAppointmentsInput) .output(ImportResult) .run(async ({ ctx, input }) => { const fingerprint = await createIdempotencyFingerprint(input, { omit: ["importId"], }); return runIdempotently(ctx.ports.idempotency, { namespace: "appointments.import", key: input.importId, scope: { tenantId: ctx.tenant?.id, actorId: ctx.actor?.id, }, fingerprint, ttlSec: 60 * 60 * 24, run: () => ctx.ports.uow.transaction((tx) => tx.appointments.importBatch(input.rows), ), }); }); ``` The helper reserves the key before running the workflow, completes it with the returned result, and releases the reservation if the workflow throws. If the workflow succeeds but `complete(...)` fails, the error is rethrown and the reservation remains in progress instead of being released; an immediate retry therefore cannot repeat already-finished side effects. The HTTP hook uses an `http.`-prefixed namespace, so HTTP reservations never collide with use-case namespaces. The three identities work together: the `namespace` separates unrelated operations that may receive the same key, the `scope` prevents one actor or tenant from replaying another's result, and the `fingerprint` detects when the same key is reused with different payload data. `createIdempotencyFingerprint(input, { omit: [...] })` creates a stable SHA-256 digest from a canonical representation, omitting the key itself and other request-only metadata, and does not store the original payload. Reserved tags keep non-JSON values such as a BigInt and a same-looking string, or a `Date` and its ISO string, from sharing a fingerprint; ordinary JSON payloads retain their stable representation. `runIdempotently(...)` resolves reservations the same way the hook does: `replay` returns the stored result by default, `inProgress` throws `IdempotencyInProgressError`, and `conflict` throws `IdempotencyConflictError`. Pass `replay: "error"` when an operation should reject duplicates instead of returning the stored result. ## Port wiring Add `idempotency: IdempotencyPort` from `@beignet/core/idempotency` to your `AppPorts`, and use the memory adapter only for tests, local examples, and single-process development: ```typescript // infra/port-wiring.ts import { createMemoryIdempotencyStore } from "@beignet/core/idempotency"; export const initialPorts = definePorts({ idempotency: createMemoryIdempotencyStore(), // other ports... }); ``` Reservation tokens use Web Crypto `randomUUID()` or `getRandomValues()` when available and securely fall back to `node:crypto` on supported Node runtimes. The memory adapter also accepts a `createReservationToken` option for deterministic tests; production adapters should use runtime cryptography rather than predictable ownership tokens. Creation fails clearly if neither secure source is available. Production apps should implement `IdempotencyPort` with a durable store such as SQL or Redis. A durable adapter stores one row per reserved key, and the storage operation behind `reserve(...)` must be atomic — provider packages ship this, so apps rarely write it. The standard Drizzle/libSQL path is `createDrizzleSqliteIdempotencyPort(db)` from `@beignet/provider-db-drizzle/sqlite`, with `createDrizzleSqliteIdempotencySetupStatements()` executed in your app-owned migration flow. Unfinished reservations expire after 300 seconds by default so a crashed worker cannot poison a key forever. Set `reservationTtlSec` when an operation has a different upper bound. `ttlSec` separately controls the completed replay window; omit it only when indefinite replay is intentional. Each successful reservation returns an opaque token that `complete(...)` and `fail(...)` must carry. Providers match that token atomically, so a stale executor cannot complete or release a successor's reservation after expiry. An implementation must reject either mutation when the token, fingerprint, or reservation state no longer matches. It must not silently drop the mutation: `runIdempotently(...)` relies on that rejection to avoid reporting a result as durably replayable when it was not stored. Beignet's memory and Drizzle adapters enforce this contract. The memory adapter throws `IdempotencyMutationError`; each Drizzle dialect exposes its corresponding `Drizzle*IdempotencyMutationError`. If protected work throws and releasing its reservation also fails, `runIdempotently(...)` throws an `AggregateError` that retains both failures and uses the operation error as its `cause`. At the HTTP boundary, Beignet preserves the prepared application error response and best-effort reports the settlement failure through `ctx.ports.errorReporter` when configured. ## Pruning expired records Reservations only clean up an expired record when the same key is reserved again, so a durable store grows with every distinct key an app ever accepts. Each adapter also exposes an `IdempotencyAdminPort` whose `pruneExpired(...)` deletes records whose replay window has closed, oldest first, with an optional `limit` for bounded passes. Wire it as a separate app port, for example `ports.idempotencyAdmin` bound to `createDrizzleSqliteIdempotencyAdminPort(db)`, and run it from a task or schedule rather than from request handlers: ```typescript export const pruneIdempotencyRecordsTask = defineTask( "operations.prune-idempotency-records", { input: z.object({ limit: z.number().int().positive().default(1000) }), description: "Delete idempotency records whose replay window has closed.", handle: ({ input, ctx }) => ctx.ports.idempotencyAdmin.pruneExpired({ limit: input.limit }), }, ); ``` `before` defaults to the store clock. Records completed without `ttlSec` never expire and are never pruned. Drizzle adapters preserve records renewed past the cutoff during a prune; concurrent renewals can leave a pass deleting fewer records than its `limit`. ## Unit-of-work-aware adapters For high-integrity workflows, prefer a SQL adapter that participates in the same Unit of Work as the business write, so the reservation, domain write, audit entry, and completed idempotency result share one transaction and the database commit becomes the single durability boundary — if the workflow throws or the process crashes before commit, the reservation rolls back with everything else. The use case shape changes from "idempotency wraps a transaction" to "the transaction exposes an idempotency port": ```typescript await ctx.ports.uow.transaction((tx) => runIdempotently(tx.idempotency, { namespace: "appointments.import", key: input.importId, scope: { tenantId: ctx.tenant?.id, actorId: ctx.actor?.id, }, fingerprint, ttlSec: 60 * 60 * 24, run: async () => { const result = await tx.appointments.importBatch(input.rows); await tx.audit.record(/* ... */); await events.record(tx.events, appointmentsImported, { importId: input.importId, }); return result; }, }), ); ``` Infra creates the adapter from the transaction client next to the repositories; see [Database and transactions](https://www.beignetjs.com/markdown/database.md#transactions) for the `createTransactionPorts` wiring. Idempotency prevents duplicate command execution; it does not replace durable message delivery. Use an [outbox](https://www.beignetjs.com/markdown/outbox.md) when post-commit event or job delivery must be durable, and see [Workflow primitives](https://www.beignetjs.com/markdown/workflows.md#workflow-primitives) when deciding whether a workflow needs idempotency, an outbox record, a job, a schedule, or a notification. ## Jobs and webhooks Jobs and webhooks should use keys from the system that retries them: a webhook handler keys on the provider event id (for example `stripeEvent.id` under a `webhooks.stripe.*` namespace), and a Beignet job keys on an app-owned job id or logical command id. Keep the idempotency check inside the job handler when the job itself owns the retried work — [Jobs](https://www.beignetjs.com/markdown/jobs.md#retry-safe-jobs) shows the full handler pattern. [Payments and billing](https://www.beignetjs.com/markdown/payments.md) applies this to verified Stripe webhooks. ## Testing Use the memory store in tests: ```typescript const idempotency = createMemoryIdempotencyStore(); const first = await runIdempotently(idempotency, { namespace: "posts.create", key: "key_1", fingerprint: "fingerprint_1", run: async () => ({ id: "post_1" }), }); const second = await runIdempotently(idempotency, { namespace: "posts.create", key: "key_1", fingerprint: "fingerprint_1", run: async () => ({ id: "post_2" }), }); expect(second).toEqual(first); ``` HTTP-level behavior is testable through `(await getServer()).api(...)`: send the same request twice with one key and assert the second response carries `idempotency-replayed: true`, then change the body and assert the `409` `IDEMPOTENCY_CONFLICT` envelope. This makes duplicate-submit behavior testable without depending on a database or queue provider.