
On this page
In the first part of this series, a request ended its journey in one line: the object was written to etcd. Everything else in the cluster, the scheduler, the controllers, every kubelet, learned about the change because the API server watched etcd and told them. Lose etcd, and the cluster forgets what it is supposed to be. Lose its data, and no backup of your manifests will bring back every Secret, lease and status that lived in it.
This part of Kubernetes Internals: How a Cluster Really Works opens that box. We look at what Kubernetes stores in etcd and how, how the Raft consensus algorithm keeps three or five copies of it in agreement, why a cluster needs a quorum and what happens when it loses one, and how to keep etcd healthy: compaction, defragmentation and the space quota. Then the part that matters on the worst day of the year: how to back up etcd and restore it, step by step, on a kubeadm cluster.
New to the series? Start with Kubernetes API Server Explained: The Life of a Request, which follows a write all the way to etcd. The other parts, on the scheduler, the kubelet, Services, storage and troubleshooting, can be read in any order.
What Is etcd in Kubernetes?
Definition: etcd is a distributed, strongly consistent key-value store. Kubernetes uses it as the single source of truth for cluster state: every object the API server accepts is stored in etcd, and every watch the API server serves starts from etcd's own watch of its keys. A cluster runs several etcd members, which agree on every write with the Raft consensus algorithm.
Three facts frame the rest of this article:
- The API server is etcd's only client. No controller, scheduler or kubelet talks to etcd. They talk to the API server, which reads and writes etcd for them, so every change passes authentication, authorization and admission first.
- It chooses consistency over availability. A write is acknowledged only when a majority of the members have it on disk. If no majority can be reached, etcd refuses writes rather than accept one that a later majority might not know about.
- It keeps history. Every change gets a new revision, a number that only goes up, and old versions of a key are kept until they are compacted away. That history is what makes Kubernetes'
resourceVersionand its watches work.
etcd listens on two ports: 2379 for clients, which in Kubernetes means the API server, and 2380 for its peers, the other members. Both speak gRPC over mutual TLS in any cluster built by kubeadm or a managed service.
What Kubernetes Stores in etcd
Every Kubernetes object is one key under the prefix /registry, named after its resource, namespace and name:
/registry/deployments/shop/web
/registry/pods/shop/web-7d9c5b8f4-x2kqp
/registry/secrets/shop/db-credentials
/registry/clusterroles/view
/registry/leases/kube-node-lease/worker-2You can list them on a control-plane node with etcdctl. The commands in this article assume a kubeadm cluster with three control-plane nodes, cp-1, cp-2 and cp-3, at 10.0.0.11 to 10.0.0.13, and these variables, which etcdctl reads in place of its flags:
export ETCDCTL_ENDPOINTS=https://10.0.0.11:2379,https://10.0.0.12:2379,https://10.0.0.13:2379
export ETCDCTL_CACERT=/etc/kubernetes/pki/etcd/ca.crt
export ETCDCTL_CERT=/etc/kubernetes/pki/etcd/server.crt
export ETCDCTL_KEY=/etc/kubernetes/pki/etcd/server.keyetcdctl get /registry/deployments --prefix --keys-onlyRead a value and you get mostly binary. Built-in resources are stored as protobuf, behind a four-byte prefix, k8s and a null byte; custom resources are stored as JSON. If encryption at rest is on, a Secret's value is ciphertext that starts with the provider's name, such as k8s:enc:aescbc:v1:. None of this is meant to be read or written by hand: a key changed behind the API server's back skips every check, and conversion, that the API server would have made.
What is not in etcd matters as much:
- Container logs, metrics and images. Logs live on the nodes, metrics in your monitoring system, images in a registry.
- The data in your volumes. A PersistentVolume object is in etcd; the bytes on the disk it names are not. Backing up etcd backs up the claim, not the database behind it.
- Anything another cluster component keeps for itself, such as the kubelet's checkpoints on a node.
Raft in Brief: Leaders, Followers and Terms
Several etcd members hold the same data, and they must agree on the order of every write, even while machines crash and networks drop packets. etcd does this with Raft, a consensus algorithm designed to be easy to reason about. At any moment, each member is in one of three roles:
- Leader: exactly one per term. Every write goes through it. It appends the write to its log, sends it to the others and decides when it is committed. It also sends a heartbeat to every follower, every 100 ms by default (
--heartbeat-interval). - Follower: every other member. It accepts entries from the leader and answers. A follower that receives a write from a client forwards it to the leader.
- Candidate: a follower that stopped hearing from the leader and is asking to become one.
Time is divided into terms, numbered 1, 2, 3 and on. Each term starts with an election, and at most one leader wins it. A term number travels in every message, so a member that was cut off and comes back with an old term learns at once that it is behind.
How a Leader Is Elected
Each follower runs an election timer, reset by every heartbeat. If the timer runs out, the follower decides the leader is gone:
- It becomes a candidate, adds one to the term and votes for itself.
- It asks every other member for its vote.
- A member grants its vote if it has not voted in this term yet and the candidate's log is at least as up to date as its own. It gives one vote per term, to the first candidate that asks.
- A candidate that gets votes from a majority of the members, its own included, becomes the leader for that term, and sends heartbeats at once, which resets everyone else's timers.
- If no candidate gets a majority, because two split the votes, the timers run out again, and a new term starts.
The election timeout is 1000 ms by default (--election-timeout), and each member randomizes its own timer above that value, so one of them almost always runs out first and wins before another starts. The tuning guide's rule of thumb: a heartbeat interval around the round-trip time between members, and an election timeout at least ten times it.
Two refinements matter in practice. Pre-vote, on by default (--pre-vote), makes a would-be candidate first ask whether it could win, without raising the term. A member that was cut off and rejoins then cannot force a needless election on a healthy cluster. And a new member can join as a learner, which receives the log but does not vote and does not count towards the majority until it is promoted, so a member that is still catching up cannot cost the cluster its quorum.
The canvas below runs an election, slowed down four times. The leader stops after one second; watch the ring around each follower, which is what is left of its timer, the one that runs out first, and the votes it collects. Pick three or five members, stop a second member as well, or press for another run with other random timeouts.
A ring of etcd members, slowed down four times. The leader, etcd-1, sends a heartbeat every 100 ms, then stops after one second. Each follower's election timer, a random time from 1 to 2 seconds, runs out at its own moment; the first asks for pre-votes, then for votes in term 2, and with a majority it leads. With five members it leads 1.2 s after the last heartbeat. Stop a second member of three, and the one left can never win a majority: it asks again and again, its term stays 1, and no leader is elected. Another run draws new timers.
With five members, the follower whose timer ends first asks for pre-votes, gets them, becomes a candidate for term 2, and with the votes of two others leads 1.2 s after the last heartbeat it heard. Stop a second member, and three of five are left: still a majority, and a leader is elected all the same. With three members, stopping a second leaves one of three, which can never collect two votes. Its timer runs out, it asks for pre-votes nobody answers, and it asks again, for as long as the others are gone. Thanks to pre-vote, its term stays 1, so when the others come back it does not force them into a new election. No leader is ever elected: that is quorum loss, and the next sections are about it.
How a Write Is Committed
Here is what happens to a Deployment's update after the API server has checked it and sends it to etcd:
How etcd commits a write, step by step:
- Send: the API server sends the write, a transaction that checks the object's
resourceVersion, to the member it is connected to. If that member is a follower, it forwards the write to the leader. - Append: the leader appends the entry to its log and writes it to its write-ahead log (WAL) on disk, with an
fsync. - Replicate: in parallel, the leader sends the entry to every follower. Each appends it,
fsyncs its own WAL, and answers. - Commit: as soon as a majority of the members, the leader included, have the entry on disk, the leader marks it committed. It does not wait for the rest.
- Apply: each member applies committed entries, in order, to its key-value store, which gives the change its new revision.
- Answer: the leader's member answers the API server with the new revision, which becomes the object's
resourceVersion. Watchers, the API server's watch cache first, receive the event.
Two consequences follow. First, a write's latency is a disk's latency, plus a round trip: every write waits for an fsync on a majority of the members. etcd is far more sensitive to slow disks than to slow CPUs, and a disk that stalls can delay heartbeats long enough to trigger an election. Second, adding members does not make writes faster. A five-member cluster must reach three disks for each write, where three members need only two. More members buy fault tolerance, not speed.
Reads are cheaper. etcd's default read is linearizable: the member checks with the leader that it has applied everything committed so far, then answers from its own copy, so a read never returns data older than a write that was already acknowledged. A serializable read skips that check and answers from whatever the member has, which is faster but can be stale. The API server rarely reaches etcd for reads anyway: its watch cache serves most lists and gets, and recent Kubernetes releases serve even consistent lists from it, once etcd has confirmed that the cache has caught up to its latest revision.
Quorum and Fault Tolerance
A quorum is a majority of the members: floor(n / 2) + 1. Every write and every election needs one. The number of members that can fail while a quorum remains is the cluster's fault tolerance:
| Members | Quorum | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
Read the table in pairs, and the reason for odd numbers is plain: an even number of members tolerates no more failures than the odd number below it, and every write needs one more disk to answer. Four members tolerate one failure, like three, and two members tolerate none, like one, while doubling the machines that can fail. etcd's own FAQ recommends an odd number of members, and no more than seven.
In practice:
- Three members for most production clusters: one machine can be lost, or taken down for an upgrade, at a time.
- Five members where you need to survive two failures at once, or one failure during maintenance of another member.
- One member only for clusters you can rebuild, such as a test environment. Its disk is the cluster.
Quorum also explains a rule for zones. Spread three members over three availability zones and the cluster survives the loss of any one zone. Put two of them in one zone, and losing that zone loses the quorum.
The canvas below sends one write to a cluster and plays the answers back as they arrive. Every member has a disk of its own speed. Choose how many members the cluster has and how many followers are stopped, and see when the write commits, or that it never does.
One write to an etcd cluster, over its first ten milliseconds. Each member has a disk of its own speed, and a dot marks when it has the write on disk: the leader at 1.6 ms, its followers from 2.4 ms to 8.6 ms. The write commits as soon as a majority have it. With five members and none stopped, that is 3.1 ms. Stopping followers, the fastest first, makes it wait for slower disks, 3.9 ms then 5.2 ms; a third stopped leaves two of five, and the write never commits. Four members tolerate one stopped follower, as three do.
With the defaults, five members and none stopped, the write commits at 3.1 ms, as soon as the leader and the two fastest followers have it on disk: the two slower answers arrive later and change nothing. Stop one follower, then two: the commit now waits for slower disks, 3.9 ms and then 5.2 ms, but it still commits, because three of five remain. Stop a third, and two of five can never make a majority: the write waits until the API server gives up. Try four members: one stopped follower is fine, two are not, the same as with three.
What Happens When etcd Loses Quorum
When fewer than a quorum of members are running, or they cannot reach each other, there is no leader and none can be elected. For Kubernetes, that means:
- Every write fails. Creating, updating or deleting any object times out, with errors such as
etcdserver: request timed outorcontext deadline exceeded. That includes the writes the cluster makes for itself: status updates, leases, events. - Reads are unreliable. The API server's watch cache may still answer some reads with what it last knew, but nothing new arrives in it, and its readiness check (
/readyz) reports etcd as failing. - Running workloads keep running. The kubelets do not need the API server to keep existing containers alive, and they still restart a crashed container on their own node. Traffic keeps flowing through the Service rules already programmed on each node.
- Nothing heals or changes. No Pod is scheduled, no Deployment rolls out, no node is marked
NotReadyand nothing is evicted, because the controllers that would do it cannot write either.
So a cluster without quorum is frozen, not dead. The urgent job is to bring back enough members to make a majority. If the members are gone for good, the way back is a restore from a snapshot, later in this article.
The opposite failure is quieter and more dangerous: a network partition that splits the members. The side with a majority elects a leader and keeps working. The side without one cannot commit anything, so it cannot diverge: when the network heals, its members see the higher term, follow the new leader and catch up. This is Raft doing its job.
Stacked vs External etcd Topology
Where do the members run? kubeadm offers two shapes for a highly available control plane:
| Stacked etcd | External etcd | |
|---|---|---|
| Where etcd runs | On each control-plane node, as a static Pod | On its own hosts, outside the cluster |
| Hosts for one failure | 3 | 6: three control-plane nodes and three etcd hosts |
| Coupling | Losing a node loses an API server and an etcd member together | The two fail independently |
| Who manages it | kubeadm: certificates, manifests, upgrades | You, or another tool |
| Typical use | Most self-managed clusters | Large clusters, or a shared etcd team |
In the stacked shape, kubeadm runs an etcd member next to each API server, and each member serves only the API server on its own node: the API server's --etcd-servers names https://127.0.0.1:2379. In the external shape, each API server's --etcd-servers lists every member, and its client picks one and moves to another if it fails.
On a managed service such as EKS, GKE or AKS, you see neither. The provider runs etcd, sizes it, backs it up and restores it, and gives you no access to it. What you can back up there is what the API serves, with a tool such as Velero, which the backup section comes back to.
Revisions, Compaction and the Space Quota
etcd keeps old versions of each key, a design called multi-version concurrency control (MVCC). Every write creates a new revision of the whole store, and the previous value of the key stays readable at its old revision. That history is what lets a watch resume "from revision 4512" without missing an event. It also grows forever, unless it is removed:
- Compaction discards every version older than a chosen revision. Kubernetes does this for you: the API server asks etcd to compact every five minutes (
--etcd-compaction-interval,5m0sby default). etcd's own automatic compaction is off by default, and need not be turned on in a Kubernetes cluster. - Defragmentation returns the space that compaction freed. Compaction marks pages free inside etcd's database file, but the file does not shrink until a member is defragmented. A defragmentation blocks reads and writes on that member while it rebuilds the file, so run it on one member at a time, and on the leader last.
etcdctl defrag --endpoints=https://10.0.0.12:2379etcd also has a space quota: 2 GiB by default (--quota-backend-bytes), with 8 GiB as the suggested maximum for normal environments. When a member's database grows past it, etcd raises a cluster-wide NOSPACE alarm and stops accepting writes: only reads and deletes go through. For Kubernetes, that looks like quorum loss, with the error mvcc: database space exceeded. To recover, free the space, defragment, then clear the alarm:
etcdctl alarm list
etcdctl defrag --endpoints=https://10.0.0.11:2379
etcdctl alarm disarmIf compaction is working, a database that reaches the quota usually means one kind of object has grown out of hand, often Events or the objects of a misbehaving operator. Count the keys by prefix to find it:
etcdctl get /registry --prefix --keys-only | grep -v '^$' | cut -d/ -f3 | sort | uniq -c | sort -rn | headChecking etcd Health
Three commands tell you whether a cluster is healthy:
etcdctl endpoint health --cluster
etcdctl endpoint status --cluster -w table
etcdctl member list -w tableendpoint health checks that each member can serve a request that needs the quorum. endpoint status shows, for each member, its version, the size of its database, whether it is the leader, and its Raft term and index. Run it twice, a minute apart. The terms should not move, the indexes should be close to each other, and exactly one member should say true under IS LEADER. member list shows the members the cluster believes it has, and whether any is a learner.
On a kubeadm cluster without etcdctl on the node, run it inside the etcd Pod, whose image ships it:
kubectl -n kube-system exec etcd-cp-1 -- etcdctl \
--cacert /etc/kubernetes/pki/etcd/ca.crt \
--cert /etc/kubernetes/pki/etcd/server.crt \
--key /etc/kubernetes/pki/etcd/server.key \
endpoint status --cluster -w tableFor monitoring, every member serves Prometheus metrics on its client port, at /metrics. The ones to alert on:
| Metric | What it tells you |
|---|---|
etcd_server_has_leader |
0 means this member has no leader: no quorum, or it is cut off |
etcd_server_leader_changes_seen_total |
Several changes an hour means elections are happening: slow disks, an overloaded member or a flaky network |
etcd_disk_wal_fsync_duration_seconds |
The time to make a write durable. Its 99th percentile should stay in single-digit milliseconds |
etcd_disk_backend_commit_duration_seconds |
The time to commit to the database file; slow values point at the disk as well |
etcd_mvcc_db_total_size_in_bytes |
The database's size, to compare with the quota |
etcd's hardware guide says it plainly: etcd is very sensitive to disk write latency. Give its data directory a local SSD of its own, not a network disk shared with busy neighbours, and keep members within a few milliseconds of each other on the network.
Securing etcd
Whoever can read etcd can read every Secret in the cluster, and whoever can write it can become cluster-admin without a single RBAC check. Treat access to it as root access to the cluster:
- Mutual TLS on both ports. kubeadm generates a CA for etcd alone, under
/etc/kubernetes/pki/etcd/, and certificates for the server, the peers, the API server's client and a health check. A client without a certificate signed by that CA is refused. - Nobody but the API server connects. Firewall port 2379 to the control-plane nodes, and port 2380 to the members themselves.
- Encrypt Secrets at rest. With an
EncryptionConfiguration, ideally with a KMS v2 provider, the API server encrypts Secrets before they reach etcd, so its disks, and its snapshots, hold ciphertext. - Protect the snapshots. A snapshot is the whole cluster in one file. Store it encrypted, somewhere the cluster's own credentials cannot delete it.
How to Back Up etcd
A backup of etcd is a snapshot: a consistent copy of the whole key-value store at one revision, taken from a live member without stopping it.
etcdctl snapshot save /backup/etcd-$(date +%Y%m%d-%H%M).db \
--endpoints=https://10.0.0.11:2379A snapshot is taken from one member, so give it one endpoint: etcdctl refuses to take one from several. Any healthy member will do, since they all hold the same committed data. Then check the file with etcdutl, which reads it offline:
etcdutl snapshot status /backup/etcd-20261201-0300.db -w tableIt prints the snapshot's hash, its revision, its number of keys and its size. A snapshot whose status cannot be read is not a backup.
A backup that can actually be restored needs more than the snapshot:
- The certificates. Copy
/etc/kubernetes/pki/, with etcd's CA and keys. A restore on new machines needs them, and every kubeconfig and kubelet trusts the cluster's CA. - The encryption configuration and its keys, if Secrets are encrypted at rest. Without them, the Secrets in the snapshot are ciphertext nobody can read.
- A copy off the cluster. Send it to object storage in another account or region. A backup on the control-plane node is lost with the node.
- A schedule and a test. Take one at least daily, and before every upgrade, keep several, and restore one into a scratch cluster from time to time. A backup that has never been restored is a hope.
When etcdctl is not available, you can also copy the database file, member/snap/db under the data directory, from a member whose etcd process is stopped. Such a copy has no integrity hash, so its restore needs --skip-hash-check.
Managed clusters. On EKS, GKE or AKS you cannot take an etcd snapshot. The provider protects etcd; what you protect is your objects. Keep your manifests in Git, and use a tool such as Velero to back up what the API serves, Secrets included, and the volumes behind them. That also covers the case an etcd snapshot cannot: restoring one namespace without rolling back the whole cluster.
How to Restore etcd, Step by Step
A restore puts the whole cluster back to the moment of the snapshot. Everything created, changed or deleted since is undone: Deployments rolled out since, Pods scheduled, nodes that joined. Restore when the data is lost or corrupted, or quorum cannot be brought back, not to undo one mistake.
The Kubernetes documentation is firm on one point: if any API servers are running, do not restore etcd. Stop every API server first, restore every member, then start the API servers again. A running API server would keep serving, and writing, the state it cached from the old data.
How to restore etcd on a kubeadm cluster, step by step:
-
Stop the API servers. On every control-plane node, move the static Pod's manifest out of the folder the kubelet watches, and wait for the container to stop:
bashsudo mv /etc/kubernetes/manifests/kube-apiserver.yaml /etc/kubernetes/ sudo crictl ps --name kube-apiserver -
Stop etcd the same way, on every node, and set its old data aside rather than deleting it:
bashsudo mv /etc/kubernetes/manifests/etcd.yaml /etc/kubernetes/ sudo mv /var/lib/etcd /var/lib/etcd.old -
Restore the same snapshot on every member. Copy the one snapshot file to each node, then run
etcdutl snapshot restorethere, with that member's own name and peer address. Every member's command lists the same initial cluster and the same new token:bashsudo etcdutl snapshot restore /backup/etcd-20261201-0300.db \ --name cp-1 \ --initial-cluster cp-1=https://10.0.0.11:2380,cp-2=https://10.0.0.12:2380,cp-3=https://10.0.0.13:2380 \ --initial-cluster-token etcd-restore-20261201 \ --initial-advertise-peer-urls https://10.0.0.11:2380 \ --data-dir /var/lib/etcd \ --bump-revision 1000000000 --mark-compactedThe member names must be the ones in each node's
etcd.yaml(--name), which kubeadm sets to the node's name. The restore creates a new cluster from the snapshot's data, with a new cluster ID, so the old members' identities do not carry over. -
Start etcd. Put
etcd.yamlback on every node. The flags in it that start with--initial-only matter when the data directory is empty, so the restored membership wins. Check that the members found each other:bashsudo mv /etc/kubernetes/etcd.yaml /etc/kubernetes/manifests/ etcdctl endpoint health --cluster etcdctl member list -w table -
Start the API servers. Put
kube-apiserver.yamlback on every node, and wait untilkubectl get --raw /readyzanswersok. -
Restart everything that cached the old state. The Kubernetes documentation recommends restarting
kube-scheduler,kube-controller-managerand the kubelet, so that none of them relies on stale data. Move the scheduler's and the controller manager's manifests out and back, and runsudo systemctl restart kubeleton every node. -
Check the cluster.
kubectl get nodes, then your workloads. Anything created after the snapshot is gone, and the controllers will now reconcile the cluster towards the restored state: Pods that run but are not in it are deleted, and Pods it names that are missing are created.
On a cluster with one control-plane node, it is the same procedure with one member: --initial-cluster cp-1=https://10.0.0.11:2380.
Why Bump the Revision?
The two last flags of the restore, in recent releases of etcdutl such as 3.6, deal with a subtle problem. Every client that watched the cluster before the disaster remembers a revision, and the restored cluster starts again from the snapshot's revision, which is lower. A client that resumes a watch "from revision 9 000 000" against a store at revision 8 500 000 would wait for changes it has already seen, or miss new ones.
--bump-revision 1000000000adds a billion to the restored revision, so every revision after the restore is higher than any revision a client saw before it.--mark-compactedmarks every revision before that as compacted, which ends every existing watch: each client lists again and starts from fresh data, instead of trusting a cache built on the timeline that was lost.
etcd's recovery guide names Kubernetes as the case for both: restored to an older revision, its controllers' caches may not refresh correctly. With an older etcdutl that lacks them, restarting every component in step 6 is what makes the clients list again.
Replacing a Failed Member
When one member's machine dies but the cluster keeps its quorum, you do not restore anything: you replace the member. Change the membership one member at a time, and remove the dead member before adding its replacement, or a cluster of three becomes a cluster of four with two members down, which has lost its quorum.
etcdctl member list -w table
etcdctl member remove 8e9e05c52164694d
etcdctl member add cp-3 --peer-urls=https://10.0.0.13:2380 --learnerStart etcd on the new machine with an empty data directory, --initial-cluster-state existing and the --initial-cluster that member add printed. It joins as a learner, receives the whole store from the leader, and does not count towards the quorum while it catches up. Once endpoint status shows its index close to the others', promote it to a voting member:
etcdctl member promote 2c4d1e9a0b3f5876On kubeadm, kubeadm reset on the old node removes its member for you, and kubeadm join --control-plane adds the new one, provided the cluster has its quorum when you run them.
Upgrading etcd
On kubeadm, etcd's version comes with Kubernetes: kubeadm upgrade moves the etcd static Pod to the version that release was tested with, one control-plane node at a time. If you run etcd yourself:
- Take a snapshot first. etcd cannot be downgraded with its data in the general case, and the Kubernetes documentation asks for a backup before any upgrade.
- Go one minor version at a time. etcd 3.6 requires a cluster already on 3.5; a 3.4 cluster upgrades to 3.5 first.
- Upgrade one member at a time, the leader last, and check
endpoint healthbefore moving on, so the quorum is never at risk. - Mind the tools. Since etcd 3.6,
etcdctltakes snapshots but no longer reads or restores them:snapshot statusandsnapshot restoreareetcdutl's alone. Scripts written for etcd 3.4 need the change.
Troubleshooting etcd
| Symptom | Likely cause | Where to look |
|---|---|---|
kubectl hangs, API server logs say context deadline exceeded |
No quorum, or the API server cannot reach its etcd members | etcdctl endpoint health --cluster, the etcd Pods' logs |
etcdserver: request timed out, often |
Slow commits: a slow disk, an overloaded member | etcd_disk_wal_fsync_duration_seconds, the node's disk latency |
| Leader changes several times an hour | Heartbeats arrive late: disk stalls, CPU starvation, packet loss | etcd_server_leader_changes_seen_total, the logs' elected leader lines |
mvcc: database space exceeded |
The NOSPACE alarm: the database reached the quota |
etcdctl alarm list, then compact, defrag and alarm disarm |
| Database much larger than its keys | Space freed by compaction but not returned | Compare DB SIZE in endpoint status with its use; defragment |
| One member's index far behind the others | It is slow, or was cut off and is catching up | Its disk and network; replace it if it never catches up |
x509: certificate has expired |
etcd's certificates expired | kubeadm certs check-expiration, then kubeadm certs renew |
A new member fails to join, member count is unequal |
Its --initial-cluster does not match the cluster's membership |
etcdctl member list, and the flags it was started with |
When in doubt, start with three questions, in this order: is there a leader (etcd_server_has_leader, endpoint status)? Are writes fast (the fsync histogram)? Is the database below its quota (alarm list, DB SIZE)? Almost every etcd problem in a Kubernetes cluster is one of those three.
Key Takeaways
- etcd is Kubernetes' only store of cluster state, and the API server is its only client. Back it up, and protect it like root access.
- Raft gives each term one leader, elected by a majority after a follower's randomized election timer runs out. The leader sends heartbeats every 100 ms by default; followers wait 1000 ms or more before an election.
- A write commits when a majority of members have it on disk. Its latency is an
fsyncon the slowest disk of that majority, so etcd needs fast local disks, and more members never make writes faster. - A cluster of
nmembers toleratesfloor((n - 1) / 2)failures. Run three or five; an even number adds a machine that can fail and no tolerance. - Without quorum, every write fails and the cluster freezes: running Pods keep running, but nothing is scheduled, updated or healed.
- The API server compacts history every five minutes; defragment members one at a time to return the space, and watch the 2 GiB default quota and its
NOSPACEalarm. - Back up with
etcdctl snapshot saveagainst one member, check it withetcdutl snapshot status, and keep the certificates and encryption keys with it, off the cluster. - Restore with every API server stopped: the same snapshot on every member with
etcdutl snapshot restore,--bump-revisionand--mark-compacted, then the API servers, then a restart of the scheduler, the controllers and the kubelets.
FAQ
What is etcd used for in Kubernetes?
etcd stores the whole state of a Kubernetes cluster: every object the API server accepts, such as Pods, Deployments, Services, Secrets, ConfigMaps and leases, under keys that start with /registry. The API server is its only client. It writes every change there and serves watches from etcd's own watch of its keys.
Why does etcd need an odd number of members?
Because a quorum is a majority. With an even number of members, the quorum is as large as with one member more, so the cluster tolerates no more failures than the odd number below it. Four members tolerate one failure, like three, while adding a fourth machine that can fail. Three or five members is the usual choice.
How many etcd members can fail?
A cluster of n members keeps working while a majority, floor(n / 2) + 1, are running and can reach each other. Three members tolerate one failure, five tolerate two, and seven tolerate three. A single-member cluster tolerates none.
What happens to Kubernetes if etcd goes down?
The API server can no longer write anything, so every create, update and delete fails, and controllers, the scheduler and kubelets cannot record changes. Containers that are already running keep running, and their nodes keep serving traffic, but nothing is scheduled, scaled or healed until etcd has a quorum again.
How do I back up etcd in Kubernetes?
On a control-plane node, run etcdctl snapshot save <file> against one member, with etcd's CA, certificate and key, then check the file with etcdutl snapshot status. Copy the snapshot off the cluster together with /etc/kubernetes/pki and any encryption configuration, take one at least daily and before upgrades, and test a restore regularly.
How do I restore etcd from a snapshot?
Stop every API server and every etcd member. On each member, run etcdutl snapshot restore with the same snapshot file, its own --name and peer URL, the same --initial-cluster and a new --initial-cluster-token, into the data directory etcd uses. Start etcd, check its health, then start the API servers and restart the scheduler, the controller manager and the kubelets.
What is the difference between etcdctl and etcdutl?
etcdctl is a client: it talks to running members over the network, to read and write keys, manage members, check health and take snapshots. etcdutl works offline, on etcd's files: it reads a snapshot's status, restores a snapshot into a new data directory, and defragments a stopped member. Since etcd 3.6, snapshot status and restore are only in etcdutl.
What's Next
You have opened the last box in the path a request takes: the store at its end, kept in agreement by Raft, safe as long as a majority of its members can reach each other, and recoverable from a snapshot when they cannot. One question is left: what acts on the state etcd holds? In the next part of Kubernetes Internals: How a Cluster Really Works, Kubernetes Controllers Explained: The Reconciliation Loop, we follow the controllers that keep comparing that state with the cluster and close the gap. If you are on call for a cluster, keep the Kubernetes Troubleshooting playbook next to this one, and see the whole series for every part.



Comments
No comments yet.
Join the discussion
Sign in to ask a question or share what worked for you.