Summary#
The Amazon Builders' Library is a set of long articles by Amazon's senior engineers. Each one explains how Amazon runs one hard part of a distributed system: retries, overload, queues, caches, health checks, deployments, dashboards. This page reads 23 of those articles through one lens: what the authors assumed, what they built, which constraints are easy to miss, and what Amazon gave up to get there. The thread running through all of them is one idea. A system should behave the same way on its worst day as on its best day. Rarely used code paths, modal behaviour and synchronized clients are the enemy. Constant work, bounded queues, local decisions and boring, continuously exercised paths are the cure.
The articles were fetched from the AWS site in December 2026 (published between 2019 and 2025). One more entry in the Library, "Architecting and operating resilient serverless systems at scale", is a recorded talk with no article text, so it is not covered here; the serverless page covers the topic. Every company fact below comes from them. Where the page adds math, analogies or general engineering context, that is the handbook's own explanation.
Why It Exists#
Most outages at large companies are not caused by one broken server. They are caused by healthy parts reacting badly to a small failure. A database slows down a little. Clients time out and retry. The retries add load. The database slows down more. Every layer above it retries too. Within minutes a 5% problem has become a 100% outage, and it stays that way after the original cause is gone. Amazon's engineers have names for every piece of this spiral: retry amplification, positive feedback loops, modal behaviour, insurmountable backlogs, correlated failure.
Textbooks teach the building blocks: replicas, load balancers, queues, caches. They rarely teach how those blocks misbehave together under stress. The Builders' Library is valuable because it is written by people who were paged when the blocks misbehaved. Its advice is often the opposite of the intuitive answer:
- Intuition says "add a fallback". Amazon says fallbacks are rarely tested and often make outages worse.
- Intuition says "a queue makes the system more available". Amazon says a queue can turn a one-hour outage into a five-hour recovery.
- Intuition says "health checks should test every dependency". Amazon says deep health checks can take a whole fleet out of service at once.
- Intuition says "only push configuration when it changes". Amazon says push the whole configuration every few seconds, whether it changed or not.
This page uses the four-step learning approach from the engineering-blog list it comes from. For each article it asks:
- Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
- Production architecture. What did Amazon actually build?
- Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
- Sacrifice. What did Amazon give up to get the benefit?
How It Works#
The 23 articles group into six families. The diagram shows how they connect. Each family answers one question about a request's life: how it is sent, how the server protects itself, how work is queued, how the fleet survives failures, how code changes safely, and how humans see what is happening.
Lesson 1: Timeouts, retries, and backoff with jitter#
Assumptions. Calls inside one AWS Region usually take a few milliseconds. Most failures are partial (some requests fail) or transient (requests fail for a short time). Traffic arrives in bursts, not at a smooth rate. Bursts come from client behaviour, from recovery after an outage, and from things as simple as cron jobs that fire on the minute.
Production architecture. Amazon's rule is that every remote call gets a timeout, and so does every call between processes on the same machine. That means both a connection timeout (how long to wait for a connection to open) and a request timeout (how long to wait for the answer). To pick the value, a team chooses an acceptable rate of false timeouts: calls that would have succeeded if the client had waited a little longer. Suppose the team accepts 0.1%. They then look up the downstream service's p99.9 latency and set the timeout there. The article lists three cases where this simple rule breaks:
- Clients across the internet. Network latency dominates there, so the timeout must cover a reasonable worst-case global round trip.
- Tight latency distributions. If p99.9 sits close to p50, a timeout at p99.9 trips on tiny slowdowns. Add padding.
- Timeouts that miss work. Some timeout settings do not cover DNS lookups or TLS handshakes. The article singles out Linux
SO_RCVTIMEO, a per-read socket timeout, as unsuitable for an end-to-end deadline.
The article tells a story about the last case. A team had set a 20 ms timeout to a dependency. It worked all day, except just after deployments, when a few calls timed out. The timer included opening a new TLS connection, and a handshake took longer than 20 ms. Connections were reused afterwards, so only the first calls on fresh servers failed. The first fix was a longer timeout when a new connection was being made. The better fix was to open connections at process start, before the server took traffic.
Retries come next. The article calls retries selfish: a client that retries spends more of the server's capacity to raise its own chance of success. That is fine when failures are rare. It is harmful when failures come from overload, because each retry adds load to a server that is already failing from too much load. Amazon's default is capped exponential backoff: wait longer after each failure, up to a ceiling, and give up after a small number of attempts.
Jitter solves a subtler problem. If 10,000 clients all fail at the same moment and all back off by exactly 100 ms, they all retry at the same moment, 100 ms later. Backoff alone just moves the spike. Adding a random component to each wait spreads the retries across the window. Amazon applies jitter far beyond retries: to every timer, periodic job and delayed task. The article says that on Amazon EBS and AWS Lambda, clients sending work "once per minute" from many servers lined up in the first seconds of each minute. Jittering those schedules did the same work on less server capacity.
There is a twist for scheduled work. Amazon does not pick a fresh random offset on each run. It derives a consistent offset per host, for example from a hash of the host name. A host then fires at the same offset every time. If that pattern overloads something, it does so repeatably, and humans can spot repeatable patterns. Truly random jitter makes such overloads appear at random, which is much harder to debug.
Overlooked constraints.
- Retries multiply across layers. Picture five layers of services, each trying 3 times. When the database at the bottom fails, it receives 3⁵ = 243 attempts for every user request. The database will not recover under that load. Amazon's rule is to retry at one point in the stack, usually near the top, for cheap operations.
- Circuit breakers have a cost. A circuit breaker stops calling a dependency once errors pass a threshold. It is widely recommended. Amazon notes it adds modal behaviour: the system has a second operating mode that is hard to test and can slow recovery. Amazon's preferred limiter is a local retry token bucket. Each retry spends a token. When tokens run out, retries continue only at a small fixed rate. The AWS SDKs have shipped this behaviour since 2016.
- Only idempotent calls are safe to retry. A call is idempotent if repeating it has the same effect as doing it once. Read-only calls usually are. "Create" calls usually are not, unless the API adds a token (Lesson 2).
- 4xx vs 5xx is blurry. HTTP says client errors (4xx) should not be retried and server errors (5xx) may be. Eventual consistency breaks this rule. A "not found" error can turn into a success a moment later, once a write propagates.
What Amazon sacrificed. Every timeout below p100 means some calls fail that would have succeeded. Amazon accepts a fixed false-timeout rate, about one call in a thousand in the example, to keep slow calls from tying up threads, memory and ports. Capping retries means some transient failures are passed upward instead of hidden. Amazon prefers to surface them rather than risk amplifying an overload.
Deep Dive: the arithmetic of retry amplification and jitterShow
Layered retries. With k layers and r attempts per layer (one try plus retries), the bottom layer sees r^k attempts per top-level request when everything fails. With 3 attempts and 5 layers that is 243. With 2 attempts it is still 32. Even "just one retry" at every layer is dangerous in a deep call graph.
Retry budgets. A token bucket holds a fixed number of tokens, say 10. Each retry spends one. Each success adds back a fraction, say 0.1 tokens. In steady state with a 1% error rate, a client earns about 0.1 tokens per 1% of calls and spends 0.01. The bucket stays full and every failure is retried. When errors jump to 50%, the bucket drains after about 20 failures. From then on, retries are limited to what successes earn back: about one retry per 10 successes, roughly a 10% retry rate, instead of 100%. The overloaded server sees about 1.1× its normal load, not 2×. Library names vary: AWS SDKs call it "retry quota", gRPC calls it "retry throttling", Finagle calls it "retry budget".
Why jitter works. Suppose N clients fail at the same instant and each waits a uniformly random time between 0 and W. The expected arrival rate during the window is N / W. Without jitter it is N requests in one instant. With N = 10,000 and W = 1 s, jitter turns a 10,000-request spike into about 10 requests per millisecond. The companion article on AWS's architecture blog, "Exponential Backoff and Jitter" (Marc Brooker, 2015), compared variants in simulation. "Full jitter" picks a random wait between 0 and the capped exponential value. It finished the work with far fewer total calls than backoff with no jitter. Its cost is a slightly longer completion time for the unluckiest clients.
Consistent per-host jitter. A common recipe is offset = hash(hostname) mod period. It spreads hosts evenly, like random jitter, yet a given host keeps the same slot. Overload then appears as a stable pattern on a graph, which an engineer can trace to the hosts in that slot.
Lesson 2: Making retries safe with idempotent APIs#
Assumptions. Big workflows at Amazon are built by a controlling process that calls many small services. Launching one EC2 instance involves a placement service, EBS volume creation, network interface creation and VM provisioning. Any of those calls can fail. The simplest way to drive the workflow to success is to retry each call until it works. That only holds if a retry cannot create a second copy of anything.
Production architecture. The article starts with a customer who wants exactly one instance running, a singleton workload. Their provisioning script calls RunInstances and gets no reply because the network timed out. Did the instance launch? A plain retry might start a second one. The alternative is a reconciliation step: list what exists and work out what happened. That is heavy work for a rare case, and even then the script cannot tell whether an instance it finds was created by this request or by some other process.
Amazon's answer is a caller-provided client request identifier. In EC2 it is called the ClientToken. The client generates a unique ID per logical request and sends it with every attempt. The server keys an "idempotency session" by caller identity plus token.
- First request with that token: process it normally.
- Repeat with the same token: return a response with the same meaning as the first one.
Two details make this work in production:
- Atomic bookkeeping. Recording the token and making the changes must be one ACID operation. Otherwise a crash could leave the token recorded but the resource missing, or the reverse.
- The token is visible. It appears in CloudTrail logs and in
DescribeInstancesoutput, so a customer can see which request created which resource.
Amazon rejected a tempting shortcut: treating two requests with identical parameters as duplicates. For two "create table" requests a second apart, that guess is probably right. For "launch an instance" it is wrong, because a customer may really want two identical instances. Only the caller knows their intent, so only the caller can say "these two are the same request".
Semantic equivalence. What should a retry return when the first attempt already succeeded? Returning ResourceAlreadyExists causes no extra effect on the server, so technically the API is idempotent. But the client now sees an error for a request that, from its point of view, succeeded. That changes the client's control flow and makes automatic retry unsafe. Amazon instead returns a semantically equivalent response: the same instance ID and the same token, with the current state. The first answer said pending. A retry a few minutes later says running. The AWS SDKs and CLI generate a token automatically for operations that support one and reuse it on every retry. Calling code never knows a retry happened.
Overlooked constraints.
- Late arrivals. A retry may arrive after another actor has deleted the resource. EC2 still honours the original contract and returns the equivalent response, now showing
terminated. Amazon calls this following the principle of least astonishment. - Retention. The server cannot remember tokens forever. Storage grows, and a future collision with an old token would surprise someone. For EC2 instances Amazon keeps a token for the resource's lifetime plus an interval after which any late retry would no longer be valid.
- Changed parameters. If a known token arrives with different parameters, Amazon assumes the caller meant a different request and returns a validation error. To check this, the server stores the original parameters alongside the token.
What Amazon sacrificed. The server stores every token, its parameters and its result for a long time. It does that bookkeeping atomically with the real work, and it builds equivalent responses for retries. The article says plainly that this contract has a cost. Some services are better off moving faster with a weaker contract. Amazon pays the cost where "at most once" truly matters, as when launching paid compute.
Lesson 3: Avoiding fallback in distributed systems#
Assumptions. When a critical call fails, there are four broad responses:
- Retry the call.
- Proactive retry (also called hedging): send several copies of the call in parallel and use the first answer.
- Failover: send the same call to another copy of the endpoint.
- Fallback: use a different mechanism to get a similar result.
The article argues that Amazon almost never uses fallback.
The single-machine view. On one machine, a common pattern is to exit when malloc fails, because the whole machine is probably out of memory. Suppose you add a malloc2 that allocates memory another way when malloc fails. That fallback is:
- Hard to test. You would need to recreate a real low-memory state at exactly the right moment.
- Able to fail itself. Then you need a fallback for the fallback.
- Puzzling. If
malloc2were better, why not always use it? It must be worse somehow, for example slower because it uses disk. - Able to deepen the trouble. The machine is already struggling, and a slower allocator adds a second problem.
- A latent bug. It might first run years after it was written, when nobody remembers how it works.
Even innocent fallback logic can change a system's character. Logging a stack trace on every error is harmless until errors spike. Then a CPU-bound service suddenly becomes disk-bound. When a critical single-machine program truly must survive memory exhaustion, Amazon pre-allocates all heap memory at startup. It did this in monitoring daemons on production hosts and in the EC2 daemons that track customers' CPU bursts.
The outage that taught the lesson. Around 2001, amazon.com added shipping speeds to product pages. That data lived in the supply-chain database, and a page could show 25 or more products. The database could not keep up with web traffic, so the team put a cache process on each web server. They also wrote a fallback: if the cache was unhealthy, query the database directly. It worked for months. Then the caches all failed at about the same time. Every web server hit the database, and the database locked up. Web processes blocked waiting on it, so the whole website went down. That same database served the fulfillment centers, so fulfillment stopped worldwide. The fallback turned a missing page widget into a company-wide outage.
The logic was circular. If the database could serve the traffic directly, the cache was not needed. If it could not, the fallback was a trap. The bug also stayed hidden for months, because it only fired when many caches failed together.
What Amazon does instead.
- Make the primary path more reliable. For example, use a store with higher built-in availability, such as DynamoDB, instead of switching between two stores. The article cites DynamoDB carrying amazon.com on Prime Day 2017.
- Let the caller handle the error. AWS SDKs and CLIs already retry. A clean error is often better than a clever substitute.
- Push data ahead of time. Remove the remote call from the critical path. IAM role credentials for EC2 are pushed to every instance and stay valid for hours. If the push system breaks, instances keep working with the credentials they already have.
- Turn fallback into failover. If you need a second path, run it all the time. Use both answers, or pick randomly between them, so the second path is proven every second rather than once a year.
- Keep retries from becoming fallback. Track retry rates and alarm when they rise, because rare retries are another untested mode. Better still, use proactive retries all the time, as in quorum reads (ask 3 replicas, use the first 2 answers). The redundant load is constant, so it does not rise during an outage. This links to constant work (Lesson 13).
Overlooked constraints. "Graceful degradation" is not banned. The rule is narrower: a critical path must not switch to an untested mechanism that puts more load on a shared dependency. Hiding a widget (fail closed) is fine. Hammering the database because the cache died (fail over to a weaker path) is not.
What Amazon sacrificed. Without a fallback, some failures show up as errors that a fallback might have hidden. Amazon trades a slightly worse best case for a much better worst case: fewer cascading outages, shorter recovery, and less dormant code.
Lesson 4: Using load shedding to avoid overload#
Assumptions. Under heavy load, servers get slower. Threads contend for locks, context switches pile up, garbage collection runs longer and I/O queues grow. Past an inflection point, latency climbs steeply. The article ties this to the Universal Scalability Law, an extension of Amdahl's law. Throughput is limited by the parts of the work that cannot run in parallel, and contention can make throughput fall as you add load.
The key distinction: throughput vs goodput. Throughput is every request the server receives per second. Goodput is the subset answered correctly and in time for the client to use it. Once median latency reaches the client timeout, half the requests time out, so availability is 50%. Yet the server is still busy doing all of that work. The overload also feeds itself:
- Timed-out requests are wasted work.
- Clients retry, which multiplies the incoming load.
- Layered retries multiply it again.
Overload becomes a stable state, not a passing spike.
Production architecture. Load shedding means a server near its limit rejects some requests quickly, so the requests it accepts finish in time. Goodput then levels off at the server's capacity instead of collapsing. The article's practical rules:
- Test far past the breaking point. If you have not load-tested well beyond where the service breaks, assume it will fail in the worst possible way. The ideal test result is goodput that flattens near full use and stays flat as load keeps rising. One useful technique: run steady load against a test fleet and remove servers one by one. This pushes per-host load up without needing a bigger load generator.
- Measure from the client side too. Server-side numbers can look healthy while clients time out.
- Make rejection cheap. A stray log line or socket setting can make rejecting a request nearly as costly as serving it. In rare cases a fast rejection is worse than holding the request, because clients retry instantly. Then Amazon delays rejections until about the latency of a success, but only where holding a request costs little, for example not tying up a thread.
- Prioritize. The most important request is the load balancer's health check. If a server is too busy to answer it, the load balancer removes the server, and the remaining fleet gets even more overloaded. After health checks, priorities depend on the service. A search-engine crawler is less urgent than a human shopper. Clients who burst above their quota rank below clients within quota.
- Watch the clock. If the client has already given up, finishing the request is pure waste. Clients send a timeout hint, either an absolute deadline or a duration. Absolute deadlines need synchronized clocks, which is one reason the Amazon Time Sync Service exists. Durations need a monotonic timer and a clear start point. Requests can sit in TCP buffers before the server even reads them, so the server's stopwatch starts late. Amazon passes the remaining time down every hop of a call chain and drops doomed requests when they come off a queue.
- Finish what you started. Wasted work feeds the overload loop, so services do bounded work per request, using pagination instead of unbounded lists. If clients must call
start()and thenend(), prioritizeend(); otherwise clients start tasks they cannot finish. Likewise, prefer later-page requests over first-page requests, so clients do not throw away N−1 pages of work. - Watch the queues. Bound both the length of every in-memory queue and the time a request may wait in it. Drop requests that are too old. Where the protocol allows, use LIFO order (last in, first out), so the freshest requests, whose clients are still waiting, go first. HTTP/2 allows this; HTTP/1.1 pipelining does not. Classic ELB had a surge queue that hid how long a request had waited. The Application Load Balancer instead fails fast when it is full.
- Protect in layers. A proxy cap like NGINX
max_connsis a crude last resort: it cannot tell important traffic from unimportant. Amazon's guidance is to set load balancer and proxy limits high and let the server shed load using its own local knowledge. Keep enough threads and file descriptors free to answer health checks.iptablescan reject connections far more cheaply than any application. It can also limit the connection rate per source IP, which works behind a Network Load Balancer because NLB preserves the client's source IP. In front of everything, API Gateway rate limits and AWS WAF can drop excess traffic before it reaches the service.
Visibility.
- Track false rejections. A rejection while the server still had spare capacity is a false positive. The target rate is zero.
- Log who was shed. Record the client and the operation for every shed request.
- Keep shed requests out of latency metrics. Rejections are fast, so including them hides slow successes. If a service sheds 60% of requests, the median latency can look excellent while every real request is slow.
Overlooked constraints.
- Shedding can silence autoscaling. Suppose the shedder holds CPU at 60% and autoscaling triggers at 60% CPU. The scaler never sees a reason to add hosts.
- Shedding hides lost headroom. Amazon sizes fleets so that losing one Availability Zone still meets latency goals. A fleet that is shedding may be much closer to its limit than CPU graphs suggest, so it may not survive losing a zone.
- Deliberate shedding needs agreement. A team might decide not to provision zone-failure headroom for crawler traffic and shed it instead. Clients must know, or a zone failure will look like a sudden outage to them. Amazon makes such decisions as early as possible, at the service that first receives the request, so different layers do not apply conflicting priorities.
What Amazon sacrificed. Shedding deliberately fails some requests. Amazon accepts lower raw availability to protect the latency of accepted requests. It also accepts hard tuning work: the article opens with years of failing to find good default connection limits for its service framework. Its closing point is that per-request isolation in Lambda and Fargate sidesteps some of this tuning. Each invocation has its own resources, so one request cannot slow another on the same host. Goodput stays flat without hand-tuned limits.
Lesson 5: Putting the smaller service in control#
Assumptions. AWS systems split into a data plane and a control plane.
- Data plane: the servers that execute customer requests. In EC2 these are the physical hosts running instances.
- Control plane: the services that manage configuration. In EC2 they tell hosts which instances to run, update VPC settings, collect metering data and deploy software.
The two must stay in sync. The data plane is often more than 100 times larger than the control plane.
The default design and its trap. The simplest design has each data plane host call the control plane's API, periodically or on demand. The control plane sits behind a load balancer, answers from its database and forgets the caller. It is stateless and easy to run. In steady state, calls from many hosts arrive at random times and load is smooth. The trap is correlation. Several things can make hosts call at the same time:
- A bug or config change that raises the polling rate.
- Recovery after an outage, when every host reconnects at once.
- A few failures that trigger retries, which cause more failures and more retries.
One small change makes 100 times as many clients act together. Concurrent load passes the control plane's breaking point, and its goodput falls to zero. Load shedding on the control plane and jittered retries on the hosts help, but they need careful tuning.
Production architecture: three ways to let the small fleet set the pace.
- Use S3 as the middleman. The control plane periodically writes the whole configuration into an S3 bucket. Data plane hosts poll the bucket and cache the file locally. Operational state flows the other way through another bucket. S3 is built for huge numbers of readers, so the control plane can stay small. If it goes down, hosts keep running on the last known configuration. That property is static stability (Lesson 10). AWS Hyperplane, the network system behind Network Load Balancer, NAT Gateway and PrivateLink, works this way. A periodic job scans DynamoDB tables of customer configuration and writes S3 files; the data plane downloads them and updates its routing.
- Reverse the direction. When configuration is too large and dynamic to recompute often, as in EC2, or must arrive within seconds, as for a container service, the control plane pushes to the data plane. An overloaded control plane then slows down but keeps making progress, instead of collapsing. The costs are real. The control plane needs an up-to-date inventory of hosts. It must handle unreachable hosts. Every host needs exactly one owner, with no control server owning too many. Amazon assigns hosts with consistent hashing. Each control server writes a heartbeat to a shared table such as DynamoDB. Each one reads the list of live peers and computes the same hash ring, so it knows which hosts are its own.
- Decouple discovery from control. Each data plane host opens one long-lived connection to a control server behind a Network Load Balancer. After that, the control server drives the conversation over that connection, much like a server push. A busy control server can refuse the connection, and the host tries another. This keeps the overload resistance of option 2 without a host inventory or a hash ring. Every decision uses only local state. The cost is a more complex protocol. At extreme ratios, 1,000 to 1 or more, a host sends only a small UDP message and waits for the control plane to connect back. A TCP plus TLS handshake per host would by itself overwhelm the control plane. A variant of this is how EC2 control planes push configuration to the Nitro system.
Overlooked constraint. The dangerous number is the ratio between fleets, not the absolute load. A design that works at 10 to 1 can fail at 100 to 1 with no change in steady-state traffic, because the worst case is "all clients at once".
What Amazon sacrificed. Option 1 adds propagation delay: config is only as fresh as the last S3 write plus the polling interval. Options 2 and 3 replace a simple stateless API with membership tracking, hash rings or a custom protocol. Amazon accepts that complexity to keep the small fleet from being overwhelmed.
Lesson 6: Avoiding insurmountable queue backlogs#
Assumptions. Queues make asynchronous systems more durable. A message survives server crashes and dependency outages and is retried until it succeeds. Many Amazon systems rely on queues:
- Order fulfillment at amazon.com.
- Amazon RDS, which waits for EC2 instances before configuring databases.
- CloudWatch, which batches metrics and logs.
- Lambda's asynchronous invocations, which return at once and run the function later, with retries.
- AWS IoT Core, which delivers MQTT messages to devices that may be offline.
Many of these use SQS, which gives at-least-once delivery: a message may arrive more than once, but is not lost.
The hidden risk: bimodal behaviour. A queue-based system has two modes:
- Fast mode: no backlog, and messages are processed in milliseconds.
- Slow mode: a backlog builds whenever arrivals outpace processing, for example during an outage or a surge. End-to-end latency then grows by the minute.
Draining the backlog takes spare capacity, not just normal capacity. Suppose processing stops for one hour while messages keep arriving. To catch up within the next hour, the system needs twice its normal capacity: one share for new work and one for the backlog. If dependencies cannot take double load, recovery takes longer still. Synchronous systems drop requests during an outage and recover the moment it ends. Asynchronous systems keep every request and pay for it afterwards.
A worked example from the article shows the scale. A customer's unthrottled spike creates a system-wide backlog. It takes about 30 minutes for an operator to notice, understand and mitigate it. Meanwhile, the producers have scaled up and enqueued 10 times what the consumers can process. Working through that takes about 300 minutes. A half-hour spike becomes a five-hour outage.
Measuring asynchronous health.
- Producer-side errors only reflect the queue's own availability: SQS's, not yours.
- Consumer-side errors overstate trouble, because many failures succeed on retry.
- Dead-letter queue (DLQ) volume is a true failure signal but arrives too late to detect problems.
- Message age is the best latency signal: now minus enqueue time, measured on dequeue. SQS gives every message a timestamp.
AWS IoT refines message age. AgeOfFirstAttempt measures only messages being delivered for the first time. It ignores devices that are offline or deliberately reading slowly, which are expected to build small backlogs. AgeOfFirstSubscriberFirstAttempt times only the first subscriber's delivery, because a topic with a million subscribers is naturally slower to fan out than a topic with one. First-attempt latency is tracked separately from retry latency across Amazon. A request ID travels inside each message, so traces can be stitched together across hops, for example with X-Ray.
Production architecture: the anti-backlog toolkit.
- Never expose an internal queue directly. Callers go through a thin API that authenticates them, tags each message with the caller's identity and applies per-customer rate limits with bursting. Limits grow as customers grow. They are guardrails that buy time for provisioning, not hard ceilings.
- Protect every layer. Some work always slips past the front door, so each component needs its own protection.
- Use one queue per workload when there are few workloads. With many, polling every queue costs too much; IoT cannot have a queue per device.
- Shuffle-shard the queues. Lambda provisions a fixed set of queues and hashes each customer to a few of them. Each new message goes into whichever of the customer's queues is shortest. A spiking customer backs up only its own queues, and other customers' messages flow around them. A small number of queues gives strong isolation (the math is in Lesson 11).
- Sideline excess traffic. When a consumer dequeues a message from a customer over its rate, it moves the message to a spillover queue. That queue is drained when capacity frees up. This approximates a priority queue.
- Sideline old traffic. Move messages older than a threshold to a backlog queue that is processed only after the live queue is caught up. This approximates LIFO, which real-time customers prefer: fresh data first, history later.
- Drop stale messages. If an anti-entropy sweeper periodically re-syncs full state, deltas older than the last sweep can be dropped cheaply.
- Limit concurrency per workload. Little's law says concurrency = arrival rate × latency. At 100 messages/s and 100 ms per message, a workload uses about 10 threads. If its latency jumps to 10 s, it needs about 1,000 threads and can starve everyone else. The IoT rules engine routes messages to customer endpoints such as Elasticsearch clusters or Kinesis streams. It uses non-blocking I/O, a per-workload semaphore, rate limits that adapt over time, and separate thread pools per workload.
- Send backpressure upstream. Shrink a workload's intake throttle in proportion to its backlog. This only works if the backlog can be measured per workload. SQS reports total depth, not depth per attribute, so on a shared queue backpressure would also hit innocent tenants. Amazon's order pipeline deliberately does not apply backpressure. It keeps accepting orders and prioritizes the most urgent ones.
- Use delay queues. Re-enqueue deferred work with a delivery delay of a few minutes, so fresh work goes first.
- Watch in-flight limits. SQS caps how many messages can be in flight (received but not yet deleted). A bug that forgets to delete messages fills this cap until the visibility timeout expires. SQS FIFO queues only look at the 20,000 oldest unprocessed messages. A backlog in a few message groups can starve every other group.
- Alarm on any DLQ message. A message in the DLQ means a bug. The DLQ keeps the message so it can be reprocessed after the fix.
- Keep polling headroom. If every poll returns a message, consumers are at capacity, and the next spike becomes a lasting backlog. Track the share of empty polls as a headroom signal.
- Heartbeat long jobs. When processing outlives the visibility timeout, SQS gives the message to a second consumer, then a third, and so on. That is a self-inflicted fork bomb that gets worse as the system slows. Consumers either stop when the timeout passes or extend it with heartbeats, much like renewing a lease.
- Plan for cross-host debugging. Record queue depths, propagate trace IDs, and use a workflow service such as Step Functions for complex flows.
What Amazon sacrificed. Shuffle-sharded and sidelined queues give up strict FIFO order across a customer's messages. TTL drops give up some deltas, relying on the sweeper to repair state. Per-workload limits mean a large customer can be throttled while total capacity sits idle. Amazon chooses bounded recovery time over perfect ordering and maximum utilization.
Lesson 7: Using dependency isolation to contain concurrency overload#
Assumptions. Overload comes in two shapes. The first is more requests: a lunch-time surge. Load shedding and rate limits (Lessons 4 and 8) handle that. The second is slower requests: the arrival rate stays flat, but each request takes longer because a dependency slowed down. The article uses a bank branch as its picture. Tellers are threads, the line is the queue, and a network outage that makes every transaction slower fills the bank just as surely as a crowd does. The second kind of overload does not start with the callers, so front-door limits cannot see it.
Production architecture. The core tool is Little's law: concurrency = arrival rate × latency. Triple the arrival rate or triple the latency and you get the same tripled concurrency. Concurrency is what servers actually run out of. Even an idle request, parked while it waits on a database, holds:
- Memory. If the host runs out, the kernel's out-of-memory killer may pick the server process, or a helper process the service quietly needs, which produces a gray failure (the service looks up but misbehaves).
- File descriptors, one per open socket or file, capped per process.
- Connection pool slots to databases and HTTP dependencies.
- Threads, if the code blocks. Non-blocking I/O frees threads but only moves the bottleneck to the other resources in this list.
- Queue space. A bounded FIFO queue still causes harm: by the time old work is dequeued, its caller may have given up, and the server does it anyway.
Amazon's answer is a bulkhead: a separate concurrency limit per dependency or per group of APIs. The name comes from the walls that divide a ship's hull so one leak floods one compartment. The simplest version is an overall limit: count up when a request starts, count down when it ends, and reject new work above a ceiling. The better version splits that limit. The article's example is a BankService with two APIs. TransactCheck needs only a ledger. TransactCash needs the ledger and a slow VaultService. With a separate limit for each, a slow vault fills only the cash compartment, and check deposits keep flowing. In a threaded server that could be two thread pools. Amazon usually prefers one pool plus a counter per API, because counters can be changed at runtime while pool sizes typically cannot.
There are three ways to divide the budget. Say load tests show the service handles 50 concurrent requests whatever the mix.
| Allocation | Example | Strength | Weakness |
|---|---|---|---|
| Hard | 25 per API | A slow dependency can take at most half | Errors at low utilization if the mix shifts to one API |
| Soft | 35 per API, 50 total | Absorbs an uneven mix | A slow API can hog 35 slots and leave only 15 |
| Dynamic | Borrow the shared buffer briefly, then shrink back | Absorbs bursts and limits long slowdowns | Complex, hard to prove correct for every workload |
A related framing labels work droppable or non-droppable. Above, say, 90% of maximum concurrency, the server accepts only non-droppable work. More tiers can be added, each with its own threshold. Amazon's stated rule is to start with the simplest scheme and add complexity only after testing or operations prove it is needed.
Real services apply this in several places:
- Lambda's worker manager. When an invoke arrives, the worker manager either finds a warm execution environment (fast path) or asks the placement service to create one (slow path). It cannot know in advance which path a request will take, so it uses one thread pool but caps how many threads may wait on placement. If placement slows down, warm invokes still have threads.
- Lambda per-function concurrency. Customers can reserve concurrency per function. Splitting APIs into separate functions gives each its own bulkhead, so this is Amazon's internal pattern sold as a feature.
- The EC2 control plane. EC2 has one Regional endpoint, so callers can describe an instance by ID without knowing its Availability Zone. That front end does only validation, authentication, authorization and AZ lookup. It then forwards the request to a zonal service that shares fate with that zone. The Regional front end keeps strict resource isolation, including separate thread pools and concurrency limits for each zone. Trouble in one zone then cannot use up the front end.
- Splitting services. If an API has different dependencies and failure modes, running it as its own service is the strongest bulkhead. Application Load Balancer or API Gateway can keep one public endpoint in front while routing different paths to different fleets.
Overlooked constraints.
-
Timeouts are not bulkheads. If a call normally takes 10 ms and its timeout is 100 ms or 1 s, a slow dependency still multiplies concurrency by 10 or 100 before any timeout fires. Retries make it worse because they hold the slot longer. Amazon sets timeouts for other reasons, chiefly to match its own caller's timeout so it does not keep working after the caller has gone. Concurrency is controlled by the bulkhead.
-
The dependency may not be slow at all. If a dependency starts throttling and the SDK retries with backoff, the calling code slows down even though each remote call is fast. Likewise, a
ListTransactionsAPI that usually needs one 10-row page from the database needs ten back-to-back pages when clients ask for 100 rows. Remote latency is unchanged, but the business logic takes ten times longer. So the bulkhead must wrap the code path that uses the dependency, not just the network call. Constant work (Lesson 13) removes this kind of modal behaviour at the source. -
Caches create two modes. With a cache in front of
VaultService, cache hits are fast and misses are slow. If misses and hits share one limit, a slow vault lets misses fill the service and hits fail too. Limit only the concurrency of calls to the vault, and cache hits stay available during the vault outage. -
Partitioned dependencies confuse circuit breakers. DynamoDB partitions have their own limits; the article cites 3,000 reads per second per partition at the time it was written. One hot partition in a 10-partition table cuts availability to 90%, not 0%. A single circuit breaker around "DynamoDB" sees a burst of throttles from that one partition, opens, and fails requests that healthy partitions would have served. The false-positive blast radius is then bigger than the real one. Fixes, from best to worst:
- Use a partition-aware breaker when the client knows the partitioning, as with a client-sharded Memcached or Redis cluster.
- Scope the breaker to the table, which has its own limits.
- Feed partition keys into a heavy-hitters algorithm to spot a hot key.
Even an imprecise breaker beats none, because without it the hot partition would use up the whole service's concurrency.
-
Untested breakers do not work. Amazon instruments each bulkhead's concurrency at the start of every request and graphs median and maximum. It also deploys new bulkheads in "instrumentation only" mode first, to check that the limit would not reject real traffic, before switching to enforcement. It then tests them with fault injection, for example AWS Fault Injection Simulator.
What Amazon sacrificed. Hard and soft limits reject work while the server has idle capacity, and a coarse breaker rejects calls that a healthy partition would have served. Splitting services adds deployment, monitoring and on-call overhead. Amazon also states a preference for failing fast over queueing. With deep synchronous call chains, upstream services can hide a fast error with techniques such as serving stale cache, but latency is hard to hide and uses up resources everywhere. The bulkhead turns a slowdown into fast errors for one feature so the rest of the service stays quick.
Deep Dive: sizing bulkheads with Little's lawShow
Start from measured numbers. Say an API receives 400 requests per second and its dependency normally answers in 25 ms. Little's law gives 400 × 0.025 = 10 concurrent requests in steady state. Peak traffic is 2× the average, so plan for 20.
Ask what a slowdown does. If the dependency's latency rises to 1 s (its timeout), the same 400 requests per second need 400 concurrent slots. If the server's safe total is 200, this one API would starve every other API on the box. A bulkhead of, say, 40 slots (2× peak) means that during the slowdown this API serves 40 requests per second at 1 s each and rejects the other 360 at once. Every other API keeps its full capacity.
Pick limits from instrumentation, not guesses. In "instrumentation only" mode, record the bulkhead's concurrency at each request start for a week. Set the limit above the observed peak, often at 1.5× to 2×, so that it trips only in the slow mode. Alarm when concurrency approaches the limit, so a limit that has grown too small is found before it rejects real traffic.
Why per-API counters beat per-API thread pools. A counter is one atomic increment and one atomic decrement per request. Its limit is a config value that can change while the process runs. Separate thread pools waste memory on idle threads and usually need a restart to resize. Non-blocking servers have no threads to divide anyway, so a counter is the only option.
Relation to library bulkheads. Resilience4j, the Java library, offers a semaphore bulkhead, which is the counter, and a thread-pool bulkhead. The Amazon article calls bulkheads a kind of circuit breaker: both fail new work fast when things are not working well, and both shed load so the system can recover. The difference is the trigger. A classic breaker trips on error rate. A bulkhead trips on concurrency, which catches slowness that never produces an error.
Lesson 8: Fairness in multi-tenant systems#
Assumptions. A multi-tenant system serves many customers or workloads on shared resources. Sharing is the point: higher utilization, less hardware, fewer people to operate it, and less energy. The article's working assumption is that tenants' loads are uncorrelated. So when total load jumps suddenly, the jump almost certainly comes from one tenant. Fairness means every tenant should feel like the only tenant.
The author's history explains why Amazon cares. In the mid-2000s, his team ran website-fleet tools (deployment, forecasting, auditing) on self-managed MySQL. Adding a new tool's tables to an existing, lightly loaded database was tempting. Then one night the deployment tool slowed down. The cause was a separate fleet auditor's nightly sync cron job hammering the same database. The auditor did not care about latency; the deployment tool's users did. Single-tenant databases used as multi-tenant ones gave the worst of both worlds. RDS made separate databases cheaper to run. DynamoDB, which the author joined to launch in 2012, went further: a table gets a fraction of several servers across AZs, and the fraction grows and shrinks with the workload.
Production architecture. Fairness systems resemble bin packing, the classic computer science problem of fitting items into as few bins as possible:
- Place new workloads on servers with room.
- Watch each workload and server, and move workloads off servers that get too full.
- Grow or shrink the fleet as total use changes.
- Let workloads stretch past their allocation while the server has idle capacity, and hold them to it when the server is full.
Advanced systems also predict which workloads coexist well and pair them, so one can borrow what the other is not using. Borrowing must be invisible. When the lender wants its capacity back, it must get it almost at once, and a borrower that has grown used to extra capacity must be moved to another bin quickly.
At the front door, two mechanisms work together:
- Load shedding returns HTTP 503 when the server itself is out of capacity, buying time for Auto Scaling. Amazon prefers consistent latency for admitted work over slowness for all, because slowness spreads through a distributed system.
- Per-tenant quotas return HTTP 429 when one tenant exceeds its own plan. The unplanned part of one tenant's load is rejected, and everyone else keeps steady performance. Some older AWS services still send 503 for throttling, because 429 arrived only in RFC 6585 (2012) and AWS will not break existing clients.
A subtle detail ties back to Lesson 4. Behind a least-outstanding-requests load balancer, Amazon sometimes slows down error responses to match normal latency. Otherwise a server that answers errors instantly looks idle, and the balancer sends it even more traffic.
Kinds of quota. Count quotas limit how many things a tenant may have at once, like EC2 instances per account. Rate quotas limit requests per second. Quotas may apply per account or per resource, like a DynamoDB table. Expensive APIs get lower quotas. When cost is not known up front, for example a query that may return 1 KB or 1 MB, a service can charge the cheapest cost on admission, then debit the true cost after the call. The tenant's balance may go negative until time pays it back.
Hard vs stacked allocation. With hard allocation, three tenants each get a third of capacity, and a spiking tenant is capped at its third even if the others are idle. With stacked allocation, a tenant may burst into unused capacity, but owners reclaim their share first. Worked example from the article: tenant A has a 1,000 TPS quota. The service can handle 10,000 TPS and is serving 5,000. A spikes from 500 to 3,000 TPS. A hard limit rejects 2,000 TPS. A stacked limit serves them while there is room, drops them first when other tenants grow, and flags the overage to both A's operators and the service's operators.
Bursts are also shaped by use-case knowledge. EC2 instances and their EBS volumes are busiest at boot, while they download and start software. So EBS gives generous up-front burst quotas, which shortens boot times without weakening long-run fairness. Some services raise quotas automatically as tenants grow. Others keep them fixed on purpose because customers use them for cost control, for example Lambda's concurrency limit per function.
Layers of admission control. Amazon puts several layers in front of a service, so most rejected traffic never reaches the service fleet:
- AWS Shield for DDoS protection.
- AWS WAF rules, attached to CloudFront, Application Load Balancer or API Gateway.
- API Gateway throttling, on its own large fleet.
- The service's own local and distributed limits.
Local admission control is usually a token bucket. Each request takes a token. Tokens refill at the quota rate, up to a burst capacity. Too much burst defeats the limit, so Amazon sometimes chains two buckets: a low-rate bucket with a large burst, then a high-rate bucket with a small burst. Together they allow a large burst but bound how fast it can be spent. Guava's RateLimiter is one off-the-shelf local limiter.
Distributed admission control is harder because a tenant's traffic spreads across a fleet:
| Approach | How | Breaks when |
|---|---|---|
| Divide the quota | Each of N servers enforces quota ÷ N locally | Traffic is not uniform: connection-level balancing, few client connections, many load balancers with sticky DNS |
| Consistent hashing to rate trackers | Hash the throttle key to a tracker, for example in ElastiCache for Redis | One key is very hot, so its tracker becomes a hot spot; fall back to local limits as that key's rate climbs |
| Gossip observed rates | Servers share per-key rates periodically | Accuracy versus overhead trade-offs |
Reactive admission control handles the surprises: a buggy client sending malformed requests, an unexpectedly expensive workload, a customer asking for help blocking its own runaway traffic. Rules must match on attributes such as user agent, URI or source IP. They must load dynamically, keep an audit trail, and ideally run first in evaluation mode, which checks that a rule would hit the right traffic before it goes live.
High-cardinality keys (every IPv6 address, every DynamoDB item, every S3 object) cannot each get a counter in memory. Amazon uses heavy hitters, top talkers and counting Bloom filters, which bound memory at a known cost in accuracy. To see which keys dominate, it uses CloudWatch Contributor Insights.
Overlooked constraints.
- Quotas both raise and lower availability. A throttled tenant sees errors even when the service had spare capacity. So Amazon treats quotas as an inconvenience to minimize. Tenants need metrics showing use versus quota and alarms before they hit it; DynamoDB publishes consumed and provisioned throughput to CloudWatch. The service should also alarm when it throttles many tenants or a lot of traffic.
- Clients must react correctly. A synchronous caller should give up fast. Since the SDK's "standard" retry mode, the AWS SDK stops retrying when throttles are frequent. An asynchronous batch job should slow down instead, because finishing later is acceptable. An asynchronous job that must keep up behaves more like a synchronous one (Lesson 6).
- Measure the limiter itself. Log the throttle key and limit on every request. Compute true fleet-wide rates offline with CloudWatch Logs Insights or Athena. Then report false positives (wrongly rejected) and false negatives (wrongly admitted) per key.
- API shape drives quota pressure. The best fix is often an API that removes the need to poll. AWS separates data-plane APIs, which are expected to grow with use (S3 GetObject, DynamoDB GetItem, SQS ReceiveMessage), from control-plane APIs, which are meant to be called occasionally (S3 CreateBucket, DynamoDB DescribeTable, EC2 DescribeInstances). Data planes scale elastically and give burst room. Control planes get API redesigns:
- Change streams. Instead of polling
DescribeInstancesacross a growing fleet, consume CloudTrail's event log. - Exports to data-plane storage. S3 Inventory writes a manifest of a bucket's objects into an S3 object, which can be read at data-plane rates instead of calling
ListObjectsrepeatedly. - Bulk asynchronous APIs. AWS IoT bulk provisioning takes a file of changes and returns a file of results, so customers never write their own retry and rate-spreading loop.
- Project control data locally. EC2's instance metadata service gives each instance its own metadata without a remote call.
- Change streams. Instead of polling
What Amazon sacrificed. Quotas give up some customer throughput, and sometimes availability as customers see it, to protect everyone else. Stacked bursting gives up strict predictability for the bursting tenant, whose extra traffic can be cut whenever neighbours wake up. Distributed limiters give up exact accuracy to avoid a central counter on every request. Amazon's view is that, done well, fairness gives customers multi-tenant cost with single-tenant performance.
Deep Dive: composed token buckets and cost-based debitsShow
One bucket. A bucket with refill rate r tokens per second and capacity b admits at most b + r·t requests in any window of length t. With r = 100 and b = 1,000, a tenant idle for 10 seconds can fire 1,000 requests in a single instant. That might overload one server.
Two buckets in series. Bucket A has r = 100, b = 1,000. Bucket B has r = 500, b = 50. A request must take a token from both. Over a long window the limit is still 100 per second (bucket A's rate). But no instant can admit more than 50, and the burst can drain at no more than about 500 per second. The 1,000-token burst is spread over about two seconds instead of one moment, which is what downstream systems need.
Cost known only after the call. Admit every request at the minimum cost of 1 token. When the response is built, compute its true cost, say one token per 4 KB returned, and subtract the difference. A 1 MB response costs 256 tokens. The balance can go negative, and the tenant is then rejected until refill brings it back above zero. Such debt-based accounting keeps the admission check O(1) and still charges heavy queries fairly. It is the same idea DynamoDB applies with capacity units based on item size.
Why divide-by-N drifts. With 20 servers and a 1,000 TPS quota, each server allows 50 TPS. If a client keeps 4 long-lived connections and the load balancer pins each connection to a server, only 4 servers see its traffic. It is then capped at 200 TPS, a false positive of 80%. If it opens hundreds of short connections, the traffic evens out and the limit is accurate. That is why Amazon notes the issue fades at scale but bites for clients with few connections.
Bounded-memory counting. Space-saving style heavy-hitter algorithms keep k counters. Any key whose true share of traffic is above about 1/k is guaranteed to be tracked. So with 1,000 counters, any key above about 0.1% of traffic is found, using a few kilobytes of memory, however many distinct keys exist. A counting Bloom filter answers "has this key exceeded X?" with a tunable false-positive rate and no false negatives, at a few bits per key. The article points to research on hierarchical heavy hitters (Zhang et al., AT&T Labs, 2004) and to active queue management from networking, such as Random Early Detection (Floyd and Jacobson, 1993) and stochastic fairness queueing (McKenney).
Lesson 9: Leader election in distributed systems#
Assumptions. Leader election gives one process special powers: to assign work, own a piece of data, or handle every request. Amazon's starting position is caution. Before adding a leader, teams first ask whether a workflow service such as Step Functions, idempotent APIs or optimistic locking would remove the need for one.
Why teams still want a leader:
- Easier to reason about. All concurrency sits in one place, there are fewer partial failure modes, and there is one place to look for logs and metrics.
- More efficient. The leader can simply inform others of changes instead of building agreement on each one.
- Consistent. It sees and orders every change, so clients get consistency easily.
- Cheaper. It can keep one consistent cache.
- Simpler code. It need not handle another node editing the same state at the same moment.
Why they hesitate:
- A single point of failure. If a bad leader is not detected and replaced, everything stops.
- A single point of scaling. Growing past one leader means re-architecting.
- A single point of trust. A leader doing the wrong thing with no one checking has a huge blast radius.
- Hard to deploy partially. One-box, A/B, blue/green and incremental deployment with automatic rollback (Lessons 17 to 19) all assume many independent copies.
The common mitigation is to shrink the leader's scope by sharding. Each item of data still has exactly one leader, but there are many leaders. DynamoDB, EBS and EFS use this design. The cost is design complexity in choosing how to shard.
Production architecture. Amazon's most common mechanism is the lease. One database row records the current leader. The leader heartbeats it periodically. If heartbeats stop for long enough, other candidates may take over. Amazon's preferred clients are the DynamoDB lock client and ZooKeeper's lease-based recipes, which are well tested, rather than custom implementations. Examples across Amazon:
- Relational databases. Almost every RDBMS deployment elects a primary for writes, sometimes automatically and often by a human operator.
- EBS. It spreads a volume across many storage servers and elects a primary per region of the volume to order reads and writes. Followers take over by the same mechanism. Consistency comes from the leader, and the data path avoids per-request coordination. DynamoDB, QLDB and Kinesis use the same approach.
- The Kinesis Client Library (KCL). It uses leases so each shard has exactly one consumer, which makes scale-out stream processing easy.
Leases rely on durations, not clocks. Amazon avoids depending on synchronized wall-clock time in distributed systems, even with EC2's time sync service. It uses time "only for human consumption". A lease needs only local elapsed time ("I renewed 4 seconds ago"), not agreement on what time it is. That avoids leap seconds and clock drift, which the article notes can grow under sustained high CPU. But the timer must be monotonic. A library whose clock occasionally jumps backwards silently breaks the lease.
Overlooked constraints.
- Exactly one leader is impossible to guarantee. There is usually one leader, but during failures there can be zero or two. A paused or partitioned old leader may still be working, and from outside it is hard to tell whether a node is dead or just unreachable.
- The real bug is acting without the lease. A leader on a slow or lossy network may believe it holds the lease longer than it does. A garbage-collection pause between "check lease" and "write data" lets the lease expire in the gap. Amazon calls hardening against these the biggest practical challenge.
- Failover must not lose work. Amazon always makes work durable before telling anyone it is done, or else accepts data loss. Idempotent steps let a new leader safely redo whatever the old leader may have half finished.
- Two kinds of systems. If the leader's work is idempotent, two leaders only waste effort. Such systems can use weaker, more available election. If correctness needs at most one leader, election must be strictly consistent and must depose the old leader before a new one starts. That is much harder. In practice Amazon adds a second safety net: the underlying database rejects conflicting writes even if two nodes both think they hold the lease.
Amazon's best practices, as listed in the article:
- Check the remaining lease time often, especially right before any side effect outside the leader.
- Assume slow networks, timeouts, retries and GC pauses can end the lease early.
- Do not heartbeat from a background thread. If the worker cannot be stopped when the lease expires, that is a correctness bug. If the worker dies while the heartbeat thread keeps renewing, that is an availability bug: a zombie leader that holds the lease and does nothing.
- Track how much work the leader can do versus how much it does, and plan scaling before it runs out.
- Make it easy to find the current leader and every past leader, with an audit log.
- Model and verify the algorithm, for example in TLA+. This catches rare bugs that come from assuming more than the election protocol guarantees.
What Amazon sacrificed. Leader-based designs give up horizontal write scaling inside a shard, and some availability during failover (the gap between lease expiry and takeover). They also give up the cheap safety of partial deployments. Amazon accepts these in exchange for simple consistency and efficient data paths, then fences the risks with sharding, durable-before-ack and database-level conflict checks.
Deep Dive: lease timing, fencing and why durations workShow
The safety condition. Let the lease length be L and let the candidate wait L on its own monotonic clock after the last renewal it observed. Let ε be the worst-case drift between the two machines' measured durations, and let δ be the delay between the leader's last successful renewal and its check. The old leader must stop acting by L − δ − ε on its own clock after the renewal it sent. In practice leaders stop at a safety margin, say acting only while more than 30% of L remains, and candidates wait a little longer than L. Durations drift slowly (parts per million on quartz clocks), so ε is microseconds over a 10 s lease. Wall clocks, by contrast, can jump by seconds after an NTP correction.
Why the margin is not enough. No margin covers an arbitrary pause. A 12 s GC pause or a VM migration can land between "lease OK" and "write". That is why the database-level check in the diagram matters. Each lease grant carries a monotonically increasing token (the version number). Storage remembers the highest token it has seen and rejects lower ones. Martin Kleppmann's essay "How to do distributed locking" (2016), which the Amazon article recommends, argues this point: a lock without fencing is only an efficiency optimisation, not a correctness guarantee.
Choosing L. A short lease means fast failover but more renewals and more risk of losing leadership during a brief network blip. A long lease means fewer false failovers but longer outages when the leader really dies. With L = 10 s and a 2 s renewal interval, the system survives four lost renewals in a row, and failover takes 10 to 12 s. KCL-style shard leases often use this order of magnitude. Database primaries often use longer windows, because a false failover there costs more than a few extra seconds of downtime.
Lineage. Leases come from Gray and Cheriton, "Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency" (SOSP 1989). Google's Chubby (Burrows, OSDI 2006) built a coarse-grained lock service on Paxos with leases and sequencers, an early form of fencing token. ZooKeeper's ephemeral nodes and the DynamoDB lock client's conditional writes are modern versions of the same idea: a consistent store decides who holds the lease, and time only decides when to try again.
Lesson 10: Static stability using Availability Zones#
Assumptions. An AWS Region contains several Availability Zones (AZs). Each AZ is one or more data centres, far enough from the others to escape a shared fire, flood or lightning strike, with its own power, cooling and network. AZs are linked by fast private fibre. Amazon assumes an AZ will be impaired at some point. The design question is what the system has to do when that happens.
Production architecture. A system is statically stable if it keeps working when a dependency fails, without having to change anything. It may stop seeing updates (new, changed or deleted items), but whatever worked before keeps working.
The idea rests on splitting a system into two planes, terms borrowed from networking:
- The control plane makes changes. For an EC2 launch, it finds a physical host that respects placement groups and tenancy, allocates a network interface from the subnet, prepares an EBS volume, mints IAM role credentials, installs security group rules, stores the results in several downstream services, and pushes configuration to the host and the network edge.
- The data plane is the daily work of what already exists: routing packets through VPC route tables, reading and writing EBS volumes.
Amazon gives three reasons to keep them apart:
- Customers care more about the data plane. A running instance staying up matters more than being able to launch a new one.
- The data plane runs at far higher volume, often by orders of magnitude, so each plane needs to scale on its own axis.
- The control plane has more moving parts, so it is statistically more likely to fail.
So the EC2 data plane is built to need no control plane at runtime. Each physical host holds locally everything it needs to route its instances' packets inside and outside the VPC. If the control plane is impaired, the host misses new instances and new security group rules, but every existing flow keeps working.
The anti-pattern is "run in several AZs and auto-scale the survivors when one fails". The problem is not that new instances cannot launch. It is that recovery now depends on the control plane at the worst possible moment, together with the application's own start-up chain: download configuration, register with service discovery, fetch credentials. Those are the most complex parts of the system, during the event most likely to break them.
Amazon uses two statically stable patterns:
- Active-active across AZs (stateless fleets). An Auto Scaling group spans three or more AZs behind a load balancer, over-provisioned by 50%. Each AZ runs at only about 66% of its load-tested capacity, so any two AZs can carry the full load. When an AZ fails, its hosts fail health checks, the load balancer moves traffic away, and nobody does anything. Elastic Load Balancing itself is provisioned the same way. Queue consumers follow the same pattern: impaired workers stop pulling, and healthy ones pick up the slack.
- Active-standby across AZs (stateful leaders). RDS places a warm standby in a different AZ from the primary, using a subnet group that spans AZs. On failure, RDS promotes the standby and repoints the DNS name. Leader-based clusters do the same: they elect a leader from a standby already running instead of launching a replacement just in time.
In both patterns the capacity needed for the failure was paid for in advance.
Inside EC2: AZ independence. EC2 goes further because it is the foundation that others build their availability on:
- Zonal deployment calendar. Software for hosts, edge devices, DNS resolvers and launch-path components reaches different AZs on different days, on top of the usual one-box-then-1/N rollout. A bad deployment hurts one AZ and is rolled back there.
- AZ-local packet flows. Traffic is designed to stay inside its AZ.
- Zonal building blocks. NAT gateway is a zonal resource. Customers create one per AZ, with per-AZ route tables. A NAT problem in one AZ then cannot spread to the others. The price is extra setup for customers and zonal environments for the EC2 team. Amazon accepts it because NAT gateway is part of every instance's data plane.
- Durability still crosses AZs. Each zonal stack runs on its own, but hard state is replicated across AZs (cross-AZ read replicas, backups in S3) for disaster recovery. The replicas are not needed for the primary AZ to run.
Overlooked constraints.
- The 2/3 arithmetic. Gray failures, such as bugs that pass health checks, are invisible to the load balancer. If a request crosses two regional services, each spread evenly over three AZs with one AZ bad, its chance of avoiding the bad AZ is 2/3 × 2/3 = 4/9, worse than a coin flip. With N regional hops, it is (2/3)^N. If each service calls its zonal neighbour in the same AZ, the chance stays at 2/3 however long the chain is. That is the case for zone-local building blocks.
- Choose per layer. Regional calls regional is simpler and right for most services, including higher-level ones such as API Gateway and serverless offerings. Regional calls zonal or zonal calls zonal is for components in the critical data path, such as network appliances. It contains AZ failures and also avoids cross-AZ data-transfer charges.
- Static stability is about what you must do, not about how much capacity you have. A system with plenty of headroom can still fail statically if failover requires a control-plane call, for example a DNS update through an API that is itself impaired.
What Amazon sacrificed. Running each AZ at about 66% means paying for roughly a third more hardware than steady state needs, every day, for a failure that happens rarely. Zonal designs add operational surface: three environments instead of one, and more resources for customers to manage. Warm standbys sit idle. Amazon buys certainty of recovery with permanent spare capacity.
Deep Dive: how much spare capacity static stability costsShow
The general formula. With n AZs and tolerance for losing one, the survivors must carry 100% of the load. Each AZ must be able to take 1/(n−1) of the load while normally carrying 1/n. Steady-state utilization per AZ is therefore (n−1)/n of its tested capacity, and the over-provisioning factor is n/(n−1).
| AZs | Utilization at steady state | Extra capacity vs needed |
|---|---|---|
| 2 | 50% | +100% |
| 3 | 66.7% | +50% |
| 4 | 75% | +33% |
| 6 | 83% | +20% |
This is why Amazon's example uses three AZs and 50%. Adding AZs makes static stability cheaper, but every added AZ is another place for deployments and data to be managed.
Worked example. A service peaks at 30,000 requests per second, and one host safely handles 500. It needs 60 hosts at peak. Across three AZs that is 20 per AZ, and the AZ-loss rule requires 30 per AZ, so 90 hosts in total. Dynamic scaling during the outage would start from 60 hosts and have to launch 30 more, during an event in which launches are the most likely thing to fail.
Static stability elsewhere. The same idea appears outside AZs: Lesson 13's Hyperplane nodes keep serving the last configuration they loaded if S3 is unreachable. Clients that cache credentials with an expiry longer than any expected outage keep working when the credential service fails. Lesson 15 describes caches that serve stale data when the source is down. In each case the data plane carries enough state to keep running on its own.
Lesson 11: Workload isolation using shuffle sharding#
Assumptions. Route 53 began with a simple customer need. People wanted S3, CloudFront and ELB at the root of their domain (example.com, not just www.example.com). DNS has not allowed a CNAME at the zone apex since its 1980s design, so AWS had to host customers' domains and answer with its services' ever-changing IP addresses itself. The hardest problem for any DNS host is DDoS. DNS runs over UDP, so source addresses are easy to spoof. Thousands of attacks hit domains every day, from extortionists, "booters" paid to take sites down, and vandals. Adding servers does not win this race: a server costs thousands of dollars, and attackers rent bots for pennies. Scrubbing appliances for every domain would have cost tens of millions of dollars and months of lead time. The team needed to spend defence only on the domains actually under attack.
Production architecture. Picture eight workers (servers, queues, databases, whatever the unit is).
- No sharding. Every worker handles every customer. This is efficient, and losing one worker costs only an eighth of capacity. But a poison request or a flood that kills one worker moves to the next, and the next, until everyone is down.
- Plain sharding. Four shards of two workers. A problem customer takes out its own shard, so impact falls to 25%. The price is more slack capacity, because each shard has only two workers to cover for each other.
- Shuffle sharding. Each customer gets its own virtual shard: a combination of two of the eight workers. In the article's picture, the "rainbow" customer gets workers 1 and 4, "rose" gets 1 and 8, and "sunflower" shares one worker with rainbow. If rainbow brings a flood, workers 1 and 4 suffer. Rose still has worker 8 and sunflower still has worker 6. A client that retries on another worker of its shard sees no outage. Eight workers give C(8,2) = 28 distinct pairs, so with many customers the impact of one bad customer falls to about 1/28, seven times better than plain sharding on the same hardware.
The striking property is that it gets better with scale. More workers means many more combinations, until there are more possible shards than customers, and every customer can have a unique one.
Route 53's numbers. Capacity is divided into 2,048 virtual name servers. They are virtual so they can be moved across physical hosts to manage capacity. Every hosted zone gets four of them. C(2048, 4) is about 730 billion combinations, so every domain gets a unique set. Route 53 also guarantees that no two domains share more than two name servers. When one domain is attacked, its four name servers spike, no other domain notices, and Route 53 can move the target onto dedicated attack capacity. It also runs its own AWS Shield traffic scrubbers, but the shuffle sharding is what keeps everyone else unaffected.
Shuffle sharding now appears across AWS, including Lambda's queues in Lesson 6. A refinement is recursive shuffle sharding: shard at several layers, so a customer's own customers are isolated from each other too. Amazon open-sourced Infima, the Route 53 library with several shuffle-sharding implementations.
Overlooked constraints.
- Clients must be fault tolerant. Shuffle sharding limits damage to "at most some workers in your shard". It turns that into no outage only if clients try another member of their shard. DNS resolvers already retry other name servers, which is why it fits DNS so well.
- The workload must be mappable to a shard. Shuffle sharding needs a key (domain, account, tenant) to hash. Unkeyed traffic, such as a flood of junk queries for random names, needs other defences, like scrubbing.
- Overlap must be managed, not just hoped for. Random assignment gives low overlap on average. A guarantee like "share at most two" requires checking each new assignment against existing ones.
- It is not free on every axis. Each worker now serves an unpredictable mix of customers, so capacity planning and debugging have to think in terms of virtual shards.
What Amazon sacrificed. Very little hardware: shuffle sharding rearranges existing capacity, which is why the article calls it frugal. The real costs are a customer that is attacked does lose its own shard until it is moved, clients need retry logic, and the mapping layer is more complex than "shard = hash mod 4".
Deep Dive: shuffle-sharding probabilityShow
Counting shards. With n workers and shard size k, there are C(n, k) possible shards. For n = 8, k = 2 that is 28. For Route 53, n = 2048, k = 4:
C(2048, 4) = 2048 × 2047 × 2046 × 2045 / 24 ≈ 7.3 × 10¹¹, the 730 billion in the article.
Chance that a random other customer is fully hit. If the attacked customer's k workers fail, another customer is fully down only if its own shard is the same set of k workers. With random assignment that probability is 1 / C(n, k). For n = 8, k = 2 it is 1/28, about 3.6%. For n = 100, k = 5 it is 1/75,287,520.
Partial overlap. The chance that another customer shares exactly j of its k workers with the victim is
P(j) = C(k, j) × C(n − k, k − j) / C(n, k)
(a hypergeometric distribution). For n = 8, k = 2: share none, 15/28 (54%); share one, 12/28 (43%); share both, 1/28 (3.6%). A customer that shares one worker still has one healthy worker. This is why retries turn partial overlap into no outage.
Comparison with plain sharding. With n/k fixed shards, one bad customer takes down k/n of everyone. With shuffle sharding, the fraction fully down is about 1 / C(n, k), which shrinks combinatorially while plain sharding's shrinks linearly. For n = 100, k = 5, plain sharding loses 5% of customers. Shuffle sharding fully loses about one customer in 75 million, and about 23% share at least one worker. Most of those (about 21% of all customers) share exactly one and keep four healthy workers.
Guaranteed overlap limits. Route 53's "no more than two in common" is a constraint on the assignment, similar to a constant-weight code with a minimum distance. It is enforced by checking a candidate shard against existing ones, or by building shards with a combinatorial construction instead of pure randomness. With 730 billion shards and millions of domains, a candidate that breaks the rule can simply be discarded and drawn again.
Lesson 12: Minimizing correlated failures in distributed systems#
Assumptions. Redundancy works because probabilities multiply. If one server has a 0.01% chance of failing on a given day, two independent servers both fail with probability 0.0001% (one in a million). That multiplication holds only if failures are independent. The article's household analogy: after a cabinet refit, the plastic brackets in one cabinet broke after a year, then the next a week later, and within three months every bracket in the house had failed. One unknown common cause, whether a bad batch, the wrong bracket rating or humidity, turned independent parts into one failure. A correlated failure is several components failing from one cause. It differs from a cascading failure, in which one failure overloads the next component, which then fails in turn.
Production architecture. The article traces Amazon's history. Early on, a service ran on several physical servers behind a load balancer that sent a small HTTP health check to each server and removed those that failed several in a row (Lesson 14). The load balancer itself was a primary-secondary pair with DNS failover, and the database a replicated primary-standby pair. Today ALB, NLB and DynamoDB provide those building blocks, but the principle is the same. Amazon then attacks each source of correlation:
| Source | Example | Amazon's defence |
|---|---|---|
| Shared physical infrastructure | Power, cooling, network in one data centre | Regions and AZs; EC2, EBS, ELB and VPC run independent stacks per AZ. AZs were a core feature when EC2 went public in 2008 |
| Shared dependencies | DNS ("It wasn't DNS. It definitely wasn't DNS... It was DNS.") | Deliberate engineering to make such dependencies zonal and redundant |
| Hardware batches and age | A latent defect in one batch; failure rates rise as parts age | Diversity and fleet-wide tracking |
| Deployments | One bad change to every AZ | Never deploy to several AZs at once (Lesson 18) |
| Operator actions and tools | Running a command on every host in parallel, even a harmless grep | Velocity controls and feedback loops; tools never touch hosts in more than one AZ, or more than one cell, at a time. The patching system has both |
| Identical software | Every host hits the same limit at the same moment | Shuffle sharding so no two hosts see the same workload |
| Identical behaviour | All clients fail over or refresh together | Jitter on timers, limits and thresholds |
Cells. Beyond AZs, AWS services increasingly use a cellular architecture: the service is divided into identical, independent copies called cells, each serving a subset of customers. A bug, a bad deployment or a poison request then affects one cell. Tools and runbooks respect cell boundaries in the same way they respect AZs.
The lemmings problem. In the video game Lemmings, every creature follows the same rule, so when one walks off a cliff, they all do. A fleet running identical software behind a load balancer that spreads load perfectly evenly behaves the same way. The article's old example is running out of file descriptors: if load pushes one host past its limit, even balancing pushes every host past it at once. Modern defaults make that particular limit rare, but every other limit and bug has the same shape.
Correlated behaviour. The author's broadband failed in his neighbourhood during the COVID-19 work-from-home period. He tethered to his phone, as did many neighbours, and the cellular network slowed under the sudden shared load. A failover by everyone at once broke a second, unrelated system. Computers are easier to change than people, so Amazon adds jitter to:
- How often each host runs housekeeping jobs.
- Retry delays (Lesson 1).
- Thresholds for mode shifts, such as when to refresh state from a remote store.
- Expiry times of short-lived credentials and secrets.
- Cache TTLs across hosts.
- Resource limits such as JVM heap and connection pool sizes, where safe.
Overlooked constraints.
- Jitter makes bugs harder to reproduce. Amazon's fix, as in Lesson 1, is to seed jitter from the host name or IP address. Each host is then predictable and repeatable, but differs from its neighbours.
- Even load balancing creates correlation. Load balancers are meant to make every host look the same, which is exactly what makes them fail together. Shuffle sharding and limit jitter deliberately make hosts slightly different.
- Fault boundaries must be practised. AZs work as a boundary for operations tools because services are already built and tested to survive an AZ loss. A boundary nobody has tested is not one you can rely on.
What Amazon sacrificed. Rolling changes one AZ or cell at a time makes fleet-wide fixes slower, sometimes even urgent ones. Per-host variation in limits gives up some uniformity and tuning precision. Cells add routing layers and many copies to operate. All of it buys back the multiplication of probabilities that redundancy promises.
Deep Dive: how a small correlation destroys redundancyShow
Independent model. With two replicas each available 99.9% of the time, both are down together 0.1% × 0.1% = 0.0001% of the time. That is "six nines" from two "three nines" parts.
Add a common cause. Suppose a shared factor (same rack power, same bad deployment) takes both replicas down for 0.01% of the time, and the rest of their downtime is independent. Combined unavailability is then roughly 0.01% + 0.0001% ≈ 0.0101%. Availability has fallen from 99.9999% to about 99.99%. The shared cause, though ten times rarer than one replica's own failures, now accounts for 99% of the downtime. Adding a third replica barely helps, because the common term does not shrink.
Lesson. When a system is redundant, its availability is set by its most common shared cause, not by component quality. That is why Amazon spends its effort on removing shared fate (AZs, cells, staggered deployments, jitter) rather than on more expensive servers. The opening story makes the same point: a single redundant server with hot-swappable CPUs once cost more than a small company. Cheap servers with independent failures beat it.
Measuring correlation. A practical check is to compare the observed rate of "two replicas failed within the same hour" with the rate predicted by independence (p² for per-hour failure probability p). If the observed rate is much higher, a hidden common cause exists. Post-incident reviews that ask "what else shared this?" turn up the specific one.
Lesson 13: Reliability, constant work and a good cup of coffee#
Assumptions. Variability is the enemy of reliable systems, and it peaks at the worst moments: load surges, reconfigurations, and responses to power or network failures. When a system slows under stress, queues grow, clients retry, and the system slows further. Getting timeouts and retries right (Lesson 1) helps, but any slowdown while responding to a failure is still downtime.
The analogy is a big coffee urn. A barista makes one cup at a time and has a queue at rush hour. An urn holds hundreds of cups hot whether three people show up or three hundred. In big-O terms it is O(1), not O(N). The article adds two honest caveats. An empty urn must be refilled, so it works up to a limit; the hundreds of urns at AWS re:Invent show how that limit is raised. And an urn with a thermostat does slightly less work as it empties, since there is less coffee to keep warm. That is anti-fragility: improving under stress.
Production architecture. Constant work systems have three traits:
- They do not scale up or slow down with load or stress.
- They have no modes: the same operations run under every condition.
- Any variation is toward doing less work under stress.
A cache looks anti-fragile at first, since it gets better under load, but it has modes. An empty cache makes responses much slower, and an overloaded one can send all traffic to its source and knock it over (Lesson 15). The article uses two examples.
Example 1: Route 53 health checks. Customers attach health checks to DNS answers: weighted sets, or primary and secondary pairs. AWS services such as ELB and RDS configure these on customers' behalf.
- A fleet of health checkers spread across many Regions probes each target every few seconds. Tens of checkers probe each target.
- They send results to a smaller fleet of aggregators, which apply smoothing: for example, a target is unhealthy only if at least three checkers saw it fail. Customers can set these thresholds.
- Checkers and aggregators are organized in cells. The capacity of each cell is known from testing, so a new cell is added before a cell fills.
- The best trick: each checker always sends a result set sized to the maximum it can support, say 10,000 entries, even if only 10 checks are configured. The other 9,990 are dummies. Network load and aggregator work never change as customers add checks.
- The aggregators send a fixed-size table of every health status to the DNS servers every few seconds. The DNS servers store it in memory almost as-is. Aggregators push, because there are many more DNS servers than aggregators; this is Lesson 5's "smaller service in control".
- When a DNS query arrives, the server finds all candidate answers and checks each against the in-memory table. It checks every candidate even when the first one is healthy, so a status change never alters the work done per query.
The natural design would turn each status change into DNS record edits. That is a trap. One health check can back hundreds of records, and an AZ power loss can fail tens of thousands of checks at once, producing millions of edits at the exact moment speed matters most. In the constant-work design, nothing switches into an "AZ down" mode. The same memory is read, the same CPU time is spent, and only the chosen answers differ. If some checkers sat in the failed AZ, total work even goes down.
Example 2: S3 as a configuration loop for Hyperplane. Network Load Balancers run on AWS Hyperplane, an internal service embedded in the EC2 network. NLB configuration changes, such as adding targets during a flash crowd, are urgent. A workflow that pushes each change as an event to every node slows down exactly when many changes arrive at once, and slow systems invite retries. Instead:
- Each customer change is merged at once into a configuration file in S3.
- Every Hyperplane node fetches and fully loads the whole file every few seconds, whether or not anything changed. In effect it always processes the maximum number of changes.
- The file is sized to its maximum from day one, with empty slots, even in a brand-new Region with a handful of load balancers.
- If nodes are lost, total work drops: fewer S3 fetches, not more retries.
- It is cheap. Fetching one S3 object in a loop from hundreds of machines costs far less than building and running a sophisticated propagation system.
Self-healing. A constant-work loop always starts from a clean slate. If a file was truncated by a network glitch, the next cycle fixes it. If a DNS server missed an update, it gets the next one, with no backlog. Workflow systems, by contrast, are edge-triggered: changes must be detected, actions must run in exactly the right order, and failures need extra repair logic. Workflows are not naturally self-healing; you have to make them so.
Overlooked constraints.
- O(1) means a constant number of operations, not one operation. The article suggests O(C). Both systems do thousands of operations per cycle; what matters is that the number never depends on health statuses or customer configuration.
- Waste is real for some resources. Physical constant work wastes coffee. For propagation and configuration systems, sending 10,000 results costs about the same as sending 1, and dropping retries and state machines can even save energy. But running 100 web servers all night when the off-peak need is 50 wastes money. There, elastic scaling wins. Because it happens daily, its code paths are exercised often enough to stay healthy.
- Simple means easy to understand, not few parts. A unicycle has fewer parts than a bicycle and is much harder to ride. The test is whether a team that did not build the design can understand and operate it. The article notes how many configuration systems can be just "apply the full configuration in a loop".
What Amazon sacrificed. Constant work spends bandwidth and CPU on dummy entries and on reloading unchanged files. Propagation latency is set by the loop period, a few seconds, and does not improve when the system is idle. Capacity must be planned for the maximum from the start. Amazon trades efficiency in the common case for identical behaviour in the worst case.
Deep Dive: edge-triggered vs level-triggered propagationShow
Two models. An edge-triggered system acts on changes ("target X went unhealthy, remove its records"). A level-triggered system acts on current state ("here is the full table; use it"). The terms come from electronics and interrupt handling. Constant work is level-triggered propagation done at a fixed rate.
Cost under a mass failure. Suppose an AZ outage fails 30,000 health checks at once, and on average each backs 50 DNS records.
- Edge-triggered: 1.5 million record changes must be written, replicated to every DNS server, and applied in order. At, say, 10,000 changes per second, convergence takes 150 seconds, with the system at peak load, and failed writes need retry and reconciliation logic.
- Level-triggered: the next cycle carries the same fixed-size table it always carries, with 30,000 bits flipped. Convergence takes one cycle, a few seconds, and nothing gets busier.
Sizing the fixed payload. A status table of 1 million checks at 1 bit each is 125 KB. Pushing it every 5 seconds to 1,000 DNS servers is 25 MB/s across the fleet, which is trivial for a data-centre network and identical on the quietest and worst days. For Hyperplane, a configuration file sized for the Region's maximum might be many megabytes. Hundreds of nodes fetching it every few seconds is a predictable S3 load, and S3 is built for exactly this read pattern.
Choosing the loop period. Propagation delay is up to one period plus processing time. A 5-second loop gives worst-case freshness of about 5 to 10 seconds. Halving the period doubles the fixed cost. Choose it from the business need ("DNS failover within 30 seconds"), then confirm the fixed cost fits.
Where it appears elsewhere. Kubernetes controllers use a similar reconcile loop: read desired state, read actual state, act on the difference, and also re-run periodically, so missed events heal themselves. Anti-entropy sweepers (Lesson 6) and Merkle-tree repair in Dynamo-style stores are other level-triggered safety nets placed behind edge-triggered fast paths.
Lesson 14: Implementing health checks#
Assumptions. Hardware is designed to fail eventually, and all software crashes at some point. The naive model is binary: a server either works or it dies and gets out of the way. Real failing servers are worse than dead. They keep accepting traffic and do disproportionate harm.
The author's own early bug shows how. While adding instrumentation to the Amazon.com rendering fleet, he shipped a bug that, rarely, made a web server render blank error pages on every request until its process was restarted. Three things made it worse:
- The server did not know it was unhealthy.
- It also lost the ability to report its health, so neither automation nor its normal alarms reacted.
- It became very fast, because a blank page is cheaper than a real one. The load balancer of the time favoured fast servers and sent it more traffic.
The bug was rolled back quickly, but only because other alarms fired on error rate and latency measured elsewhere.
Production architecture. A failed server in a fleet of 10 already caps availability at 90%. A failure that answers fast becomes a black hole under "least requests" balancing, and also for queue pollers that pull work as fast as they can. Amazon sometimes slows down failed responses to match normal latency to prevent this (Lesson 8). Servers fail independently for many reasons:
- Unwritable disks.
- Sudden clock skew that makes signed calls fail authentication.
- Failure to fetch new crypto material, so encryption and decryption break.
- Crashed support processes.
- Memory leaks and deadlocks.
They also fail together, when a shared dependency or the network breaks. That is the core tension. A thorough check catches single-host faults quickly, but if it fails for a shared, non-critical reason, automation removes every host at once. The rule that follows: stop sending traffic to one bad server, but keep sending traffic if the whole fleet looks bad.
Amazon uses four kinds of check:
| Check | Tests | Catches | Risk |
|---|---|---|---|
| Liveness | Port accepts TCP; basic HTTP returns 200; EC2 status checks such as network reachability | Dead process, dead host | Misses a host that answers but answers wrongly |
| Local health | Can read and write disk (stateless services still write logs, metrics and metering data); proxy-to-app pass-through; required support processes (monitoring, metering, credential refresh) running | Host-specific faults; does not depend on anything shared with peers | Low false-positive risk |
| Dependency health | Fresh configuration and metadata; can reach peers and dependencies; no deadlock, leak or corrupted state | Expired credentials, a broken update agent, odd network paths | False positives when the dependency itself is down: every host fails together |
| Anomaly detection | Compares each host's error rate, latency and other metrics with the fleet | Clock skew (AWS request signing rejects clients more than 5 minutes off), old code on a host that was offline, hosts blaming clients with 4xx, hosts that are suspiciously fast | Needs similar work per host, a homogeneous fleet (or metrics grouped by instance type), and data reported from outside the host |
In the blank-page story, the existing check was deep enough to see the renderer was running but not deep enough to see it answered correctly. Anomaly detection would have spotted a host that was faster than its peers and returned many errors. The best data source is the client side: ALB access logs record which backend served each request, how long it took and whether it failed, even when the host's own monitoring is broken.
Reacting safely. A host can remove itself, by failing its load balancer check or by stopping its queue polling, or it can report to a central authority that decides. The patterns:
- Fail open. NLB, ALB and Route 53 stop routing to one failed target, but if all targets fail, they route to all of them. NLB also routes away from an AZ only if every host in that AZ is unhealthy. Fail open makes deeper checks safer. But Amazon is wary of logic it cannot fully reason about. A slightly flaky shared database makes hosts flap in and out without ever crossing the fail-open threshold. So most teams keep fast load-balancer checks local and send deeper dependency checks to slower, central systems.
- Without a circuit breaker: the work producer (the load balancer or the queue-polling thread) runs only liveness and local checks, and removes a host only for a definitely local fault such as a bad disk. External monitors run dependency checks and anomaly detection. They may terminate hosts, raise alarms or page an operator, with thresholds and rate limits. Stateful fleets (DynamoDB, S3, RDS) have strict durability rules around replacing servers, so their automation stops and calls a human when thresholds are crossed. Since a very broken host may not self-report, monitors also poll each host.
- Prioritize health checks over work. In overload, the danger is not that a host returns errors; it is that it fails to answer the health check in time, because of CPU contention, GC pauses or no free worker threads. The load balancer then removes it, the others get more load, and they fail too, a downward spiral. Fixes:
- Size the worker pool above the proxy's max connections, from a few spare workers to twice the proxy limit, because health checks need connections too. Idle workers are cheap.
- Enforce a max concurrent requests limit in the server that always lets health checks through. Implementations range from a Java semaphore to analysis of CPU trends.
- Run dependency checks in a background thread that sets an
isHealthyflag the ping handler reads. The ping answers instantly, and the load on dependencies is steady. Watch that thread: if it dies, the host stops detecting both failure and recovery.
Scope of impact. A health check on a soft dependency, one used only by some requests, turns it into a hard dependency for the whole host. Without fail-open protection, an outage of that dependency then takes down the entire service. A service with a control-plane API and a data-plane API should not fail its data plane because the control plane's database is down. A read API that can serve cached results while the database is down should not fail its checks either. The article notes that "which dependencies would a health check pull in?" is also a useful lens for deciding how small to make a microservice.
Things that have gone wrong, and the backstops.
- Deployments. A start script that forks the process and immediately reports "deployment done" lets a broken build roll across the fleet. Backstops:
- Alarms on fleet size, load, latency and errors that halt and roll back the deployment.
- Phased deployments by AZ with integration tests after each phase.
- Pre-production test stages.
- Asynchronous processors. No load balancer checks queue workers. A host with a full disk or no file descriptors keeps pulling messages and failing them. Backstops: SQS redelivers after the visibility timeout, and alarms fire on processing errors.
- Full disks. Both processing and logging fail, so the host goes dark. Backstops: proxy metrics from ALB or API Gateway, and SQS delay metrics, which are measured outside the host. The same reasoning is why Auto Scaling groups use external load-balancer checks. Some teams run a Lambda function every minute that checks every host, keeps state in DynamoDB, and refuses to mark too many hosts unhealthy at once.
- Zombies. A host that was partitioned or powered off for a long time comes back with old code that writes to a changed schema or uses old configuration. The fix is to make the health check return the running software version. A central agent compares versions across the fleet and keeps outdated hosts out of service.
What Amazon sacrificed. Keeping fast checks shallow means some sick hosts stay in service until slower central systems catch them. Fail open means sending traffic to hosts that may be broken. Rate-limited remediation means a mass failure is handled partly by humans. Amazon accepts slower single-host repair to remove the risk of automation shutting down the whole fleet.
Lesson 15: Caching challenges and strategies#
Assumptions. The story repeats across Amazon. A new service calls a slow or costly dependency. A cache is added, and latency, cost and small dependency blips all improve. Soon no one remembers life before the cache, and the dependency is scaled down to match the lower load. Then traffic shifts, the cache fleet fails, or a deployment empties it, and the full load hits a dependency that can no longer take it. The service has become addicted to its cache. The root problem is modal behaviour: hits and misses behave very differently, and an unexpected shift in their mix can be catastrophic.
When Amazon caches. A cache is worth considering when:
- Latency or cost of a dependency grows with call volume, or it will start throttling.
- Request patterns cause hot-key or hot-partition throttling.
- A result can be reused across many requests. If each request needs a unique result, the hit rate is negligible and the cache does nothing.
- The service and its clients tolerate eventual consistency. How stale the data gets depends on how fast the source changes and on the refresh policy. Slow-changing data can be cached longer.
Local vs external.
| On-box (in-process) cache | External cache (Memcached, Redis) | |
|---|---|---|
| Effort | Simple hash table or caching HTTP client; no extra fleet | Extra fleet to monitor, scale and patch |
| Coherence | Each host differs, so a client can see new data then old data | One shared value (mostly; failed updates still cause drift) |
| Load on the dependency | Grows with fleet size | Independent of fleet size |
| Cold start | Every new host and every deployment starts empty | Survives service deployments |
| Capacity | Limited by host memory | Larger, so fewer evictions |
| Availability | Same as the host | Different and often lower (maintenance windows, no zero-downtime upgrades) |
Operating an external cache safely.
- Plan for it being down. Falling back to the dependency on every miss sends a spike during a long cache outage, which is the fallback trap from Lesson 3. Amazon prefers an in-memory cache as a second layer, or load shedding that caps the request rate to the dependency. It load tests with the cache disabled to prove the safeguards work.
- Find leading indicators of capacity. One team found Redis CPU climbed steeply as request rate approached its limit, so it set the alarm from load tests.
- Scale without a mass miss. Not every cache server supports adding nodes without downtime, and not every client library does consistent hashing. Test adding and removing nodes before production.
- Treat cached data like persisted data. New code must read old formats, and old code must survive new fields during a mixed deployment. An unhandled format becomes a poison pill. But detecting a version mismatch and discarding entries can itself trigger a mass refresh that browns out the dependency (Lesson 17 covers serialization in depth).
- Write update code carefully. Caches generally lack conditional puts and transactions, so the code that fills them must never leave an invalid state.
Inline vs side caches.
- Inline (read-through or write-through) caches hide caching behind the data API. Examples are DAX for DynamoDB, and HTTP caches: local clients, Nginx or Varnish proxies, and CDNs. Clients do not change, and caching logic leaves application code. But the cache is now in the availability path: if the Varnish fleet goes down, it looks to the caller as if the dependency went down. An inline cache also only exists where the protocol supports one.
- Side caches (ElastiCache, Ehcache, Guava) are generic stores that application code checks before calling the source and fills afterwards. The application can compensate when the cache is down, at the cost of more code.
Expiry, size and eviction. The usual expiry is a TTL, chosen from clients' tolerance for staleness and how fast the data changes. Size should come from a model of request volume and key distribution that gives a high hit rate. Eviction is usually LRU. Then measure reality: hits, misses, cache size and requests sent downstream. Amazon has seen outages made worse by a TTL and size that a developer picked once and never revisited.
Two resilience refinements:
- Soft TTL and hard TTL. After the soft TTL, the client tries to refresh. If the source is down or slow, it keeps serving the cached value until the hard TTL. The IAM client uses this.
- Backpressure on top. A browning-out dependency can signal backpressure. Callers then serve everything they have until the hard TTL and call only for items they do not have, until the signal clears. This lets the dependency recover while callers stay available.
Errors and negative caching. Either serve the last good value (soft and hard TTL), or cache the error with its own, usually shorter, TTL and pass it on. Which is right depends on whether clients prefer stale data or errors. What matters is that something is cached. Otherwise a deleted resource or a struggling dependency gets hammered with the same doomed request, and Amazon has seen exactly that raise failure rates.
Security.
- Encrypt cache traffic and data at rest, which ElastiCache for Redis supports, especially for user data.
- Guard against cache poisoning, where a protocol flaw lets an attacker plant a value that everyone then receives.
- Remember timing side channels: a hit is faster than a miss, so response time can reveal what other tenants requested.
Thundering herd. Many requests miss on the same key at once, or a new host joins with an empty cache. The fix is request coalescing: only one request per missing key goes downstream, and the others wait for its result. Some libraries and inline caches (Nginx, Varnish) provide it, and it can be added on top of any cache.
What Amazon sacrificed. Amazon's stance is sceptical: caching is adopted only when the gain in cost, latency or availability clearly beats the added risk. Load-testing without the cache means keeping enough dependency capacity, or enough load shedding, to survive without it, which gives back some of the savings. Soft and hard TTLs and negative caching trade freshness for availability.
Deep Dive: cache addiction in numbersShow
The setup. A service receives 20,000 requests per second, and each needs one lookup. Its cache hit rate is 95%, so the database sees 1,000 reads per second. After a year, the database has been sized for 1,500 reads per second, 50% headroom over observed load.
A cold cache. A deployment flushes in-process caches fleet-wide, or the external cache cluster fails. The database suddenly sees up to 20,000 reads per second, 13 times its capacity. It browns out. Latency rises, and Lesson 7's concurrency math takes the callers down too.
Partial drops are dangerous too. If the hit rate falls from 95% to 90% because traffic shifted to long-tail keys, misses double, from 1,000 to 2,000 per second, which is already above capacity. Small changes in hit rate cause large changes in miss load because load scales with 1 − hit rate.
Defences, quantified.
- Rate cap: limit database calls to 1,500 per second. Under a cold cache, the service serves 1,500 requests per second from the database, stores each result, and sheds the rest with a fast error. Because hot keys refill first, the hit rate climbs back within minutes and the shed share falls towards zero. That is partial availability instead of a total outage.
- Request coalescing: suppose the 19,000 misses per second right after the flush fall mostly on 2,000 hot keys. Without coalescing, every miss goes to the database. With it, each hot key is fetched once while the other requests for it wait about 50 ms for that result, so the hot set costs about 2,000 reads in total instead of thousands per second. Database load is set by distinct missing keys, not raw request rate.
- Soft and hard TTL: if the soft TTL is 5 minutes and the hard TTL 1 hour, a 30-minute database outage costs no errors for any key read in the previous hour.
Local caches multiply load. With in-process caches, each of N hosts refills every key on its own. 200 hosts with a 60-second TTL on 10,000 hot keys produce 200 × 10,000 / 60 ≈ 33,000 refills per second, independent of user traffic. An external cache shared by all hosts would need about 170 per second. This is the article's "downstream load is proportional to fleet size" point.
Lesson 16: Challenges with distributed systems#
Assumptions. When the author joined Amazon in 1999, servers had pet names like "fishy" and "online-01". Distributed computing was already hard, with problems of latency, scaling, networking APIs, marshalling and Paxos. As systems grew, theoretical edge cases became daily events. The article sets out why distributed systems are hard before the other articles explain how Amazon copes. Its answer: independent failures plus nondeterminism, and the fact that you cannot always know whether something failed.
Three kinds of distributed system, by difficulty.
| Kind | Examples | Time budget | Difficulty |
|---|---|---|---|
| Offline | Batch jobs, big-data analysis, render farms, protein folding | Hours | Almost all the benefits of distribution, almost none of the pain |
| Soft real-time | Search index builders, detecting impaired servers, IAM roles for EC2 pushing credentials to every instance | Minutes to hours; for EC2 role credentials, hours before old ones expire | Moderate |
| Hard real-time (request/reply) | Web front ends, the order pipeline, card payments, every AWS API, telephony | Milliseconds while a customer waits | Hardest; the article's focus |
Production architecture: the eight steps of one round trip. A single call across the network always involves:
- Post request: the client puts the message on the network.
- Deliver request: the network delivers it to the server.
- Validate request: the server checks it.
- Update server state.
- Post reply.
- Deliver reply.
- Validate reply: the client checks it.
- Update client state.
No step can be skipped, and the client, the network and the server fail independently, so each step can fail on its own. The article calls these "the eight failure modes of the apocalypse".
On one machine, the code board.find("pacman") can also fail: an overheating CPU, a failed power supply, a kernel panic, out of memory, a full disk, a cosmic-ray bit flip. But those failures share fate: the whole machine dies, and nobody writes a unit test for it. Across a network, there is no shared fate. The client keeps running when the server or the network dies, so it must handle each case. One remote call becomes a five-way outcome:
(error, reply) = network.send(remote, actionData)
switch error
case POST_FAILED: // the server certainly did not get it
case RETRYABLE: // the server got it and reported a transient failure
case FATAL: // the server got it and rejected it
case UNKNOWN: // timeout: it may or may not have happened
case SUCCESS:
if validate(reply) // use the reply
else // reply is corrupt or incompatibleIn the article's walk-through, one networked find expands to about fifteen client and server steps. The server, for instance, also checks whether it already gave up on the user for inactivity and refreshes a keep-alive table.
Overlooked constraints.
- The test matrix explodes. The Pac-Man snippet calls the board four times, and each call now has five outcomes. A success on one call says nothing about the next, because the server can die between them. So 10 single-machine test scenarios become about 200. On the server, four handlers with five tests each make 20. Then come sequences of calls, for example
findsucceeds,movereturns UNKNOWN, and the client callsfindagain. Does the server handle that? You only know if you test it. - UNKNOWN is the hardest case.
isEven(n)is obvious.distributedIsEven(n)has a third branch with no good answer. With side effects it is worse: awithdrawcall that times out may or may not have moved the money. That is the problem idempotency tokens solve (Lesson 2). The article's stance is to distrust every line that could touch the network. - It is recursive. Machines form groups (per AZ), groups form Regions, and Regions talk to Regions. GROUP1 calling GROUP2 has all eight failure modes at the group level. Inside GROUP2, server S20 must copy the request to S25 before acknowledging, and that has all eight again. Every layer of abstraction multiplies the cases instead of hiding them.
- Distributed bugs are latent. They can sit in production for months until the rare combination of failures occurs.
- Distributed bugs spread like epidemics, because they involve the network, which is the one thing connecting all machines. The article's example is an old, site-wide Amazon.com outage. One remote catalog server's disk filled up. Its error handling made it return empty responses, very fast. The load balancer did not check response size, but it noticed the speed and sent that server a huge share of traffic. One server with a full disk took the whole website down. It was removed quickly, and the lessons were shared across Amazon. This is the same black-hole pattern as in Lesson 14.
What Amazon sacrificed. Amazon chooses hard real-time request/reply systems because customers are waiting, and accepts the most expensive testing burden of the three kinds. Much of the rest of the Library is ways to shrink the matrix: idempotency turns UNKNOWN into "retry safely", constant work removes modes, static stability removes runtime dependencies, and cells limit how far a latent bug spreads. Lessons 1 to 15 can be read as answers to this article.
Deep Dive: counting the failure space and taming itShow
Client side. With c remote calls in a scenario and 5 outcomes each, there are up to 5^c outcome combinations. Four calls give 625. Most share handling code, which is why the article's practical count is "each scenario about 20 times". Even that linear blow-up, 10 scenarios to 200, is beyond what teams write by hand.
Recursion. If a group-level request triggers an internal replication request, and both can fail in 8 ways, the article's minimum is 8 + 8 tests. Interactions, such as a replica write succeeding while the group-level reply is lost, push it toward 8 × 8 = 64.
How the industry tames it (the techniques referenced across the Library and the wider field):
- Make UNKNOWN safe. Idempotent operations with client tokens (Lesson 2) turn "did it happen?" into "retry and get the same answer".
- Collapse outcomes. Many teams map every failure to RETRYABLE or FATAL early, so business logic handles two cases instead of five.
- Inject faults. Test harnesses drop, delay, duplicate and reorder messages. Jepsen-style testing does this for databases. AWS Fault Injection Simulator does it for real infrastructure.
- Model check. TLA+ explores every interleaving of a small model. Amazon described using it on S3, DynamoDB and other systems in "How Amazon Web Services Uses Formal Methods" (Newcombe et al., Communications of the ACM, 2015). The leader-election article above recommends it.
- Detect black holes. Check response size and error rate per host, not just latency, and treat a host that is much faster than its peers as suspect (Lesson 14).
Lesson 17: Ensuring rollback safety during deployments#
Assumptions. Amazon has a tenet: avoid one-way doors. A one-way door is a choice you cannot easily undo. A deployment that cannot be rolled back is a one-way door. This article assumes that the old version and the new version both work fine on their own. The danger is the transition: the period when some hosts run version N and some run N+1, and the moment you go back from N+1 to N. A change that can be rolled back without breaking anything the old version supported is called backward compatible. Amazon checks this for every revision, not only big ones.
Standalone versus distributed. A program running as one process on one device upgrades atomically. Old and new never run at the same time. The only rule is that each version can read data the other wrote. A distributed service is different. It upgrades with a rolling deployment so it stays available. That means old and new code run side by side for minutes or hours, and they talk to each other through RPC calls and through shared state such as metadata files, checkpoints and records in S3 or a database. A reader on one version may misread, or fail to read, what a writer on the other version produced.
The most common cause of failed rollbacks: protocol changes. Two examples from the article show how wide "protocol" is:
- Format change. New code starts compressing data before writing it. Once compressed data exists, old code cannot read it, because it does not know to decompress. If the data sits in a shared blob store, servers that have not been upgraded fail to read it during the rollout, not just after a rollback.
- Timing change. Two servers send each other a heartbeat every 5 seconds and drop the connection if none arrives in that window. A commit changes the period to 10 seconds. It looks like a one-number change. But during the rollout, new servers send every 10 seconds, old servers wait only 5, and old servers drop their connections to new ones. Across a big fleet that is an availability dip caused by a constant.
Because such changes are hard to spot in code review, Amazon does not rely on review. It tests rollback safety explicitly.
Production architecture: the two-phase deployment. Suppose a service stores objects in S3 as XML and wants to switch to JSON. Doing it in one deployment breaks the fleet: upgraded hosts write JSON that old hosts cannot parse. So the change is split:
| Version | Reads | Writes | Safe to roll back? |
|---|---|---|---|
| V1 (today) | XML | XML | n/a |
| V2: Prepare | XML and JSON | XML | Yes: no JSON exists yet, so losing the JSON reader costs nothing |
| V3: Activate | XML and JSON | JSON | Yes, back to V2: V2 can read the JSON written meanwhile |
| Later: cleanup | JSON only | JSON | Only after a backfill rewrites every old XML object |
The same trick fixes the heartbeat case. Prepare: every server accepts a 10-second gap but still sends every 5 seconds. Activate: servers start sending every 10 seconds.
Overlooked constraints.
- "Mostly deployed" is not deployed. Tools such as AWS CodeDeploy count a deployment as successful when a minimum number of hosts are healthy (
minimumHealthyHosts). For two-phase changes that is not enough. If one host missed the Prepare step, it will fail to read every JSON object after Activate. Amazon verifies that every single host reached Prepare before Activate starts. The author describes doing this host by host for a DynamoDB protocol change spanning many microservices. - Each step is reversible, but the pair is not. You can undo Activate (go to V2) or Prepare (go to V1), but you cannot jump from V3 back to V1, because V1 cannot read JSON. So a bake period of a few days separates the phases, long enough to be fairly sure you will not need V1 again.
- Old data lives forever unless you move it. You cannot remove the XML reader after Activate, because objects written before Prepare are still XML. Removing it needs a backfill: a tool that rewrites every object while the service keeps serving reads and writes. That tool is real engineering work with its own concurrency problems.
- Deploy order matters, and it reverses. For serialization changes, readers deploy before writers when rolling forward, and writers roll back before readers when rolling back. Test and prod must use the same order.
Serialization practices the article recommends.
- Do not invent a format. A custom binary layout looks simple and fast in version 1. Versions 2 to 10 hit problems JSON, Protocol Buffers, Cap'n Proto and FlatBuffers already solve: escaping, compatibility rules, and knowing whether a field was set or defaulted.
- Version the serializer, separately from the build. Store the serializer version with the data or in its metadata. Keep old serializer versions working in new code. Emit a metric of which data versions are being read and written, so operators can see a mixed fleet. Apply the same rule to RPC and API versions.
- Do not serialize types you do not own. Serializing Java collections by reflection ties your stored data to the JDK's private class layout. A JDK upgrade can change it and break deserialization. The same goes for classes from shared libraries owned by other teams.
- Tolerate and preserve unknown fields. If an old host reads a record with a field it does not know, it should keep the field when it writes the record back. Then new hosts can add fields without a two-phase deployment, because old hosts will not wipe them. Protocol Buffers does this by design.
How Amazon verifies it: upgrade-downgrade testing. Two real incidents shaped the test setup:
- A test environment had one server per service, so every deployment there was atomic, and mixed versions never ran together. Now test environments have several servers across AZs, like prod. The article notes that Amazon values frugality, but not at the cost of quality.
- Another test environment had several servers but deployed to all at once to save time. Again, no mixed fleet. Now test and prod use the same deployment configuration.
The test itself has three stages. Each lasts long enough for every API, workflow and batch job to run at least once, while synthetic traffic creates and reads records in quick succession:
- Deploy to about half the fleet, so old and new coexist.
- Finish the deployment.
- Roll back, the same way, until all hosts run the old version.
No errors in any stage means the change is safe in both directions.
What Amazon sacrificed. Speed of change. A format switch that could be one commit becomes three deployments, days of bake time, and a backfill job. Engineers also give up the freedom to use clever custom formats and reflection-based serialization. In return, rollback, which is Amazon's first response to any incident (Lesson 20), always works.
Deep Dive: compatibility rules as a small algebraShow
Let R(v) be the set of formats version v can read and W(v) the format it writes. During a rolling deployment between a and b, both versions are live, and both can read data written by either. So a transition a → b is safe exactly when:
W(a) ∈ R(b)(new hosts read old data), andW(b) ∈ R(a)(old hosts read new data), and- everything already stored is in
R(a) ∩ R(b).
Check the XML/JSON plan. V1 → V2: W(V1)=XML is in R(V2)=, and W(V2)=XML is in R(V1)=. Safe. V2 → V3: W(V2)=XML is in R(V3), and W(V3)=JSON is in R(V2). Safe. V1 → V3 directly: W(V3)=JSON is not in R(V1). Unsafe, which is why the jump is forbidden and why a long bake separates the phases. V3 → V4 (JSON-only reader) is safe only once stored data contains no XML, which is the backfill condition.
The heartbeat case fits the same shape with timing instead of formats. Let send(v) be the send interval and timeout(v) the receive timeout. A mixed fleet is safe when send(x) < timeout(y) for all live x, y. With send 5 and timeout 5 → send 10 and timeout 10 in one step, send(new)=10 is not below timeout(old)=5. Prepare raises only the timeout, keeping send=5 < 10. Activate raises send to 10, and every live timeout is now 10. In practice you would keep a margin, such as a timeout of 2 to 3 heartbeat periods, because heartbeats can be delayed by GC pauses or network jitter.
Unknown-field preservation removes the need for Prepare when adding an optional field, because R(old) already "reads" the new format by ignoring the field and W(old) writes it back unchanged. It does not help when the meaning of an existing field changes, such as units switching from seconds to milliseconds. Those still need two phases or a new field name.
Related production practices. The same algebra underlies the expand/contract pattern for database schema changes covered in online data migrations: add the new column (expand), dual-write, backfill, switch reads, then drop the old column (contract). Each step is individually reversible; the pair "add and drop" is not.
Lesson 18: Automating safe, hands-off deployments#
Assumptions. Amazon developers merge code and then forget about it. No one watches the deployment. The pipeline deploys to production several times a day, and the last human to look at a change is the code reviewer. For that to be safe, the pipeline must catch bad changes before production, limit the damage of any that slip through, and roll them back by itself. AWS's number one rule for production deployments is: never cause impact in more than one Region at a time, or in more than one AZ of a Region at a time.
Production architecture: four phases. A typical pipeline has source, build, test and prod.
1. Sources. Pipelines deploy far more than application code. Static web assets, tests, tools, infrastructure as code, runtime configuration such as rate-limit increases and feature flags, and even the host operating system all go through pipelines with the same safety checks and automatic rollback. Dependencies such as libraries, language runtimes and AMI IDs are bumped to the latest version at least weekly. A typical microservice has several pipelines: application, infrastructure, OS patching, config/feature flags, and operator tools. Separating them means a failing integration test in the app pipeline does not block an infrastructure fix. They all look alike, because a bad feature flag can hurt production as much as bad code.
2. Code review. Every commit to mainline must be approved by a member of the owning team, and the pipeline refuses to deploy unreviewed commits. Reviewers check correctness and deployability: enough unit, integration and canary tests, enough instrumentation to detect problems during rollout, and safe rollback. Some teams attach a checklist to every review, covering three areas: testing (new unit and integration tests, commands run locally), monitoring (covered by existing alarms, no unexpected change in CPU, memory, limits or downstream calls, can deploy without firing alarms), and rollout (can merge right away, dependent changes already in prod, can roll back cleanly).
3. Build and unit tests. Teams pick their own compilers, test frameworks, linters, static analysis and coverage thresholds. Builds run with no network access, which forces reproducible builds. Unit tests mock every dependency, which lets them test edge cases such as unexpected errors from AWS APIs. The output is packaged and signed.
4. Pre-production stages: alpha, beta, gamma. Alpha and beta run functional API tests and end-to-end integration tests. Gamma is as close to production as possible: same deployment configuration, same monitoring and alarms, same continuous canaries, and deployed in multiple Regions to catch regional differences.
- Integration tests call real APIs on real infrastructure for every meaningful customer scenario, both positive and negative (invalid input must return the correct error). They test whole workflows: create a resource, poll until it is ready, use it. They also check the assumptions the unit-test mocks made. Some pipelines add fuzz tests for internal errors and a short load test for latency and throughput regressions.
- Gamma one-box. The new build goes to one VM, one container, or a small slice of Lambda invocations, for 30 to 60 minutes, while the rest of gamma runs the current build. The one box joins the same load balancer or polls the same queue, so it gets its share naturally. With 10 containers it gets 10% of the canary traffic. This tests the mixed fleet from Lesson 17.
- Dependency compatibility. In gamma, a team's microservices call the gamma endpoints of their own sibling services, but the production endpoints of other teams' services such as S3 and DynamoDB. Some pipelines add a zeta stage where every call goes to production endpoints, including the team's own services, to prove the change works with what is live today.
5. Production: waves, one-box, rolling. Deploying to 24 Regions and 76 AZs one at a time would be safest but take weeks. So Regions are grouped into waves of growing size:
| Wave | Typical target | Why |
|---|---|---|
| 1 | One low-traffic Region, one AZ or cell at a time | Smallest blast radius for the first prod exposure |
| 2 | One high-traffic Region, one AZ or cell at a time | Busy enough to exercise every new code path |
| 3 | About 3 Regions in parallel | Confidence is building |
| 4 | Up to about 12 Regions in parallel | |
| 5 | All remaining Regions |
Even in big waves, each step touches only one AZ or cell per Region, which keeps the "never two AZs at once" rule. New changes can enter wave 1 as soon as the previous set moves on, so changes do not pile up into big bundles.
Inside each wave:
- Prod one-box first: one box per Region or AZ, serving at most about 10% of that AZ's or Region's traffic. Bad result means automatic rollback and no promotion.
- Rolling deployment for the rest, replacing at most 33% of boxes at a time so at least 66% of capacity always serves traffic. Every service is already sized to survive the loss of one AZ (Lesson 10), so 66% is enough. A new batch starts only after boxes in the previous batch pass health checks. Some teams roll forward only 5% at a time but roll back 33% at a time, because a slow rollback prolongs the damage.
6. Alarms and automatic rollback. Each microservice in each Region has a high-severity alarm: an OR of alarms on fault rate, p50, p90 and p99 latency, CPU, memory, disk, errors in logs, and failing health checks. It pages the on-call engineer and rolls back any deployment in progress; usually the rollback has begun before the engineer opens their laptop. A change can hurt a neighbour, so the deployment system watches a team-level aggregate alarm: the OR of every microservice's high-severity alarm plus the canary alarm. If any of them fires, every deployment the team has in flight in that Region rolls back.
A one-box serves too little traffic to move service-wide metrics, so one-box stages add alarms scoped to requests served by that one box: its own fault rate, latencies, resources and health checks. On top of team-defined alarms, the deployment system watches the standard metrics that Amazon's internal web framework emits, such as request count, latency and fault count, and rolls back on anomalies, for example request count dropping to zero.
7. Bake time. Some failures are slow. A memory leak or a bug in a nightly job may not show for hours, especially during quiet periods. If the pipeline promoted immediately, the bug could reach several Regions before it surfaced in the first. So each stage bakes: it keeps watching the aggregate alarm before promoting. Typical minimums: 1 hour after each one-box, 12 hours after the first regional wave, 2 to 4 hours after later waves, plus extra per Region, AZ and cell. Bake also requires a minimum number of data points, such as "at least 100 calls to the Create API", so a quiet API cannot pass by not being called. Default settings get a change to every Region in about 4 to 5 business days; critical services go slower. An urgent fix (a security patch, an outage mitigation) can have bake times reduced, but only after review by the organization's Principal Engineers, with only the minimal change in flight and with people watching.
8. Blockers and time windows. Before any prod stage starts, the pipeline checks the team's aggregate alarm and organization-wide large-scale event alarms. If something is already wrong, it does not deploy, because a new change could make an ongoing incident worse or harder to diagnose. Developers can override this to ship the fix. Time windows limit when deployments start. Too narrow and changes pile up, so the next deployment carries more risk. Too wide and failures happen at 3 a.m. when the on-call takes longer to respond. Most teams exclude nights, weekends and holidays; many also exclude Fridays and late afternoons, because a slow-burning problem from a 4 p.m. deployment shows up at night.
9. Pipelines as code. A team owns many pipelines, each with many stages for an ever-growing list of Regions and AZs. Amazon's internal pipelines-as-code tool pulls the central list of Regions and AZs, so a new Region appears in every pipeline automatically. Teams use inheritance: a parent class defines the waves and bake times, and each microservice's pipeline subclasses it.
Overlooked constraints.
- Config is code. Many large outages come from configuration, not code. Giving flags and limits their own pipeline with one-box stages and rollback is the defence.
- A one-box is invisible to fleet metrics. At 10% of an AZ's traffic, a one-box with a 50% error rate moves the fleet by 5%, which may stay under the alarm threshold. Per-box alarms fix that.
- Absence of traffic hides bugs. A deployment at a quiet hour can "pass" because nothing called the broken API. Data-point minimums in bake time close this gap.
- Rollback must be faster than rollout. Hence 5% forward, 33% back.
- Capacity during deployment is borrowed from failure headroom. The 33% batch is safe only because services already carry AZ-loss headroom. A service sized with no slack cannot use the same batch size.
What Amazon sacrificed. Latency to global availability: 4 to 5 business days for a change to reach every Region, much longer than a "deploy everywhere in an hour" shop. Pre-production environments in many Regions, and extra pipelines, cost money and engineering effort. Teams give up deploying on Friday afternoon. In exchange, almost no one babysits deployments, and a bad change usually hurts one AZ in one small Region for a few minutes before it rolls itself back.
Deep Dive: sizing bake time and data-point minimumsShow
Why data points, not just minutes. Suppose a bug fails 1 in 50 Create calls. With n Create calls observed, the chance of seeing no failure is (1 − 1/50)^n. At n = 20 that is about 67%, so the bug usually passes. At n = 100 it is about 13%. At n = 300 it is about 0.2%. A minimum such as 100 requests is a statistical test with a known miss rate. The Going Faster article's example of 3,000 positive data points and zero negative ones gives a miss rate of about e^(−3000p). For p = 1/1000, (0.999)^3000 ≈ e^(−3) ≈ 5%. For p = 1/10,000 it is about 74%. So even 3,000 clean requests only rule out failure rates above roughly 1 in 1,000. Rarer bugs are what later waves and longer bakes are for.
Why a long first bake. Slow-burn faults, such as leaks, clock or date bugs, cache expiry and daily batch jobs, often have a natural period of hours to a day. A 12-hour bake after wave 1 covers half a daily cycle in at least one Region, so a daily job or a peak period has a good chance of running against the new code before more Regions get it. Later waves can bake for 2 to 4 hours because the change has already lived through one long window.
Blast radius arithmetic. With 3 AZs per Region and one AZ at a time, the worst bad deployment in wave 1 affects about 1/3 of one small Region's capacity until rollback. The one-box stage shrinks that to about 10% of one AZ, so about 3% of that Region. Rollback times are minutes. If alarms fire within 5 minutes and rollback takes 10, the bad build serves 3% of one small Region for about 15 minutes. Compare that with an all-at-once deployment of the same bug: 100% of all Regions for the same 15 minutes, assuming you notice as fast.
Choosing batch size. If f is the fraction of capacity taken out per batch and h is the headroom (fraction of capacity you can lose and still serve peak), then you need f ≤ h. With 3 AZs and AZ-loss sizing, h ≈ 1/3, giving the 33% batch. A service in 2 AZs with 50% headroom could use bigger batches; a service running at 85% utilisation with no zonal headroom needs batches under 15%.
Lesson 19: Going faster with continuous delivery#
Assumptions. More than ten years before the article, Amazon measured how long it took to get a change from check-in to production. The answer was 16 days on average. Of those, about 1.5 days was writing code and less than an hour was actually building and deploying. Almost 14 days was waiting: for someone to start a build, to run a deployment, to run tests. The problem was not slow machines. It was people in the loop.
Production architecture: Brazil, Apollo, Pipelines. Amazon already had Brazil, a hosted build system that turns source into a deployable artifact, but a human had to start each build. It had Apollo, a deployment system, but a human had to upload the artifact. Amazon built Pipelines to connect them and automate every step in between. The pilot team cut check-in-to-production time by 90%.
Early Pipelines allowed only one release process per application. This limitation turned out to be a feature: many teams had separate processes for bug fixes and for big releases, and forcing one process made them consistent and simpler, and produced fewer defects. Adoption was by "seductive adoption": the Pipelines team had to make the tool so good that teams asked for it.
Overlooked constraint: measuring automation can reward skipping tests. Amazon tracked the share of teams with fully automated pipelines. Some organizations responded by automating release without adding tests, which met the goal and lowered quality. Amazon's answer was cultural, via the Ownership principle: the small, single-threaded team that owns a service is the team that gets paged and fixes it, so it has its own reason to test enough. But too much testing also loses, because competitors ship faster. "How much is enough" stays a judgement call for each team.
Overlooked constraint: best practices do not spread by email. Teams discovered good release techniques independently and announced them on mailing lists and in operations meetings. Not everyone saw them, and leaders could not tell whether their teams had adopted them. Amazon's fix was to mechanize learning: build best-practice checks into the tools. Each organization can configure which checks apply. A new check starts as a warning in the tool engineers use daily, so everyone sees it and learns when it will become mandatory, and the community can debate and refine it before enforcement. A group of senior engineers built the check list by cataloguing why releases failed and what would have prevented each failure.
The priority order. That exercise led to an explicit ranking: availability first, then speed, then developer convenience.
Four layers of defence against a defect reaching customers.
- Deployment hygiene. After deploy, quick checks confirm the new artifact started and is serving, for example with lifecycle hooks in a CodeDeploy AppSpec file to stop, start and validate. Check there is enough capacity (CodeDeploy's minimum healthy hosts). If the engine detects failure, roll back.
- Testing before production. Automated unit tests (including style, coverage and complexity checks) and integration tests (including failure injection and browser automation), with a strong bias toward also putting load and security tests in the pipeline. Smaller, faster tests come first, for quicker feedback. A pre-production stage runs with production configuration: it connects to production resources and data stores and calls the real production APIs of dependencies, but receives no customer traffic. It proves that the same code and config will work in prod.
- Validating in production. Deploy to cells, fully independent copies of the service, starting with a small group of customers. Watch error rates and roll back automatically if they rise. The article's example gate: wait for 3,000 positive data points with no negative ones. Then wait a fixed time as well, to "test the tests": maybe someone outside the team finds something the automated tests missed. Teams pick minutes or hours; the bigger the impact and the slower the fix, the slower the rollout. The rollout then speeds up as confidence grows, reaching the first customer quickly but the last customer slowly. Synthetic traffic runs at least once a minute against all public APIs and dependencies, so a broken production system is noticed fast even with no real traffic.
- Controlling when software is released. Pipelines halt on alarms (with an override so the fix itself can ship). They have time windows: AWS teams generally deploy during business hours so people are around, while some other Amazon teams prefer low-traffic hours. And they can block artifacts by content: refuse any build containing a known-bad package version or Git commit. This matters because deleting the bad package from the repository does not stop pipelines that have already built artifacts with it.
How the change was made. Measure the pain, fix it, iterate, celebrate. Teams unsure about continuous deployment were encouraged to encode their existing manual process in a pipeline first, manual steps and all. The pipeline was just a visual view of the release. As trust grew, they turned on automatic promotion one stage at a time until no step needed a human. Opt-out mechanisms exist for teams that need an exemption. Today new code is written to be fully automated from day one.
What Amazon sacrificed. Team autonomy over release process, at least partly: one process per app, organization-wide checks enforced by tools. Also heavy investment in internal tooling (Brazil, Apollo, Pipelines) instead of buying it. The return: from 16 days of mostly waiting to changes that flow automatically, with smaller, safer releases.
Deep Dive: why waiting dominates, in queueing termsShow
The 16-day number is a textbook case of flow efficiency: value-adding time divided by total lead time. Here (1.5 days + 1 hour) / 16 days ≈ 10%. Each handoff to a human adds a queue. If a build only starts when someone gets to it, and people batch that work (once a day, once a week), the expected wait per handoff is about half the batching interval. Five handoffs with weekly batching average about 2.5 weeks of waiting, close to what Amazon measured. Automation removes the batching interval, so the waiting term goes to near zero.
Removing waits also changes batch size, which changes risk. With releases every two weeks, each release carries two weeks of changes; if each change has an independent 1% chance of causing an incident and a team merges 30 changes in two weeks, the chance a release is bad is 1 − 0.99^30 ≈ 26%, and when it is, you must search 30 changes for the culprit. With one change per release, each release is bad 1% of the time and the culprit is obvious. Total incidents stay similar, but each is smaller and faster to fix, and rollback removes exactly one change. This is the same argument that later research on software delivery performance (the DORA metrics: deployment frequency, lead time, change failure rate, time to restore) found across many companies: high performers deploy more often and have lower change failure rates.
Lesson 20: My CI/CD pipeline is my release captain#
Assumptions. Amazon teams used to rotate a release captain each week. That developer chose the release date, decided which changes went in, assigned a version number, cut a release branch, built and tested release candidates, and wrote and got approval for a manual plan: which build goes where, in what order, which metrics to check before each next step, and how to roll back each environment. Developers disliked the job because it took them away from building. An old team wiki summed up the change: the team had moved to pipelines and no longer managed individual releases. The pipeline is now the release captain.
Production architecture, part 1: trunk-based development. A change is on its way to prod as soon as its review is approved and merged. There are no release branches. Most teams use trunk-based development: small, frequent commits to one shared branch (called mainline internally), instead of long-lived feature branches merged in big chunks. Developers work on a local clone of mainline. Their tooling may back up local commits to a personal branch, but nothing else. Work is split into small changes that each get reviewed, merged and released on their own, typically after a few hours to a few days of local work. Before review, the developer rebases on the latest mainline. The review tool pushes the commits to a short-lived Git reference tied to that review, which is discarded after merge.
The rare exception: an urgent security fix may get a short-lived release branch containing only the fix, without unrelated undeployed changes from mainline, so it can be fast-tracked. Principal Engineers and operational-safety experts review it, and the branch is retired once the fix is everywhere.
Part 2: stages, approvals and promotions. The pipeline models production as many small environments: Regions, then one environment per AZ, plus a one-box environment per AZ. A release moves through stages. Each stage deploys to one or more environments in parallel, then runs approval steps (integration tests, alarm monitoring). If everything passes, the stage approves the release and promotes it to the next stage. If anything fails, no promotion, and prod environments usually roll back automatically. The article's sample pipeline reaches 26 Regions in five waves. In wave 3, for instance, stage 1 deploys one-box environments in the first AZ of each wave Region in parallel, stage 2 the full first-AZ environments, stages 3 and 4 the second AZ, and stages 5 and 6 the third AZ.
Part 3: many releases in flight. With a human captain, there was one release at a time, because tracking several by hand was error-prone. That made changes wait: anything merged during a week-long rollout waited for the next release, and the next release grew bigger and riskier. Now each stage acts as an independent workflow. As soon as it finishes with its current release, it takes the next approved one, without waiting for later stages. Many releases are in flight at once, each in a different stage. Order is preserved: if a newer release catches up with an older one, the newer supersedes the older. A release that fails pre-prod tests is simply overtaken by the next one with the fix. If a big stage (say, a huge Region with many EC2 instances) is slow, several releases may queue in front of it; when it frees up, only the latest approved one is promoted.
Part 4: immutable, transparent artifacts. Every merge produces a new immutable artifact with a unique ID: AMIs, Docker images with unique tags, Lambda packages, CloudFormation templates stored in S3 under unique names. Later stages deploy that exact artifact and never touch the source repository. The pipeline records which commit built which artifact and which environments run it, so developers can see the deployment history of an environment, or where a given commit has reached, for example "has my bug fix reached every Region yet?". No one computes version numbers.
Part 5: rollbacks first. The first question to an on-call engineer in an incident is: "Do you have any recent deployments that need to be rolled back?" Amazon mitigates first and debugs later. Rolling back every recent deployment across the team's microservices is often the fastest fix, even before anyone knows whether a deployment caused the problem. Hunting for the guilty commit, or rolling forward a fix, prolongs customer impact.
- Alarms roll back automatically, so the rollback has usually started before the engineer is engaged.
- A manual rollback is a few clicks: the pipeline picks the last release that was deployed and approved in that environment, shows a diff of source and library changes, and on approval runs a normal deployment of the older artifact. The rollback restores application, infrastructure templates and config together, because they are in the same artifact.
- Immutable environments make rollback clean. Deploying into the same directory on an EC2 host can leave newer files behind that change the old code's behaviour. Replacing AMIs, containers and Lambda versions avoids that. Teams that do deploy onto existing hosts write each version to a new directory and flip a symlink, and rollback does the same in reverse.
- Latent changes. Sometimes the culprit was deployed a week ago and several deployments have happened since. Rolling back one step does not remove it. The developer can pick an older release, but must weigh losing a week of features and fixes against waiting for a roll-forward. The UI shows each release's history, contents and approval status to help.
- Starting a rollback disables promotions into and out of the affected environments, so the pipeline does not redeploy the bad release. The developer may proactively roll back other environments that might be affected, or wait for a fix if the problem is local.
- The repository is untouched by rollback. The bad code is still on mainline until someone merges a fix or a revert commit. Then the pipeline rolls it forward, and the developer re-enables promotions.
Overlooked constraints.
- Rollback is a deployment. It has to pass the same steps, take the same time per batch, and is only safe if the change was backward compatible (Lesson 17).
- Superseding hides releases. A release that is overtaken never reaches later stages on its own. That is fine, because its changes are included in the newer one, but it means a fix can sit behind a slow stage.
- Not everything can do this. Mobile apps and device firmware ship versioned releases that users install, so those teams still run release branches and schedules.
What Amazon sacrificed. The ability to hand-pick what goes in a release, and the comfort of long-lived feature branches. Developers must slice work into small changes that are safe to ship half-finished, usually behind feature flags. Every service must support immutable artifacts and infrastructure as code. In return, the weekly captain job disappears, changes reach prod in small, traceable steps, and rollback is boring.
Deep Dive: why 'roll back first' is the right defaultShow
Let T_rb be time to roll back, T_diag time to find the cause, and T_fix time to build and deploy a fix. Rolling forward ends impact at T_diag + T_fix; rolling back ends it at T_rb. With automated rollback, T_rb is minutes. T_diag alone is often tens of minutes to hours, and T_fix through a cautious pipeline can be hours. So whenever a recent deployment has even a moderate chance p of being the cause, the expected impact time of "roll back now" is p · T_rb + (1 − p)(T_rb + T_diag + T_fix), versus T_diag + T_fix for "investigate first". Rolling back first costs only T_rb extra in the case where the deploy was innocent, and saves T_diag + T_fix − T_rb when it was guilty. With T_rb = 10 minutes and T_diag + T_fix = 2 hours, rolling back first wins whenever p > 10/120 ≈ 8%.
That calculation only holds if rollback is safe (backward-compatible changes, Lesson 17), fast (immutable artifacts, big rollback batches, Lesson 18) and cheap to undo again (rolling forward later is just another deployment). Amazon invested in all three precisely so that the cheap, mechanical action could be taken first, without a debate during an incident.
Lesson 21: Instrumenting distributed systems for operational visibility#
Assumptions. At Amazon the team that writes a service also runs it, and everyone on that team, from developers to managers, acts as its owner and operator. They set yearly goals for availability and latency and need data to meet them. Two facts shape what they measure:
- Tail latency matters more than the average. Amazon looks at p99.9 and p99.99, because one slow request in 1,000 or 10,000 is still a customer having a bad time. The article reports an empirical asymmetry: work that cuts high-percentile latency usually cuts the median too, while work that cuts the median often leaves the tail alone.
- Latency multiplies across services. An amazon.com page is assembled by many services. A tail-latency bump deep in the call chain shows up, amplified, at the top.
Production architecture: log first, aggregate later. The core design decision is unusual. Services do not keep counters in memory and flush summaries to a metrics system every minute. Instead, every unit of work writes one structured log entry containing all its counters, timers and properties. A separate pipeline (for AWS customers, the CloudWatch Logs agent to CloudWatch Logs) computes aggregate metrics from those logs in near real time, and CloudWatch Alarms reads the aggregates. One instrumentation path gives you both the dashboard number and the exact request behind it.
There are two kinds of log, usually in separate files:
| Log | Shape | Used for |
|---|---|---|
| Request (service) log | One structured entry per unit of work: who called, what for, counters, timers, properties | Metrics, alarms, audit trail, per-request trace |
| Application (debug) log | Unstructured lines (Log4j-style warn and error) | Stack traces and local detail |
A shared instrumentation library means common HTTP clients record their own calls automatically, so a team that calls another service gets dependency metrics for free.
How deep instrumentation goes. The article takes a 15-line getProductInfo handler (local cache, then remote cache, then database) and lists the questions an operator would need answered: which product and category, who called, local cache hit or miss, remote cache hit, time to read and to deserialize from the remote cache, how full the local cache is, how long the DB query took, whether it failed and why (timeout, bad query, lost connection, connection pool full, slow to connect), how long cache population took and whether it evicted items, and how big the response was. The instrumentation code is longer than the business logic. Libraries help, but someone still has to decide which questions matter.
Drilling down works in three levels: aggregated metrics and alarms show something is off; per-stage timers show which part is slow; raw request logs for that window show the exact error or the request attribute that triggers the edge case. A trace ID stamped by the front-door service and passed to every dependency lets you join logs across services afterwards, or in near real time with AWS X-Ray.
Request-log practices (how to log):
- Exactly one entry per unit of work. Not several per request, not one per batch. In non-blocking services, pass a single metrics object through the pipeline stages and write it once at the end. Plan this up front; it is hard to retrofit.
- Long-running tasks (minutes to hours) are the exception: write periodic progress entries.
- Log the request before validating it, so rejected, unauthenticated and throttled requests are still recorded. Sanitize first: truncate (no 1 MB strings), escape, and strip control characters, so a caller cannot inject fake log lines.
- A verbosity knob you can raise per host, per client or by sampling while debugging, and remember to turn back down.
- Short but readable metric names. Amazon's log format repeats every counter name as text in every entry and has been in use for over 15 years, so name length is a real cost. Amazon has been moving toward the binary Amazon Ion format.
- Disk sized for max throughput. Load-test at maximum sustained load, or overload, for hours and confirm logs are shipped off-box as fast as they are written. Put logs on their own partition so a full log disk does not take down the root filesystem.
- Decide what happens when the disk fills: refuse traffic, or run blind without logs? Running blind is risky, so detect nearly-full disks.
- Synchronize clocks with Chrony or ntpd and monitor drift. Amazon does not rely on synchronized clocks in its distributed algorithms, but logs from different hosts are meaningless without them.
- Emit zeros. For availability, emit 1 on success and 0 on failure, so the average of the metric is the availability rate. A leader-election process can emit 1 when leader and 0 when follower; if a follower stops emitting zeros, it is broken and cannot take over.
What to log:
- Latency and availability of every dependency call. Without this you are left comparing graphs and guessing whether a dependency spike caused your failure.
- Break dependency metrics down by call, resource, status code and retry count. DynamoDB callers who logged per table, per error code and per retry count discovered that "network latency" was really throttling retries, pagination or conditional-check-failure retries.
- Queue depth whenever you touch a queue (cheap for in-memory queues, often free in distributed-queue API responses), plus time in queue, which requires stamping an enqueue time on each message.
- A counter per error reason, starting with one per exception class, so error trends show on graphs without log mining.
- Errors grouped by cause. At minimum, client's fault versus server's fault. Finer: DynamoDB conditional-write failures are expected behaviour, while "invalid request" errors are probably bugs.
- Metadata about the request that a customer would expect you to have, such as DynamoDB's table name and whether a read was consistent, but not the data itself.
- Access control and encryption on logs, with regular review of who has access.
- No overly sensitive data. Log who made the request, not payload fields that do not affect routing. If parsing a customer message fails, do not log the message. Use opt-in logging of fields, so a sensitive field added later is excluded by default. API Gateway's configurable access log is an example.
- Trace IDs passed in method signatures. In multithreaded code, framework magic (thread-locals) is error-prone, so Amazon passes trace IDs, the metrics object, and a general Context object explicitly. AWS services also propagate customers' X-Ray trace IDs so customers can trace across AWS services.
- Separate latency by outcome and size. Errors such as throttling, access-denied and validation are fast. If many clients get throttled, a single "Time" metric improves while customers suffer. Log a separate success-latency timer and alarm on that. For size-dependent operations, emit
SmallRequestLatencyandLargeRequestLatency.
Application-log practices: keep it free of spam (consider disabling INFO and DEBUG on the request path in production; the request log is the place for tracing); include the request ID so you can jump between logs (set it correctly when a thread picks up new work); rate-limit error logging so a failure storm does not write gigabytes of stack traces; use lazy format strings so disabled DEBUG lines cost nothing; and log the request IDs returned by failed downstream calls so the other team can find their side.
High-throughput practices. Most Amazon services log every request. DynamoDB, which served over 20 million requests per second of Amazon-internal traffic alone at peak, still logs every request, for troubleshooting, audit and compliance. Techniques when per-host throughput gets high:
| Technique | Benefit | Cost |
|---|---|---|
| Sampling (every Nth, with a skipped-count field; reservoir sampling; favour errors and slow requests) | Less volume | Cannot answer "what happened to this customer's request"; some compliance regimes forbid it |
| Background serialization and flush thread | Takes logging off the request path | Simple |
| Rotate every minute, not every hour | Shipping agent reads from page cache; CPU and IO spread evenly | More files |
| Write pre-compressed | About half the disk IO, no periodic compression spike | Need a format that survives truncation on crash |
| ramdisk / tmpfs | No disk writes | Works best with per-minute rotation |
| In-memory aggregates | Needed at hundreds of thousands of TPS per host | Lose per-request detail; do not optimize early |
| Monitor logging's own CPU and IO | Know when you approach limits | Long load tests needed to prove agents keep up |
Analysis tools. Locally: cat, grep, cut, sort, uniq, plus jq and RecordStream. A classic "top talker" query is a pipeline of grep, cut, sort and uniq -c. At scale: CloudWatch Logs Insights, X-Ray, Athena, EMR, Redshift. Teams watch for the moment local tools stop scaling and move to distributed analysis before an incident forces them to.
Overlooked constraints. Logging every request is expensive, in CPU, disk, network and storage, and the article accepts that cost because without detail you cannot answer customers. Logging can also fail the service (full disks) or leak data. And instrumentation is never finished: each investigation that hits a dead end should end with a new metric, tested and code-reviewed.
What Amazon sacrificed. Cheap telemetry and short code. Every handler carries more instrumentation than logic, and the log pipeline is a major system in its own right. In return a single approach gives fleet-level dashboards and the full story of any one request.
Deep Dive: why 'log first, aggregate later' and the 1/0 availability trick workShow
Aggregates cannot be disaggregated. If each host keeps a running average latency and flushes it each minute, you can never recover p99 for the fleet: averages of averages are not percentiles, and percentiles of percentiles are not either. With raw per-request entries, any statistic (p99.9 across the fleet, p99 for one customer, p50 for requests larger than 1 MB) can be computed after the fact, including ones you did not think of before the incident. That flexibility is the real reason for logging everything. The modern equivalents are "wide events" or "canonical log lines" (one rich record per request, discussed on the observability page) and mergeable sketches such as t-digest or HDR histograms when you must pre-aggregate.
The 1/0 trick. Let x_i = 1 for success and 0 for failure. The mean is Σx_i / n = successes / requests = availability. Because the statistic is just a mean, every metrics system can compute it per host, per AZ or per API, and it combines correctly across dimensions by weighting by sample count. Two side benefits: a missing metric now means "the service stopped reporting", never "no errors", and sparse error metrics no longer produce empty graphs (Lesson 22 makes the same point for dashboards).
Throttling pollutes latency, worked. Suppose 1,000 requests per second succeed at 50 ms. A misbehaving client adds 4,000 per second that are throttled in 1 ms. The blended average falls from 50 ms to (1000·50 + 4000·1)/5000 ≈ 10.8 ms, and p50 drops to about 1 ms. The dashboard "improves" by 5× during an incident. A success-only latency metric stays at 50 ms and the throttle count spikes, which is the true picture.
Sampling estimate. With 1-in-N sampling and a "skipped" count, the estimated total is the sum over sampled entries of (1 + skipped). For a rare error with rate p among R requests, the expected sampled count is pR/N. At R = 1 million, p = 10⁻⁴ and N = 100, you keep about 1 example, enough to see that it exists but not to debug a specific customer complaint. That is why Amazon prefers to log everything and why error-biased sampling exists when you cannot.
Lesson 22: Building dashboards for operational visibility#
Assumptions. At AWS scale, automated alarms, remediation workflows (such as shifting traffic away from an AZ) and automated deployments handle almost everything. Still, humans need to see what is happening: to quantify impact, check that automation is doing the right thing, and in rare safety-critical steps, confirm it. The article's sharpest claim: any process that depends on a human regularly looking at a dashboard will eventually fail through human error, however often the review happens. So detection belongs to alarms, and dashboards are for understanding once an alarm has fired. Alarms come in two kinds: proactive (approaching a limit, before impact) and reactive (already impaired). The page sends the operator straight to the right dashboard and runbook.
Amazon calls building and maintaining dashboards dashboarding and treats it as a first-class engineering activity alongside design, coding, testing and deployment.
Who uses dashboards. During an incident, several on-call operators work through tasks (quantify customer impact, triage, trace across services to the root cause, watch automated remediation, run runbook steps), while peer teams and business stakeholders watch impact. They coordinate through incident tools, chat rooms with bots (AWS Chatbot) and calls. Every week, operations review meetings with senior leaders and engineers pick dashboards to review with a "wheel of fortune" (a random spinner), so every team must be ready. Capacity planners use long-range business and usage dashboards.
Production architecture: dashboards by audience.
| Dashboard | Audience | Content |
|---|---|---|
| Customer experience (the most important) | Operators plus many stakeholders | Overall health and goal adherence, from the service itself, client-side instrumentation, synthetic canaries and remediation systems; "how many customers are affected, and which are worst hit?" |
| System-level | Operators | Per API: input (request counts, request-size percentiles, auth failures), processing (branch counts, backend call counts, failures and latency, fault logs, traces), output (response type counts with error breakdown per customer, response sizes, time to first byte and to last byte) |
| Service instance | Operators of one cell or partition | The customer view for a single instance, without noise from others |
| Service audit | Operators, weekly reviews | All instances in all AZs and Regions, to audit that alarms cover everything |
| Capacity planning and forecasting | Planners | Growth over long horizons |
| Microservice-specific | Owning team | Implementation-specific metrics, partly aggregated; ad-hoc queries for drill-down |
| Infrastructure | Owning team | EC2, ECS/EKS, Lambda: CPU, network, disk IO and space, cluster, auto-scaling and quota metrics |
| Dependency | Owning team | Upstream (proxies, load balancers) and downstream (data stores, queues, streams) as measured by this service, plus certificate expiry dates and dependency quota usage |
High-level dashboards stay deliberately sparse; too many graphs bury the message.
Design conventions. Consistency within and across dashboards matters most. A good test: can a new operator learn how the service works from the dashboards? Amazon also warns against assuming the reader knows as much as the author. The conventions:
- Most important at the top, because people read the first screen as the summary. For web services that is aggregate availability and end-to-end latency percentiles.
- Bigger graphs for key metrics; legends must not squeeze the plot.
- Lay out for the smallest expected screen, so a sleepy operator on a laptop at 3 a.m. does not miss graphs hidden off to the right.
- Show the time zone, and default to UTC for dashboards used across time zones.
- Same time range and resolution for every graph, and same width within a section, so events line up vertically.
- Not too many points. Three hours at one-minute resolution is 180 points, clear even in a small widget. Standard interval × period presets: 1 h × 1 min (60, live events), 12 h × 1 min (720), 1 day × 5 min (288, daily trend), 3 days × 5 min (864), 1 week × 1 h (168, weekly trend), 1 month × 1 h (744), 3 months × 1 day (90, quarterly), 9 months × 1 day (270), 15 months × 1 day (450, long-term capacity).
- Draw alarm thresholds as horizontal lines; for ML-predicted dynamic thresholds, plot the threshold series next to the actual. Also draw tested limits, hard resource limits and goals.
- No horizontal lines on dual-axis graphs (which axis does the line belong to?). Split into two graphs instead.
- Do not mix wildly different scales on one axis, such as p0 and p100 latency.
- Be careful with auto-fitted y-axes: zooming to the data range makes tiny wiggles look dramatic.
- One idea per graph. For request processing: availability % (faults ÷ requests × 100); p10, average and p90 latency; p99.9 and max latency, as three adjacent graphs.
- Explain each graph in text beside it: what it means, what normal looks like, and links to runbooks (for experts the dashboard can be the runbook), deeper dashboards, the same dashboard for other cells, the deployment pipeline, and dependency contacts.
- Single numbers or alarm-status widgets where a full time series adds nothing.
- Avoid sparse metrics. A metric emitted only on error produces empty graphs that look like "no data". Make the service emit zeros, so a blank graph means "telemetry broken".
- Per-mode graphs: if latency depends on request size or input combination, add graphs for small, medium and large, or per execution mode.
Maintenance. Code review asks "do I need to update any dashboards?", and developers update dashboards before the change deploys, so no one edits dashboards mid-incident. Dashboards are kept as infrastructure as code in version control, deployed by the same tools, and identical in alpha, beta, gamma and prod, so pipelines validate the change the same way everywhere. A dashboard that is unusually detailed is a smell: it may mean humans are doing anomaly detection that alarms should do, so teams invest in better instrumentation and alarms and prune dead graphs. Every post-mortem asks: did the dashboards clearly show customer impact, help find the root cause, and show time to recovery? If not, the action items include dashboard fixes.
What Amazon sacrificed. Engineer time on something many teams treat as an afterthought, plus the discipline of treating dashboards as code. In exchange, a new on-call can read the system, and a random weekly audit keeps every team honest.
Deep Dive: what the dashboard rules preventShow
Why the top of the page matters. In an incident the first glance decides the next ten minutes. If the top graph is CPU, operators chase CPU. Putting customer-facing availability and latency first anchors the investigation on impact, the same priority as the "mitigate first" rule in Lesson 20.
Why ~180 points. A small widget is a few hundred pixels wide. With more data points than pixels, the renderer must merge them, and depending on the method (average, min, max, last) short spikes can vanish or noise can fill the area. Keeping points below the pixel count means each spike is drawn. Switching resolution for longer ranges (5-minute points for a day, 1-hour for a week) keeps the count in the 100 to 900 range in every preset.
Why separate p99.9/max from p10/avg/p90. If p90 is 40 ms and max is 4 s, a shared linear axis spans 0 to 4,000 ms and the p90 line looks flat at the bottom, hiding a doubling from 40 to 80 ms. Splitting gives each group a readable scale. Log scales are an alternative but are easy to misread at 3 a.m.
Why random selection in ops reviews. If teams knew which dashboards would be reviewed, they would polish those. A random draw makes the expected quality of every dashboard matter, which is the same principle as random audits in accounting.
Lesson 23: Resilience lessons from the lunch rush#
Assumptions. This 2025 article is a map of the whole Library through a restaurant analogy. A restaurant's capacity (tables, cooks) is fixed for years; a cloud service's capacity is elastic. So restaurants are often overloaded, while Amazon works hard to make overload rare. Its first line of defence is automated forecasting with large buffers for events such as Prime Day and the day after Thanksgiving, automatic quota-increase requests when nearing a limit, pre-provisioning for the loss of one AZ (Lesson 10), and EC2 Auto Scaling for short-term variation. Everything else in the article is for the rare case when demand outruns all of that. It sorts techniques into three groups: operational practices (react after overload is detected), architectural practices (designed in to prevent overload), and well-behaved client practices (do not make a struggling dependency worse).
Operational practices.
- Load shedding = skipping side work. When busy, servers stop refilling salsa and rolling cutlery to focus on orders and food. Beyond a tipping point, extra load lowers goodput (work completed within the client's timeout), because accepting, queueing and context switching all add latency. Shedding keeps goodput flat. It can be per service, per API or per resource, triggered by request rate, thread-pool use or queue depth. Overload tests find the tipping point and prove goodput stays flat past it. Shedding is coarse and indiscriminate, so it is never the only tool (Lesson 4).
- Fairness and quotas = time limits on tables. On holidays a restaurant limits how long a party can hold a table. AWS enforces Service Quotas on API TPS, EC2 instance counts and Lambda concurrency, using rate-limit algorithms such as token bucket (the most popular), leaky bucket, EWMA, fixed window and sliding window, with bursting allowed when there is spare capacity. Quotas are published (console and CLI), usage is exposed as CloudWatch usage metrics so customers can alarm before hitting a limit, and increases can be requested. Cost: occasionally throttling a customer (Lesson 8).
- Auto scaling = stocking ingredients by trend. Seasonal forecasting handles summer gazpacho, but not National Gazpacho Day in December, a short spike where making more for tomorrow is useless; the kitchen "86s" (removes) the item. Similarly, a spike shorter than auto scaling's detect-and-launch time must be absorbed by the capacity buffer, then by load shedding and rate limiting while scaling catches up or the spike passes.
Architectural practices.
- Managing queue depth = the waitlist. A long waitlist makes wait estimates wrong, and customers who give up are still in the kitchen's ticket queue, so cooks make meals no one will eat. If the kitchen never learns who left, the backlog can feed itself, like a metastable failure. Fixes: bound the queue and reject excess, or serve LIFO so the freshest, most likely to succeed work goes first. Both make the queue testable at a known maximum size, at the price of rejecting or ignoring some work (Lesson 6).
- Constant work = passed hors d'oeuvres. At private events with guests coming and going, the kitchen sends out platters at a fixed rate sized for a full venue instead of taking individual orders. Load is flat; some food is wasted. The cloud version: servers poll an S3 config file every few seconds and apply it whether or not it changed. You must size for the constant rate and accept wasted work; sometimes event-driven is genuinely required (Lesson 13).
- Smaller service in control = the bartender walking the bar. With three rows of customers and far fewer bartenders, the bartender chooses whom to ask next, pulling orders. In AWS, the control plane (create, update, delete; small fleet) usually pushes to the much larger data plane, so the big fleet cannot overwhelm the small one. Costs: the big fleet must store what it receives and recover if it is lost or corrupted; the small fleet must track every node, share push work evenly, and ensure nodes that were briefly offline still converge (Lesson 5).
- Avoiding cold caches = the microwave queue. Kitchens pre-warm popular soups. When a pot runs out, servers queue at a microwave that can heat a few cups at once. A cache that started as an optimization becomes critical; when it goes cold (restart, outage, traffic shift), the origin, sized for perhaps 10% of reads, gets 100% and times out. Fixes: limit concurrency with rate limiting or shedding while warming; pre-warm from the most recent or most popular keys; or always read from the origin as well so the database is sized for full load and the cache only provides redundancy, removing the bimodal behaviour. And ask whether a cache is right at all (Lesson 15, Lesson 7).
Well-behaved clients.
- Circuit breakers = pausing food orders. When the kitchen is swamped, stopping all orders lets it catch up, but if only the grill is backed up, it needlessly blocks salads and fries. Software breakers have closed (normal), open (block calls) and half-open (let a few through to test) states. They protect the dependency and also the caller's own threads, CPU and ports. The danger is making a small event big: if keys A to H are hot because of a product launch, a whole-dependency breaker also blocks I to R and S to Z. Amazon scopes breakers to the dependency's fault domains (partition, host, customer, cell), which needs knowledge of how the dependency is partitioned, and tests thresholds so one throttled client or one latent bug cannot trip the breaker for everyone.
- Retries = asking the server again. A patron who asks once more after a while is reasonable; one who asks every passing server multiplies the work and gets several bottles of dressing. In call chains, retries multiply: with
kattempts per hop and depthn, the last service seesk^ncalls. Three attempts at each of two hops means the third service gets 9 requests and the system does 12 in total. Amazon's adaptive retries (in the AWS SDKs and CLI) add two token buckets on top of backoff with jitter:- A retry quota: each retry spends tokens, more for timeouts (a sign of severe overload) than for 500s; each success refills a fraction, such as 0.1 or 0.01 tokens, so you earn one retry per 10 or 100 successes; errors refill nothing.
- Client-side rate limiting for throttled requests: a bucket whose fill rate and size grow after successes and shrink after throttles, applied to original requests as well as retries. Rate limiting is checked first, then the retry quota. Put limiters and breakers as close to the source as possible (Lesson 1).
Operational visibility, the restaurant managers. Front-of-house and back-of-house managers each watch their area; measuring only kitchen time misses the line outside. So: measure from many perspectives; measure utilisation of CPU, memory, disk, thread pools, queues and quotas as early warnings; get dimensionality right (per-API error rates, per-AZ metrics because an AZ is a fault domain); for high-cardinality dimensions such as hosts or customers, use CloudWatch embedded metric format logs with Contributor Insights to find the top-N contributors ("which customer is driving load?", "which host is slowest?"); and hold weekly dashboard and alarm reviews (Lessons 21 and 22).
The last point. Most of these techniques are for request/response services. The article suggests asking whether pub/sub, batch or push over WebSockets would be less exposed to overload in the first place.
What Amazon sacrificed. Money, mostly: over-provisioning for AZ loss and forecast buffers mean paying for capacity that is idle on a normal day. Each technique has its own cost: shedding and quotas fail some customers; LIFO and bounded queues drop work; constant work wastes effort; push models put state-management burden on the small fleet; fine-grained breakers need deep knowledge of the dependency. Amazon uses a few well-tested techniques built into shared libraries and services, so each team does not reinvent them.
Deep Dive: retry amplification and adaptive retry quotas, workedShow
Amplification. With k total attempts per hop and n hops, the deepest service receives k^n requests per user request when everything below it is failing, and the total work across hops is k + k² + … + k^n. For k = 3, n = 2: 3 + 9 = 12, matching the article's figure. For k = 3, n = 5 the deepest service sees 243 requests per user request, which is why Amazon's rule is to retry at one layer (Lesson 1).
Retry quota bound. Suppose the bucket refills 0.1 token per success and a retry costs 1 token (5 for a timeout). With success rate s and request rate R, the sustainable retry rate is at most 0.1·s·R (plus the burst stored in the bucket). At s = 99%, that allows about 9.9% retries, more than enough to hide occasional errors. At s = 20% during an outage, it allows only 2% of R, so load on the dependency rises by at most 2% instead of the 200% that "retry twice on every failure" would add. Timeout retries at 5 tokens cut that to 0.4%. The bucket turns a fixed retry policy, which amplifies load exactly when the dependency is weakest, into one that backs off in proportion to the failure rate.
Client-side adaptive rate. The fill rate behaves like TCP congestion control: grow on success, shrink on throttle (additive increase and multiplicative decrease is the classic choice). Many clients sharing one throttled server converge toward a fair share of its capacity without explicit coordination, the same way TCP flows share a link (Chiu and Jain's 1989 analysis of increase/decrease algorithms is the standard argument for why AIMD converges to fairness).
Cold cache arithmetic. At 100,000 reads per second with a 90% hit rate, the origin serves 10,000. A cold cache sends 100,000, which is 10× its normal load. If the origin's capacity is 15,000, it saturates and latency climbs past client timeouts, so retries pile on. Limiting concurrency to the origin's 15,000 while the cache refills loses 85% of requests for a short time instead of 100% for a long time. Pre-warming the top 1% of keys, which in a typical Zipf-like distribution may cover half of reads, can halve the overload immediately.
When to Use It#
The Builders' Library is a source of patterns, not a product. Reach for its lessons when you see these signals:
- Retries in more than one layer, or no jitter on retries and periodic jobs. Every service with clients needs Lesson 1, from the first day.
- Any mutating API that clients may retry, especially one that creates resources or moves money. You need client request tokens (Lesson 2).
- Throughput that falls when load rises past a point. That is a goodput collapse, and load shedding, bounded queues and LIFO apply (Lessons 4, 6).
- One fleet much larger than another, such as thousands of agents talking to a control plane of ten hosts. Put the small side in control (Lesson 5).
- Queues whose backlog takes hours to drain after a short outage. Add TTLs, sidelining and per-tenant queues (Lesson 6).
- Several tenants sharing a fleet, with any one able to send 10× its normal load. Quotas, admission control and shuffle sharding (Lessons 8, 11).
- A data plane that must stay up when the control plane is down, or a service in several AZs. Static stability and pre-provisioned headroom (Lesson 10).
- Configuration or health state pushed to thousands of hosts. Constant work: push everything, every few seconds (Lesson 13).
- Load balancer health checks that call dependencies. Fail open and separate liveness from readiness (Lesson 14).
- A cache in front of a database sized below full read load. Plan for cold starts and cache outages (Lesson 15).
- More than a handful of deployments per week to a fleet in several zones. Pipelines with one-box, waves, bake time and automatic rollback (Lessons 17 to 20).
- Incidents where you cannot tell which dependency caused a slow request. One structured log entry per request with per-dependency timers (Lesson 21).
When NOT to Use It#
- A single-host internal tool with a few users. Shuffle sharding, cells and five-wave pipelines are overhead without benefit.
- Offline batch jobs. Lesson 16's point is that offline systems get the benefits of distribution with little of the pain; you mostly need idempotent tasks and checkpoints, not load shedding.
- Early startups that cannot afford 50% idle headroom. Static stability assumes you can pay for spare capacity; until then, accept slower recovery and invest in fast scaling and good alarms.
- Teams with no automated rollback. Copying Amazon's "deploy to prod many times a day" without the alarms, one-box stages and rollback safety is how you get frequent outages instead of frequent deploys.
- Copying numbers instead of reasoning. 33% deployment batches, 12-hour bake times and a 0.1 retry-token refill fit Amazon's scale and traffic; derive your own from your headroom, traffic and failure rates.
- Cross-region active-active with strong consistency. The Library mostly describes zonal and regional fault isolation; global consistency needs the tools in multi-region data and consensus.
How to Implement It#
A practical order for adopting the lessons in an ordinary service, from cheapest to most expensive:
- Set timeouts on every remote call, from measured latency (for example, the p99.9 of the dependency plus a margin). Never leave library defaults.
- Retry in one layer only, with capped exponential backoff, full jitter and a retry token bucket (Lessons 1, 23). Make mutating calls idempotent with a client token stored next to the result (Lesson 2).
- Instrument before you need it: one structured log line per request, success-only latency, a 1/0 availability metric, per-dependency timers with status codes (Lesson 21).
- Add admission control: a concurrency limit per dependency (Lesson 7) and per-tenant rate limits (Lesson 8), returning 429 for quota and 503 for overload.
- Bound every queue and give messages a TTL. Process newest-first when the backlog grows; sideline poison messages (Lesson 6).
- Make health checks shallow for routing, deep ones for alarms only, and fail open when most hosts look unhealthy (Lesson 14).
- Design for AZ loss: run in 3 AZs with about 50% headroom, keep the data plane free of control-plane calls on the request path (Lesson 10).
- Push configuration as constant work: one full snapshot in S3 or similar, fetched every few seconds by every host (Lesson 13).
- Build the pipeline: code review gate, unit and integration tests, a gamma stage that mirrors prod, a one-box per AZ, rolling batches sized to headroom, alarm-driven automatic rollback and bake time with data-point minimums (Lessons 18 to 20). Make every change rollback-safe with two-phase deploys (Lesson 17).
- Shard customers when blast radius matters: cells first, then shuffle sharding at the edge (Lessons 11, 12).
The snippet below combines Lessons 1, 2 and 23: one retry layer with full jitter, a retry token bucket, and an idempotency token reused on every attempt.
const bucket = { tokens: 10, max: 10 }; // retry quota (Lesson 23)
const RETRY_COST = { timeout: 5, server: 1 }; // timeouts cost more
const REFILL_ON_SUCCESS = 0.1; // 1 retry earned per 10 successes
async function callWithRetries<T>(op: (token: string) => Promise<T>, maxAttempts = 3): Promise<T> {
const idemToken = crypto.randomUUID(); // same token on every attempt (Lesson 2)
for (let attempt = 1; ; attempt++) {
try {
const res = await withTimeout(op(idemToken), 800); // ms, from measured p99.9 + margin
bucket.tokens = Math.min(bucket.max, bucket.tokens + REFILL_ON_SUCCESS);
return res;
} catch (err: any) {
const kind = err.name === "Timeout" ? "timeout" : err.status >= 500 ? "server" : null;
if (!kind || attempt >= maxAttempts) throw err; // never retry 4xx
if (bucket.tokens < RETRY_COST[kind]) throw err; // quota spent: fail fast
bucket.tokens -= RETRY_COST[kind];
const cap = 2000, base = 100; // ms
const sleep = Math.random() * Math.min(cap, base * 2 ** attempt); // full jitter
await new Promise((r) => setTimeout(r, sleep));
}
}
}
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
return Promise.race([p, new Promise<T>((_, rej) =>
setTimeout(() => rej(Object.assign(new Error("timeout"), { name: "Timeout" })), ms))]);
}| Technology | Fits when |
|---|---|
| AWS SDK adaptive retry mode | You call AWS APIs and want retry quotas plus client-side rate limiting built in |
| Resilience4j / Polly / Envoy | You need timeouts, retries, bulkheads and circuit breakers in JVM, .NET or a service mesh |
| Envoy or NGINX admission limits | You want load shedding and concurrency limits at the proxy, before application threads |
| Amazon DynamoDB lock client / ZooKeeper / etcd | You need leader election with leases (and fencing tokens on the resource) |
| Route 53 / Global Accelerator health checks | You need DNS or anycast failover driven by constant-work health checking |
| AWS AppConfig / S3 snapshot polling | You want configuration pushed as constant work with validation and rollback |
| AWS CodePipeline + CodeDeploy | You want staged deployments with minimum healthy hosts, alarms and auto-rollback |
| CloudWatch EMF + Logs Insights + Contributor Insights | You log one structured entry per request and need metrics and top-N analysis from it |
| AWS X-Ray / OpenTelemetry | You need trace IDs propagated across services |
| AWS Fault Injection Service / Chaos tools | You want to exercise failure paths, AZ loss and dependency slowness on purpose |
Trade-offs#
| Lesson | Gain | Cost |
|---|---|---|
| Retries with jitter and quotas | Hide transient errors without retry storms | Extra latency; some requests fail fast that a blind retry would have saved |
| Idempotency tokens | Safe retries for mutations | Token storage, TTLs, and a rule for "same token, different body" |
| Avoid fallback | No untested code paths in emergencies | Fewer "graceful" degradations; must make the main path robust or push data ahead of time |
| Load shedding and bounded queues | Goodput stays flat under overload | Some customers get errors early; tuning thresholds is ongoing work |
| Smaller service in control | Big fleet cannot overload the small one | The small fleet tracks membership and convergence; the big fleet must store pushed state |
| Static stability | Survive AZ or control-plane loss without acting | Pay for 50% or more idle capacity; extra work to pre-provision |
| Shuffle sharding | One bad tenant hits a tiny fraction of others | Routing complexity; per-tenant capacity is smaller |
| Constant work | Same load on good and bad days; self-healing | Wasted work and bandwidth when nothing changes; must size for the maximum |
| Health checks that fail open | No fleet-wide self-inflicted outage | Truly broken hosts may keep traffic until another signal removes them |
| Caches with soft TTL and coalescing | Lower latency and cost, survives origin blips | Cold-start risk; staleness; cache becomes critical capacity |
| Two-phase deployments | Every step can be rolled back | Three deploys, days of bake time and a backfill for one logical change |
| Waves and bake time | One-AZ blast radius per bad change | Changes take 4 to 5 business days to reach every Region |
| Log every request | Any question answerable after the fact | CPU, disk, network and storage cost; privacy controls needed |
Common Pitfalls#
- Retrying at every layer. Three attempts at each of five layers is 243 calls at the bottom. Retry once, near the caller.
- Jitter only on retries. Cron jobs, cache expiries, lease renewals and timers also synchronize. Jitter them too, or seed jitter by host.
- Fallbacks that are never exercised. A fallback path used once a year will be broken on that day. Either run it all the time or remove it.
- Deep health checks on the load balancer. One slow shared dependency marks every host unhealthy and the LB has nowhere to send traffic.
- Unbounded queues with FIFO processing during a backlog. Workers spend hours on requests whose clients gave up long ago.
- Static stability on paper only. Headroom that is never tested by actually removing an AZ will have been eaten by growth when you need it.
- Counting a deploy as done when "most" hosts succeeded. Two-phase changes need 100% of hosts on the Prepare version.
- One-box metrics drowned by fleet metrics. Alarm on the one box's own error rate, not the whole fleet's.
- Latency metrics that include fast errors. Throttling makes latency graphs look better during an incident. Use success-only latency.
- Copying Amazon's numbers. Batch sizes, bake times and token refill rates must come from your own headroom and traffic.
Real-World Examples#
All of these come from the fetched articles:
- Route 53 assigns every hosted zone four of 2,048 virtual name servers, about 730 billion combinations, so a DDoS on one customer's zone rarely overlaps fully with any other (Lesson 11). Its health checkers send the full results table every few seconds, constant work that behaves the same in any failure (Lesson 13).
- AWS Hyperplane, the internal EC2-network service that Network Load Balancers run on, pulls its whole configuration from S3 in a constant-work loop instead of applying change events (Lesson 13).
- EC2 designs its data plane to be statically stable: running instances keep working when the control plane, such as the ability to launch instances, is impaired, and capacity is pre-provisioned for the loss of an AZ (Lesson 10).
- DynamoDB logs every request, at more than 20 million requests per second of Amazon-internal traffic at peak, for troubleshooting, audit and compliance (Lesson 21). Its team ran coordinated two-phase protocol changes across many microservices, checking every host between phases (Lesson 17).
- Amazon's deployment pipelines reach every Region in about four to five business days by default, starting with one AZ in a low-traffic Region, with a 12-hour bake after the first regional wave (Lesson 18).
- Amazon's delivery speed study found an average of 16 days from check-in to production, almost 14 of them spent waiting; the Pipelines pilot cut that by 90% (Lesson 19).
- An old amazon.com outage: one catalog server with a full disk returned empty responses very fast, attracted a large share of traffic from the load balancer, and took the site down (Lesson 16).
In the Interview#
Deep Dive: applying the Library to one service, with numbersShow
Take a hypothetical product-catalog API: 30,000 requests per second at peak, p99 target 100 ms, three AZs, 60 hosts, a regional cache in front of a database, and 5,000 tenants of very uneven size.
Capacity and static stability. Peak is 30,000 RPS. If losing one AZ must need no action, the remaining two AZs must carry 30,000, so each AZ needs 15,000 RPS of capacity, 45,000 in total, which is 50% headroom (the n/(n−1) rule from Lesson 10). With 750 RPS per host at a safe 60% CPU, that is 20 hosts per AZ.
Deployment batch. Headroom h = 1/3 of capacity, so batches up to 33% are safe at peak; pick 10% forward (2 hosts per AZ at a time) and 33% for rollback.
Timeouts and retries. The database p99.9 is 25 ms; set its timeout to about 60 ms. One retry layer at the API, with a token bucket refilling 0.1 per success. At a 50% failure rate during a database brownout, retries add at most about 5% load instead of 100%.
Concurrency limits. By Little's law, 30,000 RPS × 0.02 s average DB time = 600 concurrent DB calls fleet-wide, 10 per host. Cap each host at 25 concurrent DB calls; beyond that, shed with 503 rather than queue (Lesson 7).
Cache. At a 95% hit rate the database sees 1,500 RPS. A cold regional cache would send 30,000, which is 20× normal. Either size the database for full load (expensive), or limit the database to, say, 5,000 RPS during warm-up and serve the rest with 503 plus client backoff, while pre-warming the top 1% of keys (Lesson 15).
Fairness. Default per-tenant quota 300 RPS with burst to 600, stacked with a fleet-level admission limit at 40,000. A runaway tenant at 10,000 RPS is held to its quota and never reaches the shared database (Lesson 8). With 8 cells of shuffle shards of 2 cells each, there are 28 shards, so one noisy tenant fully overlaps with only 1/28 of other tenants (Lesson 11).
Queues. The async indexing queue gets a 15-minute TTL: index updates older than that are replaced by a nightly full rebuild, so a two-hour outage does not leave an eight-hour backlog (Lesson 6).
Observability. One request log line per request with success latency, the 1/0 availability metric, per-dependency timers and tenant ID. Contributor Insights on tenant ID finds the top talkers in seconds (Lessons 21, 23).
None of these numbers come from Amazon; they show how to derive your own from the same rules.
Key Takeaways#
- Most large outages come from healthy components reacting badly to a small failure, so design for the worst day's behaviour, not the best day's.
- Retry in one layer only, with capped exponential backoff, full jitter and a retry budget, and make every retried mutation idempotent with a client token.
- Load shedding, bounded queues and newest-first processing keep goodput flat when offered load exceeds capacity.
- Avoid fallbacks that are rarely exercised; prefer making the main path robust or pushing data ahead of time.
- Static stability means pre-provisioning enough capacity in each zone that losing a zone or the control plane requires no action, at the cost of paying for idle headroom.
- Shuffle sharding and cells limit any one tenant or bad deployment to a small, mostly unique slice of the fleet.
- Constant work, such as pushing the full configuration every few seconds, makes the system's load the same in calm and chaos and makes it self-healing.
- Health checks used for routing should be shallow and should fail open when most hosts look unhealthy.
- Every change must be safe to roll back: split format and protocol changes into Prepare and Activate deployments, and test a mixed fleet and a rollback before production.
- Hands-off deployment needs a one-box stage, waves that touch one AZ per Region at a time, alarm-driven automatic rollback and bake time with minimum data points.
- Log one structured entry per request with per-dependency timers and success-only latency, so any incident question can be answered after the fact.