Networks lose messages, and a sender that hears nothing back can't tell whether its request was lost, its reply was lost, or the other side is just slow. It can retry and risk doing the work twice, or give up and risk not doing it at all. Delivery guarantees (at-most-once, at-least-once, effectively-once) name the choice, and idempotency is what makes retrying safe: with idempotency keys, deduplication tables, the outbox and inbox patterns and Kafka's transactional producer, a message may arrive many times but take effect exactly once.
Think of it like
The elevator button and the numbered check
Pressing an elevator call button ten times has the same effect as pressing it once: that is idempotency. Paying a bill by handing over cash is not; hand it over twice and you've paid twice. Checks fix this with a number: if the same check number is presented twice, the bank pays only once. An idempotency key is that check number for an API call.
Lost or duplicated: the sender can't tell
A client sends POST /payments and the request times out. Three very different things may have happened: the request never arrived, the server charged the card but the response was lost, or the server is still working. From the client's side all three look identical. Retrying fixes the first case and double charges in the second; not retrying fixes the second and loses the payment in the first.
- Clients and SDKs retry after timeouts, often automatically.
- Proxies, load balancers and service meshes retry failed or slow upstream calls.
- Message brokers redeliver when an acknowledgment is missing: an SQS visibility timeout expires, a RabbitMQ channel closes, a Kafka consumer group rebalances.
- Producers resend after a lost broker acknowledgment, and outbox relays republish after a crash.
- Humans double-click, refresh, and press back then submit again.
- Operators replay a topic or reprocess a day of data after fixing a bug.
Delivery semantics
At-most-once
- Send once, never retry; or acknowledge before processing
- No duplicates, but messages can be lost
- Cheapest and lowest latency
- Fine for metrics samples, logs you can lose, live video frames
At-least-once
- Retry until acknowledged; acknowledge only after processing
- Nothing is lost, but duplicates are normal
- The default for SQS standard queues, RabbitMQ with acks and most Kafka consumers
- Requires idempotent processing
Effectively-once
- At-least-once delivery plus deduplication or idempotent effects
- Each message's effect happens once, even if it is delivered twice
- Or: commit the effect and the progress marker atomically in one system
- What "exactly-once" in product docs actually means
| Guarantee | How it is built | Failure mode | Examples |
|---|---|---|---|
| At-most-once | No retries; consumer commits its offset before processing | Loss on any crash or dropped packet | UDP telemetry, Kafka producer with acks=0 |
| At-least-once | Retries with acknowledgments; consumer commits after processing | Duplicates after timeouts, crashes and rebalances | SQS standard, Kafka consumers, webhooks, AWS Lambda async invocations |
| Effectively-once | At-least-once plus idempotency keys, dedup tables or transactions | Duplicates outside the dedup window or outside the transactional boundary | Stripe API, SQS FIFO deduplication, Kafka transactions, Flink checkpoints |
Why exactly-once delivery is impossible
The Two Generals problem shows that two parties communicating over an unreliable channel can never be certain they agree: every acknowledgment would itself need acknowledging. For message processing the trap is concrete. A consumer has to do two things, apply the message's effect and tell the sender it is done, and those two things happen in different systems that can't commit together.
- 1
Process, then acknowledge
The consumer applies the effect and crashes before its acknowledgment goes out. The broker redelivers and the effect happens twice: at-least-once.
- 2
Acknowledge, then process
The consumer acknowledges and crashes before applying the effect. The broker considers the message done and it is lost: at-most-once.
- 3
No third order exists
Whatever the order, there is a moment between the two steps where a crash leaves them inconsistent. Faster code shrinks the window but never closes it.
Idempotent operations
An operation is idempotent if applying it several times has the same effect as applying it once. HTTP defines GET, HEAD, PUT, DELETE, OPTIONS and TRACE as idempotent (RFC 9110), which is why proxies may retry them; POST and PATCH are not. Many operations can be made naturally idempotent by stating the desired result instead of a change.
| Operation | Idempotent? | How to make retries safe |
|---|---|---|
SET balance = 100 | Yes | Already safe, but it can overwrite a concurrent change; pair it with a version check |
balance = balance + 100 | No | Record the operation ID in a dedup table in the same transaction |
INSERT INTO orders ... | No | Use a client-supplied ID with a unique constraint, or INSERT ... ON CONFLICT DO NOTHING |
UPDATE orders SET status = 'SHIPPED' WHERE id = 7 AND status = 'PAID' | Yes | A guarded state transition: retries match zero rows |
DELETE /items/7 | Yes | The second call may return 404, but the resulting state is the same |
| Charge a card, send an email | No | An idempotency key checked before the side effect, passed downstream where supported |
Idempotency keys
Stripe popularized a simple contract for non-idempotent APIs. The client generates a unique key (a UUID) for each logical operation and sends it in an Idempotency-Key header. The server stores the key with the response of the first request; any later request with the same key gets the stored response replayed, without repeating the work. The same header is being standardized by the IETF in a draft that also suggests status codes for misuse.
POST /v1/payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 5f1c7e0a-8f7d-4b8e-9a51-3c2d0e6f4b21
{"amount": 4999, "currency": "usd", "order_id": "o-981"}
HTTP/1.1 201 Created
Content-Type: application/json
Idempotent-Replayed: true
{"id": "pay_7Hq2", "status": "succeeded", "amount": 4999}- 1
Claim
Insert (account, key, request hash, status
started) under a unique constraint. Exactly one concurrent request wins. - 2
Check
If the key exists: a different request hash means the key was reused for another operation (422); status
startedmeans the original is still running (409); statuscompletedmeans replay the stored response. - 3
Execute
Do the work. Pass the key (or one derived from it) to downstream services that support idempotency.
- 4
Record
Save the response on the key row in the same transaction as the business change, so neither can exist without the other.
- 5
Release or expire
If execution fails before any side effect, delete the claim so the client can retry. Purge keys after a retention window (Stripe documents at least 24 hours).
CREATE TABLE idempotency_keys (
account_id BIGINT NOT NULL,
idem_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'started', -- started | completed
response_code INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, idem_key) -- keys are scoped per client
);
-- Claim: returns a row only for the request that wins
INSERT INTO idempotency_keys (account_id, idem_key, request_hash)
VALUES (42, '5f1c7e0a-8f7d-4b8e-9a51-3c2d0e6f4b21', 'sha256:9b1d...')
ON CONFLICT (account_id, idem_key) DO NOTHING
RETURNING 1;
-- Retention: run periodically
DELETE FROM idempotency_keys WHERE created_at < now() - interval '24 hours';When the side effect is outside your database
The card charge can't join your database transaction, so a crash between charging and recording leaves a started key with an unknown outcome. Three tools close the gap: pass an idempotency key downstream so retrying the charge is itself safe; split the handler into atomic phases with recorded recovery points, so a retry resumes from the last completed phase; and run a reconciliation job that compares your records with the processor's and fixes stragglers. Payment systems use all three; see Design a Payment System.
Deduplicating consumers
On the consuming side the pattern is an idempotent consumer: every message carries a unique ID assigned by the producer, and the consumer records processed IDs. The record must be written in the same transaction as the message's effect. Recording first and processing second (or the reverse) reopens exactly the crash window that made exactly-once delivery impossible.
Dedup table in the same database
- Insert the message ID and apply the effect in one transaction
- A unique constraint rejects duplicates, even concurrent ones
- Strongest option; the default choice
- Needs periodic cleanup of old IDs
Redis SET NX with a TTL
SET dedup:<id> 1 NX EX 86400before processing- Fast and self-expiring
- Not atomic with a database effect: a crash after SET loses the message
- Fine when the effect is itself in Redis, or a rare duplicate is tolerable
Broker-level deduplication
- SQS FIFO drops repeats of a deduplication ID within 5 minutes
- Kafka's idempotent producer drops resent batches within one producer session
- Covers only the hop into the broker
- Consumers still see redeliveries after crashes and rebalances
Whatever the store, size the dedup window to the longest gap between two deliveries of the same message: client retry horizons, broker redelivery delays, and any replay you might do by hand. A duplicate that arrives after its ID has expired is processed again. A Bloom filter can screen IDs cheaply (see Bloom Filters & Probabilistic Structures), but on its own it would discard a few legitimate messages as false positives, so confirm "maybe seen" against an exact store.
Outbox and inbox
Together, the two patterns make an at-least-once pipeline behave exactly-once end to end. The transactional outbox (covered in Distributed Transactions) writes the event into the producer's database in the same transaction as the state change, and a relay publishes it afterward. The inbox is the consumer-side mirror: the consumer records each event ID in an inbox table in the same transaction as its effect.
Kafka: idempotent producer and transactions
Kafka attacks duplicates at two levels. The idempotent producer gets a producer ID from the broker and numbers every batch per partition; if a retry resends a batch the broker already wrote, the broker recognizes the sequence number and drops it, and out-of-order sequences are rejected. Since Kafka 3.0 it is on by default (enable.idempotence=true with acks=all). It covers retries within one producer session only, not an application that restarts and sends the same record again.
Transactions (Kafka 0.11+) go further for read-process-write pipelines. A producer with a stable transactional.id can write to several partitions and commit the consumer offsets of its input in one atomic transaction. Consumers with isolation.level=read_committed never see records from aborted transactions, and a restarted instance with the same transactional ID fences off its zombie predecessor. Kafka Streams wraps all of this in one setting: processing.guarantee=exactly_once_v2.
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.ProducerFencedException;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
public class OrderEnricher {
public static void main(String[] args) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "order-enricher-1"); // stable per instance; implies idempotence
KafkaProducer<String, String> producer = new KafkaProducer<>(p, new StringSerializer(), new StringSerializer());
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
c.put(ConsumerConfig.GROUP_ID_CONFIG, "order-enricher");
c.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); // skip aborted writes
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(c, new StringDeserializer(), new StringDeserializer());
consumer.subscribe(List.of("orders"));
producer.initTransactions(); // fences any older producer with the same transactional.id
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
if (records.isEmpty()) continue;
producer.beginTransaction();
try {
Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
for (ConsumerRecord<String, String> r : records) {
producer.send(new ProducerRecord<>("orders-enriched", r.key(), enrich(r.value())));
offsets.put(new TopicPartition(r.topic(), r.partition()), new OffsetAndMetadata(r.offset() + 1));
}
producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata());
producer.commitTransaction(); // outputs and offsets become visible together
} catch (ProducerFencedException e) {
producer.close(); // a newer instance owns this transactional.id: stop
throw e;
} catch (KafkaException e) {
producer.abortTransaction();
// Rewind to the last committed offsets so the batch is processed again
consumer.committed(consumer.assignment()).forEach((tp, om) -> {
if (om != null) consumer.seek(tp, om.offset());
else consumer.seekToBeginning(List.of(tp));
});
}
}
}
static String enrich(String order) {
return order; // look up customer data, compute totals, ...
}
}Retries with backoff and jitter
Idempotency makes retries safe; backoff makes them polite. Retrying immediately and in lockstep turns a brief outage into a retry storm that keeps the dependency down. The standard recipe is exponential backoff with random jitter, a cap, and a limit on attempts (see Resilience Patterns).
- Retry only what is safe: idempotent methods, or requests that carry an idempotency key.
- Retry only what can succeed: timeouts, connection errors, 429 and 5xx (or 409 while a keyed request is in progress); never 400-class validation errors.
- Honor
Retry-Afterwhen the server sends it. - Retry at one layer: if the SDK, the service mesh and the caller each retry 3 times, one failure becomes 27 attempts.
- Budget retries (for example, at most 10% extra traffic), and send what still fails to a dead-letter queue for inspection.
Implementation
Claims the key, replays stored responses, and saves the new response in the same transaction as the business change. Uses the `idempotency_keys` table above.
import hashlib
import json
from typing import Any, Callable
import psycopg
from psycopg.types.json import Jsonb
Result = tuple[int, Any]
def with_idempotency(
conn: psycopg.Connection, # opened with autocommit=True
account_id: int,
key: str,
request: dict,
handler: Callable[[psycopg.Cursor], Result],
) -> Result:
req_hash = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
claimed = conn.execute(
"INSERT INTO idempotency_keys (account_id, idem_key, request_hash) VALUES (%s, %s, %s) "
"ON CONFLICT DO NOTHING RETURNING 1",
(account_id, key, req_hash),
).fetchone()
if claimed is None:
row = conn.execute(
"SELECT request_hash, status, response_code, response_body FROM idempotency_keys "
"WHERE account_id = %s AND idem_key = %s",
(account_id, key),
).fetchone()
if row is None:
return 409, {"error": "retry: the original request just failed"}
if row[0] != req_hash:
return 422, {"error": "key reused with a different request"}
if row[1] != "completed":
return 409, {"error": "original request still in progress"}
return row[2], row[3] # replay: no side effects
try:
with conn.transaction(), conn.cursor() as cur:
status, body = handler(cur)
cur.execute(
"UPDATE idempotency_keys SET status = 'completed', response_code = %s, response_body = %s "
"WHERE account_id = %s AND idem_key = %s",
(status, Jsonb(body), account_id, key),
)
return status, body
except Exception:
conn.execute(
"DELETE FROM idempotency_keys WHERE account_id = %s AND idem_key = %s AND status = 'started'",
(account_id, key),
)
raiseKey takeaways
- A timed-out request may have failed, succeeded, or still be running; the sender can't tell, so it must choose between possible loss and possible duplicates.
- At-most-once loses messages, at-least-once duplicates them; exactly-once delivery is impossible, but an exactly-once effect is achievable.
- Effectively-once = at-least-once delivery + idempotent processing, or effect and progress committed atomically inside one system.
- Idempotency keys let clients retry non-idempotent APIs safely: claim the key, replay the stored response, and record results in the same transaction as the work.
- Consumers deduplicate by message ID in the same transaction as the effect; outbox (producer) plus inbox (consumer) make pipelines safe end to end.
- Kafka's idempotent producer and transactions give exactly-once within Kafka only; side effects elsewhere still need idempotency.
Common pitfalls
- Generating a new idempotency key on every retry, which turns each retry into a new operation.
- Recording the processed message ID and applying the effect in separate transactions, reopening the crash window.
- Expiring dedup records sooner than the longest possible redelivery or retry delay.
- Retrying non-idempotent calls at several layers at once and multiplying load (and duplicates) during an outage.
- Believing a broker's "exactly-once" setting covers database writes, emails and API calls made by the consumer.
Interview tips
- Whenever your design retries, say what makes the retried operation idempotent.
- For payments and orders, describe the idempotency key flow end to end, including concurrent duplicates and the key's retention.
- Correct "exactly-once delivery" to "at-least-once delivery with idempotent processing" and explain the crash window that forces it.
Real-world applications
- Payment APIs (Stripe, Adyen, PayPal) accepting idempotency keys on charge and refund calls.
- Webhook receivers deduplicating redelivered events by event ID.
- Kafka Streams and Flink pipelines running with exactly-once processing guarantees.
- Order and inventory services using outbox and inbox tables around a message broker.
- Serverless functions on at-least-once triggers (SQS, EventBridge) that must tolerate duplicate invocations.
Test yourself
A client's POST times out. Which statement is true?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.