etcd
medium 30 minetcd is a small, strongly consistent key-value store.
See it run
See a line become official, leaders change, a watch catch up and a lease run out.
Operations
Put
A client writes entry 7 to a three-member cluster.
Step 1 of 5
Request
The client sends a put. A follower would pass it on to the leader.
Step 1: Request
def put(key, value): entry = log.next(term, key, value) send_to_followers(entry) # side by side wal.append_and_fsync(entry) wait_until(on_disk >= majority) revision += 1 # apply store[revision] = (key, value) notify_watchers(revision)- Cost
- round trip + fsync
- Guarantee
- majority on disk
The leader counts: with three members one follower is enough.
In the real world
The same etcd doing real jobs. Pick one and step through it.
Five members, majority three.
Step 1 of 4
Five
2 failures to spare
All are up.
Step 1: Five
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Watching without a revision
criticalChanges between the read and the watch are lost.
Wrongvalues = get_prefix(p)watch(p)Rightvalues, rev = get_prefix(p)watch(p, start=rev + 1)Adding before removing
criticalThe majority grows while a member is down.
Wrongetcdctl member add m4 ...etcdctl member remove m3Rightetcdctl member remove m3etcdctl member add m4 --learner ...etcdctl member promote m4No compaction
majorHistory fills the quota and every put is refused.
Wrong# retention not setRightauto-compaction-mode: periodicauto-compaction-retention: "1h"A lock without a check at the resource
criticalA paused holder acts after its lease ended.
Wronglock(); s3.put(report)Rightrev = lock()storage.put(report, fence=rev) # refuses smaller numbers
Interview tips
How to explain it
- A small replicated ledger.
- A majority commits each line.
- Revisions make watches complete.
Memory trick
- Three of five sign.
- Compact history, defragment the file.
- Out before in.
Reach for it when
- The data is small and critical.
- Order of changes matters.
- Ownership must expire.
Be careful with
- Slow disks: they cause elections.
- Members far apart.
- Large values and busy keys.