Skip to content

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 forGo to
The whole case on one screenEverything in one minute
Why a retailer built its own databasesWhy it exists
Dated history from monolith to DynamoDBWhere it comes from, What changed over time
Step 1: what the retail site must doScope
Step 2: the numbersEstimate
Step 3: services, API mandate, two-pizza teamsService-oriented transformation
Dynamo: ring, versions, failuresDynamo partitioning, Versioning, Failure handling
DynamoDB: partitions, adaptive capacity, GAC, TLA+DynamoDB
Shopping cart, orders, catalogue, recommendations, fulfilmentCart, Orders, Catalogue and search, Recommendations, Fulfilment
Step 4: cells, shuffle sharding, static stability, fallbackCells, Shuffle sharding, Static stability, Avoiding fallback
Route 53, CloudFront, S3 durabilityEdge and storage
Deployment pipelines, one-box, waves, bake timeDeployment safety
Prime Day numbers by yearPrime Day
Mapping each subsystem to a generic chapterWhat you can copy
Knobs, error names, arithmeticMechanics
CodeGo, Laravel
Classic problems and fixesSolving the classic problems
Which pattern for which situationChoosing
From one process to many regionsIn architecture
Runnable tests and expected experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The subsystems and the decision each one shows.

SubsystemDecisionMechanismSource
Whole platformServices that own their data, reached only through APIsService-oriented architecture, two-pizza teamsVogels 2019; AWS DevOps whitepaper; Yegge 2011 (secondary)
Shopping cartAvailability over consistency: an add is never rejectedDynamo: sloppy quorum, vector clocks, application mergeDynamo paper 2007
Key-value state (sessions, best sellers, catalogue lookups)Primary-key access only, no relational featuresDynamo, later DynamoDBDynamo paper 2007; Vogels 2017
Managed NoSQLPredictable latency for many tenantsPartitions, bursting, adaptive capacity, global admission control, Multi-Paxos, TLA+DynamoDB paper 2022
Order pipelineRetries must not create a second orderClient request identifiers (idempotency); relational stores for transactional dataBuilders' Library; Oracle-migration post 2019; details inference
RecommendationsOnline work must not grow with the number of customersItem-to-item collaborative filtering with a similar-items table built offlineIEEE Internet Computing 2003; Amazon Science 2019
Catalogue and product searchFind related products, not only exact wordsLexical plus semantic matchingAmazon Science KDD 2019; A9 history secondary
Fulfilment and inventoryWarehouses must keep working when the website has troubleDynamoDB, queues; reservation model inferencePrime Day posts; fallback article
Blast radiusA failure hits only a slice of customersCell-based architecture, shuffle shardingWell-Architected 2023; Builders' Library 2019
DependenciesKeep working when a dependency or AZ failsStatic stability, no fallback pathsBuilders' Library 2019
ChangeMost outages start with a changePipelines, one-box, waves, bake time, automatic rollbackBuilders' Library 2020

The numbers worth remembering.

NumberWhat it isSource
150+Services one page request callsDynamo paper, section 2.2
300 ms at 99.9%Example SLA, at 500 requests/sDynamo paper, section 2.2
(3,2,2)Common (N,R,W) setting for DynamoDynamo paper, section 6
99.94%Cart reads that saw exactly one versionDynamo paper, section 6.3
3 million+Checkouts in one day through the cart serviceDynamo paper, section 1
70% / 20%Old database operations that were key-value / single-tableVogels, A Decade of Dynamo, 2017
89.2 M req/sDynamoDB peak, Prime Day 2021DynamoDB paper 2022
151 M req/sDynamoDB peak, Prime Day 2025AWS News Blog 2025
75 PB / ~7,500Data and Oracle databases moved off OracleAWS News Blog 2019
28 and 730 billionShuffle shards for 8 workers taking 2, and for Route 53's 2048 servers taking 4Builders' Library 2019
50%Extra capacity so that three AZs survive the loss of oneBuilders' Library 2019
11 ninesDurability S3 is designed forAmazon 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.

PressureWeaker answerAmazon's answer (cited)
Feature speedEveryone edits one codebaseSmall teams own services behind APIs
Cart availabilityReject writes when replicas disagreeAccept every write and merge versions later
Database cost and limitsBigger Oracle clustersPurpose-built stores: Dynamo, then DynamoDB, Aurora, Redshift
Noisy customersShared fleet for everyoneCells and shuffle shards
Dependency outagesFallback code that rarely runsStatic stability: run on pre-pushed state and spare capacity
Risky changesBig-bang releases watched by peopleAutomated 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 ​

  1. "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.
  2. "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.
  3. "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.

text
     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 traffic

Real 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).

RequirementStrength neededWhere it is met (cited or inference)
Cart writesAlways accept; merge laterDynamo (paper)
Order creationExactly one order per intentIdempotent APIs (Builders' Library); store choice inference
Payment and ledgerStrong consistencyRelational stores (2019 migration post); specifics inference
Catalogue readHigh availability, can be slightly staleDynamo paper lists product catalog as primary-key access
RecommendationsFast online, freshness in hours is fineOffline 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.

text
     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.

QuantityValueType
Services per page150+Cited (Dynamo)
Example SLA300 ms for 99.9% of requests at 500 req/sCited (Dynamo)
DynamoDB peak 2021 / 2022 / 2023 / 2024 / 202589.2 M / 105.2 M / 126 M / 146 M / 151 M req/sCited (paper, Prime Day posts)
SQS peak 2022 / 2023 / 202570.5 M / 86 M / 166 M msgs/sCited (Prime Day posts)
Aurora average 2025~1.45 M transactions/sEstimate from a cited total
Per-hop budget~200 ms at p99.9Estimate

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 ​

ShopperRoute 53 (DNS)shuffle-shardedCloudFront (CDN)static assets, pagesPage rendering / aggregator servicesone page calls 150+ services (Dynamo paper, 2007)Cart servicealways writeableOrder pipelineidempotent stepsCatalogue / searchA9, semantic searchRecommendationsitem-to-item CFFulfilmentinventory, FCsDynamo, laterDynamoDBAurora / RDS(after Oracle, 2019)Index + catalogstore (inference)Similar-itemstable, built offlineDynamoDB, SQS(Prime Day posts)Each service owns its data store; no other service reads it directly.

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."

text
     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 them

Real 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.

AspectMonolith (before)Services (after, cited)
Data accessAny code reads any tableOnly through the owning service's interface
TeamFunctional departmentsTwo-pizza teams owning a product or feature
DeployCoordinated releasesEach team deploys its own pipeline (Builders' Library 2020)
FailureOne bug can stop allBounded 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.

text
     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 acks

Real 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)TokensPartitionsResult reported
1T random tokens per nodeRanges between tokensUneven; placement tied to partitioning
2T random tokens per nodeQ equal partitionsDecouples partitioning from placement
3Q/S tokens per nodeQ equal partitionsBest 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.

ABCDEFkey Khash ring(MD5 of the key)hint for DWrite K with N=3, W=21. Walk clockwise from hash(K)2. Preference list: B, C, D3. D is unreachable (down)4. Sloppy quorum: first 3 healthynodes = B, C, E5. E stores the replica with a hint:"belongs to D"6. W=2 acks from B, C: success7. D recovers; E hands the replicaback and deletes its copyPermanent loss: Merkle-treeanti-entropy repairs replicasMembership: gossip, every second

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."

text
     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 both

Real 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
199.94%
20.00057%
30.00047%
40.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).

text
     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 tree

Real 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)TechniqueAdvantage stated
PartitioningConsistent hashingIncremental scalability
High availability for writesVector clocks with reconciliation during readsVersion size decoupled from update rates
Temporary failuresSloppy quorum and hinted handoffAvailability and durability when some replicas are down
Permanent failuresAnti-entropy using Merkle treesSynchronises divergent replicas in the background
Membership and failure detectionGossip-based protocolSymmetry, 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.

text
     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 split

Real 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.

MechanismProblem it fixedLimit stated in the paper
Equal per-partition allocationSimple isolationThroughput dilution after splits; hot partitions throttled
BurstingShort spikesOnly short-lived; needs spare node capacity
Adaptive capacityLong-lived skewReactive, best-effort
Global admission controlTable-level budget across partitionsCentral service, refills every few seconds
Split for consumptionHot key rangeDoes not help a single hot item or sequential keys
Multi-Paxos + WAL + checksumsDurability, leader electionGray failures handled by asking peers before failover
TLA+ and model checkingReplication protocol bugsCovers 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.

text
     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.

ChoiceCart outcomeWho pays
Strong consistency (reject when no majority)"Try again later"The customer, at the moment of buying
Last-writer-winsOne device's add silently lostThe customer, later and silently
Siblings + union merge (Dynamo)Every add kept; deletes may resurfaceThe 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.

text
     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).

StepDuplicate riskGuard
Create orderClient retryUnique (customer_id, idempotency_key)
Reserve stockConcurrent buyersConditional decrement WHERE available >= qty
ChargeWorker retryPayment-provider idempotency key (Payments)
Publish eventRelay retryOutbox + consumer inbox (Outbox, Inbox)
Multi-step rollbackPartial failureSaga 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.

sql
-- 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 stock

Catalogue 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.

text
     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 service

Real 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.

PieceEvidenceGeneric chapter
Catalogue item lookupsDynamo paper (primary-key access)Choosing a Database
Lexical + semantic retrievalAmazon Science KDD 2019Search Systems
A9 subsidiary (2003)Wikipedia (secondary)History only
Index update pipelineNot published: inferenceChange 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).

text
     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 10

Real 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 costQuality as described
Traditional user-based collaborative filteringGrows with customers and itemsGood, does not scale
Cluster modelsLow (offline clustering)Low
Search-based (same author or keywords)LowOften too narrow
Item-to-item collaborative filteringDepends only on the user's own itemsHigh, 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.

text
     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 decremented

Real 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.

ConcernPatternChapter
OversellConditional decrement, reservation rowOptimistic vs Pessimistic Locking
Shared fate with the websiteSeparate stores, no shared cache-or-DB fallbackBulkheads
Hand-off to warehousesEvents with dedupEvent-Driven Architecture
Hot item in a saleSharded countersWrite 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.

text
     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 unaffected

Real 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.

ChoiceBlast radiusCost
One shared fleet100%Lowest
N cellsAbout 1/NRouter, per-cell overhead, cross-cell queries are hard
Cells + shuffle sharding insideSmaller still for noisy tenantsMore 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".

Cell router (thin, stateless)route by partition key, e.g. customer IDCell 1Cell 2Cell 3full stackown databad deploy orpoison requestfull stackown data10 cells: one failure leaves 90% of requests unaffected(AWS Well-Architected, 2023)customer Xcustomer Yw1w2w3w4w5w6w7w8X's poison traffic kills w1 and w3Y shares only w3, still served by w68 workers, 2 each: 28 shuffle shardsRoute 53: 2048 servers, 4 each: 730 billion(Builders' Library, 2019)

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).

text
     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 combinations

Real 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 nPer customer kShuffle shards C(n,k)
8228
644635,376
20484730,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.

text
     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 it

Real 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.

DesignNeeds during failureStatically stable?
Scale up on failureControl plane, capacity, timeNo
Pre-provisioned spare (n+1 AZ)NothingYes
Pull config on each requestThe config serviceNo
Push config, keep last good copyNothingYes

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.

text
     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 worldwide

Real 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 fallbackHowExample from the article
Make the primary more availableBetter store, more capacityDynamoDB for amazon.com on Prime Day 2017 (talk)
Let the caller retryIdempotent API + backoffRetries with jitter
Push data ahead of timeData is local when neededIAM role credentials on EC2
Failover that runs all the timeBoth paths always in useActive-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.

text
     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 nines

Real scenario: DDoS on DNS; an image-heavy product page; a deleted bucket object (durability does not protect against deletion; use versioning).

ProductPublished figureSource
Route 53Credits below 100% monthly uptimeRoute 53 SLA
CloudFront500 M+ req/min peak (2023, 2024); 3 T+ requests in Prime Day 2025 weekPrime Day posts
S3Designed for 11 nines durability, at least 3 AZsS3 storage classes page

Fix / how to use it: see CDNs, IP, DNS & GeoDNS and Object Storage.

Source+ buildAlpha, betaAPI + e2e testsGammaprod-like, canaryProd one-boxbake >= 1 hWave 11 AZ/cell, small RegionWaves 2..ngrowing sizeBake: at least 12 h after the first regional wave, 2-4 h after later waves (typical pipeline)Alarm fires (faults, latency, request count drop)automatic rollback, no human in the loop

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.

text
     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 version

Real 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).

StageCatchesCost
Unit / integration testsLogic errorsMinutes
Gamma + canaryEnvironment, config errorsHours
One-boxBackward incompatibility, crash on real traffic1 server's share of traffic
Wave 1 (one AZ/cell)Regional or scale effectsSmall share of customers
Bake timeSlow-burning problemsDays for a global rollout
Automatic rollbackHuman reaction timeMust 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).

text
     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).

YearDynamoDB peakAuroraSQS peakOther
202189.2 M req/sn/an/aTrillions of DynamoDB calls (paper)
2022105.2 M req/s5,326 instances, 288 B transactions70.5 M msgs/sSES 33,000 emails/s
2023126 M req/s5,835 instances, 318 B transactions86 M msgs/sCloudFront 500 M+ req/min
2024146 M req/s6,311 instances, 376 B+ transactionsn/a in post733 FIS experiments
2025151 M req/s500 B transactions166 M msgs/s6,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 ​

DateChangeSource
~1997Item-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 teamsVogels 2019
2003IEEE Internet Computing recommendations paper; A9 foundedPaper; Wikipedia (secondary)
2004Oracle clusters cannot meet availability and scale needs; Dynamo work beginsVogels 2017
2006AWS founded on the infrastructure skillsVogels 2019
Oct 2007Dynamo paper at SOSPPaper
Dec 2008"Eventually Consistent - Revisited"Vogels blog
Jan 18, 2012DynamoDB launchedVogels blog; 2022 paper
2011 (post date)API mandate story publishedYegge (secondary)
Oct 2017"A Decade of Dynamo"; IEEE "test of time" award for the 2003 paperVogels blog; Amazon Science
Oct 15, 2019Consumer business turns off its last Oracle database (75 PB, ~7,500 DBs)AWS News Blog
Dec 5, 2019Builders' Library: shuffle sharding, static stability, avoiding fallback, timeouts and jitterBuilders' Library
Jun 18, 2020Builders' Library: automating safe, hands-off deploymentsBuilders' Library
Jul 2022DynamoDB paper at USENIX ATCPaper
Sep 20, 2023Cell-based architecture whitepaperAWS Well-Architected
2024-2025FIS experiments grow from 733 to 6,800+ before Prime DayAWS News Blog

What you can copy ​

Amazon subsystemPattern you can copyGeneric chapter
Services + two-pizza teamsTeam-owned services, no shared databaseService Boundaries, Data Ownership
Dynamo ringConsistent hashing with virtual nodesConsistent Hashing, Sharding at System Level
Dynamo versionsVector clocks, siblings, mergeVector Clocks, CRDTs
Dynamo repairHinted handoff, Merkle anti-entropy, gossipMerkle Trees, Gossip
CartAvailability over consistencyCAP & PACELC, ACID vs BASE
DynamoDBPartitioned managed key-value, admission controlWide-Column & Key-Value, Rate Limiting
DynamoDB replicationMulti-Paxos leader per partition, leasesLeader Election, Distributed SQL & Consensus
OrdersIdempotency keys, outbox, sagasAPI Idempotency, Saga
SearchLexical + semantic retrievalSearch Systems
RecommendationsOffline model, online lookupML Systems
Cells, shuffle shardingBlast-radius reductionBulkheads & Graceful Degradation
Static stability, no fallbackPre-provisioned capacity, push configCapacity Planning & DR, Cascading Failures
Deployment wavesOne-box, bake time, rollbackAlerting That Works, Containers & Kubernetes
Prime Day preparationFault injection before peaksChaos Engineering

Mechanics ​

Knobs, in one place ​

KnobSystemValue in sourcesEffect
NDynamo3 (common)Replicas per key
RDynamo2Replies needed for a read
WDynamo2Acks needed for a write; W=1 favours availability
Tokens per node / Q partitionsDynamoStrategy 3: Q/S tokens per nodeLoad balance and placement
Gossip intervalDynamoEach node contacts a random peer every secondMembership convergence
HashDynamoMD5 of the keyRing position
Object sizeDynamoUsually less than 1 MBTarget workload
GAC refill intervalDynamoDB"In the order of few seconds"How fast routers learn table budget
Replicas per partitionDynamoDBThree, across AZsDurability, availability
OverprovisionStatic stability50% with 3 AZsSurvive one AZ loss without scaling
Shuffle shard sizeRoute 534 of 2048 virtual name serversIsolation per domain
One-box bakeDeploymentsAt least 1 hCatch crash and compatibility issues
First-wave bakeDeploymentsAt least 12 hCatch slow-burning issues

Error names you will meet ​

NameWhereMeaningRetry?
ProvisionedThroughputExceededExceptionDynamoDB (HTTP 400)Table or index over its provisioned rateYes, with backoff (SDKs retry)
ThrottlingExceptionDynamoDBRequest rate above the allowed throughput (control-plane calls too fast, or on-demand tables)Yes, with backoff
RequestLimitExceededDynamoDBAccount-level throughput limitYes, with backoff
ConditionalCheckFailedExceptionDynamoDBA condition expression was false (for example stock too low)No: business outcome
ClientToken reuse with different parametersEC2 idempotent APIsSame identifier, different intentNo: client bug
HTTP 409 out_of_stockOur Laravel exampleReservation rejectedNo
HTTP 422 idempotency_key_reusedOur Laravel exampleSame key, different bodyNo

Arithmetic ​

text
     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.

go
// 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.

go
// 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
}
go
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 ​

go
// 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 ​

go
// 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 ​

go
// 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)
}
go
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/md5 gives the same kind of ring position the Dynamo paper describes. Use it only for placement, never for security. math/big.Int.Binomial checks the shuffle-shard counts exactly.
  • In production, the AWS SDK for Go v2 retries throttling errors such as ProvisionedThroughputExceededException with backoff by default. Pass a ClientRequestToken where the API offers one (DynamoDB TransactWriteItems) or a ClientToken (EC2) to make retries idempotent.
  • A sibling store like after.Store is 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
<?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
<?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
<?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 how reserved changes atomically with available.
  • DB::transaction($callback, $attempts) retries only on deadlocks. For throttling against an AWS service, use the HTTP client's retry() 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 dynamodb driver, but it is a cache, not a cart store.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost
Cart add lost under partitionSiblings + mergeVector clocks, union mergeWrites never rejectedDeletes can resurface
Double order on retryIdempotency keyUnique (customer, key)One order per intentKey storage, TTL
OversellConditional reservationUPDATE ... WHERE available >= qtyNo lock held across requestsHot row on a hot SKU
Hot partition in a saleAdaptive capacity / GAC / splitManaged by DynamoDBNo re-keying neededSingle hot item still throttles
Noisy tenantShuffle shardingk of n workers per tenantTiny overlapClients must retry across members
Bad deployCells + wavesOne-box, one AZ, bake, rollbackSmall blast radiusSlow global rollout
AZ lossStatic stability50% spare across 3 AZsNo control-plane dependencyIdle capacity
Cache failure overloads DBAvoid fallbackShed load, push data, failover that always runsNo untested pathMore 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 ​

SituationPickExtra techniqueReason
User-facing write that must never fail (cart, wishlist, likes)AP store, siblings or CRDTMerge function, tombstones for deletesAvailability over consistency, as Dynamo did
Money, orders, stock countsRelational store (Aurora/PostgreSQL) or DynamoDB with conditions/transactionsIdempotency keys, outboxMust be exact
Primary-key lookups at large scaleDynamoDB or another managed key-value storeGood partition key70% of old operations were key-value (Vogels 2017)
RecommendationsOffline batch + online key-value lookupPeriodic rebuildOnline cost independent of catalogue size
Many tenants, uneven loadCells, then shuffle shardingThin routerBlast radius
Dependency or AZ outageStatic stabilityN+1 capacity, pushed configNo reaction needed
Tempted to add a fallbackFailover that is always exercised, or let the caller retryLoad sheddingUntested code fails at the worst time
Releasing changesPipeline with one-box and wavesBake time, auto rollbackMost 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 ​

LoadWhat changesAmazon parallel
1xOne database, one app; keys and conditional updatesEarly bookstore
10xSplit by team into services; caches; read replicasTwo-pizza teams, aggregators
100xPartitioned key-value stores, cells, shuffle sharding, wavesDynamo, DynamoDB, Builders' Library patterns
Event peaksPre-scaled capacity, fault-injection rehearsalsPrime Day preparation

Lab ​

Experiment 1: run the mechanisms (single-process Go; run on the author's machine with Go 1.24).

bash
cd docs/snippets/system-design/case-study-amazon/go
go test -count=1 -v ./...
text
--- 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/vclock

Experiment 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).

bash
# 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 422

Experiment 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 ​

BeliefReality
DynamoDB is Dynamo as a serviceDynamoDB uses Multi-Paxos leaders per partition and a WAL; it was motivated by Dynamo (2022 paper)
Amazon is eventually consistent everywhereTransactional workloads moved to Aurora/RDS (2019 post); the cart is the AP example
The API mandate memo is published by AmazonKnown through Steve Yegge's 2011 post (secondary)
R + W > N guarantees fresh reads in DynamoSloppy quorum and hinted handoff can place writes outside the usual N
Union merge is losslessAdds are never lost, but deleted items can resurface (Dynamo paper)
Consistent hashing balances load by itselfDynamo needed virtual nodes, then equal-sized partitions
Shuffle sharding works without client changesClients must try other shard members (inference from the mechanism)
Auto scaling is enough for an AZ failureStatic stability means the capacity is already running
A fallback always increases availabilityAmazon's fallback example took down the site and the fulfilment centres
Continuous deployment means everywhere at onceOne-box, waves, at least 12 h bake after the first regional wave
Recommendations are computed per user at request timeThe similar-items table is built offline (2003 paper)
The Prime Day DynamoDB peak is website trafficIt includes Alexa, the Amazon.com sites and fulfilment centres

Cheat sheet ​

TopicRemember
Opening principleFailure is the normal case; cart writes are always accepted
Dynamo toolkitConsistent hashing, vector clocks, sloppy quorum, hinted handoff, Merkle trees, gossip
Dynamo config(N,R,W) = (3,2,2) common; 99.94% single-version reads
DynamoDBPartitions, bursting, adaptive capacity, GAC, split for consumption, Multi-Paxos, TLA+
DynamoDB scale89.2 M (2021) to 151 M (2025) req/s Prime Day peaks
TeamsTwo-pizza teams own services and data
OrdersClient request identifier = idempotency; Aurora/RDS for transactional data
RecommendationsItem-to-item CF; offline similar-items table; online cost independent of catalogue
SearchLexical + semantic retrieval (KDD 2019); A9 = 2003 subsidiary (secondary)
CellsIndependent copies; 10 cells means one failure hits about 10%
Shuffle sharding8 choose 2 = 28; Route 53: 2048 choose 4 = 730 billion
Static stability3 AZs, 50% overprovision; data plane works without control plane
Avoiding fallbackUntested paths fail at the worst time; prefer failover or retry
DeploymentsAlpha, beta, gamma, one-box, waves, bake (1 h / 12 h / 2-4 h), auto rollback
Evidence ruleCited claim vs inference vs secondary

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
AmazonThe retailer whose platform is studied here; AWS is its cloud business, founded 2006
Service-oriented architectureSystem built from services that own their data and expose network interfaces
API mandateYegge's 2011 retelling (secondary) of a rule that teams communicate only through service interfaces
Two-pizza teamTeam small enough to be fed by two pizzas, owning a service end to end
DynamoAmazon's 2007 leaderless, highly available key-value store
Consistent hashingMapping 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 listThe ordered distinct nodes responsible for a key
Vector clockPer-node counters that tell causally ordered versions from concurrent ones
Semantic reconciliationApplication-level merge of concurrent versions, for example a cart union
Sloppy quorumQuorum over the first N healthy nodes rather than the fixed owners
Hinted handoffA stand-in keeps a write with a hint and returns it to the owner later
Merkle treeHash tree over key ranges used for anti-entropy comparison
Anti-entropyBackground replica synchronisation
GossipPeer-to-peer membership and failure-detection protocol
DynamoDBAWS's managed NoSQL service launched in 2012
PartitionDynamoDB's key-range unit of storage and throughput
BurstingUsing unused node capacity for short partition spikes
Adaptive capacityRaising 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 consumptionSplitting a partition at the observed hot key range
Formal verificationSpecifying a protocol (TLA+) and model-checking it
Shopping cartThe Dynamo paper's flagship always-writeable workload
Availability over consistencyChoosing to accept writes rather than refuse them when replicas disagree
Order pipelineThe sequence of services from checkout to fulfilment
IdempotencyRepeating a request has the same effect as doing it once
Client request identifierCaller-supplied id that marks retries as the same request (EC2 ClientToken)
AuroraAWS relational database (PostgreSQL/MySQL compatible) used for transactional workloads
CatalogueThe product data service and store
Product searchRetrieving and ranking products for a query
A9Amazon's search and advertising subsidiary founded 2003 (secondary)
RecommendationsSuggesting products a customer is likely to want
Item-to-item collaborative filteringRecommending neighbours of a user's items from a precomputed similar-items table
FulfilmentPicking, packing and shipping orders in fulfilment centres
Inventory reservationHolding stock for an order until it is confirmed or released
Cell-based architectureIndependent full copies of a workload, each serving a subset of customers
Cell routerThe thin layer that sends a request to its cell by partition key
Shuffle shardingGiving each customer a random small combination of workers
Static stabilityKeeping working through a dependency failure without reacting
Control plane / data planeThe part that makes changes / the part that serves requests
Avoiding fallbackPreferring reliable primaries, retries or always-on failover over rarely used fallback paths
Route 53AWS DNS service; shuffle-sharded name servers
CloudFrontAWS content delivery network
S3 durabilityS3 is designed for 11 nines durability across at least 3 AZs
Deployment safetyPractices that keep a change from causing a broad outage
One-boxDeploying to a single unit first
CanarySynthetic tests that run continuously against an environment
Bake timeWaiting and watching alarms after a stage before promoting
Prime DayAmazon's yearly sales event, with load numbers published each year
Builders' LibraryAmazon's published articles on how it builds and runs systems
InferenceA statement that is our reading, not a claim made in the cited sources

References ​

Built by Morteza Negahi