How to design an idempotency keys table for payment APIs and webhooks

The idempotency_keys table, the race-free claim, and when a unique column or a processed-events table is enough. Tested SQL, plus what 100 real schemas do.

· 9 min read · drawDB team

An idempotency keys table needs one row per client key, unique on (account_id, idempotency_key) rather than on the key alone. It also needs a fingerprint of the request, a status that is in_progress or completed, a lock timestamp, the saved response, and an expires_at. The request handler claims the key with an INSERT ... ON CONFLICT DO NOTHING and commits that right away. It then does the work and saves the response in the same transaction as the business write. A retry with the same key gets the saved response back. A retry with a different body is rejected, and a retry that arrives while the first request is still running is told to wait.

You don't always need the table. If the row you create is the whole response, as with a transfer, an order or a usage event, a unique key on that row does the job. For incoming webhooks, the provider's event id is the key, and a two-column table of processed events is enough. Those are the three shapes, and in the drawDB schema gallery all three are in use.

ShapeUse it whenUnique onStores the response
Idempotency keys tableYou run a public API whose responses clients must get back on retry(account_id, idempotency_key)Yes, status and body
Key column on the business rowThe created row is the response: a transfer, an order, a usage event(sender_id, idempotency_key)No, the row is the answer
Processed events tableYou receive webhooks from Stripe, Paddle, GitHub(provider, event_id)No

What columns does an idempotency keys table need?

Here is the PostgreSQL version. It runs as is on PostgreSQL 16, and the Stripe payments schema in the gallery carries the same table with a surrogate id:

PostgreSQL
CREATE TABLE idempotency_keys (
  account_id bigint NOT NULL REFERENCES accounts (id) ON DELETE CASCADE,
  idempotency_key varchar(255) NOT NULL,
  request_method varchar(8) NOT NULL,
  request_path varchar(255) NOT NULL,
  request_fingerprint char(64) NOT NULL,
  status varchar(12) NOT NULL DEFAULT 'in_progress',
  locked_until timestamptz,
  response_status smallint,
  response_body jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  expires_at timestamptz NOT NULL DEFAULT now() + interval '24 hours',
  PRIMARY KEY (account_id, idempotency_key),
  CONSTRAINT idempotency_keys_status_check
    CHECK (status IN ('in_progress', 'completed')),
  CONSTRAINT idempotency_keys_response_check
    CHECK ((status = 'completed') = (response_status IS NOT NULL))
);

CREATE INDEX idempotency_keys_expires_at ON idempotency_keys (expires_at);

What each column is for:

  • account_id + idempotency_key as the primary key. The key is only unique per caller. The next section covers why this matters more than anything else in the table.
  • idempotency_key varchar(255). Stripe accepts keys up to 255 characters and suggests V4 UUIDs. Cap the length so nobody can store a megabyte in your primary key.
  • request_method, request_path, request_fingerprint. The fingerprint is a SHA-256 of the canonicalised request body. A key reused with a different body or on a different endpoint is a client bug. Replaying the first response to it would be wrong in a way nobody notices until reconciliation.
  • status has two values. You might be tempted to add failed, but a request that failed with a definite answer, such as a declined card or a validation error, is completed with a 4xx response. A request that failed without one, such as a crash or a timeout, stays in_progress so a retry can pick it up.
  • locked_until. Set when a request claims the key. A crashed worker never clears it, so a retry may take over once it is in the past.
  • response_status, response_body. The CHECK constraint ties them to status, so a completed key always has something to replay.
  • expires_at with an index, for the sweep job.

How do you claim an idempotency key without a race?

Insert the row and let the primary key decide who got there first. Run this as its own short transaction and commit it before doing any work:

PostgreSQL
INSERT INTO idempotency_keys
  (account_id, idempotency_key, request_method, request_path, request_fingerprint, locked_until)
VALUES
  (42, '8e0f5c1a-6f4b-4c55-9d1e-1b2f3a4c5d6e', 'POST', '/v1/payments',
   '3f2a9c0e7b1d4a6f8e2c5b9d0a1f3e7c6b4d2a8f0e9c1b3d5a7f6e4c2b0d9a8f',
   now() + interval '30 seconds')
ON CONFLICT (account_id, idempotency_key) DO NOTHING
RETURNING status;

One row back means this request owns the key: go do the work. No row back means the key already exists, so read it:

PostgreSQL
SELECT request_method, request_path, request_fingerprint, status,
       locked_until > now() AS locked, response_status, response_body
FROM idempotency_keys
WHERE account_id = 42
  AND idempotency_key = '8e0f5c1a-6f4b-4c55-9d1e-1b2f3a4c5d6e';

Then there are four outcomes. The status codes come from the IETF Idempotency-Key header draft, which is still a draft (revision 08, October 2026) but is what new APIs converge on:

  1. Method, path or fingerprint differ. Return 422. The client reused a key for a different request.
  2. completed. Return the saved response_status and response_body unchanged, including a saved 4xx.
  3. in_progress and still locked. Return 409 and let the client retry later. This is the case that stops a double-tapped button from charging twice.
  4. in_progress and the lock has expired. The first attempt died. Take the key over with a conditional update, and only proceed if it returns a row:
PostgreSQL
UPDATE idempotency_keys
SET locked_until = now() + interval '30 seconds'
WHERE account_id = 42
  AND idempotency_key = '8e0f5c1a-6f4b-4c55-9d1e-1b2f3a4c5d6e'
  AND status = 'in_progress'
  AND locked_until < now()
RETURNING status;

Committing the claim before the work matters for two reasons. If the claim sat in the same transaction as a slow payment call, a concurrent retry's INSERT would block on the uncommitted row instead of getting its 409 straight away. And if the handler crashes, a committed claim is what lets a later retry see that something was in progress.

How do you save the response in the same transaction as the write?

Do the business write and the key update in one transaction, so that either both happened or neither did. A payment row without a completed key means a retry creates a second payment. A completed key without a payment row means a retry replays a success for money that never moved.

PostgreSQL
WITH payment AS (
  INSERT INTO payments (account_id, amount_minor, currency_code)
  VALUES (42, 2000, 'USD')
  RETURNING id, amount_minor, currency_code
)
UPDATE idempotency_keys k
SET status = 'completed',
    locked_until = NULL,
    response_status = 201,
    response_body = (SELECT to_jsonb(payment) FROM payment)
WHERE k.account_id = 42
  AND k.idempotency_key = '8e0f5c1a-6f4b-4c55-9d1e-1b2f3a4c5d6e';

In application code this is usually a plain BEGIN, two statements, COMMIT. The CTE just shows that it fits in one round trip.

The hard part is a call to another system in the middle, such as charging a card at a payment provider. Your transaction can't roll that back. Do what Brandur Leach's Stripe-style idempotency keys write-up does: commit a local record before the call, pass a key you derive from your own row downstream (payments-<payment id>, never the client's raw key), and record the result in the next transaction. If you crash between the call and the record, the retry calls the provider again with the same derived key, and the provider's own idempotency stops a second charge.

Should an idempotency key be unique per table or per customer?

Per customer. The key is generated by the client, so uniqueness only means something within one client's requests. Make the unique index (account_id, idempotency_key), or (merchant_id, ...) or (sender_id, ...), whatever identifies the caller.

A table-wide unique key works only as long as every client sends a random UUID. The first integration that sends order-1 collides with another customer's order-1. In the best case, the second customer's request fails with a conflict they can't explain. In the worst case, the handler finds the existing completed key and replays another customer's response body to them, which is a data leak. Scoping the key to the caller makes both impossible, because the lookup can never reach another account's row.

The gallery shows how easy this is to get wrong. Across its 100 schemas, 17 columns in 14 schemas act as an idempotency or dedupe key. 11 of them hold a key supplied by the client. Only one of those 11 is scoped to the caller: idempotency_keys in the Stripe schema, unique on (merchant_id, idempotency_key). The leaderboards schema scopes score submissions per game, which still lets two players in one game collide. The other nine are unique across the whole table, including client_order_id on the crypto exchange and Robinhood orders and idempotency_key on Venmo transfers. Each of them is safe only because the schema assumes the app generates UUIDs.

When is a unique key on the business row enough?

When the row you insert is the response. A Venmo-style transfer is the typical case. The client sends a key with the transfer, and on a repeat you return the transfer that already exists. There is no separate response to store, because the transfer is the response.

PostgreSQL
CREATE TABLE transfers (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sender_id bigint NOT NULL,
  recipient_id bigint NOT NULL,
  idempotency_key varchar(64) NOT NULL,
  amount_minor bigint NOT NULL CHECK (amount_minor > 0),
  currency_code char(3) NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT uq_transfers_sender_idempotency UNIQUE (sender_id, idempotency_key)
);

INSERT INTO transfers (sender_id, recipient_id, idempotency_key, amount_minor, currency_code)
VALUES (42, 77, 'c1f6d0e2-tap', 1500, 'USD')
ON CONFLICT (sender_id, idempotency_key) DO NOTHING
RETURNING id;

No row back means it is a repeat. Select the existing transfer and compare recipient_id, amount_minor and currency_code with the request. If they match, return it with a 200. If they don't, return 422. The row is your fingerprint.

This is what 12 of the 14 gallery schemas do. It is the better default whenever the endpoint creates exactly one row. It saves a table, a sweep job and a transaction. And the key lives as long as the row, so a retry a week later still finds the original. The double-entry ledger post uses this shape on journal_entries, where a replayed payment must find the existing entry instead of posting twice.

Switch to the keys table when the endpoint does several writes, calls another system, or returns errors that clients need to see again on retry. A unique column can't replay a 402 card_declined, because a declined request never inserted a row.

How do you deduplicate incoming webhooks?

Store the provider's event id with a primary key, in the same transaction as whatever the event changes:

PostgreSQL
CREATE TABLE processed_webhook_events (
  provider varchar(32) NOT NULL,
  event_id varchar(255) NOT NULL,
  event_type varchar(100) NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_id)
);

INSERT INTO processed_webhook_events (provider, event_id, event_type)
VALUES ('stripe', 'evt_1QxYz2LkdIwHu7ix', 'payment_intent.succeeded')
ON CONFLICT DO NOTHING
RETURNING event_id;

If the row comes back, apply the event and commit. If it doesn't, you have already applied it: return 200 and do nothing. Return 200 in that case, not an error, or the provider keeps retrying an event you already have.

Stripe's webhook docs say to do exactly this: track event ids, because the same event can arrive more than once and events arrive in no guaranteed order. They also say live-mode retries continue for up to three days, so keep processed events for at least a week. Put provider in the key from the start. The second payment provider always arrives sooner than planned, and their event ids are free-form strings that can collide.

The gallery only models the sending side of webhooks: webhook_deliveries in the Stripe and Shopify schemas, with one row per attempt and an event id the receiver can deduplicate on. The receiving table above is the other half.

How long should you keep idempotency keys?

At least as long as clients retry, plus room for a bad deploy. Stripe prunes keys once they are at least 24 hours old and treats a reused key after that as a new request. Brandur's write-up suggests about 72 hours, so a bug shipped on a Friday still has its keys on Monday. 24 to 72 hours is the range. Put it in expires_at at insert time rather than computing it in the sweep, so you can give a slow batch endpoint a longer window than the rest.

Delete in batches, so one sweep never holds locks on a million rows:

PostgreSQL
DELETE FROM idempotency_keys
WHERE ctid IN (
  SELECT ctid FROM idempotency_keys
  WHERE expires_at < now()
  LIMIT 10000
);

Run it in a loop until it deletes fewer than 10,000 rows. On a table this short-lived, the expires_at index makes each batch an index range scan. If the table takes hundreds of millions of keys a day, partition it by day on created_at and drop old partitions instead.

Why does a nullable unique key break on SQL Server?

Because SQL Server lets a UNIQUE constraint hold only one NULL per column. PostgreSQL, MySQL, MariaDB, SQLite and Oracle treat NULLs as distinct, so any number of rows can leave the column empty. That difference matters for optional keys. In the gallery's usage-based billing schema, usage_records.idempotency_key is nullable because some metering clients don't send one. On SQL Server, the second event without a key fails with a duplicate key error.

The fix is a filtered unique index in place of the constraint:

SQL Server
CREATE TABLE usage_records (
  id BIGINT IDENTITY(1,1) PRIMARY KEY,
  subscription_id BIGINT NOT NULL,
  quantity DECIMAL(20,6) NOT NULL,
  idempotency_key VARCHAR(120) NULL
);

CREATE UNIQUE INDEX uq_usage_records_idempotency_key
  ON usage_records (idempotency_key)
  WHERE idempotency_key IS NOT NULL;

We found this while writing this post, and it isn't limited to idempotency keys. 61 nullable single-column UNIQUE columns across 46 of the gallery's 100 schemas hit the same rule, mostly payment provider references that stay empty until the provider answers, plus optional emails and barcodes. drawDB's SQL Server export currently writes them as an inline UNIQUE, so check them before you run that DDL. The other five dialects are unaffected.

What does the MySQL version look like?

The table translates directly. JSON replaces jsonb and DATETIME(6) replaces timestamptz, with your app writing UTC:

MySQL
CREATE TABLE idempotency_keys (
  account_id BIGINT NOT NULL,
  idempotency_key VARCHAR(255) NOT NULL,
  request_method VARCHAR(8) NOT NULL,
  request_path VARCHAR(255) NOT NULL,
  request_fingerprint CHAR(64) NOT NULL,
  status VARCHAR(12) NOT NULL DEFAULT 'in_progress',
  locked_until DATETIME(6) NULL,
  response_status SMALLINT NULL,
  response_body JSON NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  expires_at DATETIME(6) NOT NULL,
  PRIMARY KEY (account_id, idempotency_key),
  KEY idempotency_keys_expires_at (expires_at),
  CONSTRAINT idempotency_keys_status_check CHECK (status IN ('in_progress', 'completed'))
);

INSERT INTO idempotency_keys
  (account_id, idempotency_key, request_method, request_path, request_fingerprint,
   locked_until, expires_at)
VALUES
  (42, '8e0f5c1a-6f4b-4c55-9d1e-1b2f3a4c5d6e', 'POST', '/v1/payments', 'f3a9',
   NOW(6) + INTERVAL 30 SECOND, NOW(6) + INTERVAL 24 HOUR);

MySQL has no ON CONFLICT ... RETURNING, so send a plain INSERT and treat error 1062 (ER_DUP_ENTRY) as "the key exists": catch it, then run the same SELECT as in PostgreSQL. Avoid the ON DUPLICATE KEY UPDATE account_id = account_id trick. Its affected-row count tells new rows from existing ones only when the driver doesn't set the CLIENT_FOUND_ROWS flag, and some drivers set it by default. Don't use INSERT IGNORE either. It also turns other errors, like a value too long for its column, into warnings, and a claim that silently stored a truncated key is worse than one that failed.

Open the Stripe payments schema to see the keys table next to the payment intents, refunds and webhook deliveries it protects, then export it to your dialect from the editor.

Frequently asked questions

Should the server or the client generate the idempotency key?

The client. The point of the key is that the client can send the same value again after a timeout, before it knows whether the first attempt reached you. A key the server generates only exists after the server has answered, which is exactly the answer the client didn't get. Ask clients for a V4 UUID per logical operation, created before the first attempt and reused on every retry.

Is Redis good enough for idempotency keys?

Only for the lock, not the record. A Redis SET NX with a TTL stops two concurrent requests, but the completed key and the business write then live in different systems, and a crash between them leaves one without the other. Keeping the key in the same database as the write lets one transaction commit both. Use Redis in front of the table if the lookup load is high, not instead of it.

Should GET, PUT and DELETE requests take an idempotency key?

No. GET, PUT and DELETE are idempotent by definition in HTTP: repeating them leaves the server in the same state. Stripe ignores keys on GET and DELETE. Keys are for POST and for PATCH operations that are not idempotent, like incrementing a counter or appending to a list.

What should the response be when a retry arrives after the key has expired?

The server can't tell it is a retry, so it runs as a new request. That is why the expiry has to be longer than any client's retry window, and why clients should give up and surface an error rather than retry forever. For operations where a late duplicate is unacceptable, such as payouts, keep a unique key on the business row as well, which never expires.

Should I store the full response body or only the id of the created resource?

The full body, for anything that clients compare or display. If you store only the id and rebuild the response on replay, a retry returns the object's current state, which may already show a refund or a status change, rather than the answer to the original request. Storing the id is fine when the endpoint returns nothing beyond a reference.