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

Paxos

The classic consensus algorithm: propose, promise, accept.

โฑ 16 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Paxos is the classic algorithm that lets a group of machines agree on one value, even when some machines crash and messages are lost or late. It was described by Leslie Lamport.

  • It works in two phases: Prepare / Promise (reserve the right to propose) and Accept / Accepted (ask the group to take the value).
  • A value is chosen when a majority of acceptors accept it. Once chosen, it never changes.
  • Each proposal has a number. Higher numbers win, and a new proposer must adopt any value that may already be chosen.

02Concept: What is it?

Paxos solves one problem: get a group to choose a single value and never change its mind. Real systems repeat it many times (Multi-Paxos) to build a log of decisions, but the core idea is this one choice.

Paxos describes three roles. One machine can play all three:

  • Proposer: suggests a value and runs the two phases.
  • Acceptor: votes. A majority of acceptors decides the outcome. They must remember (on disk) what they promised and accepted.
  • Learner: finds out what was chosen.

The two phases for a proposal numbered n:

  1. Phase 1a, Prepare(n): the proposer asks acceptors: "Will you promise to ignore any proposal numbered below n?"
  2. Phase 1b, Promise: an acceptor that has not promised a higher number says yes. It also reports the highest-numbered proposal it already accepted, if any.
  3. Phase 2a, Accept(n, v): after a majority of promises, the proposer sends the value. The rule: if any promise reported an accepted value, the proposer must use the value with the highest number. Only if none did, it may use its own.
  4. Phase 2b, Accepted: an acceptor accepts unless it has promised a higher number since. When a majority accepted, the value is chosen.
Two phases, one majority each
๐Ÿ™‹Proposerpicks number n
โ†’โ†“Prepare(n)
๐Ÿ—ณ๏ธAcceptorsPromise + old value
โ†’โ†“Accept(n, v)
โœ…Majority acceptedvalue chosen
The promise in phase 1 is what blocks older proposals. The reported value is what protects a value that may already be chosen.
๐Ÿง The one rule that makes Paxos safe
In phase 2 you may only propose your own value if no promising acceptor has already accepted something. Otherwise you must carry forward the value with the highest proposal number. This is how a chosen value survives new proposers.

03Real-Life Example

๐ŸตChoosing the Meeting Room by Notes
Five office managers must pick one meeting room, using paper notes carried by a courier. Anna wants Room A, Raj wants Room B. Anna first asks all managers: "I am number 7. Promise to ignore any plan with a lower number, and tell me if you already agreed to a room." Three say yes, and none has agreed to anything. So Anna may suggest Room A. At the same moment Raj, number 8, asks the same. The managers who answered Raj now refuse Anna's plan, as 7 is lower than 8. Raj's plan wins. If the managers had already agreed to Room A, Raj would have heard it in the replies and would have to suggest Room A too.
Meeting-room notes
Paxos
Manager who votes
Acceptor
Anna or Raj with a plan
Proposer
Plan number (7, 8)
Proposal number (ballot)
'Promise to ignore lower numbers'
Phase 1: Prepare and Promise
'Tell me what you already agreed to'
Acceptors report their accepted value
'Please agree to Room A'
Phase 2: Accept
Three of five agreed
Majority: the value is chosen
Raj must suggest Room A if it was agreed
A proposer must adopt the highest accepted value
A collision resolved by the numbers
๐Ÿ…ฟ๏ธP1 (n=1)Prepare, then Accept
โ†’โ†“blocked by
๐Ÿ…ฟ๏ธP2 (n=2)Prepare came in between
โ†’โ†“wins
โœ…Chosenvalue from P2

04Why Do We Need It?

๐ŸงฑA proven base
Paxos has a formal proof of safety. Many systems build on it, or on variants.
๐Ÿ›ก๏ธSafe when things fail
It never chooses two values, even with crashes, delays and duplicate or reordered messages.
๐ŸงฎOnly a majority needed
A few crashed nodes do not stop progress.
๐Ÿ“’Replicated logs
Multi-Paxos agrees on one entry after another, so all replicas apply the same commands in the same order.
๐ŸงฉFlexible
Variants exist for leaders, fast paths, flexible quorums and cheaper reads.
๐ŸŽ“Shows up in interviews
It is the standard example for consensus, and a base to understand Raft.
Paxos is the answer to "how can unreliable machines agree?". The proposal numbers and the majority overlap keep it safe.

05Where Do We Use It?

๐Ÿ”’Google Chubby
A lock and small-file service built on Paxos, used inside Google.
๐ŸŒGoogle Spanner
Each group of replicas of a data range runs Paxos.
โ˜๏ธAzure and other clouds
Several cloud storage and metadata services use Paxos or close variants.
๐Ÿ—„๏ธCassandra lightweight transactions
Compare-and-set operations use Paxos between replicas for one key.
๐Ÿ“จMetadata services
Leader and membership info in many storage systems.
๐ŸŽ“Teaching and papers
Multi-Paxos and its variants are the reference for replicated state machines.

06Types / Parts / How It Works

Roles and messages

MessageFrom โ†’ ToMeaning
Prepare(n)Proposer โ†’ AcceptorsPlease promise to ignore proposals below n
Promise(n, accepted)Acceptor โ†’ ProposerPromised. Here is the highest proposal I already accepted (if any)
Accept(n, v)Proposer โ†’ AcceptorsPlease accept value v with number n
Accepted(n, v)Acceptor โ†’ Proposer and learnersI accepted it
Nack / refuseAcceptor โ†’ ProposerI promised a higher number, so I refuse

Variants

From one decision to a log
Basic Paxos
One valuetwo phases each time
simple, slow if repeated
Multi-Paxos
A log of valuesstable leader skips phase 1
one round trip per entry
Other variants
Fast, Cheap, Flexible, EPaxos
fewer delays or no single leader
Basic Most used Research and special cases
Basic Paxos picks one value. Real systems run many instances, often with a stable leader.

Paxos vs Raft

PaxosRaft
GoalAgree on a value (the log is added by Multi-Paxos)Replicate a log, with leader election built in
LeaderOptional in the basic form, an optimisation in Multi-PaxosAlways, and strongly enforced
Easy to learnFamously hard to turn into a real systemDesigned to be understandable
Log gapsEntries can be chosen out of orderThe log is always contiguous
Used byChubby, Spanner, many internal systemsetcd, Consul, CockroachDB, TiKV
VisualizerPaxos step by step: promises, accepts, crashes and collisionsPick a situation, then press Next. Watch what each acceptor promises and accepts. In 'Value already chosen', see how a new proposer is forced to keep the old value.
Pick a situation
One proposer, no trouble. Two phases are enough.
๐Ÿ—ณ๏ธ
Acceptor A1
promised: none
nothing accepted
๐Ÿ—ณ๏ธ
Acceptor A2
promised: none
nothing accepted
๐Ÿ—ณ๏ธ
Acceptor A3
promised: none
nothing accepted
No value chosen yet
Step 1 of 3
Start
Three acceptors (A1, A2, A3) hold the state. Two proposers (P1, P2) want to get a value chosen. A majority means 2 of 3.

A simplified single-decision Paxos with 3 acceptors and no message delay. Numbers like (1, A) mean proposal number 1 with value A. Real systems run many rounds (Multi-Paxos) and save every promise to disk before replying.

07How to Use It / Steps / Implementation

How to think about running Paxos

  1. 1
    Pick a unique, growing proposal number
    Often a pair (counter, node id), so two proposers never use the same number.
  2. 2
    Send Prepare(n) to the acceptors
    Wait for promises from a majority. If you cannot get a majority, retry with a bigger number later.
  3. 3
    Look at the replies
    If any acceptor reports an accepted value, take the one with the highest proposal number as your value. Otherwise use your own.
  4. 4
    Send Accept(n, v)
    Wait for a majority of Accepted replies. Then v is chosen.
  5. 5
    Tell the learners
    Send the result to the nodes that need it, or let them ask a majority.
  6. 6
    Acceptors must save to disk first
    Write the promise or the accepted value to stable storage before replying. Otherwise a restart can break safety.
  7. 7
    Use a stable leader
    In Multi-Paxos, one proposer stays leader and skips phase 1 for the next entries. Others back off, which avoids endless collisions.
๐Ÿ’กUse a library, not your own code
Real Paxos has many details: log gaps, leader changes, membership changes, snapshots. Use a system that already has it, or Raft, which is better documented.
โš ๏ธLivelock
Two proposers can keep cancelling each other by using ever higher numbers. The fix is a single leader, or a random wait before retrying.

08Key Terms to Know

TermMeaning in easy words
ProposerA node that suggests a value and drives the two phases
AcceptorA node that promises and accepts. A majority of them decides
LearnerA node that learns the chosen value
Proposal number (ballot)A growing number that orders proposals. Higher wins
Prepare / PromisePhase 1: ask for and receive a promise to ignore lower numbers
Accept / AcceptedPhase 2: ask for and record acceptance of a value
ChosenA value accepted by a majority. It can never change
QuorumA majority of acceptors. Any two quorums overlap
Multi-PaxosRunning Paxos again and again, with a stable leader, to build a log
LivelockProposers keep blocking each other, so nobody finishes
Replicated state machineReplicas that apply the same ordered commands and so stay identical

09Pros, Cons and Trade-offs

โœ… Pros
  • Proven safe with crashes and lost messages
  • Needs only a majority alive
  • Very widely studied and used
  • Foundation for replicated logs
  • Many optimised variants
โš ๏ธ Cons
  • Notoriously hard to understand and implement
  • Basic Paxos is slow for a stream of values
  • Possible livelock without a leader
  • Details like membership change are not in the basic paper
  • Leader changes and log gaps need extra design

Trade-offs

ChoiceWe gainWe lose
Basic Paxos per valueSimple idea, no leaderTwo round trips for each value
Multi-Paxos with leaderOne round trip per entryLeader failure causes a pause and election
Larger clusterMore crashes toleratedMore messages and slower writes
Spread across regionsSurvives a whole region lossCross-region latency on every decision
Paxos instead of RaftMore flexibility, many variantsMore work, fewer ready-made examples
Fast Paxos / EPaxosFewer message delaysMore complex, needs larger quorums

10Common Problems and Mistakes

Common mistakes

  1. Ignoring the adopt rule. A proposer that always uses its own value can overwrite a chosen value.
  2. Not saving promises to disk. A node that restarts and forgets can promise twice, and safety breaks.
  3. Non-unique proposal numbers. Two proposers with the same number can get two values chosen.
  4. Using a minority. Counting 2 of 5 as enough breaks the overlap that makes it safe.
  5. No leader under heavy load. Proposers collide and livelock.
  6. Treating it as a database. It agrees on values. Storage, snapshots and recovery are your job.

Things to watch

โš”๏ธDuelling proposers
Two proposers keep raising numbers. Elect one leader, and add a random back-off.
๐Ÿ’พSlow disks
Each promise needs a disk flush, so disk speed sets the limit.
๐Ÿ•ณ๏ธLog gaps
In Multi-Paxos, entries may be chosen out of order, so replicas must fill holes before applying them.
๐Ÿ‘ฅMembership change
Adding or removing nodes safely is a separate, tricky problem.

11Real-World Examples

๐Ÿ”’Chubby
Google's lock service. The paper 'Paxos Made Live' tells how hard it was to turn Paxos into a real system.
๐ŸŒSpanner
Each data split is a Paxos group, spread over zones or regions.
๐ŸชฃCloud storage
Several large storage services replicate metadata with Paxos variants.
๐Ÿ—‚๏ธCassandra LWT
Lightweight transactions use Paxos to do compare-and-set safely on one key.
๐ŸงชEPaxos research
A leaderless variant that lets non-conflicting commands commit in one round trip.
๐Ÿง‘โ€๐ŸŽ“Raft
Created because Paxos was too hard to teach and implement. Many newer systems chose Raft.
๐Ÿ“Note
Which protocol a product uses can change between versions. Check its current documentation.
Mini case: a 5-acceptor group in three zones
๐ŸขZone 1A1, A2
โ†”
๐ŸขZone 2A3, A4
โ†”
๐ŸขZone 3A5
Losing a whole zone (2 acceptors) still leaves 3 of 5, which is a majority.

12Related Topics to Read Next

Consensus Algorithmsโ†’

The bigger picture that Paxos belongs to.

Raftโ†’

A consensus protocol made to be easier to understand.

Leader Electionโ†’

Multi-Paxos relies on a stable leader.

Distributed Locksโ†’

Lock services such as Chubby are built on Paxos.

Two-Phase Commit (2PC)โ†’

Also two phases, but it solves a different problem and blocks on failure.

Lamport Timestampsโ†’

From the same author, the clock idea behind ordering.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Goal: agree on one value, with crashes and lost messages.
  • โœ”Roles: proposer, acceptor, learner.
  • โœ”Phase 1: Prepare(n) โ†’ Promise (plus any value already accepted).
  • โœ”Phase 2: Accept(n, v) โ†’ Accepted. Use the highest reported value, or your own if none.
  • โœ”Chosen: a majority accepted. It never changes.
  • โœ”Safety: higher numbers win, majorities overlap, promises go to disk.
  • โœ”Multi-Paxos: stable leader skips phase 1, giving a replicated log.
  • โœ”One line: โ€œAsk for a promise, take over any value that may be chosen, then get a majority to accept.โ€
โ† Previous
Consensus Algorithms
Next โ†’
Raft