System Design

Core Concepts

Idempotency and Exactly-Once Delivery

Exactly-once delivery is not something you can buy. What you can build is a receiver where the second copy does nothing, and every product that advertises the first is really selling you the second inside a box it controls.

Why you are doing this at all

Somebody clicks Pay once and is charged twice. Somebody gets the same email four times. A balance ends up eleven pounds short, and nobody can say which retry did it. These are all the same bug: something retried an operation, and the operation ran twice.

The natural reaction is to look for a delivery mechanism that never does this. That search goes nowhere, because no such mechanism exists.

You cannot make delivery happen exactly once. You can make the second delivery do nothing. These are two different problems, solved in different places, and only the second one can be solved.

One situation shows why. You send a request and get no response. You might be in one of two worlds. In the first, the request never arrived. In the second, it arrived, the server did the work, and the response was lost on the way back. From where you stand, these two worlds look identical. Waiting longer doesn't tell them apart, because a slow response looks the same as a lost one too. So you have two options. You can give up and risk the work never happening, or you can send it again and risk the work happening twice.

Two failures that look the same
On the left, the request is lost on the way, so nothing runs on the server. On the right, the request arrives and the card is charged, and then the response is lost. In both, the client sent a request and got no reply, so it has to choose between giving up and sending it again.On the left, the request is lost on the way, so nothing runs on the server. On the right, the request arrives and the card is charged, and then the response is lost. In both, the client sent a request and got no reply, so it has to choose between giving up and sending it again.
The client cannot tell a lost request from a lost response. On the left, the request is lost on the way, so nothing runs on the server. On the right, the request arrives and the card is charged, and then the response is lost. In both, the client sent a request and got no reply, so it has to choose between giving up and sending it again.

This isn't a flaw in any particular network or broker. It holds for any channel that can lose messages, whether that's a TCP call to the machine next door or a queue that spans continents. Retrying is the only way to make progress, and retrying is what creates duplicates. So you can't remove duplicates upstream. They are the price of reliable delivery, and the receiver is where you pay it.

So what is being sold

Several good products advertise exactly-once. They aren't lying. If you read their own documentation carefully, you see what the phrase means in practice.

Confluent's write-up on Kafka's exactly-once semantics says the guarantee covers "consuming from a topic, materializing intermediate state in a Kafka topic and producing to one". It then says that if your application "makes an RPC call to update some remote stores", the side effects would not be guaranteed exactly once. The guarantee has an edge, and the edge is the Kafka log.

Google's Pub/Sub documentation is more direct still. Its page on exactly-once delivery warns that "a subscription might receive multiple copies of the same message due to publish side duplicates, even with exactly-once delivery enabled". The feature stops Pub/Sub from redelivering a message it knows is the same message. It can't help when the publisher retried. Then Pub/Sub holds two messages, and only your business logic knows they are the same thing.

Amazon SQS FIFO queues deduplicate, which means they drop a message they have already accepted. They recognise it by a message deduplication ID, and they remember each ID for 5 minutes. If you send the same ID again after 5 minutes, you get a second message.

Stripe's idempotency keys store the result of a request, so a retry gets the stored result instead of running the request again. In Stripe's v1 API, a key can be pruned once it is at least 24 hours old. After that, the same key starts a new request.

Where Kafka's guarantee stops
Kafka's exactly-once covers the producer, the topics and the consumer's offsets, in the green zone: reading, processing and writing back to Kafka. The consumer's writes to Postgres, the email provider and the payment API leave the log, so they sit in the red zone, where duplicates are your receiver's problem.Kafka's exactly-once covers the producer, the topics and the consumer's offsets, in the green zone: reading, processing and writing back to Kafka. The consumer's writes to Postgres, the email provider and the payment API leave the log, so they sit in the red zone, where duplicates are your receiver's problem.
The guarantee ends where the vendor's control ends. Kafka's exactly-once covers the producer, the topics and the consumer's offsets, in the green zone: reading, processing and writing back to Kafka. The consumer's writes to Postgres, the email provider and the payment API leave the log, so they sit in the red zone, where duplicates are your receiver's problem.

So the useful question is never "how do I get exactly-once delivery". It is "what happens if this runs twice, and how do I make that harmless".


The toolkit

An operation is idempotent if running it more than once leaves the system in the same state as running it once. The definition leaves three things out. It doesn't say the second run returns an error. It doesn't say you can detect the duplicate. It doesn't say nothing at all happens. It says only that the state you end up in is the same.

Some operations are already idempotent

The cheapest win here is to notice when you don't need any extra machinery at all.

operationidempotent?why
SET balance = 40yesthe result does not depend on the current value
balance = balance + 10noeach run reads a different starting point
DELETE WHERE id = 7yesthe second run deletes nothing and the state matches
INSERT with a unique keyyes, if you handle the conflictthe constraint rejects the second one
INSERT with a generated keynoyou get two rows that differ only by id
status = 'shipped'yessetting it twice is setting it once
attempts = attempts + 1noa counter is the classic non-idempotent write
adding to a setyessets absorb duplicates by definition
appending to a listnolists do not
sending an emailno, and you cannot fix itthe side effect is outside anything you control

Absolute beats relative. That rule settles most designs. An API that says "set the quantity to 3" can be retried forever. An API that says "add 1 to the quantity" can't, and no retry logic makes it safe. When you get to choose the shape of an operation, choose the absolute one. Then you have removed the problem instead of managing it.

A retried set against a retried add
Both lines show the same request arriving one to five times, on a cart that held 2 items. In green, the request that sets the quantity to 3 leaves 3 items however many times it arrives. In red, the request that adds 1 adds an item on every arrival, so five arrivals leave 7.Both lines show the same request arriving one to five times, on a cart that held 2 items. In green, the request that sets the quantity to 3 leaves 3 items however many times it arrives. In red, the request that adds 1 adds an item on every arrival, so five arrivals leave 7.
The absolute operation can be retried forever. Both lines show the same request arriving one to five times, on a cart that held 2 items. In green, the request that sets the quantity to 3 leaves 3 items however many times it arrives. In red, the request that adds 1 adds an item on every arrival, so five arrivals leave 7.

What HTTP already settled

Each HTTP method carries a promise about this. The promise is older than most API designs, and more useful than they usually treat it.

methodidempotent by specsafewhat that buys you
GETyesyesany layer may retry it without asking
HEADyesyessame
PUTyesnosend the whole target state and retry freely
DELETEyesnothe second one finds nothing and that is success
POSTnononothing may retry it on your behalf
PATCHnonoa partial change is usually relative

This matters in practice, because proxies, client libraries and load balancers act on it. A layer you didn't write will retry a GET or a PUT after a timeout, because the spec says that's safe. It won't retry a POST, for the same reason. So the method you pick decides who may retry on your behalf, and so where duplicates can come from.

Two practical points follow. First, say you can express an operation as PUT /orders/{id}, with the client choosing the id. Then everything in the path can retry it, and you need no other machinery. This is the absolute-beats-relative rule, applied to HTTP.

Second, a DELETE that returns 404 on the second call is a small design mistake that causes trouble for a long time. The retry looks like a failure. So clients write logic to tell "already deleted" apart from "never existed", and that logic is always wrong somewhere. If you return 204 both times, the operation is idempotent from the caller's side too.

Stripe accepts idempotency keys only on POST, and that follows directly from this table. The other methods don't need one.

When it is not, you need a key

For every other operation, you need a way to recognise a request as one you already handled. That means a key, and the key can come from two places.

A natural key is one the data already contains. An order has an order ID. A bank transfer has a transfer reference. A webhook from a payment provider has an event ID. If a natural key exists, use it. It costs nothing, it's the same whichever client sends the request, and it still works when a client loses its memory.

To test whether something is really a natural key, ask one question. Could two separate business events ever produce the same value? A payment provider's event ID passes, because the provider creates a new one for each event. A user ID plus a date fails, because a customer can do the same thing twice in one day. An order ID passes for the order, but it fails for a line item inside the order. So pick the key at the level the operation acts on.

If you get the level wrong, the bug is quiet. A dedup key that is coarser than the operation drops work that should have happened. Nobody notices, because a missing action leaves no trace.

A key at the wrong level
Three line items from order 81 arrive. In the top half, the dedup key is the order ID, so the check sees order 81 three times and drops items 2 and 3 as repeats, with no error. In the bottom half, the key includes the line item, so all three items are packed.Three line items from order 81 arrive. In the top half, the dedup key is the order ID, so the check sees order 81 three times and drops items 2 and 3 as repeats, with no error. In the bottom half, the key includes the line item, so all three items are packed.
A key coarser than the operation drops real work. Three line items from order 81 arrive. In the top half, the dedup key is the order ID, so the check sees order 81 three times and drops items 2 and 3 as repeats, with no error. In the bottom half, the key includes the line item, so all three items are packed.

A supplied key is one the caller generates and sends, because the operation contains nothing unique. Two identical "charge 20 pounds to card X" requests look the same. They might be a duplicate, or they might be a customer who really bought twice. Only the caller knows which, so only the caller can tell you.

Stripe's rules for supplied keys are a good model to copy. Each one exists for a reason.

rulewhy it is there
the client generates it, suggested as a v4 UUIDthe server cannot know if two requests are the same intent
up to 255 characterslong enough for a composite key, short enough to index
never sensitive datathe key ends up in logs and in the data store
parameters are compared, and a mismatch errorscatches a client reusing a key for a different request
the result is saved, including failures and 500sa retry must see what the first attempt saw
nothing is saved if validation fails or a request is already runningthose are safe to retry, so do not poison the key
pruned after at least 24 hoursthe data store cannot grow forever
only on POSTGET and DELETE are idempotent by definition

The sixth rule needs explaining. If a request fails validation before any work starts, nothing happened. Suppose the server stored "this key failed" anyway. Then a client that fixed its input and retried with the same key would be refused forever.

What the broker already does for you

Two broker mechanisms deserve more than switching on. How each one works shows exactly where it stops.

Kafka's idempotent producer gives each producer session an id, and it numbers each batch the producer sends to a partition. The broker remembers the last number it accepted from that producer for that partition. If a retried batch arrives with a number the broker has already seen, the broker acknowledges it and throws it away. Two details follow from this design. First, the broker keeps only the last five batches from each producer for each partition. So a producer with idempotence on may have at most five requests in flight on a connection. Second, the sequence belongs to the producer session. It protects against a retry within one run. It doesn't protect against a restarted job producing the same event again.

What the idempotent producer catches
Session 7 sends batch 42, and the acknowledgement is lost. The retry carries the same sequence number, so the partition acknowledges it and drops it, in green. A restarted job is a new session, 8, with its own sequence. So the same event, sent again, is appended a second time, in red.Session 7 sends batch 42, and the acknowledgement is lost. The retry carries the same sequence number, so the partition acknowledges it and drops it, in green. A restarted job is a new session, 8, with its own sequence. So the same event, sent again, is appended a second time, in red.
It drops a retried batch, not a re-sent event. Session 7 sends batch 42, and the acknowledgement is lost. The retry carries the same sequence number, so the partition acknowledges it and drops it, in green. A restarted job is a new session, 8, with its own sequence. So the same event, sent again, is appended a second time, in red.

Since Kafka 3.0, the producer turns this on by default, and Confluent measured its throughput cost as negligible. Turn it on and stop thinking about it. But don't mistake it for protection against your own application producing the same event twice. A second production of the event comes from a different producer session, with a different sequence.

SQS FIFO deduplication works on an ID you supply, or on a hash of the message body if you turn on content-based deduplication. The hash option is a trap. Two different events that happen to serialise to the same bytes count as duplicates, and the second one disappears without an error. If two of your events can ever have the same body, supply the ID yourself.

Back of envelopeHow many duplicates are you actually getting
Work this out for your own system before you design anything.

Assume a consumer at 5,000 messages/sec and a redelivery rate
of 0.1%, which is unremarkable for at-least-once:

  duplicates/sec    5,000 × 0.001                =      5
  per day           5 × 86,400                   = 432,000

Now a rebalance or a deploy, where in-flight work is
redelivered wholesale. 30 seconds of unacknowledged messages:

  one event         5,000 × 30                   = 150,000
  ten deploys/day                                = 1.5M

The steady rate is a trickle. Most duplicates arrive in
bursts, at deploys and incidents, which is exactly when you
are least able to reason about them.
Duplicates over one day
Each red bar is a deploy. The consumers restart, and 30 seconds of unacknowledged messages, 150,000 of them, are processed again at 5,000 a second. The steady 0.1 percent redelivery, 5 a second, is too small to see at this scale. It adds up to 432,000 a day, against 1.5 million from ten deploys.Each red bar is a deploy. The consumers restart, and 30 seconds of unacknowledged messages, 150,000 of them, are processed again at 5,000 a second. The steady 0.1 percent redelivery, 5 a second, is too small to see at this scale. It adds up to 432,000 a day, against 1.5 million from ten deploys.
Most duplicates arrive in bursts. Each red bar is a deploy. The consumers restart, and 30 seconds of unacknowledged messages, 150,000 of them, are processed again at 5,000 a second. The steady 0.1 percent redelivery, 5 a second, is too small to see at this scale. It adds up to 432,000 a day, against 1.5 million from ten deploys.

That shape is why a dedup mechanism has to be correct every time, not just usually. It meets its hardest test on a day when something else has already gone wrong.

The outbox, and why dual writes keep appearing

The hardest case in this subject has a name: the dual write. One logical change has to land in two systems, and no single atomic step covers both. Once you can recognise it, you see it everywhere.

You save an order to the database and publish an OrderPlaced event. You write a row and commit an offset. You charge a card and record the charge. Whichever write you do first, a crash between the two leaves the systems disagreeing. Retrying doesn't fix it, because the retry doesn't know how far the first attempt got.

A dual write and an outbox
In the top panel, the service writes the order (1) and then publishes the event (2) as two separate steps, so a crash between them leaves a row with no event. In the bottom panel, the order and its outbox row commit in one transaction (1). The relay reads unpublished rows (2) and publishes them (3). It retries until the broker acknowledges, so it can publish a row twice, and the consumer has to be idempotent.In the top panel, the service writes the order (1) and then publishes the event (2) as two separate steps, so a crash between them leaves a row with no event. In the bottom panel, the order and its outbox row commit in one transaction (1). The relay reads unpublished rows (2) and publishes them (3). It retries until the broker acknowledges, so it can publish a row twice, and the consumer has to be idempotent.
The outbox turns a lost event into a duplicate one. In the top panel, the service writes the order (1) and then publishes the event (2) as two separate steps, so a crash between them leaves a row with no event. In the bottom panel, the order and its outbox row commit in one transaction (1). The relay reads unpublished rows (2) and publishes them (3). It retries until the broker acknowledges, so it can publish a row twice, and the consumer has to be idempotent.

The outbox pattern turns the second write into a local one. Instead of publishing to the broker, the service inserts a row into an outbox table in the same transaction as the business change. A separate process, the relay, reads unpublished rows, sends them and marks them sent. Now only one thing can go wrong: the relay publishes a row and dies before it marks the row sent. The relay then sends the row again. That produces a duplicate, and your idempotent consumer already handles duplicates.

That's the whole trade, and it's worth saying out loud in an interview: the outbox turns a correctness problem you cannot solve into a duplicate problem you already know how to solve. It doesn't give you exactly-once. It gives you at-least-once delivery with nothing lost. Together with an idempotent receiver, that is as close as you can get.

Back of envelopeWhat the outbox costs
Per business write you now do:

  1 extra row inserted     ~200 B, same transaction, ~no latency
  1 read by the relay      batched, up to 500 rows per poll
  1 publish                the send you were doing anyway
  1 update marking sent    batched with the same rows

At 2,000 writes/sec:
  outbox inserts           2,000/sec, inside existing txns
  relay polls at 200ms     2,000 × 0.2 = 400 rows per poll
  relay writes             2,000/sec spread over 5 batches/sec

Storage, keeping 7 days for replay:
  2,000 × 86,400 × 7 × 200 B                   ≈ 242 GB

The cost is a table that needs pruning and one more process
to operate. The latency cost on the write path is one insert.

Where the dedup state lives

Every mechanism in this subject answers one question. Where do you record that you have seen this request before, and is that record written in the same place as the effect? The effect is the change the operation makes: the row, the charge, the email.

mechanismstate liveswindowcatches concurrent duplicates?
unique constraint on a natural keyyour databaseforeveryes, the database arbitrates
idempotency key table, same databaseyour databaseas long as you keep rowsyes, if the insert is the check
idempotency key in Redisseparate from the effecta TTLonly if you use SET NX
Kafka producer id and sequence numberthe broker's logthe producer sessionyes, within one producer
SQS FIFO deduplication IDthe queue5 minutesyes
Pub/Sub exactly-oncethe subscriptionone message, while outstandingyes for redelivery, no for republish
"check if it exists, then insert"nowhere usefulnoneno, and this is the bug

The last row is the mistake this subject exists to prevent, so here is exactly why it fails. A read followed by a write is two operations. Two duplicates that arrive at the same moment both read "not seen". Both conclude they are first, and both do the work. Reading more carefully doesn't fix it. The check and the claim have to be one operation. In practice that means a unique constraint, or a conditional insert, which succeeds only if the key isn't there yet. It can also be a compare-and-set, a write that succeeds only if the stored value is still the one you read.

Two copies, one millisecond apart
In the top half, each copy reads the key first. B reads before A has written anything, so both see no key and both charge the card. In the bottom half, each copy starts with an insert. A's insert succeeds and A charges the card. B's insert hits the unique constraint, so B stops, and the card is charged once.In the top half, each copy reads the key first. B reads before A has written anything, so both see no key and both charge the card. In the bottom half, each copy starts with an insert. A's insert succeeds and A charges the card. B's insert hits the unique constraint, so B stops, and the card is charged once.
Only an insert can be the check. In the top half, each copy reads the key first. B reads before A has written anything, so both see no key and both charge the card. In the bottom half, each copy starts with an insert. A's insert succeeds and A charges the card. B's insert hits the unique constraint, so B stops, and the card is charged once.

The ordering trap

Idempotency handles one message arriving twice. It doesn't handle two different messages arriving in the wrong order, and people often mix the two up.

Say a slow retry of "set status to pending" lands after "set status to shipped". Every write was idempotent, and the final state is still wrong. A better key won't fix this. The message has to carry a version, a timestamp or an epoch, and the write has to be conditional: it refuses anything older than what is already stored. That is the fencing pattern linked above. You use it together with idempotency, not instead of it.

A late retry undoes a newer write
Both rows receive the same two messages: shipped with version 2, then a slow retry of pending with version 1. In the top row, each write is idempotent, and the retry still sets the status back to pending, in red. In the bottom row, the write checks the version. It refuses version 1 because version 2 is stored, and the order stays shipped.Both rows receive the same two messages: shipped with version 2, then a slow retry of pending with version 1. In the top row, each write is idempotent, and the retry still sets the status back to pending, in red. In the bottom row, the write checks the version. It refuses version 1 because version 2 is stored, and the order stays shipped.
A version on the write stops an old message winning. Both rows receive the same two messages: shipped with version 2, then a slow retry of pending with version 1. In the top row, each write is idempotent, and the retry still sets the status back to pending, in red. In the bottom row, the write checks the version. It refuses version 1 because version 2 is stored, and the order stays shipped.

The method

Six steps, in this order. The order matters, because each step can remove the need for the next.

The method as a flow
Each step is tried in order. Step 1 ends the work if the operation can be made absolute, and step 2 ends it if a natural key can take a unique constraint. Only an operation that gets past both needs the rest: a supplied key, an atomic dedup write, a window sized from the retry policy, and a stored response to replay.Each step is tried in order. Step 1 ends the work if the operation can be made absolute, and step 2 ends it if a natural key can take a unique constraint. Only an operation that gets past both needs the rest: a supplied key, an atomic dedup write, a window sized from the retry policy, and a stored response to replay.
Remove the problem first, then build the machinery. Each step is tried in order. Step 1 ends the work if the operation can be made absolute, and step 2 ends it if a natural key can take a unique constraint. Only an operation that gets past both needs the rest: a supplied key, an atomic dedup write, a window sized from the retry policy, and a stored response to replay.

1. Can you change the operation so the question never comes up? Use absolute instead of relative, SET instead of +=, a target state instead of a change. If you can, stop here. This is the only step that removes the problem instead of handling it.

2. Is there a natural key in the data already? An order ID, a provider's event ID, a transfer reference. If there is, put a unique constraint on it and let the database reject the second copy. Stop here.

3. If not, make the caller supply one. Document it. Make it required on anything that moves money or sends a message. Reject requests that arrive without one, instead of quietly accepting the risk.

4. Write the dedup record and the effect in one atomic step. If both live in the same database, use one transaction. If they don't, you have a dual write, and you need the outbox pattern or you need to move one of them. This is the step people skip, and without it the dedup mechanism protects nothing.

5. Choose the window from your retry policy, not from a round number. The window is how long you keep the dedup record. Ask how long after the original a retry can plausibly arrive. The dedup record has to outlive that, with a margin. Work the number out, instead of picking a day because a day sounds safe.

6. Decide what a replay returns. A replay is the server answering a retry from what it stored. The strongest answer is to store the original response and return it again, because then the client can't tell that it retried. Returning an error that says "already done" is honest, but it pushes work onto the caller. Returning a fresh success for an operation you didn't perform is a lie, and sooner or later it costs you.


Worked examples, start to finish

Charging a card

A customer clicks Pay, and your server calls the payment provider. The connection drops before you see a response. Did the charge happen?

The naive answer is to look: query the provider for recent charges on that card and see if one matches. This fails for two reasons. First, there is a delay between a charge being created and it showing up in a search. Second, a customer who really bought the same thing twice in a minute looks exactly like a duplicate.

The working answer is a key. The client generates it before the first attempt, and it sends the same key on every retry of that attempt.

Two copies of the same request can also arrive at the same instant. People forget this case, because it never happens while you test by hand. A user double-clicks, or a load balancer retries on an idle connection, and two threads on two servers start the same charge a millisecond apart. Neither has seen the other. If each one starts by looking up the key, both look, both find nothing, and both charge.

So the first step isn't a lookup. It is a conditional insert: insert the key with the state started, and let the unique constraint decide which copy wins. The losing copy learns it lost from the failed insert, not from a read. There is no gap between deciding and claiming, because one statement does both.

The record has three states, and each one has a job. Started means somebody is working on this request right now. A second arrival is told to come back later, with a 409, instead of running in parallel. Completed holds the stored status and body, and a replay returns them unchanged. Failed holds a stored response too, because Stripe's rule about saving 500s is right. If the first attempt failed at the provider, the retry must get that same failure. A 500 doesn't prove the charge didn't happen, so a fresh attempt could charge the customer a second time.

One insert decides each arrival
The server first inserts the key with the state started. If the insert succeeds (1), this is the first arrival. The server charges the card, stores the response as completed or failed, and returns it. If the key already exists (2), the server reads the row and does no new work. A finished row replays its stored response. A row still marked started returns 409, and the client retries later. A row whose request hash differs returns 422.The server first inserts the key with the state started. If the insert succeeds (1), this is the first arrival. The server charges the card, stores the response as completed or failed, and returns it. If the key already exists (2), the server reads the row and does no new work. A finished row replays its stored response. A row still marked started returns 409, and the client retries later. A row whose request hash differs returns 422.
The claim is an insert, not a read. The server first inserts the key with the state started. If the insert succeeds (1), this is the first arrival. The server charges the card, stores the response as completed or failed, and returns it. If the key already exists (2), the server reads the row and does no new work. A finished row replays its stored response. A row still marked started returns 409, and the client retries later. A row whose request hash differs returns 422.
Back of envelopeSizing the key store
Assume a payments API at 2,000 writes/sec, keys kept 24 hours.

  keys per day    2,000 × 86,400              = 172.8M
  per record      key 36 B + status + body
                  + parameter hash            ≈ 1.5 KB average
  ────────────────────────────────────────────────────────
  24 hour store   172.8M × 1.5 KB             ≈ 260 GB

Too big for memory, comfortable for a table with a TTL.

If you only store a hash of the response instead of the body:
  per record      ≈ 120 B
  24 hour store   172.8M × 120 B              ≈ 21 GB

But then a replay cannot return the original response, only
confirm that one happened. Decide which you are buying.

The decision: store the full response, keyed by (account_id, idempotency_key), in the same database as the charge record, and write it in the same transaction. Scope the key to the account, not globally. If the key is global, one customer's key can collide with another's, and you've built a way to leak charge results between accounts.

Moving money between accounts

A transfer debits one account and credits another. It isn't idempotent in any form. Both writes are relative, so running the transfer twice moves the money twice.

You can't fix this by making the operation absolute. "Set the balance to 90" is wrong as soon as any other transaction touches the account. So this is a case where step 1 of the method doesn't apply.

Naive

Check whether the transfer already exists, then apply it

Read the transfers table for the reference. If it isn't there, debit, credit, and insert the transfer record.

Two copies that arrive together both read an empty result. Both apply the transfer, and both insert. If the reference column has no unique constraint, you now have two rows and the money has moved twice. If it does have one, the second insert fails, but only after that copy's debit and credit have run. Unless all three writes are in one transaction, you end up with a wrong balance and an error at the same time.

The read is doing nothing useful. It makes the gap smaller, but it doesn't close it.

Senior

Insert the transfer record first, in the same transaction as the balance writes

Begin a transaction. Insert into transfers, with a unique constraint on the reference. If the insert raises a conflict, roll back and return the existing transfer. Otherwise debit, credit and commit.

The insert is now the check. The database decides which copy wins, so the two duplicates can't both succeed. The balance writes share the transaction, so there is no state where one happened without the other. The dedup record and the effect are in one atomic step, which is step 4 of the method.

The cost: the transfer reference has to exist before the money moves, and the caller has to send the same one on every retry. That's a change to the API contract, and it's the right change.

Staff

Make the ledger append-only and derive the balance

Question the idea that a balance is a number you update. Store entries that never change instead, one row for each movement of money. A transfer writes two entries, a debit and a credit, and each one carries the transfer reference. A unique constraint on the reference and the account together stops either entry being written twice. The balance is the sum of the entries.

Now every write is an insert. The unique constraint is the whole dedup mechanism, and nothing in the system does a read-modify-write, where you read a value, change it and write it back. A duplicate is rejected by the constraint and changes nothing, because no value was ever being overwritten.

The cost: reads get more expensive. So you keep a stored balance, updated from the entries, and treat it as a cache you can rebuild. That's real extra work to run. In return, you can state why the system is correct in one sentence: each account's entry for a transfer can be written only once. A one-sentence argument is easy to check, and it stays true while other people change the code over the years.

An append-only ledger
Transfer T-901 wrote two entries, a debit from account A and a credit to account B. When a retry tries to insert A's debit again, the unique constraint on the reference and the account rejects it, and nothing changes. A's balance, 60, is the sum of its entries, kept as a cache that can be rebuilt.Transfer T-901 wrote two entries, a debit from account A and a credit to account B. When a retry tries to insert A's debit again, the unique constraint on the reference and the account rejects it, and nothing changes. A's balance, 60, is the sum of its entries, kept as a cache that can be rebuilt.
A duplicate entry is refused, so the balance cannot move twice. Transfer T-901 wrote two entries, a debit from account A and a credit to account B. When a retry tries to insert A's debit again, the unique constraint on the reference and the account rejects it, and nothing changes. A's balance, 60, is the sum of its entries, kept as a cache that can be rebuilt.

The decision: append-only entries, with a unique constraint on the reference and the account, and a balance calculated from them. If that change is too large for the system you're in, the senior answer is correct. Say why you didn't take the staff one.

Sending an email

A user signs up, and you send a welcome email. The job runs twice, and the user gets two emails.

Everything above fails here, for a specific reason. The effect is outside any database you control. You can't put the email provider's send and your dedup record in one transaction, however you arrange them, because they live in two systems.

So you choose which failure you prefer.

Mark it sent, then send. If the process dies in between, the email never goes, and nothing knows. That's at-most-once, and for a marketing email it's fine.

Send, then mark it sent. If the process dies in between, the retry sends a second email. That's at-least-once, and for a password reset it's fine. Two reset emails are annoying, and a missing one turns into a support ticket.

Give the provider a key. Some email providers accept an idempotency key and drop a repeat send that carries it. Resend, for example, takes an Idempotency-Key header and keeps each key for 24 hours. This moves the problem inside the provider's boundary. It's the best answer available, and it still has limits: the provider's window and the provider's rules.

Three ways to send one email
If the job marks the email sent and then crashes, the email is never sent. If it sends the email and then crashes before marking it, the retry sends a second one. If the send carries a key, the provider drops the repeat, but only while it keeps the key, which is 24 hours at Resend.If the job marks the email sent and then crashes, the email is never sent. If it sends the email and then crashes before marking it, the retry sends a second one. If the send carries a key, the provider drops the repeat, but only while it keeps the key, which is 24 hours at Resend.
Without one transaction, you choose which failure you get. If the job marks the email sent and then crashes, the email is never sent. If it sends the email and then crashes before marking it, the retry sends a second one. If the send carries a key, the provider drops the repeat, but only while it keeps the key, which is 24 hours at Resend.

The decision: at-least-once for anything the user is waiting on, with a provider-side key where the provider accepts one. At-most-once for anything they aren't waiting on. For the emails that matter, also write an outbox row in the same transaction as the signup, and let a worker drain it. Then the send is always attempted.

A consumer that writes to a database

This case shows why Kafka's exactly-once feature solves less than people hope.

Your consumer reads an event from a topic, writes a row to Postgres, and commits the offset, which is its saved position in the topic. Three things can go wrong, and two of them are crashes.

  • It writes the row, then crashes before committing the offset. On restart the event is delivered again, and the row is written twice.
  • It commits the offset, then crashes before writing the row. The event is gone, and the row is missing.

The third isn't a crash at all. A consumer group rebalances when an instance joins, leaves, or is judged too slow, and every partition that instance held moves to another one. Anything it processed but hadn't committed goes to the new owner and is processed again. A deploy restarts every consumer, and each restart usually triggers a rebalance. So this path runs several times a day in a healthy system. That's why the duplicate arithmetic earlier came out in bursts and not as a steady trickle.

Kafka's transactions don't help here, because the offset commit and the Postgres write are in two different systems. The guarantee covers Kafka to Kafka, as Confluent's own write-up says.

Naive

Commit the offset after the write and hope the gap is small

It usually works, and that's the problem. The gap is milliseconds, so the bug shows up rarely and gets closed as "cannot reproduce".

It also gets much worse in exactly the conditions you care about. A deploy, a rebalance or a slow database all widen the gap. So your duplicate rate spikes during incidents, instead of spreading evenly across the year.

Senior

Make the write idempotent and stop worrying about the offset

Give every event an ID at the producer, and make the consumer's write conditional on that ID. Use an upsert keyed on it, which inserts the row or updates it if it exists. Or use an insert with a unique constraint, and ignore the conflict.

Now a redelivery is harmless by design. You can commit the offset whenever you like, because a replayed event produces the same row. You've stopped trying to make delivery exact, and made the effect exact instead. That's the main claim of this page, turned into code.

The cost is a dedup column and an index on every table a consumer writes to, plus the rule that every producer stamps an ID. That's cheap.

Staff

Store the offset in the same database as the data

Question the idea that Kafka has to own your position. Write the row and the consumed offset into Postgres in one transaction. On startup, seek to the offset stored in Postgres, not the one the broker holds.

Now the two things that had to agree live in one system, so a single commit makes them agree. There is no gap at all, and you don't need a dedup column.

The cost: you've taken on offset management, which the broker was doing for you. You've also tied your consumer to a database that must be up before the consumer can start. Take this when the write volume is low enough that transactions are cheap, and correctness matters more than simple operations. Otherwise take the senior answer, and say which you chose and why.

Three ways to handle the offset
In the naive panel, the consumer writes the row (1) and then commits the offset (2), so a crash between them writes the row again after a restart. The senior panel keeps the same two steps, but a unique event_id makes the second insert do nothing. The staff panel writes the row and the offset in one Postgres transaction (1), and on restart the consumer seeks to that offset, so there is no gap.In the naive panel, the consumer writes the row (1) and then commits the offset (2), so a crash between them writes the row again after a restart. The senior panel keeps the same two steps, but a unique event_id makes the second insert do nothing. The staff panel writes the row and the offset in one Postgres transaction (1), and on restart the consumer seeks to that offset, so there is no gap.
Make the write idempotent, or put the offset beside it. In the naive panel, the consumer writes the row (1) and then commits the offset (2), so a crash between them writes the row again after a restart. The senior panel keeps the same two steps, but a unique event_id makes the second insert do nothing. The staff panel writes the row and the offset in one Postgres transaction (1), and on restart the consumer seeks to that offset, so there is no gap.

The decision: idempotent writes keyed on an event ID, for almost every system. It works alongside everything else, it survives a replay from any offset, and it doesn't care which broker you use.


Where it goes wrong

1. The dedup window is shorter than the retry window

A dedup record that expires before the last retry arrives protects nothing. One calculation prevents this.

Back of envelopeWhen a retry outlives its own dedup record
A client retries with exponential backoff. Times are from
the first attempt, before jitter:

  attempt 1    t = 0
  attempt 2    t = 2s
  attempt 3    t = 8s
  attempt 4    t = 32s
  attempt 5    t = 2m 8s
  attempt 6    t = 8m 32s      ← past an SQS FIFO 5 minute window

Plus: a message parked in a dead letter queue and replayed
by hand the next morning       t = 14 hours

Dedup window must exceed the longest plausible gap between
the first attempt and the last retry, including manual ones.

  SQS FIFO             5 minutes    survives attempt 5, not 6
  Stripe keys          24 hours     survives the manual replay
  a unique constraint  forever      survives everything
Retry times against dedup windows
Each dot is a retry at the times in the worksheet above, on a log scale. The 5 minute SQS FIFO window ends before attempt 6, in red. A 24 hour Stripe key still covers the manual replay at 14 hours. A unique constraint never expires, so it covers everything.Each dot is a retry at the times in the worksheet above, on a log scale. The 5 minute SQS FIFO window ends before attempt 6, in red. A 24 hour Stripe key still covers the manual replay at 14 hours. A unique constraint never expires, so it covers everything.
A retry after the window is not deduplicated. Each dot is a retry at the times in the worksheet above, on a log scale. The 5 minute SQS FIFO window ends before attempt 6, in red. A 24 hour Stripe key still covers the manual replay at 14 hours. A unique constraint never expires, so it covers everything.

A five minute window isn't wrong. It is a statement about which retries it covers. Say your client can retry after six minutes, or an operator replays a dead letter queue, where messages that kept failing are parked, the next day. Then the window is the guarantee, and the window is too short. This is why a unique constraint on a natural key beats every timed mechanism when you can have one: it never expires.

2. The key is scoped wrong

If an idempotency key is global, one customer can guess or collide with another customer's key and receive their stored response. Scope the key to the caller: (account_id, key), always.

Scoping too narrowly fails more quietly. A key scoped to (account_id, endpoint, key) looks tidy. It breaks as soon as a client retries against an endpoint that was redirected or renamed. Scope the key to the caller, not to the route.

3. The dedup record is written after the work

If you do the work and then record the key, a crash in between leaves the effect applied with no record of it. The retry then does the work again. If you record the key and then do the work, a crash leaves a key for work that never happened, and the retry is refused.

Neither order is safe on its own. That's why the record has a started state, and why the claim and the effect belong in one transaction.

When they can't share a transaction, the started state needs a deadline. Without one, a process that claims a key and then dies leaves the key claimed forever. Every retry is told to come back later, by a worker that no longer exists. So the rule becomes: a new attempt may take over a started record that is older than some limit.

At this point you've built a lease, a claim that expires on its own, and you should say so. Leases raise their own question. The original process might wake up after its lease expired and finish the work anyway, on top of the attempt that took over. Nothing stops it, unless the write itself checks who holds the claim now. That check is a fencing token, and it's why the two patterns keep appearing together. Idempotency stops the same work happening twice. Fencing stops work from a holder that has lost the right to do it.

A takeover with a fencing token
Worker A claims the key with token 1 and then pauses. Its 30 second deadline passes, so worker B takes over with token 2 and writes. When A wakes and writes with token 1, the database has already seen token 2, so it refuses A's write, in red.Worker A claims the key with token 1 and then pauses. Its 30 second deadline passes, so worker B takes over with token 2 and writes. When A wakes and writes with token 1, the database has already seen token 2, so it refuses A's write, in red.
The write carries the token, so a late worker is refused. Worker A claims the key with token 1 and then pauses. Its 30 second deadline passes, so worker B takes over with token 2 and writes. When A wakes and writes with token 1, the database has already seen token 2, so it refuses A's write, in red.

Pick the deadline from how long the work takes at p99, the time within which 99 percent of attempts finish, and not from a round number. If it's too short, two workers run the same job during a slow patch. If it's too long, a crashed worker's key stays blocked until the deadline passes.

4. Same key, different request

A client sometimes reuses a key for a different request. Usually it built the key from something too coarse, like a user ID plus the day.

Stripe compares the incoming parameters with the stored ones and returns an error on a mismatch. Copy that behaviour. Without it, you return the wrong stored response, and the client believes something happened that didn't. Store a hash of the request body next to the key, and return a 422 when the hashes don't match. Comparing hashes is cheap, and it turns a silent wrong answer into a loud error.

5. Dedup state and effect in different systems

A common version of this bug keeps the keys in Redis while the effect lands in Postgres. If Redis loses the key in a failover, the work runs twice. If the key is set and the Postgres write then fails, the work never runs at all.

Keys in Redis, effects in Postgres
On the left, the worker sets the key in Redis and writes to Postgres. Redis then fails over and loses the key, so the retry's SET NX succeeds and the work runs again. On the right, the key is set but the Postgres write fails. The retry finds the key in Redis and stops, so the work never runs.On the left, the worker sets the key in Redis and writes to Postgres. Redis then fails over and loses the key, so the retry's SET NX succeeds and the work runs again. On the right, the key is set but the Postgres write fails. The retry finds the key in Redis and stops, so the work never runs.
The two stores can disagree in either direction. On the left, the worker sets the key in Redis and writes to Postgres. Redis then fails over and loses the key, so the retry's SET NX succeeds and the work runs again. On the right, the key is set but the Postgres write fails. The retry finds the key in Redis and stops, so the work never runs.

If you must split them, the Redis entry has to be a lease that expires, not a permanent record, and the lasting dedup has to be a constraint in the database. Then Redis is an optimisation that keeps most duplicates away from the database. That's a fine job for it, and correctness no longer depends on it.

6. Read-then-write instead of one conditional operation

Checking whether a row exists and then inserting it is the bug from the last row of the dedup-state table. It gets through code review easily. A SELECT followed by an INSERT reads like a check. Under concurrency it isn't one, because two callers can pass it at the same time. Use INSERT ... ON CONFLICT DO NOTHING, SET NX or another conditional write, and let the storage engine decide which caller wins.

In a design discussion, the sign is the phrase "first we check if it already exists". Ask what happens when two copies check at the same moment.

7. Exactly-once treated as a setting

Someone turns on the broker's exactly-once setting and considers the problem closed. What they bought is real, and it stops at the broker.

Back of envelopeWhat exactly-once actually costs in Kafka
Confluent's published measurements:

  idempotent producer          negligible throughput impact
  transactional producer
    vs at-least-once, acks=all           3% lower
    vs at-most-once,  acks=1            20% lower
  streams, 100ms commit interval    15 to 30% lower
  streams, 30s commit interval      no measurable overhead
                                    for messages ≥ 1 KB

The commit interval is the real knob: exactness costs latency,
not throughput, and you buy it back by committing less often.

The thing to remember is not the percentage. It's that the cost is small and the coverage is narrow, so the setting is usually worth turning on and never worth relying on.

8. The dedup store is restored from a backup

This failure is rare, and it hits the mechanism where it's weakest. You restore a database, or a Redis cluster comes back from a snapshot. The dedup records are now hours behind the effects they were protecting. A retry of any operation from that gap is treated as new.

A restore that loses dedup records
Postgres keeps every effect, in the top lane. The dedup records live in Redis, which is restored at 06:00 from a 02:00 snapshot. So the records from 02:00 to 06:00 are gone, in red. A retry of any operation from that gap finds no record and runs again.Postgres keeps every effect, in the top lane. The dedup records live in Redis, which is restored at 06:00 from a 02:00 snapshot. So the records from 02:00 to 06:00 are gone, in red. A retry of any operation from that gap finds no record and runs again.
A restore moves the dedup records back, but not the effects. Postgres keeps every effect, in the top lane. The dedup records live in Redis, which is restored at 06:00 from a 02:00 snapshot. So the records from 02:00 to 06:00 are gone, in red. A retry of any operation from that gap finds no record and runs again.

The defence is the same as everywhere else on this page. Put the dedup state in the same store as the effect, so a restore moves them back together and they can't disagree. If the dedup state lives somewhere else, treat a restore of either one as an incident, and reconcile the other against it. Somebody has to have written down how to do that.

9. Retrying without a key at all

Sometimes a client library generates a fresh UUID on every attempt. Then every retry looks like a new request, and the server's dedup does nothing.

The server can't see this, because the requests are valid and different. The only defence on the server side is to make the key required and reject requests without it. Then check that your own client libraries reuse one key across all the retries of a logical call, and don't make a new key for each HTTP attempt.

The third test is slow, but automate it anyway, because a window bug stays hidden until the day a retry is unusually late. The rest of a dedup layer fails loudly when it breaks. The window fails quietly, in production, months after you shipped it.


If you memorise nothing else

The one sentenceYou cannot make delivery happen once; you can make the second delivery do nothing
Why delivery cannot be exactA lost request and a lost response look identical to the sender
What every vendor sellsExactly-once inside a boundary they control, for a bounded time
Kafka's boundaryIts own log; external side effects are excluded, in its own docs
Pub/Sub's caveatPublish-side duplicates survive exactly-once delivery
SQS FIFO window5 minutes
Stripe key retentionPruned after at least 24 hours
First question to askCan the operation be absolute instead of relative?
Second questionIs there a natural key already in the data?
The checkA conditional insert, never a read followed by a write
The rule people skipDedup record and effect in one atomic step
Window sizingLonger than your longest retry, including a manual replay
Key scope(account_id, key), never global
On replayReturn the stored response, including stored failures
When both failChoose your duplicate deliberately: an extra email or a missing one
Kafka exactly-once cost3% against at-least-once; the commit interval is the real knob

What is expected at each level

Mid-level

Know that at-least-once is what you normally have, and that the receiver has to cope with it. Define idempotent without hedging, and recognise which of a handful of operations already are.

Reach for an idempotency key when asked about duplicate payments, and know that the client generates it. You aren't expected to raise the window, the scope or the atomic dedup write without being asked. But you should follow the argument when the interviewer brings it up.

Senior

Three things should come up without prompting.

The reframe. Say that exactly-once delivery isn't available, and that you're making the effect idempotent instead. A candidate who spends the discussion looking for a broker setting has missed the question.

Where the dedup state lives relative to the effect. A key in Redis and a write in Postgres isn't a solution. Be able to say why in one sentence.

The check is a conditional write. If you describe reading to see whether you've handled something, and then handling it, you've described the bug itself.

When prompted, you should get to window sizing, to key scope, and to storing the response so that a replay looks the same as the original.

Staff+

Remove the problem before solving it. Push for absolute operations and natural keys. Reach for supplied keys only when neither of those applies. A design where most operations never needed dedup is better than one with an excellent dedup layer.

Name the boundary of any guarantee you're offered, including your own. Kafka's exactly-once stops at its log, and a provider's dedup stops at the end of its window. If you say exactly where a guarantee ends, a team three layers away won't build on it by mistake.

Choose the failure when exactly-once isn't available. Anything that crosses into a system you don't control forces at-most-once or at-least-once. Picking one on purpose, for each message type, is the real work.

Separate idempotency from ordering. A duplicate and an out-of-order retry are different bugs with different fixes. A version or epoch on the write handles the second.

Say what you would not build. No distributed transaction across a database and an email provider. No dedup cache that correctness depends on. No global namespace for idempotency keys. No exactly-once claim in your own API docs, because you can't honour it at the edges, and someone will build on it.


Sources

Every vendor figure and quotation here comes from the vendor's own published pages. The first two are worth reading in full, because both vendors state plainly where their guarantee stops.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.