The Evolution of etcd Storage: A Distributed /etc in RAM (v0.1 - v0.4)
DEV Community

The Evolution of etcd Storage: A Distributed /etc in RAM (v0.1 - v0.4)

Motivation & Series Roadmap

Storage engines are shaped by the workloads they are built to serve. Today, etcd is best known as the disk-backed datastore behind the Kubernetes control plane.

When it started in 2013, however, it was much simpler: an in-memory hierarchical directory tree serialized to JSON.

In this series, we will trace how real-world adoption changed etcd's storage layer over time. This first post starts at the beginning, when small CoreOS configuration trees made keeping everything in memory the obvious choice.

In later posts, we will cover the first major reliability overhaul, the arrival of Kubernetes and how it broke those early assumptions, and the move to a disk-backed engine built on BoltDB. From there, we will look at the scaling bottlenecks that led the team to fork BoltDB into bbolt and become database maintainers themselves. Finally, we will bring the story up to the present to see how etcd moved past its original design and what might come after bbolt.

In Part 1, we go back to etcd v0.1 through v0.4 (2013-2014). We will look at the original CoreOS workload, inspect the Go code behind its in-memory store and early Raft persistence, and benchmark a 3-node cluster to measure its throughput and latency limits.

The 2013 Workload: Why CoreOS Needed a Distributed /etc

In 2013, CoreOS set out to change how server infrastructure was operated. Instead of patching long-lived Linux hosts in place with apt or yum, CoreOS Container Linux shipped a minimal, container-only operating system modeled after ChromeOS. It consisted of the Linux kernel, systemd, a container runtime, and immutable dual-partition (A/B) automatic OS updates.

Updates were downloaded in the background to the passive partition and activated on reboot.

This minimal design created a coordination problem. Once servers reboot automatically and move containers across a cluster, you need a strongly consistent place to coordinate rolling reboots, schedule services, and share configuration. At the same time, CoreOS wanted to avoid running a JVM and Apache ZooKeeper on minimal Linux hosts.

To fill this role, they built etcd (from Unix /etc plus d for distributed and daemon) as a single static Go binary.

To understand what a "distributed /etc" meant in practice, and why this workload shaped etcd's first storage engine, let's look at how etcd sat at the center of a typical CoreOS cluster.

Inside a CoreOS Cluster: Bootstrapping Around etcd

Consider a small CoreOS cluster running a 3-replica web service behind an nginx reverse proxy on three worker machines, backed by a dedicated 3-node etcd cluster. Having three etcd nodes ensures that a single crash or reboot does not take the store down (we will look at how these nodes stay in sync later in this post).

The core design principle of the early CoreOS stack was hub-and-spoke coordination. Daemons on worker machines did not talk directly to each other: schedulers did not open RPC connections to worker agents, and update daemons did not use gossip protocols. Instead, every component only read from and wrote to etcd's shared directory tree:

Going through the bootstrap sequence shows how each part of the cluster maps to a small branch in that tree:

  • Start with an empty root: etcd starts first as a shared, hierarchical keyspace, similar to a cluster-wide /etc.
  • Workers join via fleetd: Each CoreOS worker starts fleetd, registers a liveness heartbeat under /_coreos.com/fleet/machines/, and agrees on a single active scheduler (/_coreos.com/fleet/lease/engine-leader, held here by Worker 2).
  • An admin deploys services and config: Using fleetctl and etcdctl directly against etcd (in 2013-2014, fleetctl wrote unit definitions directly into etcd without an intermediate API server), an admin submits web@1..3 and nginx along with shared application config such as /config/web/rate_limit. The active fleetd scheduler assigns those units to workers, which then start the containers locally.
  • Running containers register for discovery: Once running, each web replica publishes its IP:port under /services/web/. On Worker 3, nginx (driven by a lightweight template helper like confd) watches /services/web/ so traffic is routed only to healthy backends.
  • OS updates take turns via locksmithd: Every worker also runs locksmithd, which coordinates around a reboot semaphore under /coreos.com/updateengine/rebootlock/semaphore. This makes sure automatic A/B OS updates reboot one machine at a time instead of taking the whole cluster offline at once. (The etcd nodes themselves run locksmithd in their own one-at-a-time group for the same reason.)

It is worth noting how little data etcd actually holds once the cluster is up and running. The animation compresses each unit into a single line (13 keys in total). Even in a real CoreOS cluster, where fleet splits each unit across several internal subkeys (object, target, state), the entire working set consists of only a few dozen small keys.

Total data size stays well under 1 MB, with a small, steady stream of periodic heartbeat writes.

Storing /etc in RAM: Inside etcd v0.4's store

When the entire cluster's working set fits into a few hundred kilobytes, there is little reason to build an on-disk B+tree or an LSM-tree. Early etcd (v0.1 to v0.4) had no embedded database engine at all. Its primary storage engine was an in-memory Go directory tree (store), exposed over a simple HTTP+JSON API on port 4001.

Looking at store/store.go in etcd v0.4.9, the whole storage engine is represented by a single seven-field struct:

// store/store.go (etcd v0.4.9)
type store struct {
  Root *node
  WatcherHub *watcherHub
  CurrentIndex uint64
  Stats *Stats
  CurrentVersion int
  ttlKeyHeap *ttlKeyHeap // need to recovery manually
  worldLock sync.RWMutex // stop the world lock
}

Each coordination pattern from our CoreOS bootstrap walkthrough maps directly to one of these fields:

  • CoreOS Cluster Need HTTP+JSON Primitive Backing In-Memory Structure Hierarchical /etc paths (fleet, /config/*) Directory / leaf CRUD Root *node tree (Children map[string]*node) Mutual exclusion (locksmithd semaphore, fleetd leader lease) Atomic CAS (prevIndex / prevValue) Monotonic CurrentIndex + worldLock Ephemeral liveness (fleetd heartbeats, web@1..3 registration) Per-key TTLs (ttl=30) ttlKeyHeap min-heap Reactive config (nginx / confd following /services/web/) Long-polling watches (?wait=true) WatcherHub + 1,000-slot EventHistory ring buffer

Let's look at how each of these four components works in the code.

The Directory Tree, worldLock, and Atomic CAS

The root of the store is a Unix-like tree of node structs (store/node.go):

// store/node.go (etcd v0.4.9)
type node struct {
  Path string
  CreatedIndex uint64
  ModifiedIndex uint64
  Parent *node `json:"-"` // should not encode this field! avoid circular dependency.
  ExpireTime time.Time
  ACL string
  Value string // for key-value pair
  Children map[string]*node // for directory
  store *store
}

A node is either a leaf (holding a Value string with Children == nil) or a directory (holding a Children map[string]*node keyed by path segment). In memory, our CoreOS cluster's keyspace forms a nested tree of Go structs and maps, with ttlKeyHeap holding direct pointers to the same ephemeral *node structs:

Reading /services/web/web@1 acquires worldLock.RLock(), splits the path, and walks Root.Children["services"].Children["web"].Children["web@1"]. Every write acquires the exclusive worldLock.Lock() (commented // stop the world lock in the source code), increments the store's global monotonic CurrentIndex, and updates the affected node's ModifiedIndex.

Having a single global lock and a monotonic index makes Compare-and-Swap (CAS) straightforward to implement. Take locksmithd coordinating a 3 AM OS reboot on Worker 1 as an example. First, locksmithd reads /coreos.com/updateengine/rebootlock/semaphore and sees modifiedIndex: 5.

To claim the reboot slot, it sends a conditional PUT with prevIndex=5:

curl -X PUT http://10.0.0.1:4001/v2/keys/coreos.com/updateengine/rebootlock/semaphore \
-d prevIndex=5 \
-d value='{"semaphore":0,"max":1,"holders":["worker-1"]}'

Note that locksmith intentionally acquires this semaphore with prevIndex without a TTL or watch. A rebooting host must keep holding the slot while powered off and only releases it via another CAS after booting back up. Other hosts retry with exponential backoff.

In store.CompareAndSwap (store/store.go), the check and update run atomically under worldLock:

// store/store.go (etcd v0.4.9, trimmed)
func (s *store) CompareAndSwap(nodePath, prevValue string, prevIndex uint64, value string, expireTime time.Time) (*Event, error) {
  s.worldLock.Lock()
  defer s.worldLock.Unlock()
  n, err := s.internalGet(nodePath)
  if err != nil {
    return nil, err
  }
  if ok, which := n.Compare(prevValue, prevIndex); !ok {
    cause := getCompareFailCause(n, which, prevValue, prevIndex)
    return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  }
  s.CurrentIndex++
  // ... record Event with PrevNode ...
  n.Write(value, s.CurrentIndex)
  n.UpdateTTL(expireTime)
  s.WatcherHub.notify(e)
  return e, nil
}

If Worker 1 and Worker 2 both send a request with prevIndex=5 at the same time, whichever request runs first advances the node to modifiedIndex: 42. The second request fails n.Compare and receives 101: Compare failed ([5 != 42]).

Ephemeral Keys and ttlKeyHeap

Unlike the reboot semaphore, service registrations and machine heartbeats need to disappear automatically if a worker crashes. When web@1 starts on Worker 1, it registers an ephemeral key with a 30-second TTL:

curl -X PUT http://10.0.0.1:4001/v2/keys/services/web/web@1 \
-d value="10.0.1.1:8080" \
-d ttl=30

When store inserts /services/web/web@1 (auto-creating /services and /services/web along the way), it detects a non-zero ExpireTime and registers the *node pointer in ttlKeyHeap (store/ttl_key_heap.go). Instead of keeping a plain slice or scanning every key in the tree to find expired entries, ttlKeyHeap implements Go's standard library container/heap.Interface (Len, Less, Swap, Push, Pop):

// store/ttl_key_heap.go (etcd v0.4.9, trimmed)
type ttlKeyHeap struct {
  array []*node
  keyMap map[*node]int
}
func (h ttlKeyHeap) Len() int { return len(h.array) }
func (h ttlKeyHeap) Less(i, j int) bool { return h.array[i].ExpireTime.Before(h.array[j].ExpireTime) }
func (h ttlKeyHeap) Swap(i, j int) {
  h.array[i], h.array[j] = h.array[j], h.array[i]
  // Keep each node's current slice index up to date
  h.keyMap[h.array[i]] = i
  h.keyMap[h.array[j]] = j
}
func (h *ttlKeyHeap) Push(x interface{}) {
  n, _ := x.(*node)
  h.keyMap[n] = len(h.array)
  h.array = append(h.array, n)
}
func (h *ttlKeyHeap) Pop() interface{} {
  old := h.array
  n := len(old)
  x := old[n-1]
  h.array = old[0 : n-1]
  delete(h.keyMap, x)
  return x
}
func (h *ttlKeyHeap) update(n *node) {
  if index, ok := h.keyMap[n]; ok {
    heap.Remove(h, index)
    heap.Push(h, n)
  }
}

Two details explain how this data structure works:

  • Ordering array by ExpireTime so array[0] always expires first: Go's container/heap treats the flat slice array as an implicit binary tree where the children of index i are at 2*i + 1 and 2*i + 2. Whenever etcd inserts or removes a node via heap.Push or heap.Pop, container/heap calls Less(i, j) to compare ExpireTime on the *node pointers and swaps elements up or down a single root-to-leaf path (O(log N)). This preserves the min-heap invariant: every parent expires earlier than both of its children. As a result, the key that expires soonest always sits at array[0], so checking whether any key is due to expire takes O(1) time.
  • Tracking positions with keyMap for heartbeat refreshes and early deletes: A plain binary heap only gives direct access to the earliest element (array[0]). When web@1 refreshes its 30-second heartbeat (UpdateTTL) or is deleted manually, store finds the *node through the directory tree rather than the heap, so it does not know which index i in array that node currently occupies. Because Push, Pop, and Swap keep keyMap[node] = i synchronized on every move, update(n) and remove(n) can find the node's slice index in O(1) and rebalance via heap.Remove and heap.Push in O(log N), avoiding a linear scan of the slice.

Expiring overdue keys then becomes a simple loop in store.DeleteExpiredKeys(cutoff time.Time):

// store/store.go (etcd v0.4.9, trimmed)
func (s *store) DeleteExpiredKeys(cutoff time.Time) {
  s.worldLock.Lock()
  defer s.worldLock.Unlock()
  for {
    node := s.ttlKeyHeap.top()
    if node == nil || node.ExpireTime.After(cutoff) {
      break
    }
    s.CurrentIndex++
    e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex)
    e.PrevNode = node.Repr(false, false)
    s.ttlKeyHeap.pop()
    node.Remove(true, true, func(path string) {
      s.WatcherHub.notifyWatchers(e, path, true)
    })
    s.WatcherHub.notify(e)
  }
}

The animation below shows this behavior across our three web replicas (ttl=30s). Healthy renewals keep pushing keys down below the root, while a crashed container eventually moves to the top and expires once its timestamp is reached:

Note one important detail in the signature of DeleteExpiredKeys: it does not call time.Now() itself, and instead takes an explicit cutoff time.Time parameter. If three etcd nodes expired keys using their own local wall clocks, clock skew would cause them to expire keys at different points relative to incoming writes, leading to diverging trees and different CurrentIndex values. We will see in the next section how etcd solves this through Raft.

Long-Polling Watches: WatcherHub and the EventHistory Ring Buffer

On Worker 3, nginx (driven b

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.