Skip to content

About

Dynamo-style distributed cache in Java 21: consistent hashing, quorum replication, hinted handoff, Merkle anti-entropy

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

dynamo-cache

Java 21 License: MIT

A from-scratch Java 21 implementation of the core of Amazon's Dynamo (SOSP 2007): a leaderless, always-writeable key-value store. Keys are spread over a consistent-hashing ring with virtual nodes and replicated on N nodes; any node coordinates reads and writes with tunable R/W quorums; vector clocks track causality and concurrent writes come back to the client as siblings to reconcile. Failures are handled the way the paper describes: SWIM gossip detects them, sloppy quorums with hinted handoff keep writes available, and read repair plus Merkle-tree anti-entropy bring replicas back in sync. Every one of those mechanisms is exercised by integration tests that run real clusters over loopback TCP and inject crashes, partitions and message loss, including a seeded randomized fault test that checks that no acknowledged write is ever lost.

No frameworks: the only runtime dependency of the server is the JDK. Networking is plain blocking sockets on virtual threads with a custom binary protocol.

Features

  • Partitioning: consistent hashing ring with virtual nodes (MurmurHash3, 128 vnodes per node by default); preference lists of N distinct physical nodes.
  • Membership and failure detection: SWIM (ping, ping-req via k helpers, suspicion with incarnation-number refutation, infection-style piggybacked dissemination) implemented from scratch, plus periodic push-pull state sync so that partitions heal and restarted nodes rejoin on new ports.
  • Tunable consistency: per-cluster N, per-request R and W; any node accepts any request.
  • Versioning: vector clocks with Dynamo-style timestamp-based truncation; concurrent versions are returned as siblings; the client resolves them and writes back with the merged context.
  • Sloppy quorum and hinted handoff: requests skip unhealthy preference-list nodes (or nodes that fail mid-request) and use stand-ins that keep durable hints and hand them off on recovery.
  • Read repair: after replying to the client, the coordinator pushes the reconciled version set to stale replicas.
  • Anti-entropy: Merkle-tree comparison between replica pairs; only differing buckets are exchanged, in both directions, in one round trip.
  • Storage engine: in-memory LRU with per-version TTL, tombstones with TTL-based GC, and an optional CRC-checked append-only log with torn-write recovery and online compaction.
  • Client library and CLI: thread-safe Java client with sibling-resolver helper; a CLI with get / put / delete / status / shell.
  • Testing: 155 unit tests and 23 integration tests, including a seeded randomized fault injection test, all on ephemeral ports.
  • Benchmarks: JMH microbenchmarks and a closed-loop load generator with HdrHistogram latencies.

Architecture

flowchart TB
    subgraph Client
        C[DynamoClient / dynamo-cli]
    end

    subgraph Node["DynamoNode (one per process)"]
        direction TB
        RPC["RpcServer / RpcClient<br/>TCP, binary frames, virtual threads"]
        DISP{{"request dispatch<br/>(switch over sealed Request)"}}
        COORD["QuorumCoordinator<br/>N/R/W, sloppy quorum,<br/>clock generation, read repair"]
        REPL["ReplicaService"]
        SWIM["SwimProtocol + MembershipTable<br/>ping / ping-req / suspect / refute"]
        RING["RingView<br/>ConsistentHashRing (vnodes)"]
        HH["HintedHandoffService"]
        AE["AntiEntropyService<br/>Merkle trees"]
        STORE[("InMemoryStorageEngine<br/>LRU + TTL")]
        HINTS[("HintStore")]
        LOG[("AppendOnlyLog<br/>CRC32C records")]
    end

    C -- "ClientGet / ClientPut / ClientDelete" --> RPC
    RPC --> DISP
    DISP --> COORD
    DISP --> REPL
    DISP --> SWIM
    DISP --> AE
    COORD -- "preference list + liveness" --> RING
    SWIM -- "membership changes" --> RING
    COORD -- "ReplicaPut / ReplicaGet<br/>(local or remote)" --> REPL
    REPL --> STORE
    REPL --> HINTS
    HH --> HINTS
    AE --> STORE
    STORE --> LOG
    HINTS --> LOG
    RPC <-. "gossip, replication,<br/>anti-entropy, handoff" .-> Peers["other nodes"]
Loading

A write, end to end:

sequenceDiagram
    participant Cl as Client
    participant X as Node X (not a replica)
    participant A as Node A (coordinator)
    participant B as Node B
    participant C as Node C (down)
    participant D as Node D (stand-in)
    Cl->>X: ClientPut(k, v, context)
    X->>A: forward (writes are coordinated by a preference-list node)
    Note over A: clock = context + A's counter, past every counter A issued for k
    A->>A: local write
    A->>B: ReplicaPut(k, v@clock)
    A-xC: ReplicaPut (connection refused / SWIM says DEAD)
    A->>D: ReplicaPut(k, v@clock, hintFor=C)
    B-->>A: Ok
    Note over A: W=2 acks reached (A, B)
    A-->>X: ClientPutResponse(clock)
    X-->>Cl: clock
    D-->>A: Ok (late ack still recorded)
    Note over D,C: later: C is ALIVE again, D hands the hint off and deletes it
Loading

Modules

Module Contents
dynamo-core Ring, vector clocks, Merkle trees, storage engine and log, SWIM state machine and protocol driver, binary protocol, TCP transport, fault-injecting transport. No dependencies.
dynamo-server DynamoNode: coordinator, replica, hinted handoff, anti-entropy; the server launcher. Integration tests and the in-process TestCluster harness live here.
dynamo-client DynamoClient library and the dynamo-cli command-line tool.
dynamo-benchmarks JMH microbenchmarks and LoadGenerator.

Dynamo paper concepts, mapped to code

Paper (section) Concept Implementation
§4.2 Consistent hashing with virtual nodes ConsistentHashRing
§4.3 Replication, preference list of N distinct physical nodes ConsistentHashRing.preferenceList/walk, RingView
§4.4 Vector clocks, syntactic reconciliation, clock truncation VectorClock, Versions, Versioned
§4.4 Client-side semantic reconciliation of siblings GetResult, SiblingResolver, DynamoClient.getResolved
§4.5 get/put with tunable N, R, W; coordinator QuorumCoordinator, QuorumTracker, ReplicationConfig
§4.5 Writes coordinated by a preference-list node (request forwarding) QuorumCoordinator.forwardToPreferenceList
§4.6 Sloppy quorum QuorumCoordinator.replicate / sendWrite / sendRead (fallback walk past the preference list)
§4.6 Hinted handoff, hints kept in a separate local store HintStore, HintedHandoffService
§4.7 Anti-entropy with Merkle trees MerkleTree, AntiEntropyService
§4.8 Membership and failure detection (gossip) SWIM: MembershipTable (state machine), SwimProtocol (driver), DisseminationBuffer
§4.8 Failures are transient; ring membership changes only on explicit join/leave RingView (only LEFT removes a node), DynamoNode.leave
§4.8.2 Seed nodes for discovery SwimProtocol.start(seeds) push-pull join
§5 Read repair QuorumCoordinator.readRepair
§5 Pluggable local persistence engine StorageEngine, InMemoryStorageEngine, AppendOnlyLog
§6 Divergent versions and conflict surfacing BasicReplicationIT, PartitionIT

Key design decisions and tradeoffs

SWIM instead of Dynamo's original gossip. The paper uses a gossip-based, eventually consistent membership view and local failure detection. SWIM gives the same decentralization with bounded detection time and a low false-positive rate thanks to indirect probes and suspicion. Plain SWIM never contacts members it believes dead, so after a partition heals the two sides would never rediscover each other; like HashiCorp memberlist, every few protocol periods a node does a full push-pull sync with a random member including dead ones. A dead or restarted node refutes its own death certificate by jumping to incarnation + 1, so incarnations do not need to be persisted. Suspicion of a probe target is always re-sent in the ping to that target, even after the rumor has aged out of the piggyback buffer, so a live but slandered node always gets the chance to refute.

Ring membership vs liveness. Following §4.8, a failed node stays on the ring and its keys do not move; SWIM only decides which nodes requests skip. Only an explicit leave() (status LEFT) removes a node. This avoids data shuffling on every transient failure at the cost of relying on hinted handoff and anti-entropy during outages.

Who generates the clock. Writes are relayed to a preference-list node (Dynamo §4.5), which keeps clocks at roughly N entries. The coordinator's new counter is the maximum of the client's context, anything in its local replica, and a per-key-stripe high-water mark, plus one. The high-water mark is the subtle part: without it, two concurrent writes through the same coordinator could be assigned the same clock before either reached local storage, and one would silently disappear. As in the paper, blind writes through the same coordinator are ordered (last one wins) while writes through different coordinators without a shared context become siblings. Dotted version vectors would remove that asymmetry; see future work.

Sloppy quorum also on failure, not only on detection. A request is re-sent to the next healthy node beyond the preference list either because SWIM already reports the owner down or because the RPC itself failed or timed out. Writes therefore succeed immediately after a crash, before the failure detector has noticed (FailureHandlingIT.writesSucceedEvenBeforeTheFailureDetectorNotices).

Hints are durable. The paper keeps hints in a separate local database. Here the HintStore is a second storage engine with its own append-only log (when persistence is enabled), so an acknowledged write whose only extra copies are hints survives a crash of the stand-in. The seeded fault test depends on this.

Merkle trees rebuilt per round, per peer. For each peer, both sides hash exactly the keys whose preference list contains both of them, into a fixed-shape tree of 2^10 buckets over the token space. Leaves are an order-independent sum of mixed key digests, so a tree is built in one pass over an unordered store. This is simpler than the paper's incrementally maintained per-range trees and makes a node rebuilding from empty storage converge naturally, but costs a full scan of local keys per anti-entropy round. Fine for in-memory datasets; a production system would maintain trees incrementally.

Virtual threads, blocking I/O, ReentrantLock. Every inbound request runs on its own virtual thread, so a coordinator can simply block waiting for its quorum, and code reads top to bottom. Connections are multiplexed with correlation ids, so one TCP connection per peer pair carries many concurrent requests. Locks that can be held by virtual threads are ReentrantLock rather than synchronized, because JDK 21 pins a virtual thread to its carrier inside a monitor.

Fault injection at the transport seam. FaultInjectingTransport wraps the real TCP transport and consults a shared NetworkConditions for both the request and the response. Dropping only the response reproduces the hardest real-world case: the replica applied the write but the coordinator times out. Endpoints are identified by node id rather than address, so partitions survive restarts on new ephemeral ports.

Tombstones and TTL share one mechanism. Each version carries an absolute expiry shared by all replicas. Client TTLs and tombstone garbage collection (default one hour) are the same code path. The tradeoff is the usual one: a replica that is down longer than the tombstone TTL and is then repaired from a stale copy can resurrect a deleted value.

Build, run, test

Requires JDK 21 and Maven 3.9+.

mvn verify                 # compile (-Werror), Spotless check, 155 unit + 23 integration tests (35-50 s)
mvn spotless:apply         # format with google-java-format
mvn -DskipTests package    # build the runnable jars

Run a local 5-node cluster (ports 7001-7005, N=3 R=2 W=2):

scripts/start-cluster.sh                 # or: N=3 R=1 W=3 DATA_DIR=/tmp/dyn scripts/start-cluster.sh
dyn() { java -jar dynamo-client/target/dynamo-cli.jar --nodes 127.0.0.1:7001,127.0.0.1:7002 "$@"; }

dyn status
dyn put cart:42 milk                     # OK clock={node-2:1} context=AQZub2RlLTIB6Mb62JM0
dyn get cart:42                          # prints the value(s) and an opaque context
dyn put cart:42 milk,eggs --context AQZub2RlLTIB6Mb62JM0

scripts/kill-node.sh node-3              # SIGKILL; SWIM suspects it, then declares it DEAD
dyn put cart:43 bread                    # still succeeds: sloppy quorum, a stand-in keeps a hint
dyn status                               # node-3 shows DEAD; the stand-in reports hints=1
scripts/restart-node.sh node-3           # rejoins at incarnation 1; the hint is handed off
scripts/stop-cluster.sh

Using the client library:

try (DynamoClient client = DynamoClient.builder().nodes("127.0.0.1:7001,127.0.0.1:7002").build()) {
  client.put("cart:42", "milk");
  GetResult r = client.get("cart:42");
  if (r.hasConflict()) {
    // siblings from concurrent writes: merge them, then write back with the merged context
  }
  client.put("cart:42", "milk,eggs", r.context());
}

What the tests cover

All tests bind port 0 and can run in parallel with other processes.

Test What it proves
ConsistentHashRingTest distinct replicas, wrap-around, determinism, vnode balance (each of 5 nodes within 5% of 20%), adding a node moves ~1/n of keys and only to the new node
VectorClockTest, VersionsTest causality cases, merge is commutative/associative/idempotent (randomized), antisymmetry, pruning, deterministic tie-break, digests
MerkleTreeTest identical data gives identical trees, a single change localizes to one bucket, missing keys detected
MembershipTableTest the full SWIM override table (14 cases), refutation, suspicion timeout, rejoin after death, leave
SwimProtocolTest real SWIM over TCP: discovery via one seed, crash detection, indirect probes avoid false positives on a broken link, refutation, partition heal, restart on a new port
AppendOnlyLogTest recovery with siblings, torn-tail truncation, checksum corruption, compaction, removals
TcpTransportTest, FaultInjectingTransportTest, MessageCodecTest multiplexing 2,000 concurrent requests, timeouts, fast failure on dead peers, partitions/delay/loss, round trip and truncation of every message type
BasicReplicationIT placement on exactly N replicas, forwarding, causal ordering, concurrent writes become siblings and client resolution collapses them, tombstones, TTL
FailureHandlingIT sloppy quorum + hinted handoff, writes before detection, read repair, Merkle anti-entropy with no reads, a wiped node rebuilt by anti-entropy (each with the other repair mechanisms disabled)
PartitionIT both sides of a partition accept writes, siblings appear after healing, client resolution converges all replicas; isolated node rejects W=2 but accepts W=1
DurabilityIT acknowledged writes survive a crash of every node; hints survive a crash of the stand-in
SeededFaultInjectionIT random crashes/restarts, partitions, 2% message loss and delay from one seed; asserts no acknowledged write is lost and all replicas converge with no outstanding hints

The seeded test prints its scenario, for example [seed=1592598535] acked=192 failed=8 droppedMessages=141 schedule=[r0: crash node-1, r2: heal, r4: restart node-1, r5: partition [node-3, node-5] | [node-1, node-2, node-4], ...]. Rerun any scenario with mvn verify -Ddynamo.seed=<seed>. The seed fixes the fault schedule and the loss/delay decisions; thread interleavings are not controlled, so a seed reproduces a scenario, not an exact execution.

Benchmarks

All numbers below were measured by me on one machine: Apple M4 (10 cores), 16 GB, macOS, OpenJDK 21.0.12. Nothing else was benchmarking or building at the time; the only other load was one background VM using about half a core. Every figure is the median of 3 runs, with the [min - max] range in brackets. The 1-minute load average was 1.7 to 3.9 during the JMH runs and 7.8 to 12.1 during the cluster test, which saturates the 10 cores itself. Raw output, per-round tables and the sampled load averages are in dynamo-benchmarks/results/2026-10-15-apple-m4.txt.

Cluster load test

LoadGenerator starts a fresh 5-node in-process cluster on loopback TCP for each configuration, preloads 10,000 keys, warms up for 5 s and then runs 64 closed-loop virtual-thread clients for 15 s. Workload: 50% reads / 50% blind writes, 256 B values, uniform key choice, requests spread round-robin over all nodes (so most writes take one forwarding hop). Each of the 3 rounds is a fresh JVM that first runs an unreported 10 s pre-warm pass, and the configuration order is rotated between rounds so that JIT warm-up does not favor whichever configuration runs first. Clients, all five nodes and the load generator share the same 10 cores, so throughput is CPU-bound.

java -cp dynamo-benchmarks/target/dynamo-benchmarks.jar io.dynamocache.bench.LoadGenerator \
    --nodes 5 --duration 15 --warmup 5 --concurrency 64 --prewarm 10 \
    --configs 1/1/1,3/1/1,3/2/2,3/3/3,3/1/3,3/3/1
N R W throughput (ops/s) read p50 (ms) read p99 (ms) write p50 (ms) write p99 (ms) errors
1 1 1 141,615 [141,448 - 142,059] 0.46 [0.46 - 0.46] 0.77 [0.76 - 0.77] 0.46 [0.46 - 0.46] 0.76 [0.76 - 0.77] 0
3 1 1 88,337 [87,446 - 88,543] 0.65 [0.65 - 0.65] 1.43 [1.42 - 1.73] 0.66 [0.66 - 0.66] 1.66 [1.65 - 2.04] 0
3 2 2 80,972 [79,506 - 81,254] 0.71 [0.70 - 0.71] 1.31 [1.25 - 1.64] 0.80 [0.80 - 0.80] 1.65 [1.59 - 2.08] 0
3 3 3 76,458 [76,276 - 78,648] 0.74 [0.73 - 0.74] 1.70 [1.34 - 1.75] 0.84 [0.82 - 0.84] 1.94 [1.64 - 2.06] 0
3 1 3 82,236 [82,136 - 82,520] 0.51 [0.50 - 0.51] 1.10 [1.10 - 1.14] 0.94 [0.94 - 0.95] 2.03 [1.95 - 2.29] 0
3 3 1 84,198 [81,120 - 84,375] 0.88 [0.88 - 0.89] 1.73 [1.73 - 2.59] 0.54 [0.54 - 0.55] 1.30 [1.29 - 1.75] 0

How to read it:

  • Replication is the main cost. Going from N=1 to N=3 drops throughput by 38-46%, because every request now fans out to three replicas regardless of R and W, which triples replica work on a CPU-bound box.
  • Bigger quorums cost a little, not a lot. With N=3, throughput goes 88k → 81k → 76k ops/s for R=W=1 → 2 → 3, and median latency rises by about 0.05-0.1 ms per step. The coordinator always contacts all N replicas; R and W only decide how many replies it waits for, so a larger quorum means waiting for a slower reply.
  • R/W trades read latency against write latency. R=1/W=3 gives the fastest reads (0.51 ms p50) and the slowest writes (0.94 ms); R=3/W=1 is the mirror image (reads 0.88 ms, writes 0.54 ms).
  • Tails stay tight. p99 is 1.1-2.0 ms for every N=3 configuration, and throughput varied by 4% or less between rounds.
  • With all processes on one host there is no network latency to hide, so the ordering between configurations is meaningful but the absolute latencies are lower than a real multi-host deployment would see.

Microbenchmarks (JMH)

java -jar dynamo-benchmarks/target/dynamo-benchmarks.jar (each benchmark in its own forked JVM, 3x1 s warmup, 5x1 s measurement, average time per operation; median [min - max] over 3 full runs).

Benchmark Parameters Time per op
Ring: preference list (N=3) for a token 5 nodes x 16 / 128 / 256 vnodes 48 / 54 / 52 ns
Ring: preference list (N=3) for a token 50 nodes x 16 / 128 / 256 vnodes 44 / 50 / 53 ns
Ring: MurmurHash3 of key + preference list 50 nodes x 256 vnodes 55 [54 - 59] ns
Vector clock merge (concurrent clocks) 3 entries 32.0 [31.5 - 32.7] ns
Vector clock merge (concurrent clocks) 10 entries 48.0 [47.9 - 48.4] ns
Vector clock compare 3 / 10 entries 5.6 / 5.6 ns
Vector clock increment 3 / 10 entries 15.4 / 22.7 ns
Vector clock decode 3 / 10 entries 51 / 176 ns
Merkle tree build, depth 10 100,000 keys 99 [97 - 102] µs
Merkle tree diff, 10 differing keys depth 10 0.15 [0.15 - 0.15] µs
Encode ReplicaPut (256 B value, 2-entry clock) 81 [81 - 83] ns
Decode ReplicaPut 66 [66 - 67] ns

Ranges for every row, including the ones shortened to medians above, are in the results file. Takeaways:

  • Routing a request costs about 50 ns and barely changes with ring size: lookup is a binary search over the vnode tokens followed by a short scan, so going from 80 to 12,800 vnodes adds only a few nanoseconds. That is noise next to a network round trip.
  • Vector clock operations take tens of nanoseconds at the sizes Dynamo's truncation keeps clocks to.
  • An anti-entropy tree over 100k keys builds in about 0.1 ms of CPU, and comparing two trees that differ in a handful of keys takes 0.15 µs.

Limitations and future work

  • No dynamic rebalancing protocol. Nodes join through SWIM and the ring updates immediately; data then reaches the new owner through anti-entropy and read repair rather than an explicit range transfer, and keys a node no longer owns are not garbage collected.
  • Anti-entropy cost is a full scan of local keys per round (see tradeoffs). Incremental per-range Merkle trees would make it proportional to change rate.
  • Clock semantics: blind writes through the same coordinator are ordered rather than surfaced as siblings (as in Dynamo). Dotted version vectors (Riak 2.0) would fix this and avoid sibling explosion.
  • Tombstone resurrection is possible if a replica stays partitioned longer than the tombstone TTL.
  • Single lock per storage engine. Simple and fast enough for the benchmarks here; lock striping or a concurrent map with a separate LRU approximation would scale better on many cores.
  • No security: no TLS or authentication on the wire protocol.
  • Crash simulation in tests stops a node in-process; data in the OS page cache survives, which is equivalent to a process crash but not to power loss (use FsyncPolicy.ALWAYS for that).
  • No wire-protocol versioning: all nodes are assumed to run the same build.
  • Future: Netty transport, request hedging for tail latency, client-side partition-aware routing (skips the forwarding hop), recording operation histories in the fault tests and checking them with an external checker (Jepsen/Elle style), and metrics export (Micrometer / Prometheus).

License

MIT, see LICENSE.

About

Dynamo-style distributed cache in Java 21: consistent hashing, quorum replication, hinted handoff, Merkle anti-entropy

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages