Summary#
Networks drop packets, brokers crash and consumers die mid-task, so every messaging system must decide what happens to a message when something fails. At-most-once means a message is delivered zero or one times: fast, but messages can be lost. At-least-once means a message is delivered one or more times: nothing is lost, but duplicates happen. Exactly-once delivery over a network is impossible in general, but exactly-once processing (better called effectively-once) is achievable: at-least-once delivery plus idempotent consumers or deduplication, or a transactional system such as Kafka transactions where the read, the processing and the write commit together. Ordering is usually only guaranteed per partition or per key. Kafka can lose messages through weak producer acks, too few replicas, unclean leader election or early offset commits; acks=all, replication factor 3 and min.insync.replicas=2 prevent most of it. To publish reliably from a database, use the outbox pattern.
Why It Exists#
Every message passes through three hops: producer to broker, broker storage, and broker to consumer. Each hop has a moment where one side has done its work and the other does not know yet. If the producer sends a message and the acknowledgement is lost, the producer cannot tell whether the broker stored it. It must either resend (and risk a duplicate) or give up (and risk a loss). The same choice happens when a consumer crashes between doing the work and committing its offset. You cannot remove this choice; you can only choose which side to fail on, and then make the other side harmless. For payments, inventory and counters, that choice decides whether a customer is charged twice or not at all. This page builds on Pub/Sub and Event Streaming.
How It Works#
Where messages are lost or duplicated#
Every guarantee is a choice about these windows.
Failure windows, in depth#
The diagram above shows four places where a message can go wrong. It helps to name each one precisely, because every config flag and design pattern on this page closes exactly one of them.
Window 1: producer to broker. The producer sends a batch and starts a timer. Three things can happen. The broker stores the batch and the ack arrives (good). The broker never receives the batch (the producer times out and must resend). Or the broker stores the batch, but the ack is lost or arrives after the timeout. From the producer's side, the last two cases look identical. This is the heart of the problem: a timeout tells you nothing about whether the other side acted. A producer that resends in both cases creates duplicates in the third case. A producer that never resends loses data in the second case.
Window 2: inside the broker. The broker accepted the message, but where does it live? In the page cache of one machine? On the disks of three machines in three availability zones? If the leader acknowledges before its followers copy the data, and then the leader dies, the new leader never had the message. The message was acknowledged and still lost. This window is closed by replication settings, not by application code.
Window 3: broker to consumer. The consumer fetches a message, processes it, and then tells the broker "done" (an ack in RabbitMQ or SQS, an offset commit in Kafka). If it tells the broker before processing and then crashes, the message is lost. If it tells the broker after processing and crashes in between, the message is redelivered and processed twice.
Window 4: consumer to side effect. Even with a perfect broker, the consumer's own work may be several steps: write a row, call a payment API, send an email. A crash between step two and step three leaves a half-done effect. Retrying the whole message redoes steps one and two.
A worked number. Suppose a service publishes 10,000 messages per second and 0.01% of acks time out (one in ten thousand, a realistic rate on a busy network during deploys and broker restarts). That is one ambiguous send per second, or 86,400 per day. Without dedup, a "rare" duplicate becomes tens of thousands of duplicate rows a day. Now suppose consumers restart during a deploy every day and each restart redelivers the last 5 seconds of uncommitted work at 2,000 messages per second per consumer across 20 consumers: that is 200,000 redeliveries per deploy. Duplicates are not an edge case; they are routine traffic.
Why you cannot simply "ask again". A natural idea is: after a timeout, ask the broker "did you get message 17?" before resending. That helps, but the answer to that question can also be lost, and the broker could be in the middle of storing message 17 when you ask. Some systems do implement this pattern (the Kafka idempotent producer is essentially the broker remembering "I already have sequence 17 from you"), but it only works because the broker keeps state about the producer. The general lesson: removing ambiguity always needs state on the receiving side, either a sequence number, a message ID table, or a version number on the data.
At-most-once#
The system never retries. The producer sends once without waiting for a durable ack (acks=0, or ignoring errors), or the consumer commits before processing. If anything fails, the message is gone.
- Gain: lowest latency and overhead, no duplicates.
- Fits: metrics samples, logs at very high volume, sensor readings where the next value replaces the last, live video frames.
- Never for: orders, payments, anything a user expects to persist.
At-most-once, in depth#
At-most-once is often presented as the "bad" option, but it is the right choice in more places than people expect, and it is what you get by accident in many systems.
Where it appears on purpose. StatsD clients send metrics over UDP: no ack, no retry, no connection. If a packet is dropped, one counter increment is lost, and a dashboard showing 10,412 requests per second instead of 10,413 is still correct for every decision anyone makes. Syslog over UDP, game-state updates in multiplayer games (the next update replaces the lost one 50 ms later), live video frames (a retransmitted frame would arrive after it is useful), and Redis Pub/Sub (a disconnected subscriber simply misses messages) all choose at-most-once because a late or duplicated message is worse than a missing one.
Where it appears by accident. Many "reliable" systems quietly become at-most-once:
- A Kafka consumer with auto-commit enabled hands messages to a background thread pool and returns to
poll(). The next poll commits the offsets, even though the threads have not finished. A crash loses the in-flight work. - An SQS consumer deletes the message as soon as it receives it, "to avoid duplicates", and then processes it.
- A service publishes events with fire-and-forget code such as
producer.send(record)without checking the returned future or callback. Errors are logged at debug level and never seen. - A producer buffers records in memory (
linger.ms,batch.size) and the process is killed withSIGKILLduring a deploy. Every buffered record that was never sent is gone, even though the application code "sent" it.
Quantifying the loss. At-most-once loss rate equals the failure rate in the windows above. With a well-run broker, producer-side loss is roughly the rate of process crashes multiplied by the amount of buffered data. A producer that buffers 50 ms of data at 5,000 messages per second holds about 250 messages. If it crashes once a week, you lose about 250 messages a week, or roughly one in 12 million. For click analytics, that is noise. For an order pipeline, that is 250 angry customers.
Sampling is a cousin of at-most-once. High-volume telemetry systems often sample deliberately (keep 1% of traces). Once you sample, an extra 0.001% random loss changes nothing. If the data is already approximate, paying for at-least-once delivery buys nothing.
When duplicates are worse than loss. Some counters are additive and have no natural ID: a raw "+1" from a sensor. With at-least-once delivery and no IDs, every redelivery inflates the count. If you cannot add an ID, at-most-once gives you an undercount, while at-least-once gives you an overcount. For billing, overcounting is worse (you charge customers for usage they never had); for fraud signals, undercounting is worse. Make that choice consciously.
At-least-once#
The producer retries until it gets an ack, and the consumer commits only after processing. Nothing is lost while the broker's storage survives, but any failure between "work done" and "ack recorded" causes a redelivery.
- Gain: no loss.
- Cost: duplicates, so consumers must tolerate them.
- Fits: almost everything. This is the default for SQS, RabbitMQ with manual acks, Kafka with manual commits, and Google Pub/Sub.
At-least-once, in depth#
At-least-once has two halves. The producer half says: keep resending until the broker confirms durable storage. The consumer half says: confirm only after the work is done. Both halves are needed. A producer that retries correctly is useless if the consumer acks early, and vice versa.
Retry policy. Retries need limits and spacing. A common policy is exponential backoff with full jitter: wait a random time between 0 and min(cap, base * 2^attempt). With base 100 ms and a cap of 30 s, attempts happen at roughly 0-100 ms, 0-200 ms, 0-400 ms and so on. Jitter matters: if 5,000 producers all lose their connection when a broker restarts and all retry at exactly 100 ms, 200 ms and 400 ms, the broker gets 5,000 requests in the same instant every time. Random spacing turns those spikes into a smooth load. The retry budget should be bounded by time, not just by count (Kafka's delivery.timeout.ms, default 120 seconds), so a message is either delivered or reported as failed within a known time.
What happens after the last retry. At-least-once is a promise only while the producer keeps trying. When retries are exhausted, the application must do something: fail the user request, write the message to a local spool file and replay it later, or raise an alert. Silently dropping it after the last retry turns at-least-once back into at-most-once.
Redelivery on the consumer side. Brokers implement redelivery in different ways:
- SQS hides a received message for a visibility timeout (default 30 seconds). If the consumer does not delete it in time, it becomes visible again and another consumer receives it.
ApproximateReceiveCounttells you how many times it has been delivered; a redrive policy moves it to a dead-letter queue after N receives. - RabbitMQ redelivers unacked messages when the consumer's channel closes, and sets the
redeliveredflag. - Kafka has no per-message ack. A consumer resumes from the last committed offset, so everything after that offset is re-read after a crash or rebalance.
- Redis Streams keep a pending entries list per consumer group;
XAUTOCLAIMlets another consumer take over entries idle longer than a threshold.
Poison messages. A message that crashes the consumer every time it is processed will be redelivered forever, blocking a Kafka partition or burning CPU in a queue. At-least-once systems need a dead-letter queue (DLQ): after N failed attempts, move the message aside, alert, and keep going. Then a human or a repair job inspects and replays it.
At-least-once execution in a job scheduler
A distributed job scheduler (see Design a Distributed Job Scheduler) has the same problem in a different shape: a job is due at 09:00, a worker picks it up, and the worker dies halfway. The job must run again, so execution is at-least-once, and jobs must be safe to re-run. The standard mechanism is a lease:
- A worker claims a due job with an atomic update, for example
UPDATE jobs SET status='running', lease_until=now()+interval '60 seconds', owner='w17', attempt=attempt+1 WHERE id=$1 AND status='queued'. In Postgres, many workers can claim different jobs at once withSELECT ... FOR UPDATE SKIP LOCKED. - While it works, the worker heartbeats, extending
lease_untilevery 20 seconds. - If the worker dies, heartbeats stop. A sweeper finds rows where
status='running' AND lease_untilis in the past, and puts them back toqueued. - When the worker finishes, it sets
status='succeeded'only if it still owns the lease (WHERE owner='w17' AND attempt=3).
The dangerous case is a worker that is not dead, only slow (a long garbage-collection pause or a network partition). Its lease expires, a second worker starts the same job, and then the first wakes up and keeps going. Now two copies run at the same time. Leases cannot prevent this on their own. The fix is a fencing token: the attempt number is passed to every downstream write, and the downstream system rejects writes carrying an older attempt number than the one it has already seen. Martin Kleppmann popularised this argument in his 2016 critique of Redis-based locks; the same idea applies to any lease. Jobs that send emails or charge cards also need idempotency keys derived from the job ID and the scheduled run time (for example job-881:2026-12-02T09:00Z), so a second run of the same occurrence is a no-op at the provider.
Exactly-once and effectively-once#
True exactly-once delivery would need the sender to know for certain whether the receiver got a message. Over an unreliable network, with failures possible at any moment, that is impossible in general (the Two Generals problem). What systems offer is exactly-once processing: the effect of each message is applied once, even though the message may be delivered more than once. "Effectively-once" is the more honest name. There are two ways to get it:
- At-least-once + idempotent processing (works across any systems): duplicates arrive, but applying them again changes nothing.
- Atomic read-process-write inside one system: the output and the consumer's offset are committed in one transaction, so a crash either keeps both or neither. Kafka transactions do this when both the input and output are Kafka topics; Flink does it with checkpoints and two-phase-commit sinks.
Exactly-once never extends to arbitrary side effects outside the transaction. If a consumer sends an email or calls a payment API, Kafka transactions cannot undo that call. That edge needs idempotency (an idempotency key on the payment API call).
Exactly-once, in depth#
"Exactly-once" is the most argued-about phrase in messaging, mostly because people mean different things by it. Separate three claims:
- Exactly-once delivery: the message crosses the network to the receiver exactly one time. Impossible to guarantee in general, as shown below.
- Exactly-once processing inside one system: the system's state reflects each input exactly once, even if inputs were read more than once. Achievable with transactions or snapshots.
- End-to-end exactly-once effect: the whole pipeline, including databases and external APIs, behaves as if every message were applied once. Achievable only if every boundary is idempotent or transactional.
Why exactly-once delivery is impossible. The Two Generals problem makes this concrete. Two armies must attack at the same time, and they can only communicate by messengers who may be captured. General A sends "attack at dawn". A cannot be sure B got it, so B sends an acknowledgement. Now B cannot be sure the ack arrived, so A must ack the ack, and so on. Any finite protocol has a last message. If that last message can be lost, the sender of it cannot know whether the other side will act, so removing the last message cannot change what either side does, and by induction neither can any message. Delivery is the same: the sender of the last message in any protocol is uncertain. The proof does not say reliable systems are impossible. It says certainty about the other side's state after a finite exchange is impossible, so you must tolerate repeats or losses.
The end-to-end argument. In "End-to-End Arguments in System Design" (Saltzer, Reed and Clark, 1984), the authors argue that correctness guarantees such as "the file arrived intact" can only be fully provided by the endpoints of the system, because any layer in the middle can be bypassed by failures above it. Messaging follows directly. Even if the broker delivered a message exactly once to the consumer process, the consumer can still crash after writing to the database and before replying, and the client upstream retries the whole request. The only place that can truly detect a duplicate is the final point where the effect is applied, using an ID that travels end to end.
How exactly-once processing works inside a system. The trick is always the same: make "record the input as consumed" and "apply the output" one atomic step.
- Offsets stored with the output. A consumer writing to Postgres can store the Kafka offset in the same table or transaction as the result:
UPDATE consumer_offsets SET offset=5021 WHERE topic_partition='orders-3'in the same transaction as the business write. On restart, it reads its offset from Postgres, not from Kafka, and seeks there. A crash rolls back both or keeps both. Several Kafka Connect sink connectors work this way. - Kafka transactions. The consumer's offsets and the produced output records commit together through the transaction coordinator, as described in the deep dive below.
- Checkpointed state plus transactional sinks. Apache Flink periodically takes a consistent snapshot of all operator state and source offsets, using checkpoint barriers that flow through the dataflow graph. The approach is described in "Lightweight Asynchronous Snapshots for Distributed Dataflows" (Carbone et al., 2015) and builds on the Chandy-Lamport snapshot algorithm (1985). On failure, every operator rewinds to the last snapshot together, so internal state counts each input once. Output to Kafka or files is written in a pre-committed state and only made visible when the checkpoint completes (a two-phase commit).
- Record IDs and dedup at every stage. Google's MillWheel ("MillWheel: Fault-Tolerant Stream Processing at Internet Scale", Akidau et al., VLDB 2013) gives each record a unique ID and checks it against stored IDs at each stage, using Bloom filters to make the "never seen" case cheap. State updates and the record of processed IDs are committed atomically per key. The same ideas carried into Google Cloud Dataflow.
What exactly-once costs. Every approach adds coordination. Kafka transactions add commit round trips and make read_committed consumers wait for open transactions. Flink's exactly-once output is visible only after a checkpoint, so end-to-end latency is at least the checkpoint interval (often 10 seconds to 1 minute). Dedup tables add a write per message. In practice, teams often run pipelines as at-least-once with idempotent sinks: simpler, lower latency, and the same final result.
Idempotent consumers#
An operation is idempotent if doing it twice has the same effect as doing it once. Make consumers idempotent by design:
- Natural idempotency:
SET balance_snapshot = 120or an upsert keyed by entity ID is safe to repeat;balance = balance + 20is not. - Conditional writes with versions:
UPDATE orders SET status='shipped', version=8 WHERE id=42 AND version=7. A replay of the same event finds version 8 and changes nothing. - Processed-message table in the same transaction as the business write (below).
- Idempotency keys on external calls: pass the message ID as the
Idempotency-Keyto payment providers such as Stripe so a retried call does not charge twice. See Idempotency.
Idempotent consumers, in depth#
Making a consumer idempotent starts with classifying what it does. Each kind of operation has a different standard fix.
| Operation kind | Example | Idempotent as written? | Standard fix |
|---|---|---|---|
| Absolute set | status = 'shipped' | Yes, if events arrive in order | Add a version check for out-of-order events |
| Upsert by key | INSERT ... ON CONFLICT (id) DO UPDATE | Yes | None needed |
| Increment or decrement | stock = stock - 1 | No | Processed-ID table, or turn it into a set of rows |
| Append | Insert a new ledger row | No | Unique constraint on (source_event_id) |
| External call | Charge a card, send an SMS | No | Idempotency key at the provider, or a pending/done record |
| Fan-out | Publish three follow-up events | No | Deterministic child IDs derived from the parent ID |
Turn deltas into facts. An increment is not idempotent, but "event 7f3a reserved 1 unit of item 42" is a fact that can be stored once with a unique key. Stock is then the sum over facts, or a counter updated in the same transaction as inserting the fact. Ledgers in payment systems are built this way: every entry has a unique ID tied to its cause, so a replay hits a unique-constraint violation instead of double-booking. See Design a Payment System.
Use state machines. If an order moves created -> paid -> shipped, then an event "mark paid" is applied only when the current state is created. A duplicate finds the state already paid and does nothing. A late duplicate after shipped is also rejected. A transition table is both a business rule and a dedup mechanism.
Concurrent duplicates. Two consumers can receive the same message at the same moment, for example after an SQS visibility timeout expires while the first consumer is still working. Code that does "check whether processed, then process, then mark processed" has a race: both checks pass. The fix is to let the database decide atomically: insert the processed ID first with a unique constraint inside the transaction, and let the loser get a conflict and roll back. SELECT ... FOR UPDATE on the entity row is another option, serialising work per entity.
When the effect is not in your database. If the consumer calls an external API, you cannot put the API call inside your database transaction. The usual pattern has three steps:
- In a transaction, insert a record
(message_id, status='pending'). If it already exists withstatus='done', stop. - Call the API with
Idempotency-Key: message_id. A provider that supports keys returns the original result for a repeated key instead of acting twice. Stripe documents that its keys are kept for at least 24 hours. - Update the record to
status='done'with the provider's response.
If the consumer crashes between step 2 and step 3, the retry repeats step 2 with the same key and gets the stored result. If the provider has no idempotency support (many SMS gateways and legacy bank APIs), you cannot achieve exactly-once effect. You choose between "maybe send twice" and "maybe never send", and you add a reconciliation job that compares your records with the provider's reports.
Commutative updates. Some data types make order and duplicates harmless by construction. A set of "user IDs who liked a post" can absorb the same add twice. A max-register ("highest bid seen") ignores old values. CRDTs (conflict-free replicated data types) generalise this: their merge operation is commutative, associative and idempotent, so replicas converge no matter how often or in what order updates are delivered. See Conflict Resolution, OT and CRDTs.
Deduplication#
Deduplication detects and drops messages already seen, using a unique message ID set by the producer (not by the broker, which may assign a new ID to a resend).
-- Consumer: record the message ID and apply the effect in ONE transaction
BEGIN;
INSERT INTO processed_messages (message_id, processed_at)
VALUES ('evt-7f3a', now())
ON CONFLICT (message_id) DO NOTHING; -- 0 rows inserted => duplicate
-- only if 1 row was inserted:
UPDATE accounts SET balance = balance - 20 WHERE id = 42;
COMMIT;
-- purge processed_messages older than the max redelivery window (e.g. 7 days)Where dedup happens:
| Layer | Mechanism | Window |
|---|---|---|
| Producer to broker | Kafka idempotent producer (producer ID + sequence numbers per partition) | Per producer session |
| Broker | SQS FIFO deduplication ID | 5 minutes |
| Consumer | Processed-ID table, unique constraint, or Redis SET id NX EX 86400 | You choose; must cover replays |
| Sink | Upsert by key, versioned writes | Forever |
A Redis dedup set is fast but is not atomic with the database write: if the consumer crashes between the two, the message is either reprocessed or skipped. Keep the dedup record in the same transaction as the effect whenever the effect is in a database.
Deduplication, in depth#
Dedup has three design questions: what is the key, where is it stored, and how long is it kept.
Choosing the key. The key must be the same for every copy of the same logical message and different for every distinct message.
- Producer-assigned random IDs (UUIDv4, or UUIDv7, which is time-ordered and indexes better) catch transport-level duplicates: retries, redeliveries, replays. They do not catch an upstream service that sends the same business event twice under two different IDs.
- Deterministic business keys catch both:
order-881:payment-captured, oruser-42:password-reset:2026-12-02T10:15. Build them from fields that define "the same thing happened". Too coarse a key wrongly merges distinct events (two genuine password resets a minute apart); too fine a key lets duplicates through. - Content hashes (SHA-256 of the normalised payload) are useful when you cannot change the producer, but two genuinely separate identical events (two identical orders) will be merged.
See Unique ID Generation for ID schemes.
Sizing the dedup store. Suppose 5,000 messages per second, a 7-day window, and 40 bytes per entry (a 16-byte UUID, a timestamp, and index overhead in a compact store). That is 5,000 x 86,400 x 7 = about 3 billion entries, or around 120 GB. That is large for Redis but fine for a partitioned database table with time-based partitions (drop a whole day's partition instead of deleting rows). With a 24-hour window, the same traffic needs about 17 GB, which fits in a Redis cluster. The window must be longer than the longest possible redelivery or replay. If you ever replay Kafka from 7 days ago, a 24-hour dedup window will not protect you.
Bloom filters for the fast path. A Bloom filter answers "definitely not seen" or "maybe seen" using a few bits per item. For a false-positive rate p, it needs about 1.44 x log2(1/p) bits per item: roughly 10 bits per item for p = 1%, and 14 bits for p = 0.1%. Three billion items at 10 bits is about 3.75 GB. The filter cannot be the only check, because a false positive would drop a real message, so use it in front of the exact store: "definitely new" skips the lookup, and "maybe seen" triggers the exact check. Most messages are new, so most exact lookups disappear.
Broker-side dedup windows. Several brokers dedup for a short window. SQS FIFO drops messages with a repeated deduplication ID within 5 minutes. NATS JetStream drops messages with a repeated Nats-Msg-Id header within a configurable duplicate window. Azure Service Bus has a configurable duplicate-detection window. These handle producer retries well, but they do not replace consumer-side idempotency, because consumer redeliveries and replays happen after the broker accepted the message.
Preventing duplicate notifications on top of at-least-once delivery
A notification system (see Design a Notification System) is a classic dedup problem because the side effect, a push, SMS or email, cannot be undone. Users notice a double SMS immediately. Duplicates come from many layers: the upstream service retries its API call, the queue redelivers, a worker crashes after calling the provider, or a campaign job restarts halfway through a segment.
A layered design handles each source:
- API layer. Upstream callers pass an idempotency key, such as
order-881:shipped. The notification service stores it with a unique constraint and returns the original notification ID for a repeat. - Per-delivery key. Each attempt to reach a user on a channel gets a key such as
notif-5531:user-42:sms. Before sending, the worker atomically claims it, for example withSET key 'sending' NX EX 3600in Redis or an insert with a unique constraint. - Mark after send. After the provider accepts the message, update the key to
sentwith the provider message ID. If the worker crashes after the claim but before sending, the claim expires and a retry proceeds. If it crashes after sending but before marking, a retry seessendingand must decide: check the provider's status API if one exists, or accept a small duplicate risk. - Provider-level collapsing. For push notifications, Apple's APNs supports an
apns-collapse-idheader and Firebase Cloud Messaging supports a collapse key, so the device shows only the latest notification with that ID. This does not prevent a second send, but it hides it from the user. - Campaign checkpoints. A campaign over 10 million users records progress per batch (for example, the last user ID processed per shard). On restart, it resumes from the checkpoint, and the per-delivery keys catch users in the partly done batch.
The remaining risk is the crash between "provider accepted" and "marked sent". It is small (milliseconds per send), and you can measure it by counting keys stuck in sending. For most products, a tiny duplicate rate is better than the alternative of sometimes never notifying.
Ordering guarantees#
| Guarantee | Meaning | Where you get it |
|---|---|---|
| None | Any order | SQS standard, parallel workers |
| Per key / per partition | Messages with the same key arrive in send order | Kafka partitions, SQS FIFO message groups, Pub/Sub ordering keys |
| Global (total) order | One sequence for everything | Single partition or single queue; throughput limited to one consumer |
Retries can reorder messages: m1 fails, m2 succeeds, m1's retry lands after m2. In Kafka, the idempotent producer keeps per-partition order with up to 5 in-flight requests. On the consumer side, ordering holds only if one consumer handles a partition sequentially; processing a partition with a thread pool reorders again unless you parallelise by key.
When order cannot be guaranteed end to end, make consumers order-tolerant: include a version or timestamp in each event and ignore events older than the stored state (last-writer-wins by version).
Ordering, in depth#
Ordering and delivery guarantees interact: the mechanisms that prevent loss (retries, redelivery, parallel consumers) are exactly the ones that reorder messages.
How producer retries reorder. A producer pipelines several batches to a partition without waiting for each ack. Batch 1 fails with a transient error, batch 2 succeeds, then batch 1 is retried and lands after batch 2. Before the idempotent producer, the only way to keep order in Kafka was max.in.flight.requests.per.connection=1, which cut throughput sharply because every batch waited one round trip. The idempotent producer fixes this with sequence numbers: the broker rejects batch 2 with an out-of-order error until batch 1 arrives, so up to 5 in-flight batches keep their order.
How redelivery reorders. In a queue with competing consumers, message A goes to consumer 1, which is slow, and message B goes to consumer 2, which finishes first. If A then fails and is redelivered after a 30-second visibility timeout, it is applied a full 30 seconds after B. Queues with ordering (SQS FIFO message groups, RabbitMQ single-active-consumer, Azure Service Bus sessions) prevent this by refusing to hand out the next message of a group until the previous one is acked. That is head-of-line blocking: one slow or poison message stops its whole group. It is the price of ordering.
How rebalances reorder. In Kafka, partition order is kept within one consumer. During a rebalance, the old owner may still be processing messages up to offset 1,300 while the new owner restarts from the committed offset 1,000. For a short time, both are applying the same range. With the cooperative rebalance protocol and careful commit-on-revoke handlers, the overlap shrinks, but consumers still need to tolerate it.
Parallelism without losing order. A partition is consumed by one thread, so per-partition throughput is bounded by one thread's speed. If processing takes 20 ms per message, one partition handles 50 messages per second. To go faster without adding partitions, process per key in parallel: hash the key to one of N in-memory lanes, and each lane processes its keys in order. Confluent's open-source Parallel Consumer library does this and tracks which offsets are complete so it can commit safely. The commit point is the lowest offset not yet done, so a crash redelivers some completed messages, which is fine with idempotent consumers.
Detecting and repairing disorder. When order cannot be guaranteed, carry enough information for the consumer to repair it:
- Per-entity version numbers. The producer stamps each event with the entity's version (order 42, version 8). The consumer stores the last applied version and ignores anything older. Gaps (version 10 arrives when 8 is stored) can be buffered for a short time, or treated as "refetch the full entity from the source".
- Sequence numbers per stream. A consumer that sees sequence 105 after 103 knows 104 is missing or late.
- Logical clocks. Lamport clocks, from "Time, Clocks, and the Ordering of Events in a Distributed System" (Lamport, 1978), give an order consistent with causality without synchronised wall clocks. Vector clocks can also detect when two events are concurrent. See Time, Clocks and Ordering.
- Never trust wall-clock timestamps from different machines for ordering. Clock skew of tens of milliseconds is normal, and NTP corrections can step a clock backwards.
Total order is expensive. A single global sequence requires every message to pass through one serialisation point: one partition, one leader, or a consensus log. One Kafka partition can handle tens of megabytes per second, which is plenty for many control-plane streams but not for a firehose. Systems that truly need total order at scale, such as a stock exchange matching engine, keep the ordered part small (one sequencer per instrument) and partition everything else. See Consensus: Raft and Paxos.
How Kafka can lose messages, and how to prevent it#
| How it loses data | Why | Prevention |
|---|---|---|
Producer acks=0 or acks=1 | With acks=1, the leader acks before followers copy; if it dies, the new leader lacks the message | acks=all: wait for all in-sync replicas |
| Too few replicas | Replication factor 1 means one disk failure loses the partition | replication.factor=3, spread across racks or zones |
| ISR shrinks to the leader alone | acks=all only waits for current in-sync replicas; if only the leader is in sync, it acks alone | min.insync.replicas=2: writes fail (NotEnoughReplicas) rather than ack with one copy |
| Unclean leader election | An out-of-sync replica becomes leader and truncates messages it never had | unclean.leader.election.enable=false (the default) |
| Producer gives up | Retries exhausted or delivery timeout reached, and the app ignores the error | Retry within delivery.timeout.ms; handle send callbacks; alert on failures |
| Consumer commits early | Auto-commit commits offsets on a timer, possibly before processing finishes | enable.auto.commit=false; commit after processing |
| Retention expires | A consumer is down longer than retention.ms | Lag alerts; retention longer than the worst outage |
| Correlated power loss | Kafka acks from page cache, relying on replicas instead of fsync | Replicas in separate zones |
# Producer
acks=all
enable.idempotence=true # default in Kafka 3.0+; dedups retries per partition
delivery.timeout.ms=120000
# Topic / broker
replication.factor=3
min.insync.replicas=2 # tolerate 1 replica down and still accept writes
unclean.leader.election.enable=false
# Consumer
enable.auto.commit=false # commit after processing
isolation.level=read_committed # only when consuming transactional outputWith replication factor 3 and min.insync.replicas=2, the cluster survives one broker failure with no data loss and keeps accepting writes. If two brokers fail, writes are rejected rather than silently stored on one disk.
Kafka message loss, in depth#
The table above lists the ways Kafka loses data. Understanding why each one happens requires a short tour of Kafka replication.
In-sync replicas. Each partition has one leader and some followers. Followers fetch from the leader continuously. The leader keeps an in-sync replica set (ISR): the replicas that have caught up recently. A follower that falls behind for longer than replica.lag.time.max.ms (30 seconds by default in recent versions) is removed from the ISR. The high watermark is the highest offset copied to every member of the ISR. Consumers can only read up to the high watermark, so they never see data that could vanish in a leader failover.
The acks=1 loss, step by step. The leader appends offset 500 and immediately acks the producer. The followers are at offset 498. The leader's machine loses power. The controller elects a follower, which only has data up to 498. The producer has already moved on, believing 499 and 500 are safe. When the old leader comes back, it truncates its log to match the new leader. Offsets 499 and 500 are gone, and nobody gets an error.
Why acks=all alone is not enough. acks=all means "every replica currently in the ISR has it". If both followers fell out of the ISR (a slow disk, a network blip), the ISR is just the leader, and acks=all behaves like acks=1. min.insync.replicas=2 closes this gap: the leader refuses writes when the ISR has fewer than 2 members, and producers get NotEnoughReplicasException and retry. Note that min.insync.replicas has no effect unless producers use acks=all.
The availability trade-off in numbers. With replication factor 3 and min.insync.replicas=2, a partition accepts writes as long as 2 of 3 replicas are healthy. Suppose each broker is independently unavailable 0.1% of the time. The chance that 2 or more of 3 replicas are down at once is about 3 x 0.001 squared, or 3 in a million: around 95 seconds a year per partition. With min.insync.replicas=3, any single broker being down blocks writes, which happens about 0.3% of the time (roughly 26 hours a year). That is why 3 and 2 is the standard choice.
Unclean leader election. If every ISR member is lost, Kafka can either wait for one to come back (unavailable but no loss) or elect an out-of-sync replica (available, but it truncates everything the old ISR had that it lacked). unclean.leader.election.enable=false, the default since Kafka 0.11, chooses waiting. Some teams enable it for disposable topics such as logs, where availability matters more.
Durability without fsync. Kafka acknowledges writes once they are in the page cache of the ISR members, not after fsync. It relies on replicas failing independently. A power outage that hits all three brokers at once (same rack, same power feed) can lose recent writes. Spreading replicas across racks or availability zones with broker.rack is what makes this safe.
Producer-side and consumer-side loss. Brokers are only half the story:
- Records waiting in the producer's buffer (up to
buffer.memory, 32 MB by default) are lost if the process is killed. Callflush()andclose()on shutdown, and handleSIGTERMgracefully. - If
send()callbacks are ignored, failures afterdelivery.timeout.msvanish. Count and alert on them. - With auto-commit and synchronous processing, the offset committed in a
poll()covers only records returned by the previous poll, so it is still at-least-once. It becomes lossy only when processing is handed off to other threads or when batches are acked before downstream writes complete.
Retention as silent loss. A consumer that is down for 8 days on a topic with 7-day retention returns to find that its committed offset no longer exists. With auto.offset.reset=latest, it skips everything it missed, with no error. Alert on consumer lag in time, not only in messages, and keep retention longer than your worst realistic outage.
Publishing reliably from a database: the outbox#
A common source of loss and duplicates is the dual write: a service updates its database and then publishes an event. If it crashes in between, the database changed but no event went out. The transactional outbox fixes this by writing the event to an outbox table in the same database transaction; a relay (or CDC tool such as Debezium) publishes outbox rows to the broker, at least once. Consumers dedupe by event ID. See Change Data Capture and the Outbox Pattern.
The outbox and inbox, in depth#
The outbox turns an unsafe dual write into one local transaction plus an at-least-once relay. Its partner on the consumer side, the inbox, turns at-least-once input into an effectively-once effect. Together they form the standard reliable pipeline between services.
Outbox table shape. A typical outbox row has id (the event ID consumers dedupe on), aggregate_type and aggregate_id (which become the topic and partition key), type, payload as JSON, and created_at. Keep the payload self-contained so consumers do not need to call back for details.
Two ways to relay.
- Polling publisher. A loop runs
SELECT ... FROM outbox WHERE published = false ORDER BY id LIMIT 500, publishes the rows, then marks them published. It is simple, but it adds query load, and the polling interval adds latency (100 ms to 1 s). With several relay instances, useFOR UPDATE SKIP LOCKEDor a single elected leader so rows are not published in parallel out of order. - Log tailing (CDC). Debezium reads the database's write-ahead log (the Postgres WAL or the MySQL binlog) and publishes each outbox insert. Latency is typically tens of milliseconds and there is no polling load. Its outbox event router routes rows to topics by
aggregate_typeand usesaggregate_idas the key. The outbox rows can be deleted right after insertion, since the log already captured them. See Change Data Capture and the Outbox Pattern.
Why the relay is at-least-once. The relay publishes, then records progress (marks rows or commits its log position). A crash between the two republishes the same rows. That is acceptable because every row carries a stable id, and consumers dedupe on it.
Ordering through the outbox. Ordering is preserved per aggregate if (1) events for one aggregate are inserted in commit order, (2) the relay publishes in that order, and (3) the broker key is the aggregate ID. Concurrent transactions can commit in a different order from their insert IDs, so a polling relay ordered by an auto-increment ID can briefly skip a row whose transaction committed late. Log-based CDC avoids this because the log is in commit order.
The inbox. On the consumer side, the inbox table stores (event_id PRIMARY KEY, received_at). The consumer inserts the event ID and applies the business change in one transaction, exactly like the SQL earlier on this page. Some teams store the full payload in the inbox and process it asynchronously, which also gives them an audit trail and a place to retry failures without re-reading the broker.
Cleanup. Outbox rows can be deleted after publishing (or immediately with CDC). Inbox rows must be kept for the dedup window. Partition both tables by day so cleanup is a cheap partition drop rather than a large DELETE that bloats the table.
Alternatives. "Listen to yourself" publishes the event first and has the service update its own database by consuming its own event, which makes the event log the source of truth (see Event Sourcing and CQRS). Distributed two-phase commit between the database and the broker is possible in theory (XA), but it is rarely used, because it couples availability and adds blocking failure modes. See Distributed Transactions: 2PC, Sagas and Outbox.
Worked example: an effectively-once payment pipeline#
Consider an e-commerce checkout. When an order is placed, the payment service must charge the customer exactly once and record the charge in a ledger. Volume is 2,000 orders per second at peak, and every component may crash at any time.
Walk through each crash point:
- Order service crashes after its transaction. The outbox row is committed, so the relay publishes it later. No loss.
- Relay publishes twice. Kafka holds two copies of
evt-91. The worker's first insert succeeds and the second hits the unique key onpayments.event_id. No double charge. - Worker crashes after inserting
pendingbut before calling the provider. Redelivery findspendingand continues with the provider call. The provider has never seen the key, so it charges once. - Worker crashes after the provider charged but before recording
captured. Redelivery findspendingand calls the provider again with the same idempotency key. The provider returns the originalch_77result without charging again. The worker records it. - Worker crashes after recording but before committing the offset. Redelivery finds
capturedand only commits the offset. - The provider call times out. The outcome is unknown. The worker retries with the same key, which is safe. If the provider stays unreachable past the key's retention period, a reconciliation job compares provider reports with
pendingrows instead of blindly retrying.
Capacity of the dedup state. At 2,000 orders per second, the payments table grows by 172.8 million rows per day, and it is the business table, so no separate dedup store is needed: the unique index on event_id is the dedup. That is the cheapest possible design, because the dedup check is the insert you were going to do anyway.
Latency budget. Kafka produce with acks=all across three zones adds roughly 2 to 10 ms. The DB insert is about 2 ms, the provider call 200 to 800 ms, and the final transaction about 3 ms. Effectively-once costs one extra DB round trip (the pending insert) compared with a naive design, under 1% of the end-to-end latency.
What this design does not need. Kafka transactions are not involved. The worker's side effects live in Postgres and at the provider, outside Kafka, so a Kafka transaction would cover nothing useful. Idempotency at each boundary gives the exactly-once effect.
Guarantees across popular systems#
Vendor documentation uses the same words for different things. This table lists what each system actually offers by default and with extra configuration.
| System | Default | Dedup or exactly-once options | Ordering |
|---|---|---|---|
| Apache Kafka | At-least-once with retries and manual commits | Idempotent producer (on by default in 3.0+); transactions for Kafka-to-Kafka | Per partition |
| Amazon SQS standard | At-least-once; occasional duplicates by design | None; consumers must be idempotent | Best effort |
| Amazon SQS FIFO | Exactly-once processing within a 5-minute dedup window | Deduplication ID or content-based dedup | Per message group |
| Amazon Kinesis Data Streams | At-least-once; duplicates from producer retries and consumer restarts | Application-level dedup | Per shard |
| RabbitMQ | At-least-once with publisher confirms and manual acks | None built in; quorum queues for durable replication | Per queue, lost under redelivery with multiple consumers |
| Google Cloud Pub/Sub | At-least-once | Optional exactly-once delivery for pull subscriptions within a region | Optional ordering keys |
| Azure Service Bus | At-least-once (peek-lock) | Duplicate detection with a configurable window | Sessions |
| NATS JetStream | At-least-once with acks | Nats-Msg-Id dedup window; double ack | Per stream |
| Apache Pulsar | At-least-once | Producer dedup by sequence ID; transactions | Per partition or key |
| Redis Streams | At-least-once with consumer groups and XACK | None built in | Per stream |
| Redis Pub/Sub | At-most-once; offline subscribers miss messages | None | Per channel per connection |
Reading these claims critically. Ask three questions of any exactly-once claim. Over what window? SQS FIFO dedups for 5 minutes, so a retry after 6 minutes is a new message. Across which boundary? Kafka transactions cover Kafka topics and offsets, not your database. Under which failures? A regional exactly-once guarantee does not survive a cross-region failover. If the answer to any of these does not cover your flow, you still need idempotent consumers.
Throughput costs. Ordering and dedup features have limits. SQS FIFO supports up to 300 API calls per second per action without batching, up to 3,000 messages per second with batches of 10, and higher limits in high-throughput mode. Kafka transactions add commit markers and reduce throughput if commits are very frequent. Single-active-consumer queues process one message at a time per queue. Check these limits before choosing a system for ordered, deduplicated traffic.
Testing and monitoring delivery guarantees#
Delivery guarantees fail only under failure, so normal tests never exercise them. You have to cause failures on purpose and check invariants.
Invariant checks. Choose properties that must hold, then verify them after a chaos run:
- No loss: every ID the producer was told succeeded appears in the sink.
- No duplicate effect: no ID appears in the sink twice (or the business totals match the number of unique inputs).
- Order: for each key, the sink's version sequence never goes backwards.
A simple harness writes a known set of IDs (for example 1 to 10 million) with a recorded ack status, injects faults, waits for the pipeline to drain, and then diffs the expected and observed sets. The diff falls into four buckets: acked and present (good), acked and missing (loss, a real bug), unacked and present (fine, the ambiguous case), and present twice (duplicate).
Faults worth injecting.
- Kill consumers with
SIGKILLmid-batch, not just with a graceful shutdown. - Kill the partition leader broker while producers write with your production settings.
- Partition the network between a leader and its followers, so the ISR shrinks.
- Pause a consumer process (
SIGSTOP) longer than its session timeout, then resume it. This creates the "zombie" that thinks it still owns its partitions. - Add latency so producer requests time out after the broker has already written them.
- Fill a disk on one broker.
Jepsen. Kyle Kingsbury's Jepsen project tests distributed systems under network partitions and process pauses, and publishes the results. Its analyses of Kafka, RabbitMQ, NATS and many databases found real loss and duplication bugs, often in configurations that the documentation called safe. The habit to take from Jepsen is: never trust a guarantee you have not tested under partition.
Production metrics.
| Metric | What it tells you | Alert idea |
|---|---|---|
| Producer send errors and retries | Ambiguous sends, possible loss after the last retry | Any non-zero final failure count |
| Under-replicated partitions | ISR smaller than the replica count, so durability is reduced | Above 0 for more than 5 minutes |
| Offline partitions | No leader, writes blocked | Any |
| Consumer lag in seconds | Risk of running past retention, stale data | Lag above 10% of retention |
| Dedup hit rate | How often duplicates arrive | Sudden jumps mean an upstream retry storm |
| DLQ depth | Poison messages that were not processed | Any growth |
| Reconciliation mismatches | Loss or duplicates that slipped through | Any |
Reconciliation as the final safety net. Mature payment and billing systems run periodic jobs that compare counts or sums between the source and the sink (orders vs charges, usage events vs invoice lines) for each hour or day. Delivery guarantees reduce mismatches to near zero; reconciliation catches the rest, including bugs no one predicted.
When to Use It#
- At-most-once: high-volume telemetry where losing a sample is fine and duplicates would skew counts.
- At-least-once + idempotency: the default for business events, jobs and notifications.
- Kafka transactions / Flink exactly-once: stream processing pipelines that read from and write to Kafka (aggregations, billing counters) where double counting is unacceptable.
- Outbox: any service that must update its database and publish an event together.
When NOT to Use It#
- Do not pay for Kafka transactions when consumers are already idempotent; they add latency (commit markers, read_committed waits).
- Do not assume "exactly-once" in a vendor's docs covers your external side effects.
- Do not demand global ordering when per-key ordering is enough; it kills parallelism.
- Do not use at-most-once for anything that represents money, orders or user content.
How to Implement It#
- Decide per flow whether losses or duplicates are worse; default to at-least-once.
- Give every message a unique, producer-assigned ID and a version or timestamp.
- Configure durability:
acks=all, idempotent producer, RF 3,min.insync.replicas=2. - Commit offsets or ack after processing, never before.
- Make consumers idempotent: upserts, versioned writes, or a processed-ID table in the same transaction.
- Use idempotency keys for external APIs.
- Choose the ordering key deliberately; make consumers tolerate out-of-order events.
- Use an outbox for database-plus-event writes.
- Test failures: kill consumers mid-batch, kill brokers, drop acks, and check for losses and duplicates.
| Technology | Fits when |
|---|---|
| Kafka idempotent producer + transactions | Read-process-write between Kafka topics |
Kafka Streams (exactly_once_v2), Flink checkpoints + 2PC sinks | Exactly-once stateful stream processing |
| SQS FIFO (dedup ID, message groups) | Ordered, deduplicated queues on AWS within 5-minute windows |
| Postgres/MySQL unique constraints, upserts | Consumer-side dedup in the same transaction |
| Debezium outbox event router | Reliable publish from a database |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| At-most-once | Lowest latency, simplest | Data loss | Telemetry, disposable data |
| At-least-once | No loss | Duplicates to handle | Default for business events |
| Effectively-once via idempotency | Works across systems | Dedup storage, design effort | Consumers with side effects in a DB or API |
| Kafka transactions | Atomic consume-transform-produce | Latency, Kafka-only scope | Stream processing in Kafka |
acks=all, min.insync.replicas=2 | Survives broker failure | A few ms more latency; writes fail if 2 replicas are down | Any data you cannot lose |
| Per-key ordering | Order where it matters, parallel elsewhere | Hot keys limit throughput | Most systems |
| Dedup in the same DB transaction | Exact, atomic with the effect | One extra write per message, table growth | Effects stored in a relational DB |
Redis SET NX dedup | Sub-millisecond, shared by all workers | Not atomic with the DB write, memory cost | Side effects outside a DB, such as notifications |
| Bloom filter in front of the exact store | Removes most exact lookups | False positives need an exact check | Very high volume with long windows |
| Leases with fencing tokens | Safe re-execution of jobs | Downstream must check tokens | Job schedulers and workers |
| Log-based CDC outbox relay | Commit order, low latency, no polling | Debezium and connector operations | Services already running Kafka |
Common Pitfalls#
- Believing "exactly-once" removes the need for idempotent consumers.
- Using broker-assigned IDs for dedup, so producer retries look like new messages.
acks=allwithmin.insync.replicas=1, which still acks with one copy.- Auto-commit enabled while processing asynchronously in another thread.
- Dedup records kept for less time than the longest replay or redelivery window.
- Processing one partition with a thread pool and expecting order.
- Ignoring producer send callbacks, so failures after the last retry vanish silently.
- Killing producers with
SIGKILLand losing records still in the buffer. - Check-then-insert dedup without a unique constraint, which lets concurrent duplicates through.
- Lease-based jobs without fencing tokens, so a paused worker overwrites a newer run.
- Using wall-clock timestamps from different machines to order events.
- Dedup keys so coarse that two genuine events merge into one.
Real-World Examples#
Kafka added the idempotent producer and transactions in version 0.11 (2017), and Kafka Streams uses them for its exactly-once processing mode.
Stripe's API accepts an Idempotency-Key header so that retried requests do not create a second charge, a common way to make the external edge of a pipeline effectively-once.
Kafka's exactly-once support was designed in the open in KIP-98 (Exactly Once Delivery and Transactional Messaging) and released in Kafka 0.11 in 2017.
Google's MillWheel (VLDB 2013) and later Cloud Dataflow made per-record IDs and atomic state-plus-dedup commits the basis of exactly-once stream processing.
Apache Flink's checkpointing, based on asynchronous barrier snapshots, is the basis of its exactly-once guarantees, and its two-phase-commit sinks extend them to Kafka.
Amazon documents that SQS standard queues may deliver a message more than once, and recommends idempotent consumers. FIFO queues add a 5-minute deduplication window.
In the Interview#
Delivery guarantees in interview problems#
Interviewers rarely ask "explain exactly-once" directly. They ask design questions where duplicates or losses matter, and they listen for whether you notice. Here is how the ideas on this page map onto common prompts.
- Notification system. Say that delivery is at-least-once from the queue, and duplicates are prevented by an idempotency key at the API and a per-user, per-channel delivery key claimed atomically before calling the provider. Mention collapse IDs for push notifications, and admit the residual risk between "provider accepted" and "marked sent".
- Job scheduler. Say that execution is at-least-once using leases with heartbeats and a sweeper, that jobs must be idempotent, and that fencing tokens (the attempt number) stop a paused zombie worker from overwriting a newer run.
- Payment system. Describe the
pendingrecord, the provider idempotency key, the ledger's unique constraint, and reconciliation. - Ad click aggregator or metrics. Discuss whether a lost click or a double-counted click is worse. Choose at-least-once with dedup by click ID over a window, or Flink exactly-once into the aggregate store. See Design an Ad Click Aggregator.
- Chat or feeds. Per-conversation ordering by key, client-generated message IDs so a resend after a network drop is not a second message, and version-based ordering on the client.
A strong answer has a consistent structure: name the guarantee, name the mechanism at each hop, name the dedup key and its retention, and name what still can go wrong.
Deep Dive: Inside Kafka's idempotent producer and transactionsShow
Idempotent producer. On startup, each producer gets a producer ID (PID) and an epoch. Every batch carries a per-partition sequence number. The leader remembers the last sequence numbers per PID and partition; a retried batch with an already-written sequence is acknowledged but not appended again, and a gap is rejected, which preserves order. This removes duplicates caused by producer retries within one producer session; it does not dedupe two different sends of the same business event.
Transactions. A producer with a transactional.id registers with a transaction coordinator (a broker). It writes records to output partitions and adds the consumer's offsets to the transaction with sendOffsetsToTransaction. On commit, the coordinator writes a commit marker to every partition involved (a form of two-phase commit). Consumers with isolation.level=read_committed read only committed records, and they stop at the last stable offset, so an open transaction delays downstream reads. Reusing the same transactional.id after a restart bumps the epoch and fences the old "zombie" instance so it cannot commit.
Cost. Transactions add a few round trips per commit; throughput stays high when you commit every 100 ms or so, but end-to-end latency rises by about the commit interval.
Beyond Kafka. Flink achieves end-to-end exactly-once by aligning checkpoints with transactional sinks: it pre-commits output on each checkpoint and commits once the checkpoint completes. See Batch vs Stream Processing.
Deep Dive: Why atomic offset-plus-state gives exactly-once processingShow
It is worth seeing why the transactional approach works, not just that it works, because the same argument tells you when it breaks.
Model. A consumer reads an input log. Its state is (S, o), where S is the output state (database rows, aggregates, or output records) and o is the input offset it has consumed up to. Processing record r_o turns state S into f(S, r_o) and offset o into o + 1.
Claim. If every update of (S, o) to (f(S, r_o), o + 1) is atomic, and the consumer always resumes from the stored o, then after any sequence of crashes and restarts the state equals the result of applying each input record exactly once, in order.
Proof sketch. By induction on committed steps. Initially (S_0, 0) holds. Suppose the stored state is (S_k, k) with S_k the result of applying records 0 to k-1 once each. The consumer reads r_k and computes f(S_k, r_k). If it crashes before the atomic commit, the stored state is still (S_k, k) and the work is redone from the same starting point. That is a redelivery, but it has no effect on stored state. If the commit succeeds, the stored state is (S_(k+1), k+1). There is no reachable stored state where the output reflects r_k but the offset does not, or the reverse. So duplicates in delivery never become duplicates in effect.
Where the proof needs care.
- Determinism. On redo,
fmay produce a different output if it reads wall-clock time, random numbers, or external lookups. The stored state is still consistent (it reflects one execution), but it may differ from what an earlier aborted attempt computed. That is fine unless the aborted attempt leaked output somewhere, which leads to the next point. - Leaked side effects. If
fsends an email, the email is outside(S, o)and is repeated on every redo. The atomicity boundary must include every effect, or each external effect must be idempotent. - Zombies. Two instances may believe they own the same input partition. Both read
(S_k, k), and both try to commit. Without a check, both commits could apply. Kafka prevents this with producer epochs: a new instance with the sametransactional.idbumps the epoch, and the coordinator rejects commits from the old epoch. In a database, the equivalent is a conditional updateWHERE offset = k, so only one of the two commits succeeds.
Distributed snapshots generalise this. In a dataflow with many operators, the "state" is spread across all of them and the channels between them. Chandy and Lamport's 1985 algorithm ("Distributed Snapshots: Determining Global States of Distributed Systems") records a consistent global state without stopping the system by sending marker messages along every channel. Flink's asynchronous barrier snapshotting is a version of this for dataflows: sources inject barriers carrying a checkpoint ID, and each operator snapshots its state when barriers have arrived on all its inputs, then passes the barrier on. The snapshot is a consistent (S, o) for the whole graph, so recovery rewinds every operator and source together. The same three caveats apply: deterministic replay, sinks that participate in the commit (two-phase commit sinks), and fencing of old task instances.
Cost of a checkpoint. Aligned barriers make fast inputs wait for slow ones, so a skewed operator adds latency on every checkpoint. Flink's unaligned checkpoints, added in version 1.11, let barriers overtake buffered records and store those in-flight records in the snapshot instead. This trades larger snapshots for less stalling under back pressure. Checkpoint interval is a tuning knob: shorter intervals mean less recomputation after failure and lower latency for transactional sinks, but more snapshot I/O.
Key Takeaways#
- Failures happen between "work done" and "ack recorded", so you choose between possible loss (at-most-once) and possible duplicates (at-least-once).
- Exactly-once delivery is impossible in general; exactly-once effect is at-least-once plus idempotency, or atomic read-process-write.
- Dedup by producer-assigned IDs, in the same transaction as the effect, for longer than any replay window.
- Ordering is per key or partition; design consumers to tolerate out-of-order events.
- Kafka durability needs acks=all, RF 3, min.insync.replicas=2, no unclean election and commits after processing; use an outbox for database-plus-event writes.
- Every ambiguity window (producer ack, broker replication, consumer ack, side effect) needs either state on the receiving side or acceptance of loss or duplicates.
- Jobs and notifications are at-least-once: leases plus fencing tokens, and claim-then-mark delivery keys with provider idempotency.
- Size dedup windows by the longest replay, and use Bloom filters or time-partitioned tables to keep them cheap.
- Test guarantees with injected faults and invariant diffs, and keep reconciliation as the final net.