Distributed Key-Value Store

A DynamoDB-style store — the deep end of distributed systems — worked through the TOGAF ADM phases.

Distributed KV store, the ADM way, in 30 seconds

  • A (Vision): a highly available, horizontally scalable get(key)/put(key,value) store; principles — always writable, no single master, tunable consistency.
  • B (Business): two capabilities — write a value and read a value — by key only.
  • C (Data/App): keys distributed across nodes; each key replicated N times; peer-to-peer, no leader.
  • D (Technology): the deep core — consistent hashing for placement, N/W/R quorums for tunable consistency, gossip for membership, conflict resolution for concurrent writes.
  • E–H: start single-region, add multi-region; govern with availability and latency SLOs.
  • Lesson: 'always writable, no single master' (Phase A) forces the leaderless, quorum, eventual-consistency design in Phase D.

A coat check with no head attendant

We met the coat-check idea in the URL shortener: hand over a coat, get a numbered ticket, come back and collect it. A distributed key-value store is a coat check scaled to the point of absurdity — so many coats that no single room could hold them, and so busy that you can never hang a 'back in 5 minutes' sign on the door. There's no head attendant whose absence stops everything; any attendant can take your coat or fetch it, and they keep a few copies of each coat spread around so that one attendant calling in sick never means a lost coat.

That picture hides a brutal trade. To never close the door — to be always writable even when attendants can't reach each other — you have to accept that two attendants might occasionally take slightly different notes about the same coat and reconcile them later. A store like Amazon's Dynamo or Cassandra makes exactly that bargain: it chooses to stay up and sort out disagreements afterward, rather than refuse service to stay perfectly consistent. Understanding why it makes that bargain is the whole page.

What makes it hard — the problem before the solution

  • No single machine is big enough. The data must be spread across many nodes, and that spread has to stay smooth as nodes come and go.
  • Nodes fail constantly at scale. Each key needs copies on several nodes so one death loses nothing — and the store must keep serving through it.
  • *You can't have perfect consistency and perfect availability during a network split.* This is the CAP trade, and this design deliberately picks availability.
  • Concurrent writes can diverge. Two copies of a key can disagree after a partition, so the system needs a defined way to detect and resolve the conflict.

Why this is the deep end

A distributed key-value store (think Amazon Dynamo or Cassandra) is where almost every hard distributed-systems idea shows up at once: partitioning, replication, the CAP trade-off, quorums, membership, and conflict resolution. Walking the ADM keeps it from becoming a jumble — each phase introduces exactly the concept the next one needs.

Phase D is dense here — placement, quorums, membership, and conflicts.

Phase A — Architecture Vision

  • Vision: a store that reliably does get/put by key at massive scale, across many commodity machines.
  • Stakeholders: services that need a fast, always-available store; operators who need it to survive node and even datacenter loss.
  • Principles: always writable (availability over strict consistency — think shopping carts); no single master (no leader to fail or bottleneck); tunable consistency (let callers trade consistency for latency).

Phase B — Business Architecture

  • Value stream: a service writes a value by key → later reads it back, fast, from anywhere.
  • Write a value — put(key, value), must (almost) always succeed.
  • Read a value — get(key), fast, tolerant of occasional staleness.
  • No rich queries — key access only; that simplicity is what lets it scale.

Phase C — Information Systems Architecture (Data & Application)

Data architecture

  • Data model: opaque key → value pairs with version metadata (for conflict resolution).
  • Distribution: each key maps to a position on a ring; the nodes nearest that position own it.
  • Replication: each key lives on N nodes (e.g. 3) for durability and availability.

Application architecture

  • Peer-to-peer nodes — every node can handle any request; there is no special master.
  • A coordinator role — whichever node receives a request coordinates the read/write across replicas.
  • Membership awareness — every node knows roughly who else is in the ring.

Phase D — Technology Architecture (the core)

D1 — Placement: consistent hashing

Hash the key onto a ring; the next N nodes clockwise are its replicas.
  • Consistent hashing places keys and nodes on a ring (see Consistent hashing); a key belongs to the next N nodes clockwise.
  • Why: adding or removing a node moves only ~1/N of the keys, so the cluster grows and shrinks smoothly.
  • Virtual nodes even out the load and smooth rebalancing.
Placement: walk the ring to find a key's N replica nodes (python)
def replicas_for(key, ring, N):
    # ring: sorted list of (hash_position, node) incl. virtual nodes.
    pos = hash(key)                      # the key's point on the ring
    start = bisect_right(ring, pos)      # first node clockwise from the key
    chosen, seen = [], set()
    i = 0
    while len(chosen) < N:               # collect N DISTINCT physical nodes
        _, node = ring[(start + i) % len(ring)]
        if node not in seen:             # skip extra virtual nodes of the same box
            seen.add(node)
            chosen.append(node)
        i += 1
    return chosen                        # first is coordinator; all N hold a copy

Why leaderless, and why not a single master?

The familiar design — one leader takes all writes, followers copy them — is simpler to reason about and gives clean consistency. So why reject it here? Because Phase A asked for always writable, no single master, and a leader can't deliver that. The gaps are two. First, the leader is a bottleneck: every write in the system funnels through one node's capacity. Second, and worse, it's a single point of failure for writes: when the leader dies or a network split cuts it off, writes stop until a new leader is elected — the door closes exactly when you promised it never would.

A leaderless design pays for always-on writes with a harder job: since any node can accept a write, two nodes can accept conflicting writes to the same key during a split, and you must resolve that later (D4). That's a real cost — but it's the deliberate CAP choice. For a shopping cart or a session, staying writable and merging the occasional conflict beats refusing writes to stay pristine.

DesignWhat it buysThe gap it can't fill
Single masterClean, easy-to-reason consistency.Write bottleneck; writes halt on leader failure or partition.
Multi-master (sync)More than one write node.Cross-node coordination on every write kills availability under a split.
Leaderless + quorums (chosen)Always writable, no bottleneck, tunable consistency.Concurrent writes can diverge — you must detect and resolve conflicts.

D2 — Tunable consistency: N, W, R quorums

  • N = replicas per key, W = nodes that must ack a write, R = nodes that must respond to a read.
  • W + R > N guarantees a read overlaps the latest write (strong-ish); e.g. N=3, W=2, R=2.
  • Tune per call: W=1 for fast writes; R=1 for fast reads; higher for stronger guarantees.
  • This realizes the Phase A tunable consistency principle — the caller picks the trade (see CAP & PACELC).

The W + R > N rule is easier to feel with a picture. Say N=3, so a key sits on nodes {1,2,3}. A write with W=2 lands on at least two of them — say {1,2}. A later read with R=2 contacts at least two — say {2,3}. Those sets must share a node (here, node 2), and that shared node saw the latest write. Overlap is guaranteed precisely because 2 + 2 > 3. Drop to W=1, R=1 and the write set {1} and read set {3} can miss each other entirely — fast, but you might read stale. That's the dial, made concrete.

Setting (N=3)BehaviorUse it when
W=1, R=1Fastest, weakest — read may be stale.Logging, metrics, anything tolerant of a brief lag.
W=2, R=2Balanced — reads overlap latest write.The sensible default for most keys.
W=3, R=1Durable writes, fast reads.Write-rarely, read-constantly data.
W=1, R=3Fast writes, strong reads.Write-heavy data you occasionally need fresh.
Quorum write and read coordinated across the N replicas (python)
def put(key, value, N, W):
    nodes = replicas_for(key, ring, N)
    version = new_version()                      # metadata for conflict detection
    acks = send_to_all(nodes, "write", key, value, version)
    if count_ok(acks) >= W:                       # wait for W acknowledgements
        return "OK"                               # W=1 fast, W=N durable
    return "FAILED"

def get(key, N, R):
    nodes = replicas_for(key, ring, N)
    replies = read_from(nodes, key, wait_for=R)   # wait for R responses
    # W + R > N guarantees one reply holds the latest write.
    return newest_by_version(replies)             # resolve/return divergent versions

D3 — Membership & failure detection: gossip

  • Nodes use a gossip protocol (see Gossip protocol) to track who's alive and in the ring — no central registry.
  • A failed node's requests route to the next replica; hinted handoff stores writes temporarily and replays them when it returns.
  • This keeps the store always writable even during node failures — straight from the Phase A principle.
Hinted handoff: a neighbor holds a down node's write and replays it later (python)
def write_replica(node, key, value, version):
    if node.is_up():
        node.store(key, value, version)          # normal path
        return "stored"
    # Node is down but we still want the write to succeed (always writable).
    standin = next_healthy_node(node)             # a neighbour takes it temporarily
    standin.store_hint(for_node=node, key=key, value=value, version=version)
    return "hinted"                               # replayed to 'node' once gossip says it's back

# This is how a quorum write still completes while a replica is briefly offline.

D4 — Conflict resolution

  • Because writes can hit different replicas during a partition, two versions of a key can diverge.
  • Detect conflicts with version metadata (vector clocks or similar).
  • Resolve with last-writer-wins (simple, can lose data) or by returning both versions for the application to merge (e.g. merge two shopping carts).
  • This is the price of always writable — you trade clean consistency for availability, and handle the mess on read.
Resolve divergent versions: last-writer-wins vs application merge (python)
def resolve(versions):
    # 'versions' = the differing copies a quorum read collected for one key.
    if len(versions) == 1:
        return versions[0]                       # no conflict, easy

    # Option A: last-writer-wins — simple, but a 'losing' concurrent write is dropped.
    # return max(versions, key=lambda v: v.timestamp)

    # Option B: hand both to the app so it can MERGE (e.g. union two shopping carts).
    merged = versions[0].value
    for v in versions[1:]:
        merged = app_merge(merged, v.value)      # business decides how to combine
    return Version(value=merged, clock=merge_clocks(versions))

Scaling & bottlenecks — what breaks first

This store is built to scale by adding nodes, so the interesting failures aren't about one node melting — they're about the system's coordination and balance. Name them in order.

Breaks first as you scaleThe symptomThe fix
Hot key / hot partitionOne popular key's N nodes take disproportionate load.Cache the hot key in front; split its traffic; use virtual nodes to spread load.
Uneven key distributionSome nodes hold far more data than others.Virtual nodes smooth placement; rebalance by adding ring positions.
Conflict rate climbsLots of concurrent writes to the same keys diverge.Push resolution to the app (merge), or narrow write windows; use better version metadata.
Gossip can't keep upMembership view goes stale in a very large cluster.Tune gossip fanout/interval; partition the cluster; use seed/coordinator nodes.

Notice what is not on this list: 'the leader is overloaded' or 'writes stopped because a node died.' Those failure modes were designed out in Phase A by choosing leaderless and always-writable. The failures that remain are the price of that choice — distribution evenness and conflict handling — which is exactly the trade the whole design signed up for.

Phases E & F — Migration Planning

  • Start single-region with N=3 replication and quorum reads/writes.
  • Add multi-region replication once the single-region core is proven, accepting more conflict resolution.
  • Expose consistency knobs (W/R per call) to callers gradually, with sane defaults.

Phases G & H — Governance & Change

  • Governance (G): SLOs on availability (very high) and p99 latency; alerting on replica lag and conflict rates.
  • Change (H): adding capacity is just adding nodes to the ring — a routine, bounded operation thanks to consistent hashing.

A distributed KV store is where distributed-systems theory becomes one concrete machine — the capstone that connects nearly every component on this portal.

Why it matters

  • It's the clearest single example of the CAP trade-off made real.
  • It unifies partitioning, replication, quorums, membership, and conflict resolution in one design.
  • The Dynamo paper's ideas here echo through most modern NoSQL systems.

If ignored

  • Pick a single master and you lose the always-writable, no-bottleneck goal.
  • Skip quorum tuning and you can't trade consistency for latency where it matters.
  • Ignore conflict resolution and concurrent writes silently corrupt data.

Where it fits

  • Phase D is dense: consistent-hashing placement, N/W/R quorums, gossip membership, conflict resolution.
  • Phase A's availability-first CAP choice drives every one of those mechanisms.
  • Sits as the advanced capstone beside the interview framework.

Related topics

Interview lens

Questions it unlocks

  • Design a distributed key-value store (Dynamo/Cassandra style).
  • How do you get tunable consistency with N, W, and R?
  • How does a leaderless store stay available when nodes fail?

60-second answer

I frame it as an ADM walk. Phase A sets the CAP choice: always writable, no single master, tunable consistency. Phase B is just get and put by key. Phase C distributes keys across peer nodes, each key replicated N times, no leader. Phase D is the dense core: consistent hashing places keys on a ring so scaling moves only 1/N of data; N/W/R quorums give tunable consistency with W+R>N for strong-ish reads; gossip tracks membership with hinted handoff keeping it writable during failures; and version metadata plus conflict resolution handle concurrent writes — the accepted cost of choosing availability. E–H start single-region then go multi-region, governed by availability and latency SLOs. Every mechanism traces back to the Phase A availability-first principle.

Common traps

  • Introducing a single master and losing the always-available, no-bottleneck goal.
  • Forgetting conflict resolution for concurrent writes under partitions.
  • Treating consistency as fixed instead of tunable via W and R.

Search topics

↑↓ to move · Enter to open · Esc to close