Lesson 7 · Section 2: Core Concepts
Lesson 7: etcd for beginners: the small database that remembers everything
What etcd is before Kubernetes enters the picture: a key-value store, why it runs as a cluster, how Raft and quorum keep every copy the same, and your first etcdctl commands. · 17 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why etcd exists
Any system that runs on more than one machine has to answer an awkward question: where does the truth live? Which servers exist, what should be running, who holds a lock, what the current configuration is. Every part of the system needs to read the same answers, and the answers must survive a machine dying.
The two obvious designs both fail:
- One database server. Simple, and everyone agrees because there is only one copy. But when that server or its disk breaks, the whole system is blind until you restore it.
- Several independent copies. Now a broken machine is survivable, but the copies drift. Two clients write to two different copies at the same moment, or a network cable is pulled, and the copies give different answers. A system with two versions of the truth is worse than one that is down.
etcd is the answer to that problem: a small database that keeps several copies of its data on different
machines and guarantees that they agree. The name says where it comes from: /etc is the directory where Linux
keeps configuration, and the d stands for distributed. It was created at CoreOS in 2013, is written in Go and
is a graduated CNCF project. Kubernetes uses it as its only database, but etcd is a separate project that knows
nothing about Pods or Deployments. This lesson looks at etcd on its own; the next one opens it up inside a
cluster.
What etcd is
A key-value store, not a table database
A relational database such as PostgreSQL or MySQL stores rows in tables. Every row in a table has the same columns, and you ask questions with SQL:
| name | role | team |
|---|---|---|
| alice | admin | platform |
| bob | viewer | shop |
A key-value store is much simpler. It is one big dictionary: you hand it a key, it hands back the value. There are no tables, no columns, no joins and no query language.
| Key | Value |
|---|---|
/users/alice/role | admin |
/users/alice/team | platform |
/users/bob/role | viewer |
/shop/web/replicas | 3 |
Three things about etcd's keyspace are worth knowing from the start:
- Keys and values are just bytes. etcd does not look inside a value. It can be a number, a line of text, a JSON document or binary data. The meaning belongs to whoever wrote it.
- The keyspace is flat and sorted. There are no real folders.
/users/alice/roleis one key whose name happens to contain slashes. Because keys are stored in sorted order, all keys that begin with/users/sit next to each other, and you can ask for the whole range at once. That is called a prefix query, and it is how a flat store behaves like a tree. - It is built for small data. One request can carry about 1.5 MiB at most, and the whole database is limited to 2 GB by default (8 GB is the suggested ceiling). etcd is for configuration and state, never for images, logs or user uploads.
More than put and get
Four features turn a plain dictionary into something a system like Kubernetes can be built on:
| Feature | What it does | Why it matters |
|---|---|---|
| Revisions | Every change raises one cluster-wide counter, the revision. Old versions of a key are kept until they are compacted away. | You can read the store as it was at an earlier revision, and tell exactly which of two changes came first. |
| Watch | A client asks to be told about every change to a key or prefix, starting from a given revision. | Programs react to changes the moment they happen instead of polling, and miss nothing. |
| Transactions | "Only write this if the key still has the revision I last saw." | Two clients cannot silently overwrite each other. |
| Leases | A key can be tied to a lease that expires unless it is renewed. | Dead clients clean up after themselves: the base for locks and leader election. |
Members, leader and ports
Parts:
- Client (etcdctl or an app)
- etcd-1 (leader), in etcd cluster
- etcd-2 (follower), in etcd cluster
- etcd-3 (follower), in etcd cluster
Connections:
- Client to etcd-1: :2379
- etcd-1 and etcd-2: peer :2380
- etcd-1 and etcd-3: peer :2380
- etcd-2 and etcd-3: peer :2380
An etcd cluster is a group of etcd processes called members, normally one per machine. Every member has a full copy of the data on its own disk. At any moment one member is the leader and the rest are followers. You do not choose the leader; the members elect it, and they elect a new one within about a second if it disappears.
Each member listens on two ports, and mixing them up is a classic mistake:
| Port | Used by | For |
|---|---|---|
| 2379 | Clients: etcdctl, applications, the Kubernetes API server | Reading and writing keys |
| 2380 | Other members (peers) | Replicating data and holding elections |
A client can connect to any member. If it sends a write to a follower, the follower passes it on to the leader.
How it works
Raft: one leader, one ordered log
The copies stay identical because etcd uses a consensus algorithm called Raft. The idea is easier than its reputation: if every member applies the same changes in the same order, every member ends up with the same data. So the whole job is to agree on one ordered list of changes, the log, and Raft does that by letting a single leader decide the order.
Parts:
- Client (put color blue)
- Leader (orders every write)
- Follower A (logs it, says yes)
- Key-value store (color = blue, rev 8)
- Leader's log (written to disk)
- Follower B (down, catches up)
Connections:
- Client to Leader: 1 write
- Leader to Leader's log: 2 log
- Leader and Follower A: 3 copy
- Leader to Follower B: 3 copy
- Leader's log to Key-value store: 4 commit
- Key-value store to Client: 5 OK
- The client sends a write, for example
put color blue. It reaches the leader. - The leader appends the change to its own log on disk (the write-ahead log). Nothing has changed in the key-value store yet.
- The leader sends the log entry to every follower. Each follower writes it to its own disk and acknowledges.
- As soon as a majority of members (the leader counts as one) have the entry on disk, it is committed. Each member then applies it to its key-value store, and the revision goes up by one.
- The client gets
OK.
A follower that was slow or switched off does not block anything. When it returns, the leader sends it the entries it missed and it catches up.
That is also why the answer OK means so much in etcd: the change is already on the disks of most of the
cluster, so it survives the loss of any minority of machines.
Quorum: why a majority, and not everyone
The majority that Raft needs is called the quorum. For a cluster of n members:
quorum = floor(n / 2) + 1
Requiring everyone would mean one broken machine stops all writes, which defeats the point of having copies.
Requiring fewer than half would allow two separate groups to both accept writes. A majority is the smallest
number with a useful property: any two majorities share at least one member. That shared member carries the
committed data forward, so a new leader always knows every write that was ever answered with OK.
Parts:
- Client (write accepted)
- etcd-1 (leader), in 3 of 5: quorum
- etcd-2 (follower), in 3 of 5: quorum
- etcd-3 (follower), in 3 of 5: quorum
- Client (write refused)
- etcd-4 (cannot win a vote), in 2 of 5: no quorum
- etcd-5 (cannot win a vote), in 2 of 5: no quorum
Connections:
- Client to etcd-1: put
- etcd-1 to etcd-2
- etcd-2 to etcd-3
- Client to etcd-4: put
- etcd-4 and etcd-5
The diagram shows the property at work. A network fault splits five members into a group of three and a group of two. The group of three is a majority: it keeps (or elects) a leader and carries on. The group of two can never collect three votes, so it has no leader and refuses writes. When the network heals, the two members see that the other side has a newer log and copy it. There was never a moment with two truths. Running with two leaders that both accept writes is called split brain, and quorum is what makes it impossible.
Under the hood · Elections, terms and timing
- Raft divides time into numbered terms. Each term has at most one leader. You can see the current term in
etcdctl endpoint status -w table(the RAFT TERM column); a term that keeps climbing means leaders keep being lost, usually because of a slow disk or network. - The leader sends a heartbeat to every follower every 100 ms by default. A follower that hears nothing for the election timeout (1000 ms by default, with some random spread so that members do not all start at once) becomes a candidate, raises the term and asks the others for their vote.
- A member votes for a candidate only if the candidate's log is at least as up to date as its own. That rule is why a newly elected leader can never be missing a committed write.
- A candidate that collects a majority of votes becomes leader. If the vote is split, the timeout runs again with new random delays.
- etcd is very sensitive to disk speed, because every write waits for an
fsyncon a majority of members. This is why etcd wants SSDs, and why a slow disk on the control plane makes a whole cluster feel slow.
Under the hood · Why reads need the leader too
By default a read in etcd is linearizable: it is guaranteed to reflect every write that finished before it. To promise that, the member answering the read first confirms with a quorum that the leader is still the leader. That is why even reads fail when quorum is lost.
etcdctl get --consistency=s asks for a serializable read instead: the member answers from its own copy
without asking anyone. It is faster and works without quorum, but the answer may be slightly stale. It is a
handy way to look at the data of a cluster that is otherwise stuck.
How many members
| Members | Quorum | Failures survived | Notes |
|---|---|---|---|
| 1 | 1 | 0 | Fine for learning and for the single control plane node of a practice cluster |
| 2 | 2 | 0 | Worse than 1: two machines that can each stop the cluster |
| 3 | 2 | 1 | The usual choice for production |
| 4 | 3 | 1 | No gain over 3, and one more machine that can fail |
| 5 | 3 | 2 | For clusters that must survive a failure during maintenance |
| 7 | 4 | 3 | Rarely worth it: every write waits for more disks |
Two rules follow from the table:
- Use an odd number. Going from 3 to 4 raises the quorum from 2 to 3 but still tolerates only one failure. An even number also allows a network split into two equal halves, where neither side has a majority and the whole cluster stops.
- More members do not make etcd faster. Every write must reach a majority, so more members mean more waiting. Members add safety, not speed. Beyond five there is almost never a reason.
One more variant: API version 2 and 3
etcd has had two very different APIs, and old tutorials still show the first one:
| API v2 (historic) | API v3 (current) | |
|---|---|---|
| Data model | Real directories and keys | Flat keyspace, prefixes |
| Protocol | HTTP and JSON | gRPC |
| Commands | etcdctl set, ls, mkdir, rm | etcdctl put, get, del, watch |
Kubernetes has stored its data with v3 for many years, etcdctl has spoken v3 by default since etcd 3.4, and
etcd 3.6 no longer serves the v2 API at all. If a guide tells you to run export ETCDCTL_API=3, it was written
for etcd 3.3 or older: the line is harmless today, and no longer needed.
Using it
Example · Start a single etcd and store your first keys
etcd is a single binary. A release archive from the etcd GitHub releases page contains three programs:
| Binary | What it is |
|---|---|
etcd | The server |
etcdctl | The client. It talks to a running server over the network |
etcdutl | The offline tool. It works directly on data files and snapshots, with no server needed |
Start a server with no options. It keeps its data in ./default.etcd and listens for clients on
localhost:2379, which is also where etcdctl connects by default:
./etcd # terminal 1: a one-member cluster, logs to the screen
# terminal 2
etcdctl put /shop/web/replicas 3 # OK
etcdctl put /shop/web/image nginx:1.29 # OK
etcdctl put /shop/db/replicas 1 # OK
etcdctl get /shop/web/replicas # prints the key, then the value on the next line
etcdctl get /shop/web/replicas --print-value-only # 3
etcdctl get /shop --prefix # every key that starts with /shop
etcdctl get /shop --prefix --keys-only # only the names
etcdctl del /shop/db/replicas # 1 (the number of keys deleted)
Note what get /shop without --prefix returns: nothing. There is no key named exactly /shop, and etcd has
no folders to open.
Example · Watch a key and travel back in time
Leave a watch running in one terminal:
etcdctl watch /shop --prefix
Change a key twice in another terminal, and the watch prints each event as it happens:
etcdctl put /shop/web/replicas 5
etcdctl put /shop/web/replicas 2
PUT
/shop/web/replicas
5
PUT
/shop/web/replicas
2
Now look at the bookkeeping etcd holds for the key. JSON output shows it (shortened here; keys and values are base64 encoded in JSON, because they are bytes):
etcdctl get /shop/web/replicas -w json
{"header":{"revision":7, "raft_term":2},
"kvs":[{"key":"L3Nob3Avd2ViL3JlcGxpY2Fz","create_revision":2,"mod_revision":7,"version":3,"value":"Mg=="}],
"count":1}
create_revision is the cluster revision when the key was created, mod_revision when it last changed, and
version counts the changes to this one key. Because old revisions are kept, you can read the past:
etcdctl get /shop/web/replicas --rev=6 --print-value-only # 5
This is exactly the machinery behind kubectl get --watch and the resourceVersion you see on every Kubernetes
object.
Example · Check the health of a cluster
Against a cluster of several members, name them with --endpoints (with one local member you can leave it out):
export ETCDCTL_ENDPOINTS=10.0.0.11:2379,10.0.0.12:2379,10.0.0.13:2379
etcdctl endpoint health # can each member commit a write right now?
etcdctl endpoint status -w table # version, database size, who is leader, Raft term
etcdctl member list -w table # who belongs to the cluster, with peer and client addresses
endpoint health answers for the endpoints you named. Add --cluster to ask every member of the cluster, even if
you only know the address of one:
etcdctl --endpoints=10.0.0.11:2379 endpoint health --cluster
In endpoint status, exactly one row should show true under IS LEADER, and all members should show the same
RAFT TERM and nearly the same RAFT INDEX. A member whose index falls behind is struggling to keep up.
Tricks
Common mistakes
- Choosing an even number of members. Two members are less reliable than one, and four are no safer than three. Always 1, 3 or 5.
- Expecting folders.
etcdctl get /shopprints nothing when the keys are/shop/web/.... Add--prefix. - Confusing the ports. 2379 is for clients, 2380 for peers. Pointing
etcdctlat 2380 does not work. - Following a v2 tutorial.
etcdctl set,lsandmkdirbelong to the old API and fail on a current etcd. The v3 commands areput,getanddel. - A careless prefix delete.
etcdctl del /shop --prefixremoves every key under/shopwithout asking, andetcdctl del "" --prefixempties the whole store. Run the same line withget --keys-onlyfirst. - Treating etcd as a general database. It is for small, critical data. Large values and millions of keys make it slow, and a full database stops accepting writes until space is freed.
- Thinking more members means more speed. Every write waits for a majority of disks. Add members for safety only.
Recap
- etcd is a key-value store: flat, sorted keys, values that are just bytes, and prefix queries instead of folders.
- It runs as a cluster of members with one elected leader; clients use port 2379, peers 2380.
- Raft keeps the copies identical: the leader orders writes, and a write is committed once a majority (quorum) has it on disk.
- Without quorum etcd refuses writes rather than risk two truths, so use 3 or 5 members: they survive 1 or 2 failures.
etcdctl put,get --prefix,del,watch,endpoint healthandmember list -w tableare the commands to know before the next lesson looks inside a Kubernetes cluster.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.