Idempotency and the exactly-once illusion
Networks force retries; idempotent operations and deduplication make retries safe.
18 min readEvery timeout is ambiguous
When a call times out, the client cannot know whether the request was lost, processed with the response lost, or is still running. The only safe recovery is to retry, which means the server may receive the same request two or more times. Delivery guarantees therefore come in two practical flavours: at-most-once (never retry, sometimes lose) and at-least-once (retry, sometimes duplicate). Exactly-once delivery over an unreliable network is impossible; exactly-once effect is achievable.
Exactly-once effect = at-least-once + idempotency
An operation is idempotent if applying it twice has the same effect as once. SET balance = 50 is idempotent; ADD 10 to balance is not. Turn non-idempotent operations into idempotent ones with an idempotency key chosen by the client.
- Client generates a unique key (a UUID) per logical operation and reuses it on every retry
- Server records key plus result in the same transaction as the effect
- A repeat request with a known key returns the stored result without re-executing
- Keep keys for longer than the retry window; 24 hours is a common choice for payment APIs
Consumers and streams
Message brokers redeliver after a consumer crash, so a consumer may process message 1 042 again after restart. Make consumers idempotent by recording processed message IDs or offsets in the same database transaction as their side effects, or by using natural idempotency such as upserts keyed by event id. Kafka offers transactional read-process-write between topics, but the guarantee ends at Kafka's boundary: an email sent or an external API called still needs its own deduplication.
Concurrency control
Idempotency handles duplicates of the same request; concurrency control handles different requests racing for the same data. Use optimistic concurrency with a version column: UPDATE stock SET qty = qty - 1, version = version + 1 WHERE sku = ? AND version = ? AND qty > 0. If zero rows change, someone else won; re-read and retry or fail. This conditional update is how inventory and booking systems avoid overselling without long locks.
Key takeaways
- A timeout does not tell you whether the operation happened, so clients must retry
- Exactly-once effect comes from at-least-once delivery plus idempotent processing
- Store the idempotency key and result atomically with the side effect
- Conditional updates with version checks prevent races such as overselling
Sign in to track lessons and earn badges.