microservice.guru
← All posts

Idempotency: Surviving At-Least-Once Delivery

· Architecture · Microservices · Messaging · Reliability

By Alain Cyr, Founder, Koesion

microservice.guru — Idempotency. Without a key, a retried payment of 8,400 is sent twice. With a key, the retry is recognised and ignored.

The customer of claim 4711 received 8,400 twice.

Finance wants to know who made the mistake, and the uncomfortable answer is that nobody did. Claims asked Payments to pay. Payments paid and answered. The answer was lost on the way back. Claims waited, gave up and asked again, as it was built to do. Payments received a valid request and paid.

Sequence: Claims sends IssuePayment, Payments transfers 8,400 through the bank, the 200 OK is lost, Claims times out and retries, and Payments transfers 8,400 again

Every component did what it was designed to do.

The sender cannot know

From where Claims stands, a lost request and a lost answer look the same: silence. It has two options. It can give up, in which case some payments are never made. Or it can retry, in which case some are made twice. Those are the only choices, and they have names, at-most-once and at-least-once.

Vendors sometimes promise a third, exactly-once delivery. Read the small print. What they offer is at-least-once delivery combined with deduplication inside their own system. The moment your handler touches something outside it, like a bank, the guarantee stops.

So the practical position is this. Delivery is at least once, always. What you can build is an operation that has the same effect whether it runs once or five times. That property is idempotency, and it belongs to the receiver.

Three ways to get it

Say the result, not the change. “Set the reserve to 12,000” can be applied ten times. “Add 12,000 to the reserve” cannot. Whenever you design a command or an event, check whether it can state the final value. This costs nothing and removes a surprising share of the problem.

Lean on a key the business already has. If the domain says there is one payment per claim and settlement number, put a unique constraint on those two columns. The second insert fails, and you return the existing payment.

Have the caller name its intent. When no natural key exists, the caller generates one, a UUID, and sends it with the request and with every retry of that request. The receiver stores the key together with the result. If it sees the key again, it returns the stored result and does nothing else.

Sequence with an idempotency key: the first request inserts the key and the payment in one transaction and calls the bank; the answer is lost; the retry hits a unique violation and receives the stored answer

The retry carries the same key because it is the same intent. A new payment would get a new key.

In SQL the whole mechanism is one constraint:

BEGIN;
INSERT INTO idempotency_key (key, request_hash) VALUES ('7f3a…', 'c41d…');
-- unique violation? roll back, look up the stored response, return it
INSERT INTO payment (id, claim_id, amount) VALUES ('pay-91', '4711', 8400);
UPDATE idempotency_key SET response = '{"paymentId":"pay-91"}' WHERE key = '7f3a…';
COMMIT;

Where implementations go wrong

The idea is small. Most of the work is in four details.

The check and the effect must commit together. The tempting version keeps keys in a cache: look up the key, and if it is absent, do the work and then store it. Two retries arriving forty milliseconds apart both find nothing, and both pay.

Left: two concurrent requests both check for the key, both find nothing, both pay. Right: both try to insert the key in a transaction, the database rejects the second, and it returns the first one's answer

A cache check narrows the window. A unique constraint closes it.

Same key, different body. If a request arrives with a known key and a different amount, something is wrong on the caller’s side. Reject it. Do not quietly return the old answer.

Retention. Keys have to outlive the longest possible retry. For an HTTP API, a day is common. For a message consumer behind a queue that can back up over a weekend, think in weeks.

Downstream. If Payments deduplicates and then calls the bank without a key, a crash after the bank call and before the commit sends the money twice anyway. Derive a key for the downstream call from your own and pass it along. Idempotency has to hold along the whole chain, or it only moves the duplicate one hop further.

Table of three techniques: absolute operations, a business constraint and an idempotency key, with how each works, what it costs and an example

Try them in this order. The first two are free.

Message consumers

Everything above applies to consumers of events and commands, with the message id playing the role of the key. A table of processed message ids, written in the same transaction as the handler’s changes, is often called an inbox. It is the consuming half of the outbox.

Consumers have one more thing to deal with, which is order. A retry can arrive after a newer message. If ReserveChanged to 9,000 turns up after the one that set 12,000, applying it blindly takes you back in time. Carry a version number on the event, and ignore anything older than what you already hold.

Assume every message arrives at least twice. Design the second arrival to be boring.

Where to go next

References