Dynamo: Amazon's highly available key-value store
medium 35 minAmazon's shopping cart had to accept every add, even while servers and links failed.
A tiny Dynamo you can break
Read it, run it, change a line and run it again.
Loading editor…
Runs here. Our own toy, not Amazon's code: a ring with 8 tokens per machine, preference lists, N, R and W, vector clocks, a sloppy quorum with hints, read repair, and a Merkle comparison. Positions come from MD5, so the output is the same every run.
The same in JavaScript
// Vector clocks and a cart merge that keeps removals. Runs in Node or a browser console.const descends = (a, b) => Object.entries(b).every(([n, c]) => (a[n] ?? 0) >= c);function relation(a, b) { if (descends(a, b) && descends(b, a)) return "same"; if (descends(b, a)) return "a is older"; if (descends(a, b)) return "b is older"; return "concurrent";}const summary = (clocks) => clocks.reduce((out, c) => { for (const [n, v] of Object.entries(c)) out[n] = Math.max(out[n] ?? 0, v); return out; }, {});// A cart sibling: item -> { adds: [clock...], removes: [clock...] }function mergeCarts(siblings) { const all = {}; for (const cart of siblings) { for (const [item, { adds, removes }] of Object.entries(cart)) { all[item] ??= { adds: [], removes: [] }; all[item].adds.push(...adds); all[item].removes.push(...removes); } } // Keep an item if some add is not covered by any remove. return Object.keys(all).filter((item) => all[item].adds.some((add) => !all[item].removes.some((rm) => descends(rm, add))), );}const west = { book: { adds: [{ A: 1 }], removes: [] }, pen: { adds: [{ A: 2 }], removes: [] }, cup: { adds: [{ A: 2, B: 1 }], removes: [] } };const east = { book: { adds: [{ A: 1 }], removes: [] }, pen: { adds: [{ A: 2 }], removes: [{ A: 2, C: 1 }] } };console.log(relation({ A: 2, B: 1 }, { A: 2, C: 1 })); // concurrentconsole.log(summary([{ A: 2, B: 1 }, { A: 2, C: 1 }])); // { A: 2, B: 1, C: 1 }console.log(mergeCarts([west, east])); // [ 'book', 'cup' ]: the pen stays removedThe same in TypeScript
// The preference list: walk clockwise, skip machines already chosen.type Token = { pos: number; machine: string };export function preferenceList(tokens: Token[], keyPos: number, n: number): string[] { const ring = [...tokens].sort((a, b) => a.pos - b.pos); let start = ring.findIndex((t) => t.pos > keyPos); if (start === -1) start = 0; // wrap round past the largest position const out: string[] = []; for (let k = 0; k < ring.length && out.length < n; k++) { const m = ring[(start + k) % ring.length].machine; if (!out.includes(m)) out.push(m); } return out;}const toy: Token[] = [ { pos: 10, machine: "A" }, { pos: 22, machine: "B" }, { pos: 30, machine: "A" }, { pos: 40, machine: "C" }, { pos: 55, machine: "D" }, { pos: 70, machine: "B" }, { pos: 85, machine: "C" }, { pos: 95, machine: "D" },];console.log(preferenceList(toy, 5, 3)); // [ 'A', 'B', 'C' ]console.log(preferenceList(toy, 50, 4)); // [ 'D', 'B', 'C', 'A' ]