etcd and Raft Consensus in Kubernetes
How a small group of etcd servers agrees on every single change to your cluster, survives crashes and network splits without losing data, and why that one design choice decides how reliable your whole Kubernetes control plane can be.
Imagine a class of five students who share one notebook that records every rule of the classroom: who sits where, who is on duty, which homework is due. If only one student keeps the notebook and that student gets sick, nobody knows the rules anymore. If everyone keeps their own copy, the copies slowly drift apart and arguments begin. A smarter class makes a pact. Every new rule is announced by one student, and it only counts once most of the class has written it down. If the announcer leaves, the class quickly picks a new announcer who is guaranteed to know every rule that counted. A Kubernetes cluster works like this class, and the pact is called Raft. The notebook is etcd. Everything Kubernetes knows about itself lives inside that notebook, so understanding how its members agree is one of the most useful things an engineer can learn.
1Why Kubernetes Needs an Agreeing Memory
A cluster that forgets what it was told is not a cluster for very long.
Kubernetes is built around a simple promise. You describe what you want, such as “run three copies of this web server,” and the system works day and night to make reality match your description. For that promise to mean anything, the description must be stored somewhere safe. The place where Kubernetes keeps every description, along with the current state of every Pod, Service, Secret, ConfigMap and Node, is a database called etcd.
Now think about what happens if that database is a single machine. If the machine crashes, the cluster loses its memory. Existing containers might keep running for a while, but nobody can create, change or repair anything, and if the disk is damaged, the record of what should be running may be gone forever. A single database is a single point of failure, and for the brain of a production platform that is unacceptable.
The obvious answer is to keep several copies on several machines. But copies create a new and subtler problem. If two copies receive different instructions at nearly the same moment, which one is right? If the network between them breaks, can each side keep accepting changes? If both do, the copies disagree, and when the network heals there is no clean way to merge two different histories of a cluster. Engineers call this the split-brain problem, and it can be far worse than an outage, because the system keeps running on conflicting beliefs.
Two bank branches lose their phone line to each other. Both keep serving customers. A customer withdraws all their money at branch A, and then walks to branch B and withdraws it again. When the phones come back, the bank has paid out twice. A safe bank would insist that a withdrawal only happens when a majority of branches agree, so that a cut-off branch simply says “please wait” instead of guessing.
etcd solves this with a consensus algorithm called Raft. Consensus means getting several computers to agree on one shared history, even though some of them may crash and the network between them may lose or delay messages. With Raft, etcd gives Kubernetes a memory that is copied across several servers, never contradicts itself, and keeps working as long as a majority of those servers can talk to each other.
Raft does not try to make every server agree instantly. It makes sure that a change only becomes official when a majority has stored it, which guarantees that any future majority must include at least one server that remembers it.
2The Role of etcd in Kubernetes
Where etcd sits, who is allowed to talk to it, and what it actually stores.
etcd is a distributed key-value store. That means it holds pairs of a key, like a file path, and a value, like the contents of a file. Kubernetes stores each object under a key that includes its kind, namespace and name, and the value is the serialized object itself. When you create a Deployment, a record for it appears in etcd. When a controller updates the status of a Pod, the Pod’s record changes.
One rule of the architecture is easy to miss and extremely important: only the API server talks to etcd. The scheduler, the controller manager, the kubelets and your own tools never connect to it directly. They all talk to the API server, and the API server reads and writes etcd on their behalf. This keeps etcd well protected, keeps the number of clients small, and means all the validation, authentication and policy checks happen in one place before data is stored.
flowchart TD
U["Users and kubectl"] --> A["API Server"]
S["Scheduler"] --> A
C["Controller Manager"] --> A
K["Kubelets on every node"] --> A
A --> E1["etcd member 1"]
A --> E2["etcd member 2"]
A --> E3["etcd member 3"]
E1 E2
E2 E3
E1 E3
What lives in etcd
Almost every object you can list with a Kubernetes command is stored there: Pods, Deployments, Services, ConfigMaps, Secrets, Nodes, Namespaces, roles and bindings, custom resources, and Leases. It also holds cluster-wide records such as the registered API extensions. What it does not hold is application data. Your database rows, uploaded files and container images live elsewhere. etcd is built for small, precious, frequently read metadata, not for bulk storage.
Think of a ship’s logbook kept in the captain’s cabin. Only the first mate writes in it, after checking every entry. The crew, the cook and the navigator all send their reports to the first mate and never touch the book themselves. The logbook records what the ship is doing and what it should do next, but it does not carry the cargo.
A built-in size limit, and why
By default, etcd refuses a single request larger than about one and a half megabytes. This is the real reason why a Kubernetes object cannot grow without limit. Raft sends every write to every member, so very large values slow the whole group down. The limit nudges people to keep objects small and to put big data in proper storage systems.
| Component | Talks to etcd? | Talks to |
|---|---|---|
| API server | Yes, the only one | etcd, plus all other components |
| Scheduler | No | API server |
| Controller manager | No | API server |
| Kubelet | No | API server |
| kubectl and tools | No | API server |
Because etcd holds the state, the other control plane programs can be restarted or replaced freely. Protecting etcd is therefore the same as protecting the cluster’s memory.
3What Is Consensus?
Getting a group of unreliable computers to behave like one reliable one.
Computers fail in ordinary ways. A power supply dies, a disk slows down, a network cable is unplugged, or a program pauses for several seconds while the operating system does housekeeping. Worse, from the outside it is often impossible to tell whether a silent server has crashed or is just slow. Consensus algorithms are carefully designed recipes that let a group make decisions despite these uncertainties.
The standard way to use consensus is called a replicated state machine. Imagine every member starts with the same empty notebook. A shared list of instructions, such as “set key A to 5” and “delete key B,” is agreed upon in a fixed order. Every member then carries out the same instructions in the same order. Because each member performs identical steps from an identical start, they all end up with identical notebooks. The hard part is only one thing: agreeing on the order of the list. That agreed list is called the log, and Raft is a method for keeping it consistent.
Five cooks in five kitchens each follow the same recipe card, step by step. If every cook receives the same steps in the same order, all five dishes taste identical, even though nobody is watching the others. Consensus is the system that makes sure every kitchen gets the same card, in the same order, with no missing or swapped steps.
What kinds of failure Raft tolerates
Raft is designed for crash faults and network faults. Servers may stop and later restart. Messages may be delayed, lost, duplicated or reordered. Raft is not designed for Byzantine faults, where a server lies or is controlled by an attacker and sends deliberately misleading messages. That is why the network between etcd members must be trusted and protected, a point we will return to in the security chapter.
Where Raft comes from
Raft was published in 2014 by Diego Ongaro and John Ousterhout, in a paper whose title describes its main goal: an understandable consensus algorithm. An older algorithm called Paxos solved the same problem but was famously hard to learn and to implement correctly. Raft breaks the problem into three independent pieces, leader election, log replication and safety, which made it much easier to build. etcd uses its own Raft library, and the same library has been reused by other well-known distributed systems.
| Piece of Raft | Question it answers |
|---|---|
| Leader election | Who is in charge right now? |
| Log replication | How does the leader copy changes to everyone? |
| Safety | How do we guarantee agreed changes are never lost or reversed? |
| Membership change | How can the group grow or shrink without risk? |
4Raft in Plain Words: Roles and Terms
Three roles, one rising counter, and a handful of simple rules.
Every member of a Raft group is always in exactly one of three roles. Understanding the roles is the key that unlocks the rest of the algorithm.
Follower
The default role. A follower accepts instructions from the leader, answers requests for votes, and waits quietly. If it stops hearing from a leader for too long, it assumes the leader is gone.
Candidate
A follower that has lost patience and is asking the others to vote for it as the new leader. This role is temporary and lasts only until the election ends.
Leader
The one member that accepts new changes, writes them in the log, copies them to the followers and tells the group when they are officially committed. It also sends regular heartbeats.
Term
A number that only goes up. Each election starts a new term. A term works like a numbered school year: at most one leader per term, and a higher term always overrules a lower one.
flowchart LR
F["Follower"] -->|"No heartbeat for too long"| C["Candidate"]
C -->|"Wins a majority of votes"| L["Leader"]
C -->|"Another leader appears"| F
C -->|"No winner, try again"| C
L -->|"Sees a higher term"| F
Why terms matter
Terms act as a logical clock. Every message carries the sender’s term. If a member receives a message with a higher term than its own, it immediately updates its term and, if it was a leader or candidate, steps down to follower. If it receives a message with a lower term, it ignores it as outdated. This single rule is what prevents an old, disconnected leader from causing damage after it returns: the moment it hears a higher term, it knows its time is over.
A school elects a class captain every year. Year numbers only go forward. If a student from last year’s team comes back claiming to be captain, everyone checks the year, sees that it is old, and politely ignores them. Raft terms play exactly the role of those year numbers.
A Raft term counts elections. An etcd revision counts changes to the data. They are separate counters. The revision is the one that Kubernetes exposes to users as part of the resourceVersion of objects.
5Leader Election Step by Step
How the group picks a boss within a second or two, and never picks two at once.
When an etcd group starts, every member begins as a follower and nobody is in charge. Each follower runs a countdown timer called the election timeout. The leader, once it exists, resets that timer on every follower by sending regular small messages called heartbeats. As long as the heartbeats keep arriving, followers stay calm.
The timer runs out
A follower hears nothing from a leader for a full election timeout. By default etcd uses a heartbeat interval of one hundred milliseconds and an election timeout of one second.
Become a candidate
The follower raises its term by one, votes for itself, and becomes a candidate.
Ask for votes
It sends a vote request to all other members, saying who it is, which term it is asking about, and how up to date its log is.
Voters decide
Each member gives at most one vote per term, first come first served, and only to a candidate whose log is at least as up to date as its own.
Win with a majority
A candidate that gathers votes from a majority becomes the leader and immediately sends heartbeats to announce itself and stop other elections.
sequenceDiagram
participant A as Member A
participant B as Member B
participant C as Member C
Note over A,C: Leader has failed, timers are running
Note over B: B's timer fires first
B->>A: Vote for me in term 5
B->>C: Vote for me in term 5
A-->>B: Vote granted
C-->>B: Vote granted
Note over B: B holds a majority and becomes leader
B->>A: Heartbeat, I lead term 5
B->>C: Heartbeat, I lead term 5
Randomness prevents deadlock
What if two followers time out at exactly the same moment? Each votes for itself, the other members split their votes, and nobody reaches a majority. This is called a split vote. Raft avoids endless repetition by making each member’s election timeout slightly random, within a range. After a split vote, one member will almost always time out first in the next round, win quickly and end the tie. In practice, a healthy etcd group completes an election in about the length of one timeout.
The majority rule guarantees a single leader
Because each member votes once per term, and a leader needs a majority, two leaders can never be elected in the same term. Any two majorities of the same group overlap in at least one member, and that member would have had to vote twice to elect both, which the rules forbid. This tiny piece of arithmetic is the foundation of everything Raft promises.
A member that was cut off from the network keeps timing out and raising its term. When it returns, its inflated term could force a healthy leader to step down for no good reason. Recent etcd versions support a pre-vote step, where a would-be candidate first checks whether it could win before raising its term, which avoids this disruption.
When the teacher leaves the room, nobody panics straight away. Each student waits a slightly different amount of time before saying “Shall I take charge?” The first to speak gets the class’s nod. Because the waits are all a bit different, two students almost never speak at precisely the same instant.
6Log Replication and Commit
How one write travels from the leader to a majority and becomes permanent.
Once a leader exists, all changes go through it. If a client contacts a follower with a write, the follower passes the request along to the leader. The leader’s job is to turn each request into an entry in its log and make sure a majority of members store the same entry in the same position.
Each log entry has an index, which is its position in the list, a term, which is the term in which the leader created it, and the instruction itself. The leader appends the new entry to its own log, then sends it to all followers in a message called an append request. Each follower checks that its log matches the leader’s just before the new entry. If it does, the follower adds the entry and replies with a success. If not, the leader backs up and sends the earlier missing entries first until the follower’s log is repaired.
sequenceDiagram
participant Cl as Client
participant L as Leader
participant F1 as Follower 1
participant F2 as Follower 2
Cl->>L: Write request
L->>L: Append to own log and save to disk
L->>F1: Append entry
L->>F2: Append entry
F1->>F1: Save to disk
F1-->>L: Done
Note over L: Leader plus one follower is a majority
L->>L: Mark entry committed and apply it
L-->>Cl: Success
L->>F1: Next message tells follower the commit point
L->>F2: Next message tells follower the commit point
Committed means safe
An entry is called committed once the leader knows it is stored on a majority of members. From that moment, Raft promises it will never be lost, even if the leader crashes immediately afterwards. The leader then applies the instruction to the actual key-value data and tells the client the write succeeded. The followers learn the new commit point through later messages and apply the same instruction in the same order.
Notice that the leader does not wait for every member, only for a majority. If one follower is slow or down, writes continue without delay. The slow follower catches up later, because the leader keeps resending entries until the follower’s log matches.
A teacher announces a new rule and waits until at least half of the class plus one have written it down. At that point the rule is official, even if a few students are daydreaming. Later, the teacher re-reads the rule to the stragglers until their notebooks match.
Why the leader writes to disk first
Before acknowledging anything, every member saves the entry to a file on disk and forces the operating system to flush it to permanent storage. If a member only kept the entry in memory, a power failure after it said “done” would erase a promise it already made, and the guarantees would break. This is why disk speed is the most important performance factor for etcd, a point we will explore in the performance chapter.
A new leader cannot declare entries from older terms committed merely by counting how many members hold them. It first commits a fresh entry from its own term, and that also commits everything before it. This subtle rule prevents rare but nasty edge cases and is one reason Raft implementations are carefully tested.
7Safety: Why Committed Data Is Never Lost
Five promises that Raft keeps no matter which servers crash or which messages go missing.
Speed and convenience mean nothing if the system can forget committed data. Raft therefore comes with a short list of safety properties, each of which is proven to hold. Knowing them helps you reason about almost any failure story.
Election Safety
At most one leader can be elected in any single term, thanks to one vote per member per term and the majority requirement.
Leader Append-Only
A leader never deletes or rewrites entries in its own log. It only adds new ones at the end.
Log Matching
If two logs contain an entry with the same index and term, then those logs are identical in every entry up to that point.
Leader Completeness
Any entry committed in one term is present in the log of every leader elected in later terms.
State Machine Safety
No two members ever apply different instructions at the same position in the log.
The election restriction
The most clever rule sits inside the voting step. A member only votes for a candidate whose log is at least as up to date as its own, judged first by the term of the last entry and then by the length of the log. Combine this with the majority rule. A committed entry lives on a majority of members. A candidate needs votes from a majority to win. Any two majorities overlap, so at least one voter in the winning majority holds the committed entry, and that voter will refuse any candidate who lacks it. The result is that a candidate missing committed data can never become leader.
Suppose a class rule only counts once more than half of the students have written it down. When the class later elects a new captain, each student refuses to vote for anyone whose notebook has fewer rules than their own. Since at least one student who knows the rule must be among the voters, nobody who missed the rule can win.
What happens to uncommitted entries
Not every entry in a log is committed. If a leader crashes after saving a new entry locally but before copying it to a majority, that entry was never promised to the client. A new leader, which lacks the entry, will simply carry on. When the old leader returns as a follower, the new leader overwrites its extra entries with the correct history. Because the client never received a success reply, nothing that was promised is lost. Clients that time out must simply retry or check the result, which is why idempotent operations and resource versions are so valuable on the Kubernetes side.
| Situation | Was the client told success? | What Raft does |
|---|---|---|
| Entry stored on a majority | Yes | Keeps it forever, every future leader has it |
| Entry only on the old leader | No | May be erased when the old leader rejoins |
| Client timed out before reply | Unknown | Entry may or may not exist, so the client must check or retry safely |
A timed-out write against the API server may or may not have been stored. Controllers that are idempotent and use resource versions can safely repeat the work without fear of doubling it.
8Quorum Math and Cluster Sizing
Why three or five members is the sweet spot, and why four is a trap.
A quorum is the smallest number of members that counts as a majority. For a group of N members, the quorum is half of N, rounded down, plus one. Raft needs a quorum both to elect a leader and to commit any entry. If a quorum is available, the group works. If not, the group stops accepting changes rather than risk disagreement.
| Members | Quorum | Failures tolerated | Comment |
|---|---|---|---|
| 1 | 1 | 0 | No fault tolerance, only for testing |
| 2 | 2 | 0 | Worse than one member, since either failing stops the group |
| 3 | 2 | 1 | The most common production choice |
| 4 | 3 | 1 | No better than three, with more cost |
| 5 | 3 | 2 | Survives two failures, good for larger or critical clusters |
| 7 | 4 | 3 | Upper end of the commonly recommended range |
Why even numbers do not help
Look at the table. A group of four needs three members to agree, and so tolerates only one failure, exactly like a group of three. The fourth member adds cost and slightly slows every write, because the leader must reach more members, without improving survival. An even group can also split evenly in a network partition, leaving neither side with a majority. For these reasons, odd sizes are strongly preferred.
Why more members is not always better
It is tempting to think that more members means more safety and more speed. Safety does improve a little, but speed does not. Every write goes through the single leader and must reach a quorum, so adding members never increases write throughput. It actually makes writes a bit slower, because the leader sends each entry to more places. Beyond five or seven members, the cost outweighs the benefit. The usual guidance is to use three members for most clusters, five where the extra resilience is worth it, and to avoid going past seven.
Imagine a committee that must have more than half its members present to make a decision. With three members, two must attend. Adding a fourth member means three must attend, so the committee can still lose only one member. Meanwhile every meeting needs more people to coordinate. Adding a fifth member finally lets the committee lose two.
Three members placed on three machines in one rack still die together if the rack loses power. Place members in separate failure zones, such as different availability zones, while keeping the network delay between them small.
9Anatomy of a Kubernetes Write Through etcd
Following a single kubectl change from your keyboard all the way to durable storage.
Let us connect the dots. Suppose an engineer changes the replica count of a Deployment. Here is what happens, from the request to the safe storage of the new value.
flowchart TD
A["Engineer sends the change"] --> B["API server: authenticate, authorize, admit, validate"]
B --> C["API server sends a conditional write to etcd"]
C --> D["Any etcd member forwards it to the leader"]
D --> E["Leader appends to log and saves to disk"]
E --> F["Leader sends entry to followers"]
F --> G{"Majority saved?"}
G -->|Yes| H["Commit, apply to the data, new revision"]
G -->|No| I["Wait, retry, or fail on timeout"]
H --> J["Reply to API server, then to the engineer"]
H --> K["Watchers are notified of the change"]
Checks at the front door
The API server verifies identity, permission and validity before anything touches etcd.
A conditional write
The API server asks etcd to store the new object only if the key still has the version it was based on. This is the optimistic concurrency check that gives resourceVersion its meaning.
A Raft proposal
The condition and the new value become one entry that goes through the leader, is saved on a majority and is committed.
Apply and increase the revision
Every member applies the committed entry in the same order, so each independently arrives at the same new revision number for the key.
Notify and respond
The API server returns the new object, with its new resourceVersion, to the caller, and every watcher is sent an event about the change.
Why the revision is trustworthy
The cluster-wide revision counter that Kubernetes uses to produce resource versions is itself a product of consensus. Because all members apply the same entries in the same order, they all assign the same revision to each change. That is why a version stamp read from one member means the same thing everywhere, and why compare-and-swap writes are safe even when different etcd members serve different requests.
Think of a courthouse stamp that numbers every official document in order. The stamping happens only after the judges have agreed on the document. Anyone who sees stamp number 5012 knows exactly where the document sits in history, and no two documents can share a stamp.
Every successful write waits for at least one follower to save to disk and answer. The time you wait is therefore the leader’s disk save, the network trip to the followers, the followers’ disk saves, and the trip back.
10Reads: Linearizable versus Serializable
Reading seems simple, yet it hides a subtle choice between accuracy and speed.
You might think reads are easy because they change nothing. But in a group of members, a follower may be a little behind the leader. If a read were served from a lagging follower’s local data, it could return an old answer even though a newer one has already been committed. etcd therefore offers two read modes.
| Read mode | How it works | Guarantee | Cost |
|---|---|---|---|
| Linearizable | The member confirms with the leader what the latest committed point is, waits until it has applied up to that point, then answers | Always sees the latest committed data | An extra round of communication |
| Serializable | The member answers from its own local data right away | A consistent but possibly slightly old view | Cheapest and fastest |
sequenceDiagram
participant Cl as Client
participant F as Follower
participant L as Leader
Cl->>F: Read, latest data please
F->>L: What is the current commit point?
L->>L: Confirm still leader with a majority
L-->>F: Commit point is 900
F->>F: Wait until applied up to 900
F-->>Cl: Answer from fresh data
How this shows up in Kubernetes
Remember the resourceVersion choices on reads. When a request leaves the version unset, the API server asks etcd for a quorum read, which is the linearizable mode, and gets the most recent data. When the version is set to zero, the API server answers from its own in-memory cache, which is fed by a watch on etcd and may lag slightly. The Kubernetes freshness dial is therefore directly tied to the etcd read modes underneath, and to protect etcd from heavy traffic, the API server leans on its cache for most list requests.
A serializable read is like asking a classmate what the homework is. They answer immediately from memory, but they may have missed the teacher’s latest announcement. A linearizable read is like asking the classmate to check with the teacher first. It takes a moment longer, but you get the current answer.
Linearizable reads depend on the leader confirming its leadership with a majority. If a quorum is lost, even reads that need the latest data cannot be answered, and the API server begins to return errors or time out.
11Storage Under Raft: Logs, Snapshots and Compaction
How etcd keeps its promises across restarts without growing forever.
Raft is about agreement, but each member must also remember what was agreed after a restart. etcd uses several layers of storage that work together, and knowing them clears up many operational mysteries.
Write-ahead log
A file where each member saves every Raft entry before acknowledging it. After a crash, replaying this file restores the member’s memory of what it promised.
Raft snapshot
Every so often, a member records the current state and trims the older log entries. This keeps the log short and lets a far-behind member catch up quickly.
Backend database
A single-file database that holds the actual keys, values and their history. Committed entries are applied here.
Multi-version history
etcd keeps old versions of keys, labelled by revision, so that watches can resume and reads can look back. This is what resource versions rely on.
Compaction and defragmentation
Because etcd keeps history, the database grows with every change, even when keys are overwritten. Compaction tells etcd to forget history older than a chosen revision. The Kubernetes API server asks etcd to compact on a regular schedule, by default about every five minutes. This is exactly why watchers that fall too far behind receive the 410 Gone response: the history they wanted was compacted away.
Compaction frees space inside the database file but does not shrink the file on disk. Returning that space to the operating system requires a separate step called defragmentation. Defragmentation briefly blocks the member it runs on, so it is performed one member at a time, starting with followers, and usually during quiet periods.
Writes accumulate
Every update adds a new revision of a key and a new entry in the write-ahead log.
Raft log is snapshotted and trimmed
Once enough entries have built up, the member snapshots its state and discards old log entries it no longer needs.
History is compacted
The API server periodically compacts old revisions, marking space as reusable.
Defragmentation reclaims disk
An operator runs defragmentation, one member at a time, to shrink the file.
The space quota and the alarm
etcd protects itself with a storage quota. By default the database may grow to about two gigabytes, and operators are advised to stay well below a much higher ceiling, often cited as eight gigabytes. If the quota is exceeded, etcd raises an alarm and switches to a mode that rejects writes, while still allowing reads and deletions. The cluster then cannot change until space is freed, which is a well-known and painful incident.
Do not mix up the internal Raft snapshot, which trims the log, with a backup snapshot, which an operator takes to save the whole database to a safe place. They share a name but serve different purposes.
12Membership and Cluster Topologies
How etcd groups are shaped, grown and shrunk without breaking the majority rule.
An etcd group is not frozen forever. Servers fail and need to be replaced, and clusters grow. But changing the membership of a consensus group is dangerous. If the old group and the new group could each form a majority at the same time, you could briefly have two leaders. etcd avoids this by changing the membership one member at a time, so that any majority of the old group and any majority of the new group always overlap.
Learners: joining safely
A new member that starts with an empty database has a lot of catching up to do. If it were counted in the quorum immediately, it could make the group more fragile while it is still behind, because writes might wait on a member that cannot yet keep up. etcd therefore supports learners, which are members that receive log entries but do not vote and do not count toward the quorum. An operator adds the new member as a learner, waits until it has caught up, and only then promotes it to a full voting member. Typically only one learner is allowed at a time.
A new student joins the class mid-year. For the first few weeks they sit in and copy the notebook but do not vote on class decisions. Once they have caught up with all the rules, they receive a vote like everyone else.
Two ways to place etcd
Cluster builders choose between two layouts. In a stacked topology, each control plane machine runs an etcd member next to the API server, scheduler and controller manager. It is simple, needs fewer machines, and is the default for common cluster setup tools. In an external topology, the etcd group runs on its own dedicated machines, separate from the control plane.
flowchart TB
subgraph ST["Stacked topology"]
direction TB
S1["Control plane node 1: API server plus etcd"]
S2["Control plane node 2: API server plus etcd"]
S3["Control plane node 3: API server plus etcd"]
end
subgraph EX["External topology"]
direction TB
X1["Control plane node 1: API server"]
X2["Control plane node 2: API server"]
X3["Control plane node 3: API server"]
E1["Dedicated etcd 1"]
E2["Dedicated etcd 2"]
E3["Dedicated etcd 3"]
X1 --> E1
X2 --> E2
X3 --> E3
end
Stacked: Advantages
- Fewer machines to buy and manage
- Simpler to set up and to reason about
- Good fit for small and medium clusters
Stacked: Trade-offs
- Losing a node loses both an API server and an etcd member
- Control plane programs compete with etcd for disk and memory
- Harder to size and tune etcd independently
External: Advantages
- Failures of the control plane and etcd are decoupled
- etcd gets dedicated disks and memory
- Easier to scale and tune each part separately
External: Trade-offs
- Twice the machines to run and secure
- More certificates and network paths to manage
- More moving parts during upgrades
In managed offerings from cloud providers, etcd is run for you and is not exposed. You inherit their design choices, which is convenient, but also means you cannot take direct backups or tune it yourself.
13Failure Scenarios and What Kubernetes Feels
Walking through the bad days to see exactly how Raft and the cluster respond.
The best way to appreciate a consensus algorithm is to watch it handle trouble. Here are the most important failure situations for a three-member group and what each means for your cluster.
One follower fails
The leader still has a quorum of two out of three, so writes and reads continue without a pause. Nobody outside the group notices anything except a monitoring alert. The failed member should be repaired or replaced before a second failure arrives, because the cluster has now lost all its spare capacity.
The leader fails
Followers stop hearing heartbeats, a timer fires, and an election runs. Within roughly a couple of seconds a new leader is chosen from the remaining members, and the election restriction guarantees that it holds every committed entry. During those seconds, writes briefly stall or time out, and then resume. The API server retries internally, so most users see only a short hiccup.
Two members fail, quorum is lost
The sole survivor cannot reach a majority, so it cannot commit writes or confirm fresh reads. etcd deliberately stops rather than guess. The API server returns errors, so nothing new can be created or changed. Containers that are already running keep running, because kubelets continue to operate on their last known instructions, but nothing can heal, scale or schedule until quorum returns.
A network partition
Suppose the network splits the group into one side with two members and another with one. The two-member side still has a quorum, elects or keeps a leader, and carries on. The lone member cannot win an election or commit anything, and if it was the old leader it notices it has lost contact with a majority and steps down. When the network heals, the lone member learns the higher term, rejoins as a follower, and is brought up to date.
flowchart LR
subgraph MAJ["Majority side: 2 members"]
A["Member A"]
B["Member B leader"]
end
subgraph MIN["Minority side: 1 member"]
C["Member C"]
end
A B
B -.->|"Network cut"| C
What the data plane does meanwhile
An important point for operators is that the control plane and data plane fail differently. When etcd is unavailable, your application Pods generally keep serving traffic, because the kubelet and the container runtime do not need to ask etcd for permission to keep running. What stops working is everything that needs to change state: deployments, scaling, repairs, new Service endpoints and new Pods. That is a degraded but not dead cluster.
If the school office loses its filing system, classes already in session carry on because the teachers know their lesson plans. But nobody can enrol new students, change timetables or replace a missing teacher until the filing system returns.
A leader that cannot reach a majority within an election timeout steps down on its own. This prevents a stranded leader from believing it is still in charge and serving stale reads.
14Performance and Tuning
Disk first, network second, and only then the timers.
etcd is an unusual database. It does not need huge amounts of processor power or memory, but it is extremely sensitive to the speed and steadiness of its disk and network. Understanding why helps you size it correctly.
The disk is the heartbeat
Every Raft entry must be forced to permanent storage before it is acknowledged. The time this takes, called the fsync latency, sits in the middle of every write. If a disk is slow or has unpredictable delays, writes slow down, followers miss heartbeats and unnecessary elections occur. Guidance from the project says that the ninety-ninth percentile of the write-ahead log sync time should stay under about ten milliseconds. Fast solid-state drives on dedicated volumes are strongly recommended, and sharing a disk with noisy neighbours is a common cause of trouble.
The network sets the floor
Each write needs at least one round trip to a follower. If members are far apart, such as in different regions, every write inherits that delay, and cross-region stretching of a single etcd group is generally a bad idea. Members spread across nearby availability zones, with low and stable delay, are the usual compromise between resilience and speed.
Heartbeat and election timers
The heartbeat interval should be about as long as the typical round trip between members, and the election timeout should be at least ten times that round trip. If the election timeout is too short, ordinary hiccups cause pointless elections. If it is too long, real failures take longer to detect and recover from. The defaults of one hundred milliseconds and one second suit a single data centre. Clusters spread across zones with higher delay may raise both, trading slower failure detection for fewer false alarms.
| Factor | Why it matters | Good practice |
|---|---|---|
| Disk sync latency | Sits inside every write | Dedicated fast SSD, watch the sync time |
| Network delay between members | Adds to every commit | Keep members close, avoid long distances |
| Heartbeat and election timers | Balance detection speed against false elections | Election timeout at least ten times the round trip |
| Database size | Large files slow snapshots, restores and defragmentation | Compact regularly, stay well under the quota |
| Object size and count | Big or numerous objects load the log | Keep objects small, tame noisy controllers |
| Write rate to hot keys | Every write passes through one leader | Reduce churn, such as using Lease objects for heartbeats |
Think of the class pact again. How fast the class can adopt a rule depends on how quickly students can write it down in their notebooks and call back. A student with a slow pen delays everyone, and students sitting at opposite ends of a huge hall take longer to hear each other. Good performance means good pens and a compact room.
Separating noisy data
Some Kubernetes data is high volume and short lived, with Events being the classic example. Clusters at large scale often point the API server at a separate etcd group for events, so that this chatter cannot slow the main group that holds the important configuration. It is a simple example of dividing workloads so that one cannot hurt the other.
Because all writes funnel through the leader and wait for a majority, scaling etcd means making each member faster and the objects lighter, not simply adding more members.
15Security of the etcd Group
Whoever can talk to etcd can rewrite your whole cluster, so the doors must be locked.
Because etcd holds the entire state of the cluster, including every Secret, access to it is effectively access to everything. Anyone who can write to etcd directly can bypass every check that the API server performs, including permissions and policies. Protecting it carefully is therefore a top priority.
Two separate ports
By convention, port 2379 serves clients such as the API server, and port 2380 carries traffic between members. They should be reachable only by the machines that need them.
Mutual TLS
Members and clients prove their identity to each other with certificates, and every connection is encrypted. Separate certificates for peers and for clients keep their roles apart.
Only the API server as a client
Give only the API server a client certificate. Everything else should use the API server and its access rules.
Encrypted Secrets
Encryption of Secrets is configured in the API server, which encrypts them before storing them in etcd. Without it, Secrets sit in etcd and in its backups in a readable form.
Why Raft needs a trusted network
Remember that Raft tolerates crashes and message loss, but not liars. A malicious party who could join the peer network or forge peer messages could disrupt elections or inject changes. Mutual authentication of peers and tight network rules close that door. The safety proofs of Raft hold only when every member follows the rules, so membership must be controlled.
A backup snapshot contains the whole cluster, including Secrets. Store backups encrypted, with restricted access, and treat them with the same care as the live database.
A bank vault with a perfect procedure for counting money is useless if anyone can walk in through the back door. Raft is the counting procedure. Certificates, firewalls and encryption are the vault walls, the guards and the locks.
| Risk | Control |
|---|---|
| Unauthorised client writes | Client certificates, network rules, only the API server connects |
| Rogue peer joins the group | Peer certificates and controlled membership changes |
| Eavesdropping on traffic | Encrypted connections on both ports |
| Secrets readable on disk or in backups | Encryption at rest configured in the API server, encrypted backups |
| Lost or stolen disk | Disk encryption and careful decommissioning |
16Monitoring and Observability
The handful of signals that tell you an etcd group is healthy or heading for trouble.
An etcd group usually runs quietly for months and then causes a major incident if ignored. A small set of well-chosen signals gives early warning. They fall into four families: leadership, replication, disk and size.
Is there a leader, and does it keep changing?
The has-leader signal should always be true. The leader-changes counter should be nearly flat. Frequent changes point to slow disks, network trouble or overloaded machines.
Are proposals flowing?
Compare proposals committed with proposals applied, and watch pending and failed proposals. A growing gap means members cannot keep up.
Is saving to disk fast?
The write-ahead log sync duration and the backend commit duration are the best early warnings. Rising tail latencies come before elections.
Is the database near its quota?
Track total size and the space actually in use. A big gap suggests defragmentation, and approaching the quota demands urgent action.
| Signal | What it tells you | Healthy | Worrying |
|---|---|---|---|
| Has leader | Whether the group can make progress | Always yes | Any member reports no leader |
| Leader changes | Stability of leadership | Rare, around planned work | Several in an hour |
| Proposals failed and pending | Trouble committing changes | Near zero | Growing steadily |
| WAL sync duration | Disk speed under write load | Ninety-ninth percentile under ten milliseconds | Spikes well beyond that |
| Peer round trip time | Network health between members | Low and steady | High or jumpy |
| Database size versus quota | Risk of write-blocking alarm | Comfortably below | Close to the limit |
| API server etcd request latency | What Kubernetes actually experiences | Flat | Rising with no matching traffic |
Logs and warnings
etcd writes clear warnings when things degrade. Typical messages mention requests taking too long to apply, heartbeats not being sent on time because of a slow disk or an overloaded processor, and elections caused by missed heartbeats. Treat these messages as the earliest evidence that disks or networks are struggling, since they appear before graphs turn red.
A single slow request is noise. A rising trend in disk sync time, leader changes or database size is a story. Build alerts that watch the trend and the user-facing latency seen by the API server.
17Backup and Disaster Recovery
Raft survives a few failures, but it cannot help if a majority is destroyed or data is deleted by mistake.
It is a common misunderstanding that a three-member group is its own backup. It is not. Replication protects against machines failing, not against human mistakes. If someone deletes a namespace by accident, Raft faithfully replicates that deletion to every member. If all members are lost in one disaster, the data is gone. A separate backup is the only protection against these events.
Take regular backup snapshots
Save a consistent snapshot of the database from a healthy member on a schedule that matches how much change you can afford to lose.
Store them elsewhere
Copy snapshots, encrypted, to storage outside the cluster and preferably outside the failure zone.
Practise the restore
Regularly rebuild a test group from a snapshot to prove the backups work and the team knows the steps.
Restore as a new group
In a disaster, every member is rebuilt from the same snapshot. The restored group is a brand new cluster with a new identity, which prevents old members from rejoining and confusing it.
Reconnect the control plane
Point the API servers at the restored group and check that controllers reconcile the cluster back to the restored desired state.
Replacing a single failed member
Most incidents are not total disasters but a single dead member. As long as a quorum remains, the right approach is to remove the dead member from the group, add a fresh one as a learner, let it catch up and promote it. Doing this while the remaining members are healthy is far safer than waiting until a second failure leaves the group without quorum.
A restore returns the cluster to the moment of the snapshot. Anything created or changed after that moment is gone from the stored state. Plan how you will rediscover and repair resources that existed in the meantime, and remember that external systems may have moved on.
Photocopying the classroom notebook for five students protects against one student losing their copy. It does not protect against the whole class accidentally writing a wrong rule in all five notebooks. For that, the teacher keeps dated photocopies in a locked drawer in another building.
18Best Practices and Design Patterns
A short checklist that covers most of what experienced operators do.
Odd group sizes
Use three members, or five for critical clusters, and avoid even sizes that add cost without safety.
Separate failure zones
Place members in different zones with low delay between them, so one fault cannot take down a majority.
Fast dedicated disks
Give etcd solid-state storage that is not shared with noisy workloads.
Regular compaction and care of size
Let compaction run, defragment one member at a time when needed, and keep the database well under its quota.
Tested backups
Back up on a schedule, store copies off site and rehearse the restore.
Tight access
Mutual TLS, closed ports and the API server as the only client.
Change membership slowly
Add members as learners, change one at a time and verify health between steps.
Keep objects and write rates modest
Small objects, lease-based heartbeats, and a separate group for noisy Events at large scale.
Upgrade with care
Upgrading an etcd group is a membership operation in disguise. The safe approach is a rolling upgrade, one member at a time, checking after each step that the member has rejoined, caught up and that the group has a leader before moving on. Taking a fresh backup first gives a way back if something unexpected happens. Skipping several minor versions at once is risky, so follow the supported upgrade path.
In a three-member group, taking a second member down for maintenance while the first is still down removes the quorum. Always confirm the previous member is healthy before touching the next one.
19Common Mistakes and Anti-patterns
Five habits that quietly weaken an etcd group.
Problem
The team runs four or six etcd members, thinking that more is always safer.
Why It’s Harmful
Even sizes tolerate no more failures than the next smaller odd size, cost more, slow every write slightly and can split evenly during partitions.
Correct Approach
Use three or five members, placed in separate failure zones.
Problem
etcd shares slow, shared disks with logging agents, container images or databases.
Why It’s Harmful
Spikes in disk delay slow commits, cause missed heartbeats and trigger repeated elections, which stall the whole cluster.
Correct Approach
Provide dedicated fast storage and monitor the write-ahead log sync time.
Problem
One etcd group is stretched across distant regions to survive a regional outage.
Why It’s Harmful
Every write must cross long distances, and high delay causes false elections. The group becomes slow in normal times in exchange for rare protection.
Correct Approach
Keep the group within a low-delay area and handle regional disasters with backups and separate clusters.
Problem
The team believes replication is a backup and never takes snapshots.
Why It’s Harmful
Replication copies mistakes as faithfully as good data. An accidental deletion or a total loss of members is permanent.
Correct Approach
Schedule backups, store them off site, encrypt them and practise restoring.
Problem
Operators ignore database size until the quota alarm sets in, or run defragmentation on every member at the same time.
Why It’s Harmful
Hitting the quota makes the cluster read-only. Defragmenting all members together briefly blocks them all and can cause a quorum-wide stall.
Correct Approach
Monitor size trends, rely on regular compaction and defragment one member at a time, followers first.
| Symptom | Likely cause | First check |
|---|---|---|
| Frequent leader changes | Slow disk or network delay | Disk sync time and peer round trip |
| API server timeouts on writes | No quorum or slow commits | Has-leader signal and member health |
| Cluster becomes read-only | Space quota alarm | Database size, compaction, alarms |
| New member never catches up | Large database or poor network | Learner progress, snapshot transfer |
| Watchers keep restarting | History compacted away too quickly | Compaction settings and slow consumers |
20Advantages, Disadvantages and Trade-offs
An honest look at what the Raft choice buys Kubernetes and what it costs.
Advantages
- Strong consistency: committed data is never lost or contradicted
- Automatic recovery from leader failure within seconds
- Understandable rules that are easier to implement and debug than older algorithms
- No split brain: a minority side cannot make progress
- A single ordered history that gives Kubernetes reliable resource versions and watches
Disadvantages / Trade-offs
- All writes go through one leader, so write throughput does not grow with more members
- Every write waits for a disk sync and a network round trip
- Loss of quorum stops all changes, trading availability for consistency
- Sensitive to slow disks and unstable networks
- Not designed for malicious members or for very large data
How it compares with other choices
| Approach | Idea | Strength | Weakness |
|---|---|---|---|
| Single database | One server holds the data | Simplest to run | Single point of failure |
| Primary with asynchronous copies | Leader copies later to replicas | Fast writes | Failover can lose recent writes |
| Raft consensus | Majority must store each write | No loss of committed data, automatic failover | Needs quorum, bounded write speed |
| Paxos family | Older consensus recipe | Proven and flexible | Harder to understand and implement |
| Byzantine fault tolerant protocols | Tolerate lying members | Safe against attackers inside the group | Heavier, slower, rarely needed in a trusted control plane |
The key trade-off is consistency over availability. When the network breaks, etcd prefers to stop accepting changes on the side that lacks a majority, instead of accepting changes that might later conflict. For a control plane that decides what runs in your cluster, that is the right trade, because a briefly frozen cluster is safer than one acting on contradictory instructions.
21Real-World and Industry Examples
Where these ideas show up in everyday platform engineering.
Cluster bootstrap tools
Common setup tools offer a stacked layout by default, where each control plane machine hosts an etcd member, and an external layout for teams that want to isolate the database. The choice between them is exactly the trade-off between simplicity and independence described earlier.
Managed Kubernetes services
Cloud providers run etcd groups for their customers, usually across several availability zones, with their own backup, defragmentation and upgrade procedures. Customers gain operational peace but cannot reach etcd directly, so they rely on provider guarantees for recovery.
Very large clusters
Platforms with thousands of nodes watch etcd latency closely, use separate groups for noisy data such as events, reduce object churn and sometimes shard workloads across many clusters. The limit they push against is the single leader and its disk.
Edge and small-footprint clusters
Light distributions sometimes replace etcd with a lighter store or run a single member to save resources. They accept lower resilience in exchange for simplicity, which can be right for a shop or a remote site and wrong for a core production platform.
Disaster recovery drills
Mature teams rehearse restoring a cluster from an etcd backup in a clean environment on a regular schedule. The drill exposes missing certificates, outdated runbooks and surprises such as resources created after the backup, long before a real emergency.
Other systems built on Raft
The same family of ideas powers many other distributed databases and coordination services. Learning Raft through etcd gives an engineer a mental model that applies well beyond Kubernetes.
Experienced teams treat etcd like a precious, small, very fast database: dedicated hardware, tight alerts, rehearsed restores, and a firm rule that nobody connects to it except the API server.
22Frequently Asked Questions
Short answers to the questions beginners ask most often.
An even-sized group tolerates no more failures than the odd size just below it, costs more and can split evenly in a partition. Odd sizes give the best resilience for the cost.
Running containers generally keep running because kubelets continue with their last known instructions. What stops is anything that needs to change state, such as creating, scaling, scheduling or repairing, until etcd regains a quorum.
A client can contact any member, but a write sent to a follower is forwarded to the leader. All writes are ordered and committed by the leader.
No. Writes still pass through the single leader and need a majority, so more members add resilience at best and a little extra delay at worst. Speed comes from faster disks, lighter objects and lower network delay.
Typically about the length of one election timeout, which is one second by default, plus a short extra delay if a split vote occurs. Writes pause briefly during this time and then resume.
No. A term counts elections, while the revision that feeds resource versions counts changes to the data. They are separate counters with separate purposes.
No. Replication protects against machine failures but copies mistakes and deletions to every member. Backups stored elsewhere protect against human error and total loss.
A common cause is that the database passed its space quota, which makes etcd reject writes until space is freed through compaction, defragmentation and removal of unneeded data.
No. Raft assumes members follow the rules. Protection against intruders comes from mutual authentication, encryption and careful control of who can join or connect.
Every entry must be saved to permanent storage before it is acknowledged, so disk delay sits inside every write. Slow disks can cause missed heartbeats and unnecessary elections.
23Summary and Key Takeaways
Kubernetes keeps its entire memory in etcd, and etcd keeps that memory safe by copying it across a small group of servers that agree on every change through Raft. One leader orders all writes, a majority must save each entry before it counts, and a strict voting rule guarantees that any new leader already holds everything that was ever committed. This makes the cluster’s history trustworthy, gives resource versions their meaning, and lets the control plane survive crashes and network splits without ever disagreeing with itself. The price is that the group needs a quorum to move forward, depends on fast disks and calm networks, and still needs real backups. Understand those few ideas and most etcd behaviour becomes easy to predict.
Key Takeaways
- etcd is the cluster’s memory — only the API server talks to it, and everything else in Kubernetes reads and writes through the API server.
- Raft gives one ordered history — a single leader appends changes to a log, and a change is committed only after a majority has saved it to disk.
- Majorities overlap — the voting restriction guarantees that every new leader holds all committed entries, so committed data is never lost or reversed.
- Choose three or five members — odd sizes in separate failure zones give the best resilience, and more members never increase write speed.
- Quorum loss freezes changes, not workloads — without a majority nothing can be created or repaired, yet running containers usually keep serving traffic.
- Disk and network decide performance — fast dedicated disks, low delay between members, sensible timers and modest object sizes keep elections rare.
- Replication is not backup — take scheduled, encrypted, off-site snapshots, rehearse restores, lock down ports with mutual TLS, and monitor leader changes, disk sync time and database size.