AlgoViz

etcd

medium 30 min

etcd 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

etcd clusterClientLeaderlog 1 to 6Follower 1log 1 to 6Follower 2log 1 to 6

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

Member 1followerMember 2followerMember 3leaderMember 4followerMember 5follower

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

    critical

    Changes between the read and the watch are lost.

    Wrong
    values = get_prefix(p)watch(p)
    Right
    values, rev = get_prefix(p)watch(p, start=rev + 1)
  • Adding before removing

    critical

    The majority grows while a member is down.

    Wrong
    etcdctl member add m4 ...etcdctl member remove m3
    Right
    etcdctl member remove m3etcdctl member add m4 --learner ...etcdctl member promote m4
  • No compaction

    major

    History fills the quota and every put is refused.

    Wrong
    # retention not set
    Right
    auto-compaction-mode: periodicauto-compaction-retention: "1h"
  • A lock without a check at the resource

    critical

    A paused holder acts after its lease ended.

    Wrong
    lock(); s3.put(report)
    Right
    rev = 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.