AlgoViz

etcd

medium 30 min

etcd is a small, strongly consistent key-value store.

Video lesson · Chapter 1 of 5

A ferry terminal saves berth seven

0:00 / 4:31

etcd in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

etcd stores a small amount of data that must never be wrong: settings, the state of a cluster, who is the leader. Several servers, called members, hold identical copies. Every change goes through the Raft agreement algorithm and is committed when a majority has written it to disk.

Every change raises one global number, the revision. Old versions stay readable until they are compacted. This turns the store into an ordered ledger: a client can say "tell me everything after revision 6" and miss nothing.

Why it exists

Distributed programs need one place they can trust for a decision. etcd offers strict consistency, change streams, expiring keys and conditional transactions in one server written in Go, with a gRPC interface and an Apache 2.0 licence.

It gives that by refusing two things: large data and writes without a majority. If your data may be slightly old, or is large, another store is cheaper and faster.

A short history

  1. 2013, July

    The etcd source repository is created on GitHub. The project comes from CoreOS, which needed to coordinate reboots and settings of its Linux machines.

  2. 2014

    Diego Ongaro and John Ousterhout publish "In Search of an Understandable Consensus Algorithm", the Raft paper, at the USENIX Annual Technical Conference.

  3. 2016, June

    Version 3.0.0 is released on 30 June with the gRPC interface, leases and transactions used today.

  4. 2018 and 2020

    The Cloud Native Computing Foundation accepts etcd on 11 December 2018. It reaches the graduated level on 24 November 2020.

  5. 2023, November

    etcd becomes a special interest group of the Kubernetes project.

  6. 2025 and 2026

    Version 3.6.0 arrives on 15 May 2025 with at least 50% less memory on average and full downgrade support. Version 3.7.0 arrives on 8 July 2026 and starts entirely without the old v2 store.

Words to know

Member
One etcd server of a cluster.
Quorum
A majority of the voting members.
Term
Raft's number for a period with at most one leader.
Revision
The store's global change counter.
Lease
A time limit that keys can hang on. If nobody renews it, the keys are deleted.
Watch
A stream of changes for keys, from a chosen revision.
Compaction
Forgetting history before a revision.
Linearizable
Every read sees the latest completed write.

How it works

Step through the idea, or press Play.

Step 1 of 3

Propose. A client sends a change; the leader puts it in the log

Understand it

Start here

Five scribes, one ledger

Imagine five scribes who each keep the same numbered ledger. A line counts once three of them have signed it.

Three must sign
66666

The numbers are the whole trick. With a number you can always ask for the rest.

The idea

What it is, and what it is not

etcd is

  • A strictly consistent key-value store (CP in CAP terms)
  • An ordered history with numbers
  • Leases, watches, conditional transactions
  • Lock and election services
  • One binary with TLS and role-based access

etcd is not

  • A general database: 2 GiB by default, 8 GiB suggested maximum
  • A cache, queue or log store
  • A name server or health checker
  • A store for distant regions: every write waits for a majority
  • Writable on the smaller side of a split

What people use it for

  • Cluster state

    Kubernetes keeps pods, services, secrets and settings in it.

  • Configuration and flags

    One value everywhere, pushed by a watch.

  • Service registration

    Addresses under a prefix, each on a lease.

  • Leader election and locks

    One holder at a time, released when the lease ends.

Data model

Keys, revisions, versions

Keys are bytes in one flat, sorted space. /config/db is just a name; folders do not exist, but a range read of a prefix feels like one. Each key carries three numbers.

NumberMeaningUse
Create revisionStore revision when the key was createdOrder in locks and elections; 0 means it does not exist
Mod revisionStore revision of its last changeCompare-and-swap, fencing
VersionChanges since creation, restarts after deletionCounting changes of one key
One transaction is one revision, even if it changes many keys. Deleting writes a tombstone.

Inside one member

Inside one etcd member: a client's put reaches the gRPC server, which proposes it to Raft. Raft appends to the write-ahead log with fsync and replicates to two peers. When committed it applies to the in-memory key index, which maps a key to a revision, and to the bbolt file, which maps a revision to a value.
The key index is in memory. Values live in a bbolt file on disk, a B+ tree ordered by revision, and hot pages are cached.

Architecture

Members and majority

Three members in three zones

A client puts a key on the leader in zone A. The leader sends the log entry to follower 1 in zone B and follower 2 in zone C.
Clients may connect to any member. A follower forwards what needs agreement to the leader.

Majority and failures

Q=⌊N2⌋+1f=N−Q(N,Q,f)=(3,2,1), (4,3,1), (5,3,2), (7,4,3)Q = \left\lfloor\frac{N}{2}\right\rfloor + 1 \qquad f = N - Q \qquad (N,Q,f) = (3,2,1),\ (4,3,1),\ (5,3,2),\ (7,4,3)
An even size adds no tolerance. More than seven members is not advised, because the leader must copy to all of them.

Writes

The path of a put

One write

Logging at the leader and sending to followers happen side by side. Follower 2 may be late.

Why a write takes as long as it does

Twrite≳RTTmajority+TfsyncT_{write} \gtrsim RTT_{majority} + T_{fsync}
Within one site a round trip is well under a millisecond and the disk decides. Between continents the round trip decides.

etcd's own benchmark, with 256-byte values: one client got 583 writes a second at 1.6 ms each; 1,000 clients over all members got about 50,000 a second at 20 ms, because many entries share one fsync. Your hardware will differ.

Leaders

Elections

When the leader is silent

A member votes only for a log at least as new as its own, so a winner has every committed entry.

Defaults: a heartbeat every 100 ms, an election timeout of 1,000 ms. The timeout should be at least ten times the round trip between members, and at most 50 s. During an election writes wait. Committed entries are never lost; uncommitted ones may be, so a client that times out must check or retry safely. The new leader extends all leases.

Reads

Linearizable or serializable

ReadWho answersMay be old?Without a majority
Linearizable (default)The contacted member, after confirming the commit point with a majorityNoFails
SerializableThe contacted member aloneYesWorks
All key-value operations together are strictly serializable. Watches are ordered but may lag, normally by milliseconds. See consistency models.

Changes

Watches

A watch is a stream on a key or prefix, optionally from an old revision. Events are ordered, unique, and none is dropped as long as the history is still there. After a break, continue from the last revision seen plus one.

List, then watch

If revision 8 was already compacted, the server says so. Then list again and watch from the new number.

Expiry

Leases

Create a lease with a time to live, attach keys, and keep it alive. If the renewals stop, the lease ends and all its keys are deleted, as normal events that watchers see. A lease is not tied to a connection, so a reconnect does not end it. Expiry can be late, for example after a leader change, but not early.

Registering a service

  1. 1

    Grant

    Ask for a lease of 10 s.

  2. 2

    Put

    Write /services/web/i-1 with the address, on that lease.

  3. 3

    Keep alive

    Renew every few seconds; client libraries do it.

  4. 4

    Leave

    Revoke the lease for an instant goodbye, or crash and vanish after at most about 10 s.

Conditions

Transactions, locks and elections

A transaction is *if* comparisons hold, *then* these operations, *else* those, all in one revision. Comparisons can look at value, version, create revision, mod revision or lease. Up to 128 operations by default.

Python
# The shape of compare-and-swap on the mod revisionstore = {"/counter": ("5", 41)}          # value, mod revisiondef txn(key, expected_rev, new, rev):    value, mod = store[key]    if mod != expected_rev:        return False, value              # somebody was faster: read again    store[key] = (new, rev)    return True, newprint(txn("/counter", 41, "6", 42))print(txn("/counter", 41, "6", 43))
Compare the mod revision rather than the value: a value can change and change back.
Edit and run it in your browser

The lock service creates a key under the lock's name on your lease and waits until no older key exists, judged by create revision. Each waiter watches only the one before. The election service works the same way.

Operate

Limits and settings

Defaults in v3.7

WhatValue
Storage quota2 GiB; 8 GiB suggested maximum, a higher value logs a warning
Request size1.5 MiB
Operations per transaction128
Heartbeat and election100 ms and 1,000 ms
Ports2379 clients, 2380 peers; use TLS on both
Raft snapshotEvery 10,000 entries (100,000 before 3.6)
Auto compactionOff unless you set a retention
Pre-voteOn

How fast does history grow?

50 writes/s×1 KB×86,400 s≈4.3 GB per day50\ writes/s \times 1\ KB \times 86{,}400\ s \approx 4.3\ GB\ per\ day
An example with assumed numbers. Without compaction it would pass the 2 GiB quota in half a day, even if it is always the same few keys.

Out of space, and back

Reads and deletes still work during the alarm. Compaction frees pages inside the file; only defragmentation gives them back to the disk, and it blocks that member while it runs.

Hardware and signals

AreaAdvice
DiskSSD on its own; 50 sequential IOPS at least, 500 for heavy clusters
CPU and memory2 to 4 cores and 8 GB for typical clusters; far more with thousands of watchers
NetworkMembers close together, one per zone
Watchfsync and commit times, leader changes, failed proposals, database size against the quota
NeighboursNothing else busy on the machine: a late heartbeat means an election

Change safely

Members, backups and access

Replace a dead member of three

  1. 1

    Remove it first

    Two members remain, majority 2, and both are up.

  2. 2

    Add the new one as a learner

    It receives data without a vote, so a mistake cannot break the quorum.

  3. 3

    Promote

    When it has caught up it becomes a voter: three again.

Adding first would make four members with majority 3. With one dead, every other member would have to be perfect, and a mistyped address would block all further changes. etcd rejects such additions by default.

Backups that work

  • etcdctl snapshot save from a live member, on a schedule
  • Check with etcdutl snapshot status
  • Restore with etcdutl snapshot restore, on every member from the same file
  • For Kubernetes add a revision bump and mark it compacted, so no cache sees time go back
  • Rehearse it

Not backups

  • Three members: they copy a mistaken delete at once
  • Copying files of a running member
  • etcdctl snapshot restore: removed in 3.6
  • A snapshot stored on the same machines
  • Forcing a new cluster while old members still run

Turn on TLS for clients and peers, role-based access with key prefixes, and encryption of sensitive values before they reach etcd. Whoever can read a Kubernetes cluster's etcd can read its secrets unless encryption at rest is set.

Decide

When to choose it, and when not

Choose etcd

  • Critical metadata that must never differ
  • Watching every change in order
  • Locks, elections, leases
  • Flags and settings with instant push
  • A few gigabytes at most
  • Building a control plane, as Kubernetes does

Choose something else

  • Large data or heavy writes
  • Slightly old data is fine: an eventually consistent store
  • Members on several continents
  • Discovery with DNS and health checks: Consul
  • Logs and time series
  • Your own app on Kubernetes: use its API, not its etcd

Alternatives

etcdZooKeeperConsulRedis
AgreementRaftZABRaftAsynchronous replication
DataFlat keys with historyTree, current state onlyKey-value and servicesStructures, large data
InterfacegRPC, JSON gatewayOwn TCP protocolHTTP and DNSOwn TCP protocol
NoticesStream, resumableOnce, or persistentBlocking queriesPub/sub, lost if away
AccessRoles on key rangesList per znodeTokens and policiesUsers and command lists
Choose it forControl planes, KubernetesHadoop familyDiscovery and meshCache, speed
Details of the second column are in ZooKeeper.

Summary

The whole topic in one minute.

etcd is a replicated ledger with a key-value view. Raft elects one leader, a majority commits each entry, and the revision numbers the result. Reads are linearizable unless you ask for a cheaper one, watches replay from a revision, leases remove what is no longer renewed, and transactions compare before they write.

Keep it small, on fast disks, with 3 or 5 members close together. Compact, defragment and back it up. Use a fencing number when a lock protects something outside etcd.

  • A majority commits; the revision numbers everything.
  • Reads are linearizable by default; serializable reads are cheaper and may be old.
  • List, then watch from the next revision. If compacted, list again.
  • 2 GiB by default, 8 GiB suggested maximum: compact, defragment, back up.
  • Remove a dead member before adding its replacement.

Sources