Messaging and async

Idempotency

How to make retried requests and redelivered messages harmless with idempotency keys, deduplication tables, conditional writes and the transactional outbox.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A customer taps “Pay” on a train. The request reaches the server and the card is charged, but the train enters a tunnel before the response comes back. The app shows a spinner, then an error, and the customer taps “Pay” again. Or the app’s HTTP client does it for them, because it is configured to retry on a timeout. Either way the server receives a second, identical request and cannot tell whether it is the same payment or a second purchase.

The same thing happens between services with no person involved. A load balancer retries a request after a connection reset. A queue redelivers a message whose acknowledgement was lost. A scheduled job is run again after a partial failure. Delivery semantics showed why this cannot be prevented: over an unreliable network the only alternative to “possibly twice” is “possibly never”.

The early fixes were on the client: disable the button after the first tap, and never retry a POST. They help with impatient fingers and do nothing for a lost response, where retrying is the correct thing to do. So the fix moved to the receiver: make the operation safe to repeat. An operation is idempotent if doing it several times has the same effect as doing it once.

Naturally idempotent operations

Some operations are idempotent by their shape, and the cheapest fix is to reshape yours until it is one of them.

Not idempotent Idempotent version
balance = balance + 10 Apply ledger entry tx-881 at most once
“Add this item to the basket” “Set the quantity of item 7 to 2”
INSERT with a generated ID Upsert on an ID the caller supplies
“Send the next reminder” “Send reminder 3 for invoice 55”

The pattern is to replace a relative change with an absolute state, or to name the thing being created so that a second attempt collides with the first. HTTP encodes the same idea: GET, PUT and DELETE are defined as idempotent, and POST is not.

Idempotent does not mean “returns the same response”. A second DELETE may return 404. What matters is that the state is the same afterwards.

Watch for side effects hiding behind an idempotent write. An upsert is idempotent. An upsert followed by “send a confirmation email” is not, unless the email is sent only when the state actually changed.

Idempotency keys

When the operation cannot be reshaped, as with “charge this card”, give the request itself an identity. The client generates a unique idempotency key, usually a random UUID, and sends it with the request. Stripe’s API made the pattern widely known with its Idempotency-Key header. The server remembers each key it has seen and the result that went with it.

An idempotency key makes a payment safe to retry4 components: Mobile app, Payments API, Idempotency keys, Card processor. Connections: Mobile app to Payments API (POST with key); Payments API to Idempotency keys; Payments API to Card processor.Mobile appkey 7f3a savedPayments APIIdempotencykeysunique constraint on keyCard processorPOST with key

Step 1 of 8

A customer taps Pay. Before sending anything, the app generates a random UUID for this payment and saves it. The key identifies the payment itself, so every retry of it will carry the same value.

Read the steps as text
  1. A customer taps Pay. Before sending anything, the app generates a random UUID for this payment and saves it. The key identifies the payment itself, so every retry of it will carry the same value.
  2. The app sends the request with the key in an Idempotency-Key header. The API first tries to insert a row for that key, marked as in progress. A unique constraint guarantees that only one request can win this insert.
  3. The insert succeeded, so this is the first time the API has seen the key. It charges the card through the processor, and the charge is approved.
  4. The API saves the outcome and the response body against the key, then replies. The reply is lost because the phone has dropped off the network in a lift. The app sees only a timeout.
  5. The app cannot tell whether the payment happened, so it retries with the same key. This is the moment at which a naive API charges the card a second time.
  6. This time the insert fails on the unique constraint. The API reads the stored row, sees that the request completed, and returns the saved response without calling the processor. There is one charge, and the customer sees success.
  7. Suppose the retry had arrived while the first request was still running. The API would find the row with no result yet. It should answer 409 Conflict, or wait for the first request, and never start a second charge.
  8. Keys do not live for ever. A common choice is to expire them after 24 hours, which must be longer than any client keeps retrying. The key turns an unsafe POST into a request that is safe to retry: same key, same effect, same answer.
An idempotency key makes a payment safe to retry

The details are where implementations go wrong:

  • The client generates the key, once per operation. It is created when the user expresses the intent and reused on every retry. A key generated per HTTP attempt protects nothing.
  • Claim the key before doing the work. Insert a row for the key under a unique constraint, in the state “in progress”, and only then perform the operation. Checking with a SELECT and inserting afterwards leaves a gap in which two concurrent requests both see “not found”.
  • Handle concurrent requests with the same key. The second request finds the row in progress. Return 409 Conflict, or wait for the first to finish. Never start the work again.
  • Store the response and replay it. A retry should get the same status code and body as the original.
  • Scope and fingerprint the key. Keys are unique per customer or API credential, not globally. Store a hash of the request body, and reject a request that reuses a key with different parameters, because that is a client bug.
  • Expire keys. Stripe documents that its keys can be removed once they are at least 24 hours old. Your window must be longer than the longest period over which a client might retry.

Ideally the key row and the business change commit in one database transaction, so that they cannot disagree. When the work is a call to an external system that is impossible, and you need a recovery rule for a row left in progress by a crash: pass your key on to the provider if it supports one, or ask the provider for the outcome before trying again.

Idempotent consumers

A message consumer has the same problem over a different transport. The standard answer is a deduplication table, also called an inbox: a table of processed message IDs in the consumer’s own database.

BEGIN;
INSERT INTO processed_messages (message_id) VALUES ('evt-7f3a');
-- a unique violation here means it was already handled: skip and acknowledge
UPDATE accounts SET balance = balance + 10 WHERE id = 42;
COMMIT;

Because the ID and the business change commit together, a crash leaves both or neither. The ID must come from the producer and identify the business event, not the delivery. An ID assigned by the broker is different each time the producer publishes the same event.

Conditional writes do the same job with no extra table, when the data model allows. Make the write depend on the state it expects to find:

  • UPDATE orders SET status = 'paid' WHERE id = 42 AND status = 'pending' matches zero rows the second time.
  • A version check such as WHERE version = 7 rejects a stale or repeated update.
  • INSERT ... ON CONFLICT DO NOTHING in PostgreSQL, or an attribute_not_exists condition in DynamoDB, creates a row at most once.

The dual-write problem and the outbox

A service that saves an order and then publishes “order placed” is writing to two systems with no transaction across them. If it crashes between the two, the order exists and the event is never sent. Publishing first only reverses the failure, giving an event for an order that was never saved.

The transactional outbox removes the second write from the request. In the same local transaction as the order, the service inserts the event into an outbox table. A separate relay reads new outbox rows and publishes them to the broker, either by polling the table or by tailing the database’s change log with a tool such as Debezium.

Transactional outbox on the producer, inbox on the consumer6 components: Order service, Orders database, Outbox relay, Broker, Shipping service, Shipping database. Connections: Order service to Orders database (1. one transaction); Orders database to Outbox relay (2. read new rows); Outbox relay to Broker (3. publish); Broker to Shipping service (4. at least once); Shipping service to Shipping database (5. one transaction).Order serviceOrders databaseorders + outbox tablesOutbox relaypoller or CDCBrokerorders topicShippingserviceShippingdatabaseshipments + inbox tables1. one transaction2. read new rows3. publish4. at least once5. one transaction
Transactional outbox on the producer, inbox on the consumer

The order and the event now commit or roll back together. The relay can crash after publishing and before recording that it did, so it delivers at least once, and consumers need an inbox. An outbox on the producer plus an inbox on the consumer is the usual way to get effectively-once behaviour across services without a distributed transaction.

When to use which, and when not to

Prefer a naturally idempotent operation, since it costs nothing at run time. Use a conditional write when the entity has a state or a version to check. Use an idempotency key on any externally visible mutation that must not repeat: payments, orders, transfers. Use a deduplication table for consumers whose effects are not naturally idempotent.

Skip the machinery where a duplicate is harmless, such as a cache refresh or a “last seen” timestamp. And know the limit of any deduplication store: it works only inside its retention window. A message redriven from a dead-letter queue a week later passes straight through a 24-hour window, so anything money depends on should also have a permanent guard, such as a unique index on the payment’s business ID.

In the interview

Raise idempotency whenever a design contains a retry: a client calling a payment API, a consumer on an at-least-once queue, a saga step. Say what the key is, where it is stored, and that it commits atomically with the effect. For a payment flow that sounds like: “The client sends an idempotency key. I insert it under a unique constraint before charging, store the response, and replay it on a retry. I pass the same key to the card processor.” The payment system case study builds the full design.

Key takeaways

  • Retries are unavoidable, so the receiver must make repeating an operation have the same effect as doing it once.
  • The cheapest fix is to reshape the operation: set absolute state, or create a named thing so a second attempt collides with the first.
  • An idempotency key is generated by the client once per operation, claimed on the server under a unique constraint before the work starts, and stored with the response.
  • An idempotent consumer records the message ID in the same transaction as its business change, or uses a conditional write that fails the second time.
  • Writing to a database and publishing to a broker is a dual write. The transactional outbox makes the event part of the database transaction.
  • Deduplication stores have a retention window. Protect money with a permanent unique constraint as well.

Check yourself

1. A mobile app generates a fresh UUID as the idempotency key every time its HTTP client retries a payment request. What is the effect?
2. A server handles idempotency keys like this: SELECT the key; if it is absent, charge the card, then INSERT the key. Two identical requests arrive 5 ms apart. What happens?
3. Which statement is safe to run twice with no further protection?
4. A service commits an order to its database and then publishes "order placed" to Kafka. It sometimes crashes between the two steps. What does a transactional outbox change?
5. A consumer deduplicates with a Redis key that expires after 24 hours. Three days later an operator redrives a batch of messages from a dead-letter queue, and some had in fact been processed. What happens?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What does idempotent mean?

Performing the operation several times leaves the system in the same state as performing it once. The responses may differ; the effect may not.

Who generates an idempotency key, and when?

The client, once, when the user or caller initiates the operation. Every retry of that operation reuses the same key.

How should a server handle two concurrent requests with the same idempotency key?

Insert the key first under a unique constraint so only one request proceeds. The other sees an in-progress row and gets 409 Conflict or waits; it never repeats the work.

What is a deduplication (inbox) table?

A table of processed message IDs in the consumer's database. The ID is inserted in the same transaction as the business change, so a redelivery hits a unique violation and is skipped.

What is the dual-write problem?

A service writes to its database and to a broker with no transaction spanning both. A crash between the writes leaves data without an event, or an event without data.

How does the transactional outbox work?

The service inserts the event into an outbox table in the same local transaction as the business data. A relay (a poller or change data capture) publishes outbox rows to the broker at least once.

Review the deck