Case Study: Amazon
"customers should be able to view and add items to their shopping cart even if disks are failing, network routes are flapping" — Giuseppe DeCandia, Werner Vogels et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007, section 1
Summary: Amazon's retail site is a service-oriented system of hundreds of small, team-owned services. Its best-documented parts are the Dynamo key-value store (2007) and its successor DynamoDB (2012), item-to-item recommendations (2003), and the operating patterns in the Amazon Builders' Library: cells, shuffle sharding, static stability, avoiding fallback and automated deployment waves. Prime Day blog posts give the load numbers year by year. Focus: Each subsystem goes through the four-step method (scope, estimate, high-level design, decisions). Every architecture claim cites an Amazon or AWS paper, blog post or Builders' Library article that was fetched and read. Everything not stated in those sources is marked inference. Learning goal: Explain why Amazon chose availability over consistency for the shopping cart and how Dynamo made that work. Explain what DynamoDB changed (managed partitions, adaptive capacity, global admission control, formal verification). Use the cell, shuffle-sharding, static-stability and deployment-safety patterns in your own systems, and say which generic chapter teaches each one.
This is a case study, not a mechanism chapter. It shows how the mechanisms in other chapters fit together in one real company and links to those chapters for depth: The 4-Step Approach for the method, Consistent Hashing for ring internals, Vector Clocks, Merkle Trees & Anti-Entropy and Gossip Protocols for the Dynamo primitives, Wide-Column & Key-Value at Scale for DynamoDB as a product, API Idempotency for retry-safe APIs, and Bulkheads & Graceful Degradation for isolation in general.
How to read the evidence. A plain sentence followed by a source is a claim from that Amazon/AWS source. A sentence marked inference is our reading or a generalisation. A sentence marked secondary comes from a non-Amazon author. The code on this page is a small re-implementation for teaching. It is not Amazon's code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole case on one screen | Everything in one minute |
| Why a retailer built its own databases | Why it exists |
| Dated history from monolith to DynamoDB | Where it comes from, What changed over time |
| Step 1: what the retail site must do | Scope |
| Step 2: the numbers | Estimate |
| Step 3: services, API mandate, two-pizza teams | Service-oriented transformation |
| Dynamo: ring, versions, failures | Dynamo partitioning, Versioning, Failure handling |
| DynamoDB: partitions, adaptive capacity, GAC, TLA+ | DynamoDB |
| Shopping cart, orders, catalogue, recommendations, fulfilment | Cart, Orders, Catalogue and search, Recommendations, Fulfilment |
| Step 4: cells, shuffle sharding, static stability, fallback | Cells, Shuffle sharding, Static stability, Avoiding fallback |
| Route 53, CloudFront, S3 durability | Edge and storage |
| Deployment pipelines, one-box, waves, bake time | Deployment safety |
| Prime Day numbers by year | Prime Day |
| Mapping each subsystem to a generic chapter | What you can copy |
| Knobs, error names, arithmetic | Mechanics |
| Code | Go, Laravel |
| Classic problems and fixes | Solving the classic problems |
| Which pattern for which situation | Choosing |
| From one process to many regions | In architecture |
| Runnable tests and expected experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The subsystems and the decision each one shows.
| Subsystem | Decision | Mechanism | Source |
|---|---|---|---|
| Whole platform | Services that own their data, reached only through APIs | Service-oriented architecture, two-pizza teams | Vogels 2019; AWS DevOps whitepaper; Yegge 2011 (secondary) |
| Shopping cart | Availability over consistency: an add is never rejected | Dynamo: sloppy quorum, vector clocks, application merge | Dynamo paper 2007 |
| Key-value state (sessions, best sellers, catalogue lookups) | Primary-key access only, no relational features | Dynamo, later DynamoDB | Dynamo paper 2007; Vogels 2017 |
| Managed NoSQL | Predictable latency for many tenants | Partitions, bursting, adaptive capacity, global admission control, Multi-Paxos, TLA+ | DynamoDB paper 2022 |
| Order pipeline | Retries must not create a second order | Client request identifiers (idempotency); relational stores for transactional data | Builders' Library; Oracle-migration post 2019; details inference |
| Recommendations | Online work must not grow with the number of customers | Item-to-item collaborative filtering with a similar-items table built offline | IEEE Internet Computing 2003; Amazon Science 2019 |
| Catalogue and product search | Find related products, not only exact words | Lexical plus semantic matching | Amazon Science KDD 2019; A9 history secondary |
| Fulfilment and inventory | Warehouses must keep working when the website has trouble | DynamoDB, queues; reservation model inference | Prime Day posts; fallback article |
| Blast radius | A failure hits only a slice of customers | Cell-based architecture, shuffle sharding | Well-Architected 2023; Builders' Library 2019 |
| Dependencies | Keep working when a dependency or AZ fails | Static stability, no fallback paths | Builders' Library 2019 |
| Change | Most outages start with a change | Pipelines, one-box, waves, bake time, automatic rollback | Builders' Library 2020 |
The numbers worth remembering.
| Number | What it is | Source |
|---|---|---|
| 150+ | Services one page request calls | Dynamo paper, section 2.2 |
| 300 ms at 99.9% | Example SLA, at 500 requests/s | Dynamo paper, section 2.2 |
| (3,2,2) | Common (N,R,W) setting for Dynamo | Dynamo paper, section 6 |
| 99.94% | Cart reads that saw exactly one version | Dynamo paper, section 6.3 |
| 3 million+ | Checkouts in one day through the cart service | Dynamo paper, section 1 |
| 70% / 20% | Old database operations that were key-value / single-table | Vogels, A Decade of Dynamo, 2017 |
| 89.2 M req/s | DynamoDB peak, Prime Day 2021 | DynamoDB paper 2022 |
| 151 M req/s | DynamoDB peak, Prime Day 2025 | AWS News Blog 2025 |
| 75 PB / ~7,500 | Data and Oracle databases moved off Oracle | AWS News Blog 2019 |
| 28 and 730 billion | Shuffle shards for 8 workers taking 2, and for Route 53's 2048 servers taking 4 | Builders' Library 2019 |
| 50% | Extra capacity so that three AZs survive the loss of one | Builders' Library 2019 |
| 11 nines | Durability S3 is designed for | Amazon S3 storage classes page |
Why it exists
By the early 2000s Amazon ran one large retail application on top of a few very large databases. In 2019 Werner Vogels wrote that the "giant, monolithic 'bookstore' application and giant database" limited the company's speed. In 2017 he wrote that in 2004 the company was running Oracle Enterprise Edition with clustering and replication and still could not meet its availability, scalability and performance needs. He also wrote that about 70 percent of the database operations were plain key-value lookups (A Decade of Dynamo). The case study exists because Amazon published the trade-offs it made. Few companies wrote them down so openly.
| Pressure | Weaker answer | Amazon's answer (cited) |
|---|---|---|
| Feature speed | Everyone edits one codebase | Small teams own services behind APIs |
| Cart availability | Reject writes when replicas disagree | Accept every write and merge versions later |
| Database cost and limits | Bigger Oracle clusters | Purpose-built stores: Dynamo, then DynamoDB, Aurora, Redshift |
| Noisy customers | Shared fleet for everyone | Cells and shuffle shards |
| Dependency outages | Fallback code that rarely runs | Static stability: run on pre-pushed state and spare capacity |
| Risky changes | Big-bang releases watched by people | Automated waves with bake time and rollback |
An everyday picture used throughout. Think of a chain of supermarkets. Each department (bakery, dairy, tills) is run by a small team that serves the others through a counter, so nobody walks into another department's storeroom. That is the service interface. A shopper's basket must never refuse an item, even if the price display is broken; the price is sorted out at the till. That is the cart. Stores are grouped so that a flooded store closes only itself. Those are cells. New shelf layouts are tried in one quiet store first. That is a deployment wave.
Three common misunderstandings, up front
- "DynamoDB is Dynamo as a service." The 2022 paper says DynamoDB was motivated by Dynamo, but it uses Multi-Paxos replication groups with a leader, a write-ahead log and strongly consistent reads. That is a different design from Dynamo's leaderless sloppy quorum.
- "Amazon runs everything eventually consistent." The cart was the showcase for availability over consistency. The 2019 migration post says transactional workloads with high consistency requirements moved to Aurora and RDS.
- "The API mandate memo is an official Amazon document." The well-known text comes from Steve Yegge's 2011 post, which retells it from memory. It is a secondary source. Amazon's own accounts (Vogels 2019, the AWS DevOps whitepaper) describe the move to services and two-pizza teams, but not the memo itself.
Where it comes from
The primary sources, in the order they appeared:
- Linden, Smith, York, "Amazon.com Recommendations: Item-to-Item Collaborative Filtering", IEEE Internet Computing, January/February 2003. Amazon Science (Larry Hardesty, November 2019) says the algorithm had already been in use for six years when the paper came out. In 2017 the journal named it the paper that had best stood the test of time.
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007, also published on Werner Vogels' blog All Things Distributed. This is the paper that combined consistent hashing, vector clocks, sloppy quorum, hinted handoff, Merkle trees and gossip in one production system.
- Vogels, "Eventually Consistent - Revisited", December 2008, which defines client-side consistency models such as read-your-writes.
- Vogels, "Amazon DynamoDB", January 18, 2012, the launch post.
- Vogels, "A Decade of Dynamo", October 2, 2017, and "Modern applications at AWS", August 28, 2019, both looking back on the move from monolith to services.
- Jeff Barr, "Migration Complete", AWS News Blog, October 15, 2019: the consumer business turned off its last Oracle database.
- The Amazon Builders' Library, first articles December 5, 2019: shuffle sharding (Colm MacCárthaigh), static stability (Becky Weiss, Mike Furr), avoiding fallback (Jacob Gabrielson), timeouts and jitter (Marc Brooker). Then Automating safe, hands-off deployments (Clare Liguori, June 18, 2020) and Making retries safe with idempotent APIs (Malcolm Featonby).
- Elhemali et al., "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service", USENIX ATC 2022.
- AWS Well-Architected, "Reducing the Scope of Impact with Cell-Based Architecture", September 20, 2023.
- AWS News Blog Prime Day posts, 2022 to 2025 (Jeff Barr; Channy Yun).
Not used as evidence: the 2006 ACM Queue interview "A Conversation with Werner Vogels" was on the reading list, but queue.acm.org and dl.acm.org refused every connection from the research machine (TLS error). No quote from it appears here, and its claims are not relied on.
The concept catalogue
The catalogue follows the four-step method from The 4-Step Approach: scope what the system must do, estimate the load, sketch the high-level design one subsystem at a time, then record the cross-cutting decisions that keep it available.
Step 1: Scope Must-know
In plain words: before drawing boxes, write down what the retail site must never fail at, and what it may get slightly wrong for a moment.
Common misunderstanding: "An e-commerce site needs strong consistency everywhere because money is involved." The Dynamo paper picks one place, the cart, where accepting every write matters more than seeing one agreed version. Payments and orders are scoped differently.
Definition: functional scope here means browse the catalogue, search, get recommendations, add to cart, check out, fulfil and ship. The non-functional scope in the Dynamo paper is: an "always writeable" store for the cart, latency SLAs measured at the 99.9th percentile, failure treated as the normal case, and services that own their data.
Requirement list for the retail site (as the sources frame it)
1 Cart: add/remove must succeed even during disk, network or data-centre failure
2 Pages: each service in the call chain meets its own p99.9 latency contract
3 Orders: a retried checkout must not create a second order
4 Catalogue/search: find related products, not only exact words
5 Fulfilment: warehouses must keep working when the website struggles
6 Operations: a bad deployment or a noisy customer harms only a slice of trafficReal scenario: a customer on a train adds a book while one replica is unreachable; a holiday peak triples traffic; a failed cache must not take the supply-chain database down with it (this happened, see Avoiding fallback).
| Requirement | Strength needed | Where it is met (cited or inference) |
|---|---|---|
| Cart writes | Always accept; merge later | Dynamo (paper) |
| Order creation | Exactly one order per intent | Idempotent APIs (Builders' Library); store choice inference |
| Payment and ledger | Strong consistency | Relational stores (2019 migration post); specifics inference |
| Catalogue read | High availability, can be slightly stale | Dynamo paper lists product catalog as primary-key access |
| Recommendations | Fast online, freshness in hours is fine | Offline similar-items table (2003 paper) |
Fix / how to use it: in your own design, write the requirement list as a table of "may be stale / may be rejected / must be exact" per operation before you choose any store.
Step 2: Estimate Must-know
In plain words: turn the published numbers into rates your design must handle, and mark clearly which numbers are cited and which are your own arithmetic.
Common misunderstanding: "Amazon's numbers are secret, so a case study cannot estimate." Amazon publishes a lot: the Dynamo paper gives the 150-service fan-out and the 99.94% single-version rate, and the Prime Day posts give peaks per year.
Definition: a back-of-envelope estimate in the sense of Capacity Estimation: peak rate, fan-out, storage and the latency budget per hop.
Back-of-envelope (our arithmetic; inputs cited)
1 Page fan-out: 150+ service calls per page (Dynamo paper)
2 If one page must render in about 1 s and the critical path has about 5 sequential hops,
each hop gets about 200 ms at p99.9 (estimate, ours)
3 Aurora on Prime Day 2025: 500 billion transactions over a 4-day event
500e9 / (4 * 86,400 s) = about 1.45 million transactions/s on average (estimate)
4 DynamoDB peak 2025: 151 million requests/s (AWS News Blog)
5 Cart in 2007: 3 million+ checkouts/day = about 35 checkouts/s average;
peaks several times higher (estimate)Real scenario: the ratio between average and peak drives capacity. The DynamoDB paper describes Prime Day 2021 as a 66-hour event with trillions of calls and an 89.2 million requests/s peak.
| Quantity | Value | Type |
|---|---|---|
| Services per page | 150+ | Cited (Dynamo) |
| Example SLA | 300 ms for 99.9% of requests at 500 req/s | Cited (Dynamo) |
| DynamoDB peak 2021 / 2022 / 2023 / 2024 / 2025 | 89.2 M / 105.2 M / 126 M / 146 M / 151 M req/s | Cited (paper, Prime Day posts) |
| SQS peak 2022 / 2023 / 2025 | 70.5 M / 86 M / 166 M msgs/s | Cited (Prime Day posts) |
| Aurora average 2025 | ~1.45 M transactions/s | Estimate from a cited total |
| Per-hop budget | ~200 ms at p99.9 | Estimate |
Fix / how to use it: percentiles compound across a fan-out (see Latency Budgets & Tail Latency). That is why the Dynamo paper sets SLAs at p99.9 and not at the mean.
Step 3: High-level design, one subsystem at a time
The picture is drawn from the sources: Route 53 and CloudFront at the edge, a rendering layer calling 150+ services, and each service owning its own store. Which store backs which service, beyond what the sources name, is inference.
The service-oriented transformation, API mandate and two-pizza teams Must-know
In plain words: Amazon split the monolith into many services. Each one is owned by a small team and is reachable only through its API, so teams can ship without waiting for each other.
Common misunderstanding: "Microservices were a technology decision." In Amazon's telling, the team structure changed together with the code. Vogels writes that functional hierarchies were broken down into small autonomous teams.
Definition: a service-oriented architecture in which each service hides its data behind a network interface (SOA, Microservices). The Dynamo paper puts it this way: data stores "are only accessible within its service boundaries". A two-pizza team is the AWS DevOps whitepaper's term for a team "no larger than can be fed by two pizzas" (quoting Jeff Bezos). The API mandate is Steve Yegge's 2011 retelling (secondary): "All teams will henceforth expose their data and functionality through service interfaces."
From monolith to services (dates from Vogels 2019 and 2017)
1 about 1999-2001 one "bookstore" application and one giant database; every feature edits shared code
2 early 2000s teams reorganised into two-pizza teams, each owning a service and its data
3 2004 Oracle clusters strain under growth (Vogels 2017)
4 2006 the infrastructure skills become AWS (Vogels 2019: "founding of AWS in 2006")
5 2007 Dynamo paper: "hundreds of services", a page calls 150+ of themReal scenario: a team adding video streaming no longer rewrites shared code (Vogels's own example); a payments team changes its schema without telling the recommendations team; a page aggregator caches heavily because it calls dozens of services.
| Aspect | Monolith (before) | Services (after, cited) |
|---|---|---|
| Data access | Any code reads any table | Only through the owning service's interface |
| Team | Functional departments | Two-pizza teams owning a product or feature |
| Deploy | Coordinated releases | Each team deploys its own pipeline (Builders' Library 2020) |
| Failure | One bug can stop all | Bounded by SLAs and isolation, if designed for it |
Fix / how to use it: split along team and data ownership, not along technical layers (Service Boundaries, Data Ownership). If you inherit a monolith, migrate gradually with a strangler fig.
Dynamo partitioning: consistent hashing and virtual nodes Must-know
In plain words: every key is hashed onto a ring. The next few nodes clockwise store it, so adding a node moves only a small share of the keys.
Common misunderstanding: "Consistent hashing alone balances load." The Dynamo paper says plain consistent hashing gives uneven load and ignores differences between machines. Dynamo adds virtual nodes, and later fixed equal-sized partitions ("Strategy 3: Q/S tokens per node").
Definition: Dynamo applies MD5 to the key to get a position on the ring. Each node owns several tokens (virtual nodes). The preference list is the list of distinct nodes responsible for a key, and the coordinator writes to the first N of them. Dynamo is a "zero-hop DHT": each node knows enough to route a request directly. Ring internals are taught in Consistent Hashing and Sharding at System Level.
Put(cart:42) with N=3
1 client -> any node (or a partition-aware client library)
2 node computes MD5("cart:42") -> position p on the ring
3 walk clockwise from p: tokens of B, B, C, D ... -> distinct nodes B, C, D = preference list
4 B coordinates: writes locally, sends to C and D, waits for W-1 acksReal scenario: a holiday adds hosts and only the neighbouring ranges move; a slow host gets fewer tokens; best-seller lists, sessions and sales rank all live in their own Dynamo instances (each service "runs its own Dynamo instances").
| Strategy (Dynamo paper, section 6.2) | Tokens | Partitions | Result reported |
|---|---|---|---|
| 1 | T random tokens per node | Ranges between tokens | Uneven; placement tied to partitioning |
| 2 | T random tokens per node | Q equal partitions | Decouples partitioning from placement |
| 3 | Q/S tokens per node | Q equal partitions | Best load-balancing efficiency in the paper |
Fix / how to use it: see the Go ring in Go: virtual nodes, a preference list, and a sloppy quorum that records hints.
Dynamo versioning: vector clocks and application merge Must-know
In plain words: when two replicas take writes the other has not seen, Dynamo keeps both versions and lets the cart code merge them.
Common misunderstanding: "The newest timestamp wins." Dynamo uses vector clocks so that it can tell "newer" from "concurrent". It returns all concurrent versions to the client for semantic reconciliation.
Definition: a vector clock is a list of (node, counter) pairs attached to each version (Vector Clocks). If one clock is at least as large as another in every entry, that version replaces the older one. Otherwise the versions are siblings. In the paper's words, a merged cart means "an 'add to cart' operation is never lost. However, deleted items can resurface."
Section 4.4 example of the Dynamo paper
1 Sx writes D1 [(Sx,1)]
2 Sx writes D2 [(Sx,2)] D2 replaces D1
3 Sy writes D3 [(Sx,2),(Sy,1)] and Sz writes D4 [(Sx,2),(Sz,1)] concurrent
4 a read returns D3 and D4; the client merges them
5 Sx writes D5 [(Sx,3),(Sy,1),(Sz,1)] replaces bothReal scenario: two devices add different items during a partition and both items survive; a removal on one device reappears after the merge; in the paper's 24-hour profile, 99.94% of cart reads saw exactly one version.
| Versions returned in 24 h (cart service) | Share of requests |
|---|---|
| 1 | 99.94% |
| 2 | 0.00057% |
| 3 | 0.00047% |
| 4 | 0.00009% |
Fix / how to use it: if your merge is a union, design it as a CRDT (CRDTs). A remove that must stick needs tombstones or an observed-remove set, not a plain union.
Dynamo failure handling: sloppy quorum, hinted handoff, Merkle trees, gossip Must-know
In plain words: if a replica is down, write to the next healthy node and tell it whose data it is holding. Compare hash trees in the background to repair what was missed. Learn who is alive by gossiping.
Common misunderstanding: "R + W > N means every read sees the latest write." With a sloppy quorum the N nodes may not be the usual N. A read can miss a write that sits in a hinted replica until handoff finishes.
Definition: Dynamo performs reads and writes on "the first N healthy nodes from the preference list". A stand-in node stores a hint naming the intended node and hands the data back when that node recovers (hinted handoff). Permanent divergence is repaired by anti-entropy using Merkle trees, where parent hashes summarise key ranges (Merkle Trees). Membership and failure detection use a gossip-based protocol in which each node contacts a random peer every second (Gossip Protocols).
Write with N=3, W=2 while D is down
1 preference list B, C, D; D unreachable
2 B writes locally, C acks, E (next healthy) stores the replica with hint "for D"
3 W=2 reached (B, C): success returned to the cart
4 D recovers; gossip spreads the news; E sends the hinted replica to D and deletes it
5 later, B and D compare Merkle roots for their shared range; a mismatch walks down the treeReal scenario: a rack loses power during peak; a network route flaps between data centres; a disk dies for good and anti-entropy rebuilds its ranges.
| Problem (Dynamo paper, Table 1) | Technique | Advantage stated |
|---|---|---|
| Partitioning | Consistent hashing | Incremental scalability |
| High availability for writes | Vector clocks with reconciliation during reads | Version size decoupled from update rates |
| Temporary failures | Sloppy quorum and hinted handoff | Availability and durability when some replicas are down |
| Permanent failures | Anti-entropy using Merkle trees | Synchronises divergent replicas in the background |
| Membership and failure detection | Gossip-based protocol | Symmetry, no central registry |
Fix / how to use it: tune (N,R,W) per service. The paper's common choice is (3,2,2). The paper also lists Berkeley DB, MySQL and an in-memory buffer with persistent backing as pluggable local engines. For the theory of quorum trade-offs see Replication Topologies and CAP & PACELC.
DynamoDB: partitions, adaptive capacity, global admission control, formal verification Must-know
In plain words: DynamoDB is the managed service Amazon built after teams found running their own Dynamo too much work. It promises predictable performance by splitting tables into partitions and controlling how much each tenant may use.
Common misunderstanding: "DynamoDB is leaderless like Dynamo." The 2022 paper describes replication groups that use Multi-Paxos for leader election. Only the leader serves writes and strongly consistent reads, and a write is acknowledged once a quorum has persisted it to the write-ahead log.
Definition: a table is split into partitions by key range, and each partition has replicas in several Availability Zones. Throughput control evolved in stages. First came per-partition token buckets. Then bursting used unused node capacity. Adaptive capacity raised the throughput of hot partitions and "eliminated over 99.99% of the throttling due to skewed access pattern". Finally global admission control (GAC) replaced adaptive capacity: request routers keep local token buckets and refill them from a central GAC service "in the order of few seconds". Partitions are also split for consumption at a point chosen from the observed key distribution. Formal verification: "The core replication protocol was specified using TLA+", and new features that affect it are model-checked.
A hot key during a sale (DynamoDB paper, sections 4.1-4.3)
1 2012 launch: table throughput divided equally across partitions; a hot partition is throttled
2 bursting: the partition borrows unused node tokens for short spikes
3 adaptive capacity: long-lived skew raises the hot partition's allocation
4 split for consumption: the partition splits at the observed hot range (minutes)
5 GAC: routers admit by table-level tokens, so a partition is no longer capped by an equal share
6 a single hot item still cannot be split; DynamoDB detects this and does not splitReal scenario: a lightning deal concentrates traffic on a few items; one tenant's spike must not hurt others ("single-tenant experience ... using a multi-tenant architecture"); point-in-time restore uses partition snapshots and write-ahead logs archived to S3.
| Mechanism | Problem it fixed | Limit stated in the paper |
|---|---|---|
| Equal per-partition allocation | Simple isolation | Throughput dilution after splits; hot partitions throttled |
| Bursting | Short spikes | Only short-lived; needs spare node capacity |
| Adaptive capacity | Long-lived skew | Reactive, best-effort |
| Global admission control | Table-level budget across partitions | Central service, refills every few seconds |
| Split for consumption | Hot key range | Does not help a single hot item or sequential keys |
| Multi-Paxos + WAL + checksums | Durability, leader election | Gray failures handled by asking peers before failover |
| TLA+ and model checking | Replication protocol bugs | Covers the specified protocol, not all code |
Fix / how to use it: design partition keys for spread (Sharding at System Level), retry throttles with backoff and jitter (Timeouts, Retries & Jitter), and read Wide-Column & Key-Value at Scale for data modelling.
Shopping cart: availability over consistency Must-know
In plain words: never tell a customer "could not add to cart". If replicas disagree, keep every version and merge them.
Common misunderstanding: "Eventual consistency means data loss." In the cart, every write is kept. What you give up is a single agreed answer at read time, so the application has to merge.
Definition: the Dynamo paper's own example: "an 'Add to Cart' operation can never be forgotten or rejected", and both add and delete become put requests carrying the read context. This is availability over consistency in the PACELC sense: during a partition the system chooses A, and even without one it chooses low latency.
Two devices, one partition (illustration of the paper's rule)
1 phone reads cart v[(B,3)] = {book}
2 network splits; laptop's write lands on E with hint for B
3 phone adds kettle -> v[(B,4)] = {book, kettle}
4 laptop adds pen -> v[(B,3),(E,1)] = {book, pen}
5 next read returns both siblings; cart service merges -> {book, kettle, pen}Real scenario: holiday peaks with failing disks; a customer switching devices; a removed item reappearing after a partition, which the paper accepts as the price.
| Choice | Cart outcome | Who pays |
|---|---|---|
| Strong consistency (reject when no majority) | "Try again later" | The customer, at the moment of buying |
| Last-writer-wins | One device's add silently lost | The customer, later and silently |
| Siblings + union merge (Dynamo) | Every add kept; deletes may resurface | The application code that merges |
Fix / how to use it: see the Go before/after and the Laravel CartReconciler below. The general menu is in Consistency Models and Eventual Consistency in Database Systems.
Order pipeline: idempotency and relational stores Important
In plain words: placing an order goes through several services. Every step must be safe to retry, and the order record lives in a store that can enforce uniqueness.
Common misunderstanding: "Retries are the client's problem." The Builders' Library makes it the API's job: "our preferred approach is to incorporate a unique caller-provided client request identifier into our API contract."
Definition: an idempotent API treats requests with the same client request identifier as one request. In EC2 this identifier is called ClientToken. If the same identifier comes back with different parameters, that is treated as a different intent and the API reports an error instead of guessing. The 2019 migration post says order fulfilment was among the systems moved off Oracle. Low-latency services went to DynamoDB and ElastiCache, and "transactional relational workloads with high data consistency requirements" went to Aurora and RDS. Which store holds the order record itself is not stated: inference. So is the exact step sequence (place, pay, reserve, release to fulfilment) below.
Order flow (inference: the steps are generic, the idempotency rule is cited)
1 client POST /orders Idempotency-Key: k1 -> timeout, no response
2 client retries with k1 -> service finds k1, returns the same order id (no second order)
3 order service reserves stock (conditional update) and asks payments to authorise (key k1:pay)
4 event "OrderPlaced" -> fulfilment; consumers deduplicate by order id
5 a failed payment releases the reservation (compensation)Real scenario: a mobile network drops the response after the order was written; a worker crashes after charging the card but before marking the order; the same key reused with a different quantity (reject it).
| Step | Duplicate risk | Guard |
|---|---|---|
| Create order | Client retry | Unique (customer_id, idempotency_key) |
| Reserve stock | Concurrent buyers | Conditional decrement WHERE available >= qty |
| Charge | Worker retry | Payment-provider idempotency key (Payments) |
| Publish event | Relay retry | Outbox + consumer inbox (Outbox, Inbox) |
| Multi-step rollback | Partial failure | Saga compensation (Saga) |
Fix / how to use it: the Laravel After.php below implements the key, the unique row and the conditional reservation; the SQL schema follows.
-- Order and inventory tables for the idempotent checkout (teaching schema, PostgreSQL)
CREATE TABLE inventory (
sku text PRIMARY KEY,
available integer NOT NULL CHECK (available >= 0),
reserved integer NOT NULL DEFAULT 0 CHECK (reserved >= 0)
);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL,
idempotency_key text NOT NULL,
sku text NOT NULL REFERENCES inventory(sku),
quantity integer NOT NULL CHECK (quantity > 0),
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (customer_id, idempotency_key)
);
-- Reservation: one statement, no read-modify-write race
UPDATE inventory
SET available = available - 2, reserved = reserved + 2
WHERE sku = 'BOOK-1' AND available >= 2; -- 1 row = reserved, 0 rows = out of stockCatalogue and product search (A9 as history) Important
In plain words: the catalogue holds the product data, and search finds products for a query even when the words do not match exactly.
Common misunderstanding: "Product search is just an inverted index." Amazon's KDD 2019 paper says "Pure lexical matching via an inverted index falls short" because of synonyms, word variants and spelling errors.
Definition: the Dynamo paper lists "product catalog" among the services that need only primary-key access. Product search combines lexical retrieval with semantic matching, a neural model that retrieves related products (Amazon Science, Semantic Product Search, KDD 2019). A9 was Amazon's search and advertising subsidiary, founded in 2003 (Wikipedia, secondary). How the catalogue store, the index pipeline and the ranking services connect today is not published in the sources used: inference.
Query path (inference, except where noted)
1 query "womens running shoe" -> spelling and variant handling (woman/women, cited as a problem)
2 lexical retrieval from the inverted index + semantic retrieval by embedding (KDD 2019)
3 merge, rank, then fetch product details by id from the catalogue service (primary-key read)
4 the page renders results with recommendations from another serviceReal scenario: a misspelled query still returns products; a new product appears in search minutes after listing (inference: an indexing pipeline fed by catalogue updates); the catalogue is read far more often than it is written.
| Piece | Evidence | Generic chapter |
|---|---|---|
| Catalogue item lookups | Dynamo paper (primary-key access) | Choosing a Database |
| Lexical + semantic retrieval | Amazon Science KDD 2019 | Search Systems |
| A9 subsidiary (2003) | Wikipedia (secondary) | History only |
| Index update pipeline | Not published: inference | Change Data Capture |
Fix / how to use it: keep the catalogue (source of truth) separate from the search index (derived and rebuildable), and treat the index as eventually consistent.
Recommendations: item-to-item collaborative filtering Must-know
In plain words: instead of finding customers like you, precompute which items are bought together. At request time, look up the neighbours of the items you bought.
Common misunderstanding: "Personalised recommendations must be computed per user at request time." The 2003 paper does the expensive work offline. Its online part "scales independently of the number of customers and number of items in the product catalog".
Definition: item-to-item collaborative filtering builds a similar-items table. For each item I1, and for each customer who bought I1, it records co-purchases of other items I2, then computes a similarity (for example the cosine between item vectors). The worst case is O(N²M), but in practice it is close to O(NM) because most customers buy few items. Online, the system combines the similar items of the user's purchases and ratings. Amazon Science (2019) adds that a flaw in the relatedness measure was corrected years later, using differential probabilities (B is related to A if A's buyers are more likely than average to buy B).
Offline and online halves (2003 paper)
1 offline batch: for every item I1 -> for every buyer C of I1 -> for every item I2 of C: count(I1,I2)
2 offline: similarity(I1,I2) = cosine of their buyer vectors; keep top-k per item
3 store: similar-items table keyed by item id
4 online request: user bought {A, B} -> fetch neighbours(A), neighbours(B) -> merge, drop owned -> top 10Real scenario: "customers who bought this also bought"; cart-page recommendations based on cart items (Figure 2 of the paper); the table rebuilt periodically while serving stays fast.
| Method (2003 paper's comparison) | Online cost | Quality as described |
|---|---|---|
| Traditional user-based collaborative filtering | Grows with customers and items | Good, does not scale |
| Cluster models | Low (offline clustering) | Low |
| Search-based (same author or keywords) | Low | Often too narrow |
| Item-to-item collaborative filtering | Depends only on the user's own items | High, real time |
Fix / how to use it: split offline model building from online lookup (ML Systems); cache the similar-items table as a key-value read.
Fulfilment and inventory reservation Important
In plain words: warehouses pick, pack and ship. They must keep working even when the website has problems, and stock must not be sold twice.
Common misunderstanding: "Fulfilment is downstream, so it can share the website's databases and caches." The fallback article describes the opposite outcome. A supply-chain database that both the website and the fulfilment centres used was overloaded when the website's caches failed, and "all fulfillment centers worldwide ground to a halt".
Definition: the Prime Day posts say DynamoDB powers "all Amazon fulfillment centers". The 2022 post gives package-planning figures (60 million AWS Lambda invocations; 64 million items stored in DynamoDB). Inventory reservation is the pattern of holding stock for an order before it is picked: the reservation is created at checkout and either confirmed or released. Amazon's actual reservation model is not described in the sources used: inference.
Reservation lifecycle (inference; generic pattern)
1 checkout: available 10 -> 9, reserved 0 -> 1 (conditional update, one statement)
2 payment authorised -> reservation confirmed -> "release to fulfilment" event
3 payment fails or 30-minute timer fires -> reserved 1 -> 0, available 9 -> 10
4 warehouse picks -> reserved 1 -> 0, on_hand decrementedReal scenario: a flash sale with 100 units and 10,000 buyers; a warehouse network outage while the website keeps selling (accept orders, ship later); the website degraded while warehouses keep shipping.
| Concern | Pattern | Chapter |
|---|---|---|
| Oversell | Conditional decrement, reservation row | Optimistic vs Pessimistic Locking |
| Shared fate with the website | Separate stores, no shared cache-or-DB fallback | Bulkheads |
| Hand-off to warehouses | Events with dedup | Event-Driven Architecture |
| Hot item in a sale | Sharded counters | Write Buffering & Sharded Counters |
Fix / how to use it: the conditional UPDATE in the SQL block above, and a timer that releases expired reservations.
Step 4: Decisions that keep it available
These are cross-cutting decisions. Each one is a Builders' Library or Well-Architected pattern that applies to every subsystem above.
Cell-based architecture Must-know
In plain words: run several complete, independent copies of a service (cells) and send each customer to one of them, so a failure stays inside one cell.
Common misunderstanding: "Cells are just more replicas." Replicas share state and fate. Cells share nothing, and each holds a subset of the customers.
Definition: the 2023 Well-Architected paper says a cell "does not share state with other cells". A thin cell router sends each request by a partition key (customer ID, resource ID). It gives the arithmetic: if 10 cells serve the load, one failed cell leaves 90% of requests unaffected. Cells also contain failures such as bad deployments and poison pill requests.
Cell routing
1 request(customer=7781) -> cell router: hash or mapping table -> cell 3
2 cell 3 has its own app servers and its own data
3 deploy v2 to cell 1 only; alarms fire; roll back; cells 2..10 never saw v2
4 a poison request crashes cell 3's workers; 90% of customers are unaffectedReal scenario: a tenant whose request pattern triggers a bug; a schema migration tried in one cell first; growth by adding cells rather than growing one.
| Choice | Blast radius | Cost |
|---|---|---|
| One shared fleet | 100% | Lowest |
| N cells | About 1/N | Router, per-cell overhead, cross-cell queries are hard |
| Cells + shuffle sharding inside | Smaller still for noisy tenants | More placement logic |
Fix / how to use it: keep the router as simple as possible, because it is the one shared part. Pick a partition key that follows the "grain of the service".
Shuffle sharding Must-know
In plain words: give each customer a random small set of workers out of a large fleet. Two customers almost never get the same set, so one bad customer rarely takes down another.
Common misunderstanding: "Sharding already isolates customers." With plain sharding, every customer in the broken shard suffers. With shuffle sharding, customers who share one worker with the attacker still have their other workers.
Definition: from the Builders' Library (Colm MacCárthaigh, 2019): eight workers in shards of two give "28 unique combinations". Route 53 arranges capacity into 2048 virtual name servers and gives each domain four, "a staggering 730 billion possible shuffle shards". Clients must retry across the shard members for the isolation to work (inference from the mechanism: a client that never tries the second worker gains nothing).
Noisy customer X, quiet customer Y, 8 workers, 2 each
1 X -> {w1, w3}; Y -> {w3, w6}
2 X sends poison traffic; w1 and w3 crash
3 Y's request to w3 fails; Y retries on w6 and succeeds
4 only customers whose both workers are in {w1, w3} are down: 1 of 28 combinationsReal scenario: DDoS against one DNS domain (the Route 53 origin story); a tenant whose queries are expensive; a bad request type that crashes a worker.
| Workers n | Per customer k | Shuffle shards C(n,k) |
|---|---|---|
| 8 | 2 | 28 |
| 64 | 4 | 635,376 |
| 2048 | 4 | 730,862,190,080 (the "730 billion") |
Fix / how to use it: the Go shuffle package below computes a deterministic shard per customer and verifies the 28 and 730-billion figures in tests.
Static stability Must-know
In plain words: build the system so that when something it depends on breaks, it keeps doing what it was already doing, without needing to react.
Common misunderstanding: "Auto scaling will replace lost capacity." Replacing it needs the control plane at the moment it may be impaired. A statically stable design already has the capacity running.
Definition: "In a statically stable design, the overall system keeps working even when a dependency becomes impaired" (Builders' Library, Becky Weiss and Mike Furr, 2019). The article separates the control plane (makes changes) from the data plane (does the daily work), and designs the data plane not to need the control plane. With three Availability Zones, services "overprovision by 50 percent", so that each AZ runs at about 66% of its tested load.
AZ failure, three AZs, each sized for 1/2 of peak (150% total)
1 normal: each AZ carries 1/3 of traffic = 66% of its tested capacity
2 AZ-b impaired; the load balancer stops sending to it
3 AZ-a and AZ-c each carry 1/2 of traffic = 100% of tested capacity; no instance launch needed
4 control plane recovers later and rebalances; no customer-visible step depended on itReal scenario: EC2 instances keep running when the EC2 control plane is degraded; IAM credentials pushed to instances and valid for hours (from the fallback article); a config cache that keeps the last good value.
| Design | Needs during failure | Statically stable? |
|---|---|---|
| Scale up on failure | Control plane, capacity, time | No |
| Pre-provisioned spare (n+1 AZ) | Nothing | Yes |
| Pull config on each request | The config service | No |
| Push config, keep last good copy | Nothing | Yes |
Fix / how to use it: see Capacity Planning & DR for N+1 sizing and Caching for "serve last good value".
Avoiding fallback Important
In plain words: code that runs only during a failure is code that is never tested. Amazon prefers to make the main path more reliable, or to fail over to a path that runs all the time.
Common misunderstanding: "A fallback is always safer than failing." In the article's retail example, the fallback (query the database directly when the cache fails) was what overloaded the database, and it "was worse than no fallback strategy at all".
Definition: Jacob Gabrielson's article lists the alternatives: improve the main path's availability (for example use a store with higher inherent availability, such as DynamoDB), let the caller handle errors (retry), push data proactively, and convert fallback into failover where both paths are exercised all the time. "Fallback logic is hard to test", it may itself fail, and it can make the original problem worse.
The supply-chain outage described in the article
1 web servers read stock data through caches; on cache miss/failure they fall back to the database
2 for months this works
3 the caches fail around the same time; every web server queries the database directly
4 the database locks up; the website goes down; fulfilment centres that share it stop worldwideReal scenario: a cache-miss stampede (Caching); a secondary payment provider that has never taken real traffic; a "degraded mode" flag nobody has switched on in a year.
| Instead of fallback | How | Example from the article |
|---|---|---|
| Make the primary more available | Better store, more capacity | DynamoDB for amazon.com on Prime Day 2017 (talk) |
| Let the caller retry | Idempotent API + backoff | Retries with jitter |
| Push data ahead of time | Data is local when needed | IAM role credentials on EC2 |
| Failover that runs all the time | Both paths always in use | Active-active across AZs |
Fix / how to use it: if you must have a fallback, exercise it continuously (for example with a share of real traffic) and load-test it, and protect the shared dependency with load shedding so it cannot fail the way Cascading Failures describes.
Edge and storage: Route 53, CloudFront, S3 durability Good to know
In plain words: DNS points shoppers to the site, a CDN serves static content near them, and objects are stored in a store designed not to lose data.
Common misunderstanding: "100% DNS SLA means DNS never fails." The Route 53 SLA defines service credits when the monthly uptime is below 100%. It is a contract about money, not a physical guarantee.
Definition: Route 53 uses shuffle sharding over 2048 virtual name servers (Builders' Library). Its SLA starts credits below 100% monthly uptime. CloudFront handled over 500 million HTTP requests per minute at peak on Prime Day 2023 and 2024, and delivered over 3 trillion HTTP requests during the Prime Day 2025 week. S3 durability: S3 "is designed to exceed 99.999999999% (11 nines)" and stores data across at least three AZs by default. DynamoDB archives write-ahead logs to S3 for durability (2022 paper). Whether every amazon.com page goes through CloudFront is not stated: inference.
Static asset path (inference for amazon.com; mechanisms cited for the products)
1 browser resolves the asset domain -> Route 53 name servers (4 per domain, shuffle-sharded)
2 request to CloudFront edge -> cache hit returns the asset
3 miss -> origin (for example S3) -> object read from a store designed for 11 ninesReal scenario: DDoS on DNS; an image-heavy product page; a deleted bucket object (durability does not protect against deletion; use versioning).
| Product | Published figure | Source |
|---|---|---|
| Route 53 | Credits below 100% monthly uptime | Route 53 SLA |
| CloudFront | 500 M+ req/min peak (2023, 2024); 3 T+ requests in Prime Day 2025 week | Prime Day posts |
| S3 | Designed for 11 nines durability, at least 3 AZs | S3 storage classes page |
Fix / how to use it: see CDNs, IP, DNS & GeoDNS and Object Storage.
Deployment safety: one-box, canary, waves, bake time Must-know
In plain words: every change goes through test stages, then to one machine, then to one zone in a quiet region, then to larger waves. The pipeline waits and watches between steps and rolls back by itself.
Common misunderstanding: "Continuous deployment means deploying everywhere at once, often." At Amazon it means often and automatically, but in small, staggered steps with long bake time.
Definition: from Clare Liguori's Builders' Library article (2020): pre-production stages alpha, beta and gamma (gamma runs the same continuous canary tests as production), a one-box stage (one VM, one container, or a small share of Lambda invocations), then production waves of increasing size. The first wave goes to a low-traffic Region, one AZ or cell at a time. A typical pipeline waits at least one hour after each one-box stage, at least 12 hours after the first regional wave and two to four hours after later waves. Alarms on faults, latency or a drop in request count trigger automatic rollback. The stated goal is to avoid hitting several Regions, or several AZs, at the same time.
One change through a typical pipeline (bake times from the article)
1 commit -> build -> unit tests
2 alpha, beta: API and end-to-end tests
3 gamma (multi-Region, prod-like) + gamma one-box (30-60 min)
4 prod one-box in the first Region; bake at least 1 h
5 wave 1: one AZ/cell in a low-traffic Region; bake at least 12 h after the regional wave
6 waves 2..n: more Regions in parallel; 2-4 h bake each
7 any alarm -> automatic rollback to the previous versionReal scenario: a change that writes a new data format the old code cannot read (caught by the one-box backward-compatibility check); a slow memory leak (caught by bake time); a config change (deployed through the same pipeline).
| Stage | Catches | Cost |
|---|---|---|
| Unit / integration tests | Logic errors | Minutes |
| Gamma + canary | Environment, config errors | Hours |
| One-box | Backward incompatibility, crash on real traffic | 1 server's share of traffic |
| Wave 1 (one AZ/cell) | Regional or scale effects | Small share of customers |
| Bake time | Slow-burning problems | Days for a global rollout |
| Automatic rollback | Human reaction time | Must be rollback-safe |
Fix / how to use it: cells and AZs are also the deployment units, so a bad deploy is contained by the same boundaries that contain failures. Alarms that drive rollback are covered in Alerting That Works.
Prime Day: the published scale, by year Good to know
In plain words: once a year Amazon publishes how hard its systems were pushed during Prime Day. These are the most reliable public load numbers for the retail site.
Common misunderstanding: "Peak requests per second equals customers per second." One page fans out to many services, and each service makes many store calls. The DynamoDB figures include Alexa and fulfilment centres, not only the website.
Definition: figures from the AWS News Blog posts (2022-2025) and the 2022 DynamoDB paper (2021 figure). Each post also stresses preparation: 733 AWS Fault Injection Service experiments in 2024, and over 6,800 in 2025, partly because FIS testing was built into CI/CD pipelines (Chaos Engineering).
DynamoDB peak requests per second (millions), cited
1 2021 89.2 (DynamoDB paper, 66-hour event)
2 2022 105.2 (AWS News Blog)
3 2023 126 (AWS News Blog)
4 2024 146 (AWS News Blog)
5 2025 151 (AWS News Blog, 4-day event)Real scenario: capacity planning for a known date; resilience testing before the peak; queue backlogs absorbing bursts (SQS records each year).
| Year | DynamoDB peak | Aurora | SQS peak | Other |
|---|---|---|---|---|
| 2021 | 89.2 M req/s | n/a | n/a | Trillions of DynamoDB calls (paper) |
| 2022 | 105.2 M req/s | 5,326 instances, 288 B transactions | 70.5 M msgs/s | SES 33,000 emails/s |
| 2023 | 126 M req/s | 5,835 instances, 318 B transactions | 86 M msgs/s | CloudFront 500 M+ req/min |
| 2024 | 146 M req/s | 6,311 instances, 376 B+ transactions | n/a in post | 733 FIS experiments |
| 2025 | 151 M req/s | 500 B transactions | 166 M msgs/s | 6,800+ FIS experiments |
Fix / how to use it: read peaks as "what the platform survived", not as a target for your system. Do your own estimate as in Step 2.
What changed over time
| Date | Change | Source |
|---|---|---|
| ~1997 | Item-to-item recommendations in use (six years before the 2003 paper) | Amazon Science 2019 |
| ~1999-2001 ("about 20 years ago" in 2019) | Monolithic bookstore split into services; two-pizza teams | Vogels 2019 |
| 2003 | IEEE Internet Computing recommendations paper; A9 founded | Paper; Wikipedia (secondary) |
| 2004 | Oracle clusters cannot meet availability and scale needs; Dynamo work begins | Vogels 2017 |
| 2006 | AWS founded on the infrastructure skills | Vogels 2019 |
| Oct 2007 | Dynamo paper at SOSP | Paper |
| Dec 2008 | "Eventually Consistent - Revisited" | Vogels blog |
| Jan 18, 2012 | DynamoDB launched | Vogels blog; 2022 paper |
| 2011 (post date) | API mandate story published | Yegge (secondary) |
| Oct 2017 | "A Decade of Dynamo"; IEEE "test of time" award for the 2003 paper | Vogels blog; Amazon Science |
| Oct 15, 2019 | Consumer business turns off its last Oracle database (75 PB, ~7,500 DBs) | AWS News Blog |
| Dec 5, 2019 | Builders' Library: shuffle sharding, static stability, avoiding fallback, timeouts and jitter | Builders' Library |
| Jun 18, 2020 | Builders' Library: automating safe, hands-off deployments | Builders' Library |
| Jul 2022 | DynamoDB paper at USENIX ATC | Paper |
| Sep 20, 2023 | Cell-based architecture whitepaper | AWS Well-Architected |
| 2024-2025 | FIS experiments grow from 733 to 6,800+ before Prime Day | AWS News Blog |
What you can copy
| Amazon subsystem | Pattern you can copy | Generic chapter |
|---|---|---|
| Services + two-pizza teams | Team-owned services, no shared database | Service Boundaries, Data Ownership |
| Dynamo ring | Consistent hashing with virtual nodes | Consistent Hashing, Sharding at System Level |
| Dynamo versions | Vector clocks, siblings, merge | Vector Clocks, CRDTs |
| Dynamo repair | Hinted handoff, Merkle anti-entropy, gossip | Merkle Trees, Gossip |
| Cart | Availability over consistency | CAP & PACELC, ACID vs BASE |
| DynamoDB | Partitioned managed key-value, admission control | Wide-Column & Key-Value, Rate Limiting |
| DynamoDB replication | Multi-Paxos leader per partition, leases | Leader Election, Distributed SQL & Consensus |
| Orders | Idempotency keys, outbox, sagas | API Idempotency, Saga |
| Search | Lexical + semantic retrieval | Search Systems |
| Recommendations | Offline model, online lookup | ML Systems |
| Cells, shuffle sharding | Blast-radius reduction | Bulkheads & Graceful Degradation |
| Static stability, no fallback | Pre-provisioned capacity, push config | Capacity Planning & DR, Cascading Failures |
| Deployment waves | One-box, bake time, rollback | Alerting That Works, Containers & Kubernetes |
| Prime Day preparation | Fault injection before peaks | Chaos Engineering |
Mechanics
Knobs, in one place
| Knob | System | Value in sources | Effect |
|---|---|---|---|
| N | Dynamo | 3 (common) | Replicas per key |
| R | Dynamo | 2 | Replies needed for a read |
| W | Dynamo | 2 | Acks needed for a write; W=1 favours availability |
| Tokens per node / Q partitions | Dynamo | Strategy 3: Q/S tokens per node | Load balance and placement |
| Gossip interval | Dynamo | Each node contacts a random peer every second | Membership convergence |
| Hash | Dynamo | MD5 of the key | Ring position |
| Object size | Dynamo | Usually less than 1 MB | Target workload |
| GAC refill interval | DynamoDB | "In the order of few seconds" | How fast routers learn table budget |
| Replicas per partition | DynamoDB | Three, across AZs | Durability, availability |
| Overprovision | Static stability | 50% with 3 AZs | Survive one AZ loss without scaling |
| Shuffle shard size | Route 53 | 4 of 2048 virtual name servers | Isolation per domain |
| One-box bake | Deployments | At least 1 h | Catch crash and compatibility issues |
| First-wave bake | Deployments | At least 12 h | Catch slow-burning issues |
Error names you will meet
| Name | Where | Meaning | Retry? |
|---|---|---|---|
ProvisionedThroughputExceededException | DynamoDB (HTTP 400) | Table or index over its provisioned rate | Yes, with backoff (SDKs retry) |
ThrottlingException | DynamoDB | Request rate above the allowed throughput (control-plane calls too fast, or on-demand tables) | Yes, with backoff |
RequestLimitExceeded | DynamoDB | Account-level throughput limit | Yes, with backoff |
ConditionalCheckFailedException | DynamoDB | A condition expression was false (for example stock too low) | No: business outcome |
ClientToken reuse with different parameters | EC2 idempotent APIs | Same identifier, different intent | No: client bug |
HTTP 409 out_of_stock | Our Laravel example | Reservation rejected | No |
HTTP 422 idempotency_key_reused | Our Laravel example | Same key, different body | No |
Arithmetic
Shuffle sharding
1 C(8,2) = 28
2 C(2048,4) = 2048*2047*2046*2045 / 24 = 730,862,190,080
3 chance a random other domain shares all 4 servers with a given domain = 1 / 730,862,190,080
Static stability
4 3 AZs, survive 1: each AZ sized for 1/2 of peak -> total 150% (50% overprovision); utilisation 66% normally
5 4 AZs, survive 1: each sized for 1/3 -> total 133%
Cells
6 10 cells, 1 failed -> 90% of requests unaffected (Well-Architected example)Go
The Go code re-implements the mechanisms described in the papers so that you can run them and read them. It is not Amazon's code. All packages are tested (see Lab).
Before
A replicated cart that resolves conflicts by wall-clock timestamp. It compiles and works until two concurrent adds happen, and then one is lost without any error.
// Package before shows a replicated cart that resolves conflicts with
// last-writer-wins on a wall-clock timestamp. It is bad design, not broken
// code: two concurrent "add to cart" writes on different replicas end with
// one item silently dropped.
package before
import "time"
// Cart is one stored version.
type Cart struct {
Items map[string]int // sku -> quantity
UpdatedAt time.Time
}
// Store keeps exactly one version per key.
type Store struct{ carts map[string]Cart }
func NewStore() *Store { return &Store{carts: map[string]Cart{}} }
// Put keeps the version with the later timestamp; the other is discarded.
func (s *Store) Put(key string, c Cart) {
if old, ok := s.carts[key]; ok && old.UpdatedAt.After(c.UpdatedAt) {
return
}
s.carts[key] = c
}
func (s *Store) Get(key string) Cart { return s.carts[key] }After
Siblings tagged with vector clocks, merged by union. This is the cart rule from the Dynamo paper, including the documented side effect that a removal can come back.
// Package after keeps concurrent cart versions as siblings, tagged with
// vector clocks, and lets the application reconcile them by union, the
// approach the Dynamo paper describes for the shopping cart. Teaching
// re-implementation, NOT Amazon's code.
package after
import "academy/case-study-amazon/vclock"
// Version is one sibling: the items plus the clock that produced it.
type Version struct {
Items map[string]int
Clock vclock.Clock
}
// Store keeps every version that is not causally dominated by another.
type Store struct{ siblings map[string][]Version }
func NewStore() *Store { return &Store{siblings: map[string][]Version{}} }
// Put adds v and drops any stored version that v descends from. A stored
// version that descends from v makes v obsolete.
func (s *Store) Put(key string, v Version) {
var keep []Version
for _, old := range s.siblings[key] {
switch vclock.Compare(old.Clock, v.Clock) {
case vclock.Before, vclock.Equal:
// v supersedes old
case vclock.After:
return
default:
keep = append(keep, old)
}
}
s.siblings[key] = append(keep, v)
}
// Get returns all siblings; more than one means a conflict to reconcile.
func (s *Store) Get(key string) []Version { return s.siblings[key] }
// Reconcile merges siblings by union of items (maximum quantity per sku)
// and merges their clocks. Adds are never lost; a removal made on one
// sibling can come back, which the paper calls out explicitly.
func Reconcile(vs []Version) Version {
out := Version{Items: map[string]int{}}
var clocks []vclock.Clock
for _, v := range vs {
for sku, q := range v.Items {
if q > out.Items[sku] {
out.Items[sku] = q
}
}
clocks = append(clocks, v.Clock)
}
out.Clock = vclock.Merge(clocks...)
return out
}package after
import (
"testing"
"academy/case-study-amazon/vclock"
)
func TestConcurrentAddsBothSurvive(t *testing.T) {
s := NewStore()
base := vclock.Clock{}
s.Put("cart:42", Version{Items: map[string]int{"book": 1}, Clock: base.Tick("replicaA")})
s.Put("cart:42", Version{Items: map[string]int{"kettle": 1}, Clock: base.Tick("replicaB")})
sib := s.Get("cart:42")
if len(sib) != 2 {
t.Fatalf("want 2 siblings, got %d", len(sib))
}
merged := Reconcile(sib)
if merged.Items["book"] != 1 || merged.Items["kettle"] != 1 {
t.Fatalf("an add was lost: %v", merged.Items)
}
// The client writes the merged version back with a clock that
// descends from both siblings; the store collapses to one version.
s.Put("cart:42", Version{Items: merged.Items, Clock: merged.Clock.Tick("replicaA")})
if len(s.Get("cart:42")) != 1 {
t.Fatalf("write-back should supersede both siblings: %v", s.Get("cart:42"))
}
}
func TestDeletedItemCanResurface(t *testing.T) {
base := vclock.Clock{}.Tick("replicaA")
withBook := map[string]int{"book": 1}
removed := Version{Items: map[string]int{}, Clock: base.Tick("replicaA")}
stale := Version{Items: withBook, Clock: base.Tick("replicaB")}
merged := Reconcile([]Version{removed, stale})
if merged.Items["book"] != 1 {
t.Fatal("union merge should resurrect the removed book")
}
}
func TestOlderWriteIsIgnored(t *testing.T) {
s := NewStore()
v1 := Version{Items: map[string]int{"book": 1}, Clock: vclock.Clock{}.Tick("replicaA")}
v2 := Version{Items: map[string]int{"book": 2}, Clock: v1.Clock.Tick("replicaA")}
s.Put("cart:42", v2)
s.Put("cart:42", v1)
if got := s.Get("cart:42"); len(got) != 1 || got[0].Items["book"] != 2 {
t.Fatalf("stale write should be dropped: %v", got)
}
}Example: the vector clock
// Package vclock is a minimal vector clock in the style the Dynamo paper
// describes: a list of (node, counter) pairs attached to every version.
// It is a teaching re-implementation, NOT Amazon's code.
package vclock
// Clock maps a coordinating node to its counter.
type Clock map[string]uint64
// Order is the causal relation between two clocks.
type Order int
const (
Equal Order = iota
Before
After
Concurrent
)
// Tick returns a copy of c with node's counter incremented (a write
// coordinated by node).
func (c Clock) Tick(node string) Clock {
out := c.Copy()
out[node]++
return out
}
// Copy returns an independent clock.
func (c Clock) Copy() Clock {
out := Clock{}
for k, v := range c {
out[k] = v
}
return out
}
// Compare reports how a relates to b.
func Compare(a, b Clock) Order {
aLess, bLess := false, false
for k, av := range a {
if bv := b[k]; av < bv {
aLess = true
} else if av > bv {
bLess = true
}
}
for k, bv := range b {
if _, ok := a[k]; !ok && bv > 0 {
aLess = true
}
}
switch {
case !aLess && !bLess:
return Equal
case aLess && !bLess:
return Before
case !aLess && bLess:
return After
default:
return Concurrent
}
}
// Merge returns the element-wise maximum: the context a client sends
// back after it has reconciled several siblings.
func Merge(clocks ...Clock) Clock {
out := Clock{}
for _, c := range clocks {
for k, v := range c {
if v > out[k] {
out[k] = v
}
}
}
return out
}Example: ring, preference list, sloppy quorum and hinted handoff
// Package ring is a small teaching re-implementation of the partitioning and
// replica-placement ideas described in the 2007 Dynamo paper: a consistent-hash
// ring with virtual nodes (tokens), a preference list of N distinct nodes, and
// a sloppy quorum that skips unhealthy nodes and records hints for hinted
// handoff. It is NOT Amazon's code.
package ring
import (
"crypto/md5"
"encoding/binary"
"fmt"
"sort"
)
type token struct {
pos uint64
node string
}
// Ring maps keys to nodes. Each physical node owns several tokens
// (virtual nodes) so that load spreads evenly and a joining node takes
// a little from many peers instead of a lot from one.
type Ring struct {
tokens []token
nodes map[string]bool
}
// hash places keys and tokens on a 64-bit ring. The paper's Dynamo used
// MD5 of the key; MD5 is fine for placement and must never be used for
// security.
func hash(s string) uint64 {
sum := md5.Sum([]byte(s))
return binary.BigEndian.Uint64(sum[:8])
}
// New builds a ring with tokensPerNode virtual nodes for every node.
func New(nodes []string, tokensPerNode int) *Ring {
r := &Ring{nodes: map[string]bool{}}
for _, n := range nodes {
r.nodes[n] = true
for i := 0; i < tokensPerNode; i++ {
r.tokens = append(r.tokens, token{pos: hash(fmt.Sprintf("%s#%d", n, i)), node: n})
}
}
sort.Slice(r.tokens, func(i, j int) bool { return r.tokens[i].pos < r.tokens[j].pos })
return r
}
// walk returns distinct nodes clockwise from the key's position.
func (r *Ring) walk(key string) []string {
start := sort.Search(len(r.tokens), func(i int) bool { return r.tokens[i].pos >= hash(key) })
seen := map[string]bool{}
var out []string
for i := 0; i < len(r.tokens) && len(out) < len(r.nodes); i++ {
t := r.tokens[(start+i)%len(r.tokens)]
if !seen[t.node] {
seen[t.node] = true
out = append(out, t.node)
}
}
return out
}
// PreferenceList returns the first n distinct nodes for key (the "top N").
func (r *Ring) PreferenceList(key string, n int) []string {
all := r.walk(key)
if n > len(all) {
n = len(all)
}
return all[:n]
}
// Placement is one replica write target. HintFor is non-empty when the
// node is a stand-in for an unhealthy top-N node: it must keep the write
// in a separate hinted store and hand it back when HintFor recovers.
type Placement struct {
Node string
HintFor string
}
// SloppyQuorum returns the first n healthy nodes walking the ring. Skipped
// top-N nodes are matched, in order, with the stand-ins that replace them.
func (r *Ring) SloppyQuorum(key string, n int, healthy func(string) bool) []Placement {
all := r.walk(key)
if n > len(all) {
n = len(all)
}
var down []string
var out []Placement
for i, node := range all {
if len(out) == n {
break
}
if !healthy(node) {
if i < n {
down = append(down, node)
}
continue
}
p := Placement{Node: node}
if i >= n && len(down) > 0 {
p.HintFor, down = down[0], down[1:]
}
out = append(out, p)
}
return out
}Example: shuffle sharding
// Package shuffle assigns each customer a deterministic "shuffle shard":
// a small combination of workers chosen from a larger fleet, the technique
// the Amazon Builders' Library describes for Route 53. Teaching
// re-implementation, NOT Amazon's code.
package shuffle
import (
"crypto/sha256"
"encoding/binary"
"math/big"
"sort"
)
// Shard returns k distinct worker indexes in [0, n) for customer, chosen
// by a seeded Fisher-Yates shuffle so the same customer always gets the
// same combination.
func Shard(customer string, n, k int) []int {
if k > n {
k = n
}
seed := sha256.Sum256([]byte(customer))
idx := make([]int, n)
for i := range idx {
idx[i] = i
}
state := binary.BigEndian.Uint64(seed[:8])
for i := 0; i < k; i++ {
// xorshift64 is enough for placement; it is not for security.
state ^= state << 13
state ^= state >> 7
state ^= state << 17
j := i + int(state%uint64(n-i))
idx[i], idx[j] = idx[j], idx[i]
}
out := append([]int(nil), idx[:k]...)
sort.Ints(out)
return out
}
// Overlap counts workers two shards share.
func Overlap(a, b []int) int {
set := map[int]bool{}
for _, x := range a {
set[x] = true
}
c := 0
for _, y := range b {
if set[y] {
c++
}
}
return c
}
// Combinations returns C(n, k): how many distinct shuffle shards exist.
func Combinations(n, k int64) *big.Int {
return new(big.Int).Binomial(n, k)
}package shuffle
import (
"fmt"
"testing"
)
func TestNumbersFromTheBuildersLibrary(t *testing.T) {
if got := Combinations(8, 2).Int64(); got != 28 {
t.Fatalf("C(8,2) = %d, want 28", got)
}
// 2048 virtual name servers, 4 per domain: "730 billion" shards.
got := Combinations(2048, 4).Int64()
if got < 730_000_000_000 || got >= 731_000_000_000 {
t.Fatalf("C(2048,4) = %d, want about 730 billion", got)
}
}
func TestShardIsDeterministicAndDistinct(t *testing.T) {
a := Shard("customer-a", 8, 2)
if len(a) != 2 || a[0] == a[1] {
t.Fatalf("bad shard %v", a)
}
b := Shard("customer-a", 8, 2)
if a[0] != b[0] || a[1] != b[1] {
t.Fatalf("not deterministic: %v vs %v", a, b)
}
}
func TestFullOverlapIsRare(t *testing.T) {
poison := Shard("noisy-customer", 64, 4)
full := 0
for i := 0; i < 10000; i++ {
if Overlap(poison, Shard(fmt.Sprintf("customer-%d", i), 64, 4)) == 4 {
full++
}
}
// C(64,4) = 635376, so full overlap should almost never happen.
if full > 3 {
t.Fatalf("%d of 10000 customers share every worker with the noisy one", full)
}
}The Go angle
crypto/md5gives the same kind of ring position the Dynamo paper describes. Use it only for placement, never for security.math/big.Int.Binomialchecks the shuffle-shard counts exactly.- In production, the AWS SDK for Go v2 retries throttling errors such as
ProvisionedThroughputExceededExceptionwith backoff by default. Pass aClientRequestTokenwhere the API offers one (DynamoDBTransactWriteItems) or aClientToken(EC2) to make retries idempotent. - A sibling store like
after.Storeis what DynamoDB does not give you. DynamoDB returns one item, so in DynamoDB you would get cart-merge semantics from condition expressions or a CRDT-shaped item (inference: a design choice, not a quote).
Laravel
Before
A checkout endpoint where a client retry creates a second order, and where reading stock and then writing it can oversell.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Before: a checkout endpoint that a client retry turns into two orders,
// and that reads stock then writes it (lost update under concurrency).
class PlaceOrderController
{
public function __invoke(Request $request): JsonResponse
{
$data = $request->validate([
'sku' => ['required', 'string'],
'quantity' => ['required', 'integer', 'min:1'],
]);
$stock = DB::table('inventory')->where('sku', $data['sku'])->value('available');
if ($stock < $data['quantity']) {
return response()->json(['error' => 'out_of_stock'], 409);
}
DB::table('inventory')->where('sku', $data['sku'])
->update(['available' => $stock - $data['quantity']]);
$id = DB::table('orders')->insertGetId([
'customer_id' => $request->user()->id,
'sku' => $data['sku'],
'quantity' => $data['quantity'],
'status' => 'placed',
'created_at' => now(),
]);
return response()->json(['order_id' => $id], 201);
}
}After
An Idempotency-Key header claimed with insertOrIgnore against a unique index, a lockForUpdate read of the claimed row, and a single conditional decrement that reserves stock. Everything runs inside DB::transaction(..., attempts: 3), which retries on deadlock.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// After: the client sends an Idempotency-Key (a caller-provided client
// request identifier, the approach the Amazon Builders' Library describes),
// the order row is unique per (customer_id, idempotency_key), and stock is
// reserved with one conditional UPDATE. Teaching example, NOT Amazon's code.
class PlaceOrderController
{
public function __invoke(Request $request): JsonResponse
{
$data = $request->validate([
'sku' => ['required', 'string'],
'quantity' => ['required', 'integer', 'min:1'],
]);
$key = $request->header('Idempotency-Key');
if (! is_string($key) || strlen($key) < 16 || strlen($key) > 64) {
return response()->json(['error' => 'idempotency_key_required'], 400);
}
$customerId = $request->user()->id;
$result = DB::transaction(function () use ($data, $key, $customerId) {
// 1. Claim the key. A retry inserts nothing and falls through.
$claimed = DB::table('orders')->insertOrIgnore([
'customer_id' => $customerId,
'idempotency_key' => $key,
'sku' => $data['sku'],
'quantity' => $data['quantity'],
'status' => 'pending',
'created_at' => now(),
]);
$order = DB::table('orders')
->where('customer_id', $customerId)
->where('idempotency_key', $key)
->lockForUpdate()
->first();
if ($claimed === 0) {
// Same key with a different body is a client bug, not a retry.
if ($order->sku !== $data['sku'] || (int) $order->quantity !== $data['quantity']) {
return ['status' => 422, 'body' => ['error' => 'idempotency_key_reused']];
}
return ['status' => 200, 'body' => ['order_id' => $order->id, 'status' => $order->status]];
}
// 2. Reserve stock atomically: no read-modify-write in PHP.
$reserved = DB::table('inventory')
->where('sku', $data['sku'])
->where('available', '>=', $data['quantity'])
->decrement('available', $data['quantity'], ['reserved' => DB::raw('reserved + '.(int) $data['quantity'])]);
$status = $reserved === 1 ? 'reserved' : 'rejected_out_of_stock';
DB::table('orders')->where('id', $order->id)->update(['status' => $status]);
return ['status' => $reserved === 1 ? 201 : 409, 'body' => ['order_id' => $order->id, 'status' => $status]];
}, attempts: 3);
return response()->json($result['body'], $result['status']);
}
}Example: cart reconciliation
<?php
namespace App\Domain\Cart;
use Illuminate\Support\Collection;
// Merges concurrent cart siblings by union (max quantity per SKU), the
// reconciliation the Dynamo paper describes for the shopping cart: adds are
// never lost, a removal can come back. Teaching example, NOT Amazon's code.
final class CartReconciler
{
/**
* @param array<int, array{items: array<string, int>, clock: array<string, int>}> $siblings
* @return array{items: array<string, int>, clock: array<string, int>}
*/
public function reconcile(array $siblings): array
{
$all = new Collection($siblings);
$items = $all->pluck('items')
->flatMap(fn (array $items) => (new Collection($items))->map(fn ($q, $sku) => ['sku' => $sku, 'q' => $q])->values())
->groupBy('sku')
->map(fn (Collection $rows) => $rows->max('q'))
->all();
$clock = $all->pluck('clock')
->flatMap(fn (array $c) => (new Collection($c))->map(fn ($n, $node) => ['node' => $node, 'n' => $n])->values())
->groupBy('node')
->map(fn (Collection $rows) => $rows->max('n'))
->all();
return ['items' => $items, 'clock' => $clock];
}
}The Laravel angle
DB::table(...)->insertOrIgnore()ignores duplicate-key errors. The Laravel 13 docs warn that on MySQL it can also hide other errors because it bypasses strict mode, so validate input first (we do).decrement($column, $amount, $extra)takes extra columns to update in the same statement. That is howreservedchanges atomically withavailable.DB::transaction($callback, $attempts)retries only on deadlocks. For throttling against an AWS service, use the HTTP client'sretry()or the AWS SDK for PHP's built-in retries, and keep those calls idempotent.- For a cart stored in DynamoDB from Laravel you would use the AWS SDK for PHP directly. Laravel's cache has a
dynamodbdriver, but it is a cache, not a cart store.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost |
|---|---|---|---|---|
| Cart add lost under partition | Siblings + merge | Vector clocks, union merge | Writes never rejected | Deletes can resurface |
| Double order on retry | Idempotency key | Unique (customer, key) | One order per intent | Key storage, TTL |
| Oversell | Conditional reservation | UPDATE ... WHERE available >= qty | No lock held across requests | Hot row on a hot SKU |
| Hot partition in a sale | Adaptive capacity / GAC / split | Managed by DynamoDB | No re-keying needed | Single hot item still throttles |
| Noisy tenant | Shuffle sharding | k of n workers per tenant | Tiny overlap | Clients must retry across members |
| Bad deploy | Cells + waves | One-box, one AZ, bake, rollback | Small blast radius | Slow global rollout |
| AZ loss | Static stability | 50% spare across 3 AZs | No control-plane dependency | Idle capacity |
| Cache failure overloads DB | Avoid fallback | Shed load, push data, failover that always runs | No untested path | More engineering up front |
A cart add disappears after a network blip
Use the Go after store or the Laravel CartReconciler. Make sure every write carries the context (clock) from its read. A write without context creates an unnecessary sibling.
A retried checkout creates two orders
Apply After.php: require the key, claim it with a unique index, return the stored result on replay, and reject a reused key with a different body (the Builders' Library's "same client request ID, different intent" case).
One SKU melts the inventory table
Reserve against sharded stock rows (for example ten rows of ten units each) and pick a row at random (Sharded Counters). This is the generic fix. Amazon's actual approach is not published (inference).
A tenant's traffic kills the shared fleet
Move the tenant into a cell, then shuffle-shard inside cells. Measure the blast radius as "share of customers whose whole shard is broken".
Choosing
| Situation | Pick | Extra technique | Reason |
|---|---|---|---|
| User-facing write that must never fail (cart, wishlist, likes) | AP store, siblings or CRDT | Merge function, tombstones for deletes | Availability over consistency, as Dynamo did |
| Money, orders, stock counts | Relational store (Aurora/PostgreSQL) or DynamoDB with conditions/transactions | Idempotency keys, outbox | Must be exact |
| Primary-key lookups at large scale | DynamoDB or another managed key-value store | Good partition key | 70% of old operations were key-value (Vogels 2017) |
| Recommendations | Offline batch + online key-value lookup | Periodic rebuild | Online cost independent of catalogue size |
| Many tenants, uneven load | Cells, then shuffle sharding | Thin router | Blast radius |
| Dependency or AZ outage | Static stability | N+1 capacity, pushed config | No reaction needed |
| Tempted to add a fallback | Failover that is always exercised, or let the caller retry | Load shedding | Untested code fails at the worst time |
| Releasing changes | Pipeline with one-box and waves | Bake time, auto rollback | Most outages start with a change |
In architecture: from a single process to a distributed system
Monolith: one process, one database
This is Amazon's starting point: one bookstore application and one large database. The simplest correct versions of the ideas still apply here. Use an idempotency key and a unique index for orders, a conditional UPDATE for stock, and a deployment that goes to one server first. A cart stored in one PostgreSQL row needs no vector clocks, because there is only one copy.
Modular monolith: boundaries without the network
Give each module (cart, catalogue, orders, inventory) its own schema and forbid cross-module joins. This is the mandate's rule, "no direct reads of another team's data store" (secondary wording), applied inside one process. A later split into services then becomes a deployment change, not a rewrite.
Microservices: every arrow is a decision
Following Amazon's model, a checkout runs as: cart service (AP store) to order service (unique key, relational) to inventory (conditional reservation) to payments (provider idempotency key) to fulfilment (event with dedup). Each arrow needs a timeout, a retry policy with jitter, and an idempotent receiver. The page aggregator calls many services in parallel and caches heavily (Dynamo paper). Each service keeps its own p99.9 SLA, because the slowest dependency sets the page latency.
Distributed data: replicas, caches, regions
Dynamo spreads each key over N nodes across data centres and accepts divergence. DynamoDB keeps three replicas across AZs with one Multi-Paxos leader per partition, so strongly consistent reads go to the leader. Caches in front of shared databases must not become a hidden dependency: the fallback outage is exactly that failure. Read-your-writes for a cart can be provided by sending the same session to the same coordinator (inference; see Consistency Models).
Scaling path: 1x, 10x, 100x
| Load | What changes | Amazon parallel |
|---|---|---|
| 1x | One database, one app; keys and conditional updates | Early bookstore |
| 10x | Split by team into services; caches; read replicas | Two-pizza teams, aggregators |
| 100x | Partitioned key-value stores, cells, shuffle sharding, waves | Dynamo, DynamoDB, Builders' Library patterns |
| Event peaks | Pre-scaled capacity, fault-injection rehearsals | Prime Day preparation |
Lab
Experiment 1: run the mechanisms (single-process Go; run on the author's machine with Go 1.24).
cd docs/snippets/system-design/case-study-amazon/go
go test -count=1 -v ./...--- PASS: TestConcurrentAddsBothSurvive (0.00s)
--- PASS: TestDeletedItemCanResurface (0.00s)
--- PASS: TestOlderWriteIsIgnored (0.00s)
ok academy/case-study-amazon/after
--- PASS: TestLastWriterWinsLosesAnAdd (0.00s)
ok academy/case-study-amazon/before
--- PASS: TestPreferenceListIsDistinctAndStable (0.00s)
--- PASS: TestSloppyQuorumSkipsDownNodeAndLeavesHint (0.00s)
--- PASS: TestVirtualNodesSpreadLoad (0.08s)
ok academy/case-study-amazon/ring
--- PASS: TestNumbersFromTheBuildersLibrary (0.00s)
--- PASS: TestShardIsDeterministicAndDistinct (0.00s)
--- PASS: TestFullOverlapIsRare (0.01s)
ok academy/case-study-amazon/shuffle
--- PASS: TestDynamoPaperExample (0.00s)
--- PASS: TestEqual (0.00s)
ok academy/case-study-amazon/vclockExperiment 2: break virtual nodes. In ring_test.go, change New(nodes, 128) to New(nodes, 1) in TestVirtualNodesSpreadLoad and run go test ./ring/. Expected, not run: the test fails because one node owns far more than its share. With a single token per node, range sizes are random.
Experiment 3: idempotent checkout (Laravel; expected, not run).
# 1. first attempt
curl -s -X POST http://localhost:8000/api/orders -H 'Authorization: Bearer TOKEN' \
-H 'Idempotency-Key: 7d0c8a4e-1b8f-4c4e-9a52-1f0e1a2b3c4d' -d sku=BOOK-1 -d quantity=1
# {"order_id":1,"status":"reserved"} HTTP 201
# 2. same key again (a retry)
# {"order_id":1,"status":"reserved"} HTTP 200, no second row, stock unchanged
# 3. same key, quantity=2
# {"error":"idempotency_key_reused"} HTTP 422Experiment 4: oversell race (expected, not run). Seed inventory with available = 1. Fire two requests with different keys at the same time (xargs -P 2). Expected: one 201 reserved and one 409 rejected_out_of_stock, with available = 0, reserved = 1. With Before.php both can succeed and leave available = 0 while two orders exist.
Experiment 5: shuffle-shard overlap. Add a test that prints Overlap between Shard("a", 8, 2) and 1,000 other customers. Expected, not run: about 1/28 of them share both workers, about 12/28 share one, and about 15/28 share none (for 8 choose 2: C(2,2)·C(6,0)=1, C(2,1)·C(6,1)=12, C(6,2)=15, out of 28).
Common misconceptions
| Belief | Reality |
|---|---|
| DynamoDB is Dynamo as a service | DynamoDB uses Multi-Paxos leaders per partition and a WAL; it was motivated by Dynamo (2022 paper) |
| Amazon is eventually consistent everywhere | Transactional workloads moved to Aurora/RDS (2019 post); the cart is the AP example |
| The API mandate memo is published by Amazon | Known through Steve Yegge's 2011 post (secondary) |
| R + W > N guarantees fresh reads in Dynamo | Sloppy quorum and hinted handoff can place writes outside the usual N |
| Union merge is lossless | Adds are never lost, but deleted items can resurface (Dynamo paper) |
| Consistent hashing balances load by itself | Dynamo needed virtual nodes, then equal-sized partitions |
| Shuffle sharding works without client changes | Clients must try other shard members (inference from the mechanism) |
| Auto scaling is enough for an AZ failure | Static stability means the capacity is already running |
| A fallback always increases availability | Amazon's fallback example took down the site and the fulfilment centres |
| Continuous deployment means everywhere at once | One-box, waves, at least 12 h bake after the first regional wave |
| Recommendations are computed per user at request time | The similar-items table is built offline (2003 paper) |
| The Prime Day DynamoDB peak is website traffic | It includes Alexa, the Amazon.com sites and fulfilment centres |
Cheat sheet
| Topic | Remember |
|---|---|
| Opening principle | Failure is the normal case; cart writes are always accepted |
| Dynamo toolkit | Consistent hashing, vector clocks, sloppy quorum, hinted handoff, Merkle trees, gossip |
| Dynamo config | (N,R,W) = (3,2,2) common; 99.94% single-version reads |
| DynamoDB | Partitions, bursting, adaptive capacity, GAC, split for consumption, Multi-Paxos, TLA+ |
| DynamoDB scale | 89.2 M (2021) to 151 M (2025) req/s Prime Day peaks |
| Teams | Two-pizza teams own services and data |
| Orders | Client request identifier = idempotency; Aurora/RDS for transactional data |
| Recommendations | Item-to-item CF; offline similar-items table; online cost independent of catalogue |
| Search | Lexical + semantic retrieval (KDD 2019); A9 = 2003 subsidiary (secondary) |
| Cells | Independent copies; 10 cells means one failure hits about 10% |
| Shuffle sharding | 8 choose 2 = 28; Route 53: 2048 choose 4 = 730 billion |
| Static stability | 3 AZs, 50% overprovision; data plane works without control plane |
| Avoiding fallback | Untested paths fail at the worst time; prefer failover or retry |
| Deployments | Alpha, beta, gamma, one-box, waves, bake (1 h / 12 h / 2-4 h), auto rollback |
| Evidence rule | Cited claim vs inference vs secondary |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why did the shopping cart need an "always writeable" store, and what did Amazon give up for it? Must-know
Answer
Answer: Rejecting an add-to-cart costs a sale and the customer's trust, so Dynamo accepts writes even when replicas cannot agree. It gives up a single agreed version at read time. Concurrent versions come back as siblings that the application merges, and deleted items can resurface.
2 — What is the difference between a strict quorum and Dynamo's sloppy quorum? Must-know
Answer
Answer: A strict quorum uses the fixed N owners of a key and fails if not enough of them are reachable. A sloppy quorum uses the first N healthy nodes on the preference list, so a stand-in can accept a write with a hint and hand it back later (hinted handoff). Availability goes up, but R + W > N no longer guarantees overlap with the latest write.
3 — What do Merkle trees add that hinted handoff does not? Important
Answer
Answer: Hinted handoff covers temporary failures. If a hint is lost or a node is gone for good, replicas diverge permanently. Merkle trees let two replicas compare one root hash per key range and walk down only into the parts that differ, so anti-entropy moves little data.
4 — Name three ways DynamoDB differs from the 2007 Dynamo design. Good to know
Answer
Answer: It is a managed multi-tenant service, not a per-team installation. It uses Multi-Paxos replication groups with a leader (strongly consistent reads, write-ahead log) instead of leaderless siblings. And it has admission control (token buckets, bursting, adaptive capacity, then global admission control) for predictable performance. The core replication protocol is also specified in TLA+ and model-checked.
5 — Why did DynamoDB replace adaptive capacity with global admission control? Good to know
Answer
Answer: Bursting helped only short spikes, and adaptive capacity was reactive and best-effort. GAC tracks table-level consumption centrally and refills each request router's local token bucket every few seconds, so admission no longer depends on a partition's equal share of the table's throughput.
6 — Why does item-to-item collaborative filtering scale better than user-based filtering? Important
Answer
Answer: The expensive similar-items table is built offline. Online, the work depends only on how many items the user has bought or rated, not on the number of customers or catalogue items.
7 — Eight workers, two per customer. How many shuffle shards are there, and what happens to a customer who shares one worker with a poisoned customer? Important
Answer
Answer: C(8,2) = 28. The customer loses the shared worker but can still be served by its other worker, as long as the client retries on the other member.
8 — With three AZs and static stability, how much capacity do you run, and why? Must-know
Answer
Answer: 150% of peak (50% overprovision), so each AZ runs at about 66% of its tested load. If one AZ fails, the other two carry everything without launching instances, so recovery does not depend on the control plane while it may be impaired.
9 — What went wrong with the cache-to-database fallback in the Builders' Library article? Must-know
Answer
Answer: The caches failed around the same time, every web server fell back to querying the database directly, and the database locked up. The website went down, and because fulfilment centres used the same supply-chain database, they stopped worldwide. The fallback made the outage worse than having no fallback.
10 — Put these deployment stages in order and say what each catches: one-box, gamma, wave 1, bake time. Must-know
Answer
Answer: Gamma (prod-like environment, canaries: config and environment errors), then one-box (a single unit with real traffic: crashes and backward incompatibility), then wave 1 (one AZ or cell in a low-traffic Region: scale and regional effects). Bake time sits after each stage (at least 1 h after one-box, at least 12 h after the first regional wave) to catch slow-burning problems before the next stage.
11 — Which claims on this page are inference, and why does that matter? Important
Answer
Answer: For example: which store holds the order record, the exact order and reservation steps, how the search index is updated, whether every page goes through CloudFront, and that shuffle sharding needs client retries. These are not stated in the sources. The label tells you to verify a claim before you rely on it as a fact about Amazon.
Glossary
| Term | Meaning |
|---|---|
| Amazon | The retailer whose platform is studied here; AWS is its cloud business, founded 2006 |
| Service-oriented architecture | System built from services that own their data and expose network interfaces |
| API mandate | Yegge's 2011 retelling (secondary) of a rule that teams communicate only through service interfaces |
| Two-pizza team | Team small enough to be fed by two pizzas, owning a service end to end |
| Dynamo | Amazon's 2007 leaderless, highly available key-value store |
| Consistent hashing | Mapping keys and nodes onto a ring so membership changes move few keys |
| Virtual node (token) | One of several ring positions owned by a physical node |
| Preference list | The ordered distinct nodes responsible for a key |
| Vector clock | Per-node counters that tell causally ordered versions from concurrent ones |
| Semantic reconciliation | Application-level merge of concurrent versions, for example a cart union |
| Sloppy quorum | Quorum over the first N healthy nodes rather than the fixed owners |
| Hinted handoff | A stand-in keeps a write with a hint and returns it to the owner later |
| Merkle tree | Hash tree over key ranges used for anti-entropy comparison |
| Anti-entropy | Background replica synchronisation |
| Gossip | Peer-to-peer membership and failure-detection protocol |
| DynamoDB | AWS's managed NoSQL service launched in 2012 |
| Partition | DynamoDB's key-range unit of storage and throughput |
| Bursting | Using unused node capacity for short partition spikes |
| Adaptive capacity | Raising a hot partition's throughput for long-lived skew |
| Global admission control (GAC) | Central table-level token tracking that refills request-router buckets |
| Split for consumption | Splitting a partition at the observed hot key range |
| Formal verification | Specifying a protocol (TLA+) and model-checking it |
| Shopping cart | The Dynamo paper's flagship always-writeable workload |
| Availability over consistency | Choosing to accept writes rather than refuse them when replicas disagree |
| Order pipeline | The sequence of services from checkout to fulfilment |
| Idempotency | Repeating a request has the same effect as doing it once |
| Client request identifier | Caller-supplied id that marks retries as the same request (EC2 ClientToken) |
| Aurora | AWS relational database (PostgreSQL/MySQL compatible) used for transactional workloads |
| Catalogue | The product data service and store |
| Product search | Retrieving and ranking products for a query |
| A9 | Amazon's search and advertising subsidiary founded 2003 (secondary) |
| Recommendations | Suggesting products a customer is likely to want |
| Item-to-item collaborative filtering | Recommending neighbours of a user's items from a precomputed similar-items table |
| Fulfilment | Picking, packing and shipping orders in fulfilment centres |
| Inventory reservation | Holding stock for an order until it is confirmed or released |
| Cell-based architecture | Independent full copies of a workload, each serving a subset of customers |
| Cell router | The thin layer that sends a request to its cell by partition key |
| Shuffle sharding | Giving each customer a random small combination of workers |
| Static stability | Keeping working through a dependency failure without reacting |
| Control plane / data plane | The part that makes changes / the part that serves requests |
| Avoiding fallback | Preferring reliable primaries, retries or always-on failover over rarely used fallback paths |
| Route 53 | AWS DNS service; shuffle-sharded name servers |
| CloudFront | AWS content delivery network |
| S3 durability | S3 is designed for 11 nines durability across at least 3 AZs |
| Deployment safety | Practices that keep a change from causing a broad outage |
| One-box | Deploying to a single unit first |
| Canary | Synthetic tests that run continuously against an environment |
| Bake time | Waiting and watching alarms after a stage before promoting |
| Prime Day | Amazon's yearly sales event, with load numbers published each year |
| Builders' Library | Amazon's published articles on how it builds and runs systems |
| Inference | A statement that is our reading, not a claim made in the cited sources |
References
- Giuseppe DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007; HTML on All Things Distributed
- Mostafa Elhemali et al., Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service, USENIX ATC 2022 (presentation page)
- Werner Vogels, Eventually Consistent - Revisited, 2008; Amazon DynamoDB, 2012; A Decade of Dynamo, 2017; Modern applications at AWS, 2019
- Greg Linden, Brent Smith, Jeremy York, Amazon.com Recommendations: Item-to-Item Collaborative Filtering, IEEE Internet Computing, 2003 (copy hosted by the University of Maryland)
- Larry Hardesty, The history of Amazon's recommendation algorithm, Amazon Science, 2019
- Amazon Science, Semantic product search, KDD 2019
- Amazon Builders' Library: Workload isolation using shuffle-sharding; Static stability using Availability Zones; Avoiding fallback in distributed systems; Automating safe, hands-off deployments; Making retries safe with idempotent APIs; Timeouts, retries, and backoff with jitter
- AWS Well-Architected, Reducing the Scope of Impact with Cell-Based Architecture and What is a cell-based architecture?, 2023
- AWS whitepaper, Introduction to DevOps on AWS: Two-Pizza Teams
- AWS News Blog: Migration Complete – Amazon's Consumer Business Just Turned off its Final Oracle Database, 2019; Prime Day 2022, 2023, 2024, 2025
- AWS product pages: Amazon S3 storage classes; Amazon Route 53 SLA; DynamoDB error handling
- Laravel 13: Database: Getting Started (transactions), Query Builder (insertOrIgnore, increment/decrement, lockForUpdate), Cache
- Secondary: Steve Yegge, Stevey's Google Platforms Rant, 2011 (API mandate story); Wikipedia, A9.com