CREATE TABLE idempotency_keys (
request_key text NOT NULL,
endpoint text NOT NULL,
request_fingerprint text NOT NULL,
status text NOT NULL DEFAULT 'in_progress'
CHECK (status IN ('in_progress', 'completed')),
response_code integer,
response_body jsonb,
resource_id bigint,
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
PRIMARY KEY (request_key, endpoint)
);
-- Cheap lookup of in-flight attempts for the TTL sweeper.
CREATE INDEX idempotency_keys_in_progress_idx
ON idempotency_keys (created_at)
WHERE status = 'in_progress';
CREATE FUNCTION claim_idempotency_key(
p_request_key text,
p_endpoint text,
p_fingerprint text
)
RETURNS TABLE (did_claim boolean, response_code integer, response_body jsonb)
LANGUAGE plpgsql
AS $$
DECLARE
v_existing idempotency_keys%ROWTYPE;
BEGIN
-- Serialize concurrent requests that share this key (released at commit).
PERFORM pg_advisory_xact_lock(hashtextextended(p_endpoint || ':' || p_request_key, 0));
INSERT INTO idempotency_keys (request_key, endpoint, request_fingerprint)
VALUES (p_request_key, p_endpoint, p_fingerprint)
ON CONFLICT (request_key, endpoint) DO NOTHING;
IF FOUND THEN
RETURN QUERY SELECT true, NULL::integer, NULL::jsonb;
RETURN;
END IF;
SELECT * INTO v_existing
FROM idempotency_keys
WHERE request_key = p_request_key AND endpoint = p_endpoint;
IF v_existing.request_fingerprint <> p_fingerprint THEN
RAISE EXCEPTION 'idempotency key reused with a different payload'
USING ERRCODE = '23505';
END IF;
RETURN QUERY SELECT false, v_existing.response_code, v_existing.response_body;
END;
$$;
CREATE FUNCTION complete_idempotency_key(
p_request_key text,
p_endpoint text,
p_code integer,
p_body jsonb,
p_resource_id bigint
)
RETURNS void
LANGUAGE sql
AS $$
UPDATE idempotency_keys
SET status = 'completed',
response_code = p_code,
response_body = p_body,
resource_id = p_resource_id,
completed_at = now()
WHERE request_key = p_request_key AND endpoint = p_endpoint;
$$;
-- Runs inside a single transaction so the advisory lock spans the work.
CREATE FUNCTION create_order_idempotent(
p_request_key text,
p_fingerprint text,
p_customer_id bigint,
p_total_cents integer
)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
DECLARE
v_claim record;
v_order record;
v_body jsonb;
BEGIN
SELECT * INTO v_claim
FROM claim_idempotency_key(p_request_key, 'POST /orders', p_fingerprint);
IF NOT v_claim.did_claim THEN
-- Retry of a completed request: replay the cached response verbatim.
RETURN v_claim.response_body;
END IF;
INSERT INTO orders (customer_id, total_cents, status)
VALUES (p_customer_id, p_total_cents, 'pending')
RETURNING * INTO v_order;
v_body := jsonb_build_object(
'id', v_order.id,
'status', v_order.status,
'total', v_order.total_cents
);
PERFORM complete_idempotency_key(
p_request_key, 'POST /orders', 201, v_body, v_order.id
);
RETURN v_body;
END;
$$;
Create endpoints are the classic place where retries hurt: a client sends POST /orders, the network times out, the client retries, and now two orders exist. An idempotency key fixes this by letting the client attach a unique token to a logical operation, so the server can recognize a retry and return the original result instead of doing the work twice. This snippet shows the storage and locking machinery in raw SQL.
The idempotency schema tab defines idempotency_keys as a durable record of each attempt. The primary key is (request_key, endpoint) so the same token can be reused across different routes without colliding. A request_fingerprint column stores a hash of the request body; this guards against a client accidentally reusing a key for a different payload, which should be rejected rather than silently returning a stale response. The status column tracks the lifecycle (in_progress, completed), and response_code/response_body cache the final result so a retry can be replayed byte-for-byte. The partial index on status = 'in_progress' keeps lookups of in-flight work cheap.
The claim_idempotency_key tab is the heart of the pattern. It takes a transaction-scoped advisory lock keyed by a hash of the token with pg_advisory_xact_lock, which serializes concurrent requests that share a key without locking the whole table. Under that lock it does an INSERT ... ON CONFLICT DO NOTHING: the first caller inserts an in_progress row and gets the green light to run the business logic, while a concurrent duplicate finds the existing row. The function returns a did_claim boolean plus any cached response, so the caller knows whether to proceed or short-circuit.
The create_order flow tab ties it together in one transaction. It calls claim_idempotency_key; on a fresh claim it inserts the order and calls complete_idempotency_key to persist the cached response, and on a duplicate it simply returns the stored body. The fingerprint mismatch path raises so misused keys fail loudly. The trade-offs worth noting: advisory locks are per-connection and released at commit, so everything must live in one transaction; and stale in_progress rows from crashed requests need a sweeper job with a TTL. Used carefully, this turns non-idempotent creates into safely retryable operations.
Related snips
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
Share this code
Here's the card — post it anywhere.