Skip to main content

Idempotency Key Implementation for Payment APIs

Last Updated: 2026-12-01 Status: Complete

An idempotency key implementation (see idempotency key) lets a client retry a money-moving request any number of times and get exactly one effect. This page shows the server side: a Postgres table, insert-first locking, request fingerprints, recovery points for multi-step operations, and a NestJS interceptor that returns RFC 9457 problem details. It builds on the Idempotency in Payments post, which explains why; this page explains how.

Quick Reference​

DecisionRecommendation
Who generates the keyThe caller, tied to business intent (checkout attempt, billing period, payout)
Scope of uniqueness(tenant_id, key), never the key alone
Concurrency controlUnique constraint plus insert-first (INSERT ... ON CONFLICT DO NOTHING)
Same key, different body422, detected by a request fingerprint
Same key, still running409
Missing key where required400
What to persistDefinitive outcomes; release the key on failures before any side effect
RetentionA design choice; longer for recurring billing and payouts
Standards statusInternet-Draft (draft-ietf-httpapi-idempotency-key-header-09, 21 November 2026), not yet an RFC

What Does the Blog Post Already Establish?​

The model, in five lines. Keys are generated by the caller and tied to intent. Keys stop at the API boundary: below your platform and your processor API, ISO 8583 has no key, and uncertainty is resolved with reversals and the STAN (DE 11), RRN (DE 37) and network transaction ID. A timeout is an explicit unknown state. A unique constraint prevents the race between two simultaneous requests. A key reused with different parameters is a client error. Module 4 agrees in Reversal or Repeat and Idempotency at Each Layer. Nothing on this page implies that a key reaches the network or the issuer.

What Does the idempotency_keys Table Look Like?​

CREATE TABLE idempotency_keys (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL, -- platform or account scope
idempotency_key text NOT NULL CHECK (char_length(idempotency_key) <= 255),
request_fingerprint bytea NOT NULL, -- sha256(method + path + canonical body)
status text NOT NULL CHECK (status IN ('in_progress', 'completed')),
recovery_point text NOT NULL DEFAULT 'started',
response_status int,
response_body jsonb,
locked_at timestamptz, -- set while a worker owns the request
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
CONSTRAINT uq_idempotency_scope UNIQUE (tenant_id, idempotency_key)
);
CREATE INDEX ix_idempotency_expires ON idempotency_keys (expires_at);
ColumnWhy it exists
tenant_idTwo tenants must be able to use the same key string. Scoping also prevents one tenant from reading another's stored response.
request_fingerprintDetects a reused key with a different payload. Hash the method, the path and a canonical body (sorted keys, no insignificant whitespace).
status, locked_atDistinguish "finished" from "a worker is running this now". A stale lock means a crashed worker.
recovery_pointWhere a multi-step operation stopped, so a retry resumes instead of restarting.
response_status, response_bodyWhat to replay. Store the body you returned, not the processor's raw response.
expires_atEnables a pruning job. Retention is covered below.

How Does Insert-First Locking Work?​

Do not read, then insert. Insert first and let the unique constraint decide who owns the request.

The insert commits before any business work, so a concurrent duplicate sees in_progress immediately. This is the unique-constraint fix from the blog post, made concrete.

How Do Atomic Phases and Recovery Points Work?​

A payment operation usually touches your database and a processor. Brandur Leach's "Implementing Stripe-like Idempotency Keys in Postgres" splits such an operation into atomic phases: stretches of purely local database work that commit together with an update to the key's recovery_point. Calls to the outside world sit between phases, never inside a database transaction.

PhaseLocal transaction doesRecovery point after
1. CreateInsert the payment row in authorizing, advance the keypayment_created
2. Mark call startedCommit the marker before the call, so a crash cannot hide that the call may have happenedprocessor_call_started
3. Call processorOutside any transaction, using a derived key (see below)n/a
4. Record outcomeStore the processor result, update payment state, write the outbox row, store the response, set status = 'completed'finished

finished and status = 'completed' are the same event: phase 4 writes both in one transaction. A retry that finds payment_created never reached the processor, so it can safely continue to phase 2. A retry that finds processor_call_started cannot know whether the call happened, so it always takes the status-lookup or reversal path instead of starting a new authorization. If the outcome cannot be determined, the payment goes to unknown and is resolved by status lookup or reversal. That is the blog's explicit unknown state, now persisted. States and transitions are designed in State Machines.

NestJS Implementation​

An interceptor reads the header and delegates to a service. The service owns the SQL.

import { createHash } from 'node:crypto';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';

export type BeginResult =
| { kind: 'execute'; id: string }
| { kind: 'replay'; status: number; body: unknown };

const problem = (status: number, slug: string, title: string, detail: string) =>
new HttpException({ type: `https://api.example.com/problems/${slug}`, title, status, detail }, status);

@Injectable()
export class IdempotencyService {
constructor(private readonly dataSource: DataSource) {}

fingerprint(method: string, path: string, body: unknown): Buffer {
return createHash('sha256').update(`${method} ${path} ${canonicalJson(body)}`).digest();
}

async begin(tenantId: string, key: string, fp: Buffer, ttlHours: number): Promise<BeginResult> {
return this.dataSource.transaction(async (m) => {
const inserted = await m.query(
`INSERT INTO idempotency_keys (tenant_id, idempotency_key, request_fingerprint, status, locked_at, expires_at)
VALUES ($1, $2, $3, 'in_progress', now(), now() + make_interval(hours => $4))
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING RETURNING id`,
[tenantId, key, fp, ttlHours],
);
if (inserted.length) return { kind: 'execute', id: inserted[0].id };

const [row] = await m.query(
`SELECT id, request_fingerprint, status, response_status, response_body
FROM idempotency_keys WHERE tenant_id = $1 AND idempotency_key = $2`,
[tenantId, key],
);
if (!fp.equals(row.request_fingerprint)) {
throw problem(HttpStatus.UNPROCESSABLE_ENTITY, 'idempotency-key-reused', 'Idempotency key reused',
'This key was first used with a different request.');
}
if (row.status === 'completed') {
return { kind: 'replay', status: row.response_status, body: row.response_body };
}
// Stale-lock takeover from recovery_point is omitted here; see the table above.
throw problem(HttpStatus.CONFLICT, 'idempotency-request-in-progress', 'Request in progress',
'A request with this key is still being processed. Retry shortly.');
});
}
}

function canonicalJson(v: unknown): string {
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;
if (v && typeof v === 'object') {
const o = v as Record<string, unknown>;
return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(',')}}`;
}
return JSON.stringify(v);
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, catchError, from, mergeMap, of, throwError } from 'rxjs';

@Injectable()
export class IdempotencyInterceptor implements NestInterceptor {
constructor(private readonly svc: IdempotencyService) {}

intercept(ctx: ExecutionContext, next: CallHandler): Observable<unknown> {
const req = ctx.switchToHttp().getRequest();
const res = ctx.switchToHttp().getResponse();
const key = req.headers['idempotency-key'] as string | undefined;
if (!key) throw problem(400, 'idempotency-key-missing', 'Idempotency-Key required', 'Send an Idempotency-Key header.');

const fp = this.svc.fingerprint(req.method, req.path, req.body);
const ttlHours = 24; // illustrative only; choose from the retention facts below
return from(this.svc.begin(req.tenantId, key, fp, ttlHours)).pipe(
mergeMap((r) => {
if (r.kind === 'replay') {
res.status(r.status).setHeader('Idempotent-Replayed', 'true');
return of(r.body);
}
return next.handle().pipe(
mergeMap((body) => from(this.svc.complete(r.id, res.statusCode, body)).pipe(mergeMap(() => of(body)))),
catchError((err) => from(this.svc.onFailure(r.id, err)).pipe(mergeMap(() => throwError(() => err)))),
);
}),
);
}
}

complete stores the response and sets status = 'completed'. onFailure applies the failure policy below.

Interceptors run before pipes

NestJS runs interceptors before pipes, so begin() inserts the key before ValidationPipe has validated the DTO. A validation failure (400 or 422) therefore reaches onFailure with a key already stored. onFailure must delete the key for validation errors and for any error raised before a side effect; only deterministic business results (success, decline) are stored and replayed. ::: req.tenantId comes from your authentication layer; see Access Control. A global exception filter should render the HttpException payloads as application/problem+json (RFC 9457), covered in Payments API Design.

Where the interceptor stops

This is the shape of the logic, not a finished library. The multi-phase operation (recovery points, stale-lock takeover) belongs in the service that runs the payment, because only that service knows its phases.

What Status Codes Should the Idempotency Layer Return?​

The IETF draft (Internet-Draft (draft-ietf-httpapi-idempotency-key-header-09, 21 November 2026), not yet an RFC) recommends:

SituationStatusNotes
Key required but missing400Mark the header required per endpoint.
Retry while the original is processing409Client retries later with the same key.
Same key, different payload422Client bug; never process, never replay.

Errors use RFC 9457 problem details. The blog post allowed either 409 or 422 for a reused key; this page picks 422 for payload mismatch and 409 for in-flight, which matches the draft. Adyen's docs describe a duplicate sent while the first request is in progress as HTTP 422 or 409 with error code 704, so check your processor's behavior before mapping it.

What Should You Store and Replay? Stripe v1, Stripe v2 and Adyen​

DesignBehavior (vendor docs)Trade-off
Stripe v1Saves status and body of the first execution once it begins and replays it, including 500 errors. Validation failures and conflicts with a concurrent request are not saved.Simple and predictable. A transient server error is replayed forever for that key, so the client must use a new key to retry.
Stripe v2Re-executes failed or partially failed work and returns an updated response. Successful operations are not repeated.Retries can heal a transient failure. The server must make each step safely resumable.
AdyenKey scoped to the company account; a duplicate while in progress returns 422 or 409 with error 704; error 703 (HTTP 503) means the idempotency store is unavailable; a transient-error: true header means retry with the same key and backoff.Makes the in-flight and store-outage cases explicit to the client.

Recommendation. Persist definitive outcomes: a 2xx and a deterministic 4xx business result such as a decline. Release the key (delete the row, or mark it retryable) on failures that happened before any downstream side effect, such as a database outage in phase 1, so the same key can be retried. If the failure happened after a side effect may have occurred, do not release: keep the recovery point and resolve the outcome first. This gives v2's healing without risking a second charge.

How Long Should Keys Be Kept?​

Retention is a design choice, not a constant. Stripe documents: API v1: keys may be pruned once at least 24 hours old; API v2: retries replayed within 30 days. Adyen documents: 7 to 14 days; keys up to 64 characters. Pick a window longer than your longest realistic client retry loop plus queue delay, then prune by expires_at.

  • Checkout: a short window is enough because the key is tied to one attempt.
  • Recurring billing: key per billing period, for example sub_{subscriptionId}_{billingPeriod}, with retention covering the dunning window. See Retry Strategy.
  • Payouts: scheduled payouts use payout_{merchantId}_{currency}_{payoutDate}: one key per merchant, currency and payout date, so a rerun of the same schedule reuses it. This extends the blog's payout_{merchantId}_{date}_{sequence} with currency, because otherwise a merchant's USD and EUR payouts on the same day collide. Manual or instant payouts use the caller's own request key. Keep keys at least until the payout reaches a terminal state. After pruning, a unique business reference on the payout row is the last line of defense.

A key that expires while a client could still retry turns a retry into a new request. Document your window in the API reference.

How Do You Make Downstream Calls Idempotent?​

Your inbound key is not your outbound key. Derive a stable key per attempt for the processor API, as in Cascading: for example {paymentId}:{attemptNumber}. Reuse it only when retrying the same attempt at the same provider. A deliberate retry after a decline is a new attempt with a new key.

When the processor call times out, the outcome is unknown:

  1. Look up the status by your reference or key, if the processor offers it.
  2. If you connect at ISO 8583, send a reversal before any new authorization (Module 4: Reversal or Repeat).
  3. Only then permit a new attempt.

Which Other Operations Need Their Own Keys?​

OperationKey strategy
CaptureKey per capture request; the payment state machine also rejects a second full capture.
RefundKey per refund intent; a retry must not double-refund. Also cap cumulative refunds at the captured amount.
PayoutKey per payout; see the payout design in Payouts.
Ledger postingA unique external reference per journal entry, so replaying an event cannot post twice. See Double-Entry Ledger.

Receivers need the same discipline for events and webhooks: see Event-Driven Payment Architecture and Webhook Delivery and Signature Verification.

Time-Sensitive

Vendor idempotency behavior and the IETF draft change. Retention values and status above come from vendor documentation and the draft as of 2026-12-01; see Key Numbers and re-verify before relying on them.

References​

Share: