Skip to content

Money, consistency and distributed data · Part 3 of 10

Idempotency keys for APIs and message consumers

Networks retry and brokers redeliver, so every operation that moves money must be safe to receive twice. A unique key and a stored result make a repeat harmless.

· 4 min read

paymentsapiidempotency

Distributed systems fail in ambiguous ways. A client sends a payment request, the connection drops, and it cannot tell whether the server processed it. The only safe response is to try again, which is only safe if repeating the request does no harm. That property is called idempotency.

What idempotent means

An operation is idempotent when doing it once or many times leaves the system in the same final state. Setting a status to "paid" is idempotent. Adding 100,000 to a balance is not: doing it twice adds 200,000. Money operations are naturally the second kind, so you add idempotency deliberately.

Idempotency keys on an API

The client generates a unique key for each logical operation and sends it, usually in an Idempotency-Key header. The server stores the key with the outcome and uses a database unique constraint to guarantee that only one request wins.

Code
CREATE TABLE idempotency_keys (
  idem_key      VARCHAR(64) NOT NULL PRIMARY KEY,
  request_hash  CHAR(64)    NOT NULL,      -- fingerprint of the request body
  status        VARCHAR(20) NOT NULL,      -- IN_PROGRESS, DONE
  response_code SMALLINT    NULL,
  response_body JSON        NULL,
  created_at    DATETIME(3) NOT NULL
) ENGINE=InnoDB;

The handling logic is short.

  1. Insert the key inside the same transaction as the business change. If the insert fails with a duplicate-key error, this request has been seen.
  2. If the stored request hash differs from the new one, the client reused a key for a different payload. Reject it with a client error, because that is a bug on their side.
  3. If the stored record is DONE, return the stored response without doing the work again.
  4. Otherwise do the work, store the response and commit together.

Handling concurrent duplicates

Two copies of the same request can arrive at the same time. InnoDB helps here: the second INSERT of the same primary key waits for the first transaction to finish. If the first commits, the second gets a duplicate-key error and returns the stored result. If the first rolls back, the second proceeds. The unique index is doing the coordination, so you do not need an extra lock. Expire old keys after a period that exceeds the longest realistic retry window, for example a day or a few days.

Idempotent consumers

The same problem appears on the receiving end of a queue. Brokers such as Kafka deliver at least once, so a consumer can see an event twice after a crash or rebalance. Record each processed event id in the same transaction that applies its effect.

SQL
START TRANSACTION;
INSERT INTO processed_events (event_id) VALUES ('evt-7c21');   -- duplicate: skip and roll back
UPDATE wallets SET balance = balance + 100000 WHERE id = 1;
INSERT INTO ledger_entries (txn_id, wallet_id, amount, created_at)
VALUES (2001, 1, 100000, CURRENT_TIMESTAMP(3));
COMMIT;

If event_id is the primary key of processed_events, a replayed event fails the first statement. The consumer rolls back, treats the event as already handled, and moves on. Because marking and applying happen in one transaction, you cannot end up with money added but the event unmarked, or the reverse. This is the practical meaning of exactly-once effects: at-least-once delivery plus an idempotent consumer.

Natural idempotency and its limits

  • Prefer operations that are idempotent by design: SET status = 'PAID' rather than increments, upserts keyed by a business id, and overwrite-by-partition in pipelines.
  • Use a stable business key where one exists, such as an order id or a provider transaction id, instead of a random key, so retries and different entry points converge.
  • Side effects outside your database, such as sending an email or calling a payment provider, are not covered by your table. Pass the same idempotency key to providers that support it, and record intent before acting.

Takeaway

Treat every network call and message as something that can arrive twice. Use a unique key committed in the same transaction as the effect, store the result so a repeat returns the same answer, fingerprint the request to catch key misuse, and apply the same pattern in consumers with a processed-events table.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.