SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Two Generals Problem

Why two machines can never be fully sure the other got the last message.

⏱ 11 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The Two Generals Problem shows that two machines connected by an unreliable link can never be completely sure they agree on something. Whoever sends the last message cannot know it arrived.

  • Two generals must attack at the same time, but their messengers may be caught.
  • Every acknowledgement needs its own acknowledgement. The chain never ends.
  • In practice we accept a tiny doubt and use retries plus idempotent operations.

02Concept: What is it?

Two armies sit on opposite hills with an enemy in the valley between them. Each army alone loses, but if both attack at the same time they win. The generals can only talk by sending a messenger through the valley, and any messenger may be caught.

General A sends "Attack at dawn." But A will not attack unless sure B got it. B receives it and replies "Agreed." But now B is unsure that A got the reply, so B should not attack either. A gets the reply and sends "I got your agreement", and the doubt moves again, to the new last message.

The chain of doubt
🏰A: Attack at dawnB may not have it
→↓1
🏯B: Agreeddid A get this?
←2
🏰A: Got your replydid B get this?
→↓3 ...
♾️and so on
Whoever sent the last message is always the one who is unsure.

It has been proven that no protocol solves this, with any number of messages, over a link that can lose messages. If it did, you could take the shortest solution and remove its last message. The solution must still work, so that message was never needed, and we can repeat that until nothing is left, which is absurd.

🧠Not the same as Byzantine
In the Two Generals Problem everyone is honest. The only trouble is that the link is unreliable. In the Byzantine Generals Problem the generals themselves may lie.

03Real-Life Example

🍡Did You Get My Text?
You text a friend "Meet at 6?". They reply "Yes!". You are happy, but they do not know if you saw "Yes!". So you send "Great, see you". Now you do not know if that arrived. At some point both of you just stop and turn up, accepting a small chance that one of you is not there.
The generals
Real systems
Two armies on hills
Two services or two databases
A messenger through the valley
A network message
Messenger caught
Packet lost or connection cut
Attack at dawn
Commit this transaction
Needing to attack together
Needing both sides to agree
Sending one more acknowledgement
A longer handshake
Deciding to attack anyway
Accepting a small risk, then repairing
What a client sees when the reply is lost
πŸ’³Client: pay 50
→↓request
🏦Server charges the cardpayment done
⇒⇣reply lost
❓Client does not knowretry or not?

04Why Do We Need It?

🧱A hard limit
Better code or faster servers cannot remove this doubt. It comes from the network itself.
🧠Shapes every design
It is the reason we plan for retries, duplicates and reconciliation.
πŸ”Explains idempotency
If you cannot know whether a request ran, you must make running it twice safe.
πŸ’³Explains distributed transactions
Commit protocols like 2PC block or risk disagreement, because of this exact problem.
🀝Explains handshakes
TCP uses three steps, not because three is perfect, but because it is enough in practice.
πŸ—£οΈStrong interview answer
Naming it shows you know exactly-once delivery over a network is not a real thing.
Two machines can get very sure, but never completely sure. Good designs make the leftover doubt harmless.

05Where Do We Use It?

πŸ“‘TCP connection setup
The 3-way handshake and the closing handshake reduce doubt but cannot remove it.
πŸ’³Payments
A timeout after a charge request may mean it worked or not. Idempotency keys make retries safe.
πŸ”€Two-phase commit
If the coordinator crashes after prepare, participants may wait, unsure of the decision.
πŸ“¨Message queues
A consumer that crashes before acking may get the same message again.
🌐HTTP APIs
A client that times out cannot tell if the server did the work.
πŸ“‹Webhooks
Senders retry until they get a 200, so receivers must handle duplicates.

06Types / Parts / How It Works

What we do instead of solving it

TechniqueHow it copesLeftover risk
Acknowledgements and retriesResend until you hear backDuplicates
Idempotency keysThe receiver ignores repeats of the same requestNeeds storage for keys
Sequence numbersThe receiver spots gaps and duplicatesState per connection
TimeoutsStop waiting after a limitYou may give up too early
ReconciliationCheck and repair later (compare ledgers)A short period of mismatch
Two-phase commitA coordinator decides, everyone followsCan block if the coordinator dies
Probabilistic certaintyMore acks make an error less and less likelyNever zero

The three end results for a request

βœ…Done, reply arrivedall good
❌Lost before the serverretry is needed
❓Done, reply lostretry would repeat it
πŸ“The client cannot tell the last two apart
In both of them the client sees only a timeout. That is the Two Generals Problem in a single sentence.
TCP's answer: enough steps to be sure in practice
πŸ“€SYNcan we talk?
→↓
πŸ“₯SYN-ACKyes, can you hear me?
←
πŸ“€ACKyes. Go.
Three messages make a lost connection setup very unlikely. They do not make it impossible.
Client Server
VisualizerSend messengers through a dangerous valleyRaise the chance of a messenger being caught and send more acknowledgements. Watch how the last sender is never sure, and a single lost message stops the chain.
🏰
General A
#1Attack at dawn➑️arrived
#2Got it. Attack at dawn⬅️arrived
#3Got your 'got it'➑️caught
🏯
General B
Messages after a lost one are dimmed: that general would not know to send them as planned.
Messengers sent
3
Caught
1
Chain unbroken
2
messages in a row that arrived
Last sender sure?
never
no ack for the last message
Message 3 (from A) was lost. A cannot tell whether it was lost or whether the reply is just slow, so A waits, then must send again. The plan is not yet agreed.

A fixed pattern stands in for chance, so the same slider setting always shows the same story. More acknowledgements make a wrong guess less likely (this is what a TCP handshake does) but never remove the doubt completely.

07How to Use It / Steps / Implementation

Living with it

  1. 1
    Assume the reply can be lost
    For every call, plan for the case where the work was done but you were never told.
  2. 2
    Give each request an ID
    A unique key per logical action, made once on the client.
  3. 3
    Make the server idempotent
    Store the key and the result. A repeat returns the saved result without doing the work again.
  4. 4
    Retry with backoff
    Wait a little longer each time, and add jitter. Do not hammer a struggling server.
  5. 5
    Put a limit on it
    Stop after a deadline and report an unknown outcome to the user or a repair job.
  6. 6
    Add a way to ask
    A status endpoint lets a client find out what happened to request X.
  7. 7
    Reconcile later
    A nightly check that compares both sides and fixes gaps catches the rare leftovers.
πŸ’‘Ask, don't guess
"Did my payment go through?" is a question the client can ask again. A status check is safer than repeating a write.

08Key Terms to Know

TermMeaning in easy words
Two Generals ProblemThe proof that two parties cannot be certain of agreement over a lossy link
Acknowledgement (ack)A message saying another message was received
Unreliable linkA connection that may lose, delay or duplicate messages
Common knowledgeBoth know it, both know that both know it, and so on forever
IdempotentDoing it twice has the same effect as doing it once
Idempotency keyA unique ID that lets a server recognise a repeated request
HandshakeA short exchange used to set up agreement, such as TCP's three steps
TimeoutA limit on how long to wait for a reply
ReconciliationComparing two records later and fixing differences
Unknown outcomeThe state where a request may or may not have run

09Pros, Cons and Trade-offs

βœ… Pros
  • Gives a clear reason for retries and idempotency
  • Stops you chasing impossible guarantees
  • Makes designs honest about uncertainty
  • Simple to explain and remember
  • Leads to practical tools: keys, status checks, reconciliation
⚠️ Cons
  • There is no complete fix, only risk reduction
  • Idempotency needs extra storage and design
  • Reconciliation adds jobs and delay
  • More acknowledgements cost latency
  • Teams often skip the failure case until it bites

Trade-offs

ChoiceWe gainWe lose
More acknowledgementsSmaller chance of errorMore delay and traffic, still not zero
Retry on timeoutWork eventually donePossible duplicates
No retryNo duplicatesPossible lost work
Idempotency keysSafe retriesKey storage and cleanup
Status check before retryAvoids repeating a writeAn extra call

10Common Problems and Mistakes

Common mistakes

  1. Treating a timeout as a failure. The work may be done. Retrying a non-idempotent call can charge twice.
  2. Promising exactly-once delivery. Over a lossy link, it is not possible. What you can build is exactly-once effect.
  3. Adding acks to "fix" it. Another ack just moves the doubt to the new last message.
  4. Retrying with no backoff. Retries can flood a server that was already struggling.
  5. No record of what was sent. Without a log, you cannot repair the unknown outcome later.
  6. Mixing it up with Byzantine faults. Here, nobody lies. The link is unreliable.

Things to watch

πŸ”‚Duplicates
Retries mean every receiver sees repeats sooner or later.
πŸ•³οΈLost final message
The last message in any protocol is the risky one. Design what happens if it vanishes.
⏳Blocking
A participant waiting for a decision that never comes can hold locks for a long time.
πŸ“’Drift between systems
Without reconciliation, tiny mismatches pile up silently.

11Real-World Examples

πŸ“„Akkoyunlu et al. (1975)
First described the problem. Gray later named it the Two Generals Paradox.
πŸ’³Stripe idempotency keys
Clients send an Idempotency-Key header, so a retried charge is not applied twice.
πŸ“‘TCP
Three-way handshake and sequence numbers reduce, but do not remove, the doubt.
πŸ“¨Kafka and SQS
At-least-once delivery with consumer-side dedupe is the standard answer.
🏦Bank settlement
Daily reconciliation catches transfers where one side recorded it and the other did not.
πŸ”€Two-phase commit
The blocking window after the prepare vote is this problem in database form.
Mini case: safe retry after a lost reply
πŸ’³Pay 50, key K1
⇒⇣reply lost
πŸ”Retry pay 50, key K1
→↓
🧾Server sees K1 againreturns the saved result
The same key makes the second try a lookup, not a second charge.

12Related Topics to Read Next

Idempotency→

The main tool for retrying safely.

Delivery Semantics→

At most once, at least once and what exactly-once means.

Exactly-Once Processing→

How to get the effect once on top of unreliable delivery.

Two-Phase Commit (2PC)β†’

A protocol that runs into this doubt.

Byzantine Fault Tolerance (BFT)β†’

The harder cousin where participants may lie.

Network Partitions→

What happens when the link is fully cut.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Problem: two honest parties, a lossy link, need certainty of agreement.
  • βœ”Result: impossible. The last sender never knows it arrived.
  • βœ”More acks: lower risk, never zero.
  • βœ”Timeout means: unknown, not failed.
  • βœ”Practical answer: retries + idempotency keys + status check.
  • βœ”Exactly-once: delivery impossible, effect possible with dedupe.
  • βœ”Not Byzantine: nobody lies here, the link is the problem.
  • βœ”One line: β€œYou can be almost sure, but never completely sure.”
← Previous
Distributed Unique ID Generation (Snowflake, UUID)
Next β†’
Byzantine Fault Tolerance (BFT)