Skip to content

Netflix TechBlog: Microservices, Caching and Streaming at Scale

Advanced 255 min read Part 18 of 18

How Netflix stays up: Hystrix and Zuul, EVCache, active-active regions, load shedding, chaos and canaries, data abstractions, Open Connect and live streaming.

Summary#

Netflix runs one of the largest consumer services on the public cloud and one of the largest content networks in the world. Its engineering blog is unusual in two ways. It started early, publishing the circuit breaker, service discovery and gateway designs that later became the default vocabulary of microservices. It also keeps publishing the second and third versions, explaining what the first version got wrong. This page reads 51 Netflix TechBlog posts, written between 2011 and 2025, and follows each idea from its first form to its current one.

The posts form eight families: resilience and the edge (Hystrix, Eureka, Zuul 1 and 2, edge load balancing, connection subsetting), caching and multi-region (EVCache, active-active regions, region evacuation), traffic and safety (prioritized load shedding, chaos experiments, canary analysis, predictive autoscaling, the SPS metric), observability (tracing, Atlas), data platforms (key-value, time-series and counter abstractions, the write-ahead log, Keystone and Kafka, delay queues), orchestration and APIs (Conductor, Maestro, GraphQL federation, traffic migration by replay), content and media (Tudum, downloads, Open Connect, encoding pipelines) and live and experimentation (the live pipeline and origin, edge authentication, sequential A/B testing, in-video search). All Netflix facts below come from the fetched posts. The math, analogies and worked examples marked "handbook's illustration" are this handbook's own.

Why It Exists#

A textbook microservices diagram shows a gateway, a dozen services and some databases, and assumes every call succeeds. Netflix's posts start from the opposite assumption: with hundreds of services and billions of calls, something is always failing. That assumption forces design choices the textbook skips:

  • Dependencies fail by getting slow, not by stopping. A slow dependency ties up threads in every caller, and the callers fail too. Isolation, timeouts and fallbacks have to be built into every client.
  • The gateway is where the whole system is visible. Routing, debugging, load shedding, authentication and regional failover all happen at the edge, so the edge must be programmable and cheap per connection.
  • A region is a unit of failure. The service must be able to move every user out of an AWS region in minutes, and every region must be ready to absorb the extra load.
  • Data has a few shapes, used by thousands of apps. Rather than let every team learn Cassandra's sharp edges, Netflix wraps storage in abstractions: key-value, time-series, counters and a write-ahead log.
  • Video is the product, and it is huge. Most bytes are served from Netflix's own appliances inside ISPs, filled overnight by predicting what people will watch.

The textbook pages (microservices patterns, resilience patterns, distributed caching, CDN) explain each idea in isolation. Netflix's posts show how the ideas behave together under real traffic, and what each one cost.

For each post the page asks:

  1. Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
  2. Production architecture. What did Netflix actually build?
  3. Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
  4. Sacrifice. What did Netflix give up to get the benefit?

How It Works#

The diagram shows where each family of posts sits on the path of a member's request. A device connects to Zuul at the edge of an AWS region. Zuul authenticates, sheds load if needed and routes to backend services, found through Eureka and protected by Hystrix-style isolation. Services read EVCache and the data abstractions, publish events into Keystone and Kafka, and run workflows on Conductor and Maestro. Video bytes do not take this path at all: they come from Open Connect appliances near the member. Observability, chaos and canary systems watch everything.

The lessons below follow the eight families in order. Each one covers a single post, or two closely linked posts, and ends with what the design gave up.

Lesson 1: Making the Netflix API more resilient (2011), the circuit breaker arrives#

Assumptions. In 2011 the Netflix API brokered catalog and subscriber data between internal services and hundreds of device types. It handled about a billion requests a day, around 20,000 requests per second at peak. If any internal service failed, that failure could spread to the API and break the experience for every member. The team set three principles: a failing dependency must not break the member experience, the API must take corrective action by itself, and the team must be able to see what is happening now, not just 15 minutes ago.

Production architecture.

  • Decorated calls. Every call to a dependency is wrapped in code that records its result. When a service fails too often, the API stops calling it, serves fallbacks and lets the service recover. It then lets a few calls through, and if they succeed it reopens traffic. This is the circuit breaker pattern from Michael Nygard's book Release It!, extended in one way.
  • Three ways to trip. A call counts as a failure if it times out, if the thread pool and bounded queue for that dependency are 100% full, or if the client library throws. All three feed one error rate per dependency. When it crosses a threshold, the circuit opens and fallbacks are served without trying the remote call.
  • Three kinds of fallback. A custom fallback uses data the API already has, such as a cookie or a local JVM cache. Fail silent returns null when the data is optional. Fail fast returns a 5xx when the data is required, which hurts the device but keeps API servers healthy and lets the system recover quickly. Full custom coverage is the goal, but hard to maintain across many dependencies.
  • A 10-second rolling window. Stats are counted over the last 10 seconds only. At 20,000 requests per second that is 200,000 device requests, which can mean more than 1,000,000 calls into upstream services. Decisions should be based on what just happened.
  • A dashboard on the same stats. Each of the roughly 60 circuits is a circle: its size is call volume and its colour is health. A sparkline shows the last 2 minutes, for display only.

A real incident. A bug caused the API to sometimes put a half-populated Java object into a shared cache. The team bypassed the cache and read the database directly while fixing it. The database then throttled the API for sending too much traffic. The database-select circuit tripped automatically and the custom fallback read a local query cache that held most of the active data. The dashboard showed an 80% error rate on the circuit and 157 of 200 servers serving fallbacks, but video views per second barely moved compared with the week before.

Overlooked constraints.

  • Disabling a cache is a load test you did not plan. The database had never seen the uncached read rate. Any "bypass the cache" switch needs a check of the downstream's capacity first.
  • A fallback is only as good as its data. The local query cache worked because it held most of the active set. A fallback cache that is cold or tiny turns into fail-fast.
  • Real-time stats are a control input, not just a chart. The same 10-second numbers drove both the breaker and the dashboard, so what operators saw was exactly what the software was acting on.

What Netflix sacrificed. Correctness for availability during failures: members may see stale or less personalised data. It also took on a permanent engineering cost, since every dependency needs a fallback that someone maintains.

Deep Dive: sizing a rolling window and a trip thresholdShow

A rolling window is usually built from buckets. A 10-second window with 10 one-second buckets keeps four counters per bucket (success, failure, timeout, rejection) per dependency. That is 40 counters per dependency, or 2,400 for 60 circuits, which is tiny. Each second the oldest bucket is dropped and a new one is started, so the window slides without storing individual requests.

Why a minimum request count matters (handbook's illustration): if an instance makes 2 calls to a rare dependency in 10 seconds and 1 fails, the error rate is 50%. That is a coin flip, not a signal. Requiring, say, 20 requests in the window before the breaker may trip means a 50% threshold needs at least 10 failures. At 20,000 API requests per second spread over 200 servers, each server sees about 100 requests per second. A dependency called once per request gets 1,000 calls per 10 s per server, so a 50% threshold is reached in about a second of a full outage, while a rare dependency called 1% of the time (10 calls per window) would never trip on noise.

The cost of tripping too late is threads. With a 1 s timeout and 100 calls per second to a dead dependency, Little's law says 100 × 1 = 100 threads are blocked at any time. The breaker's job is to bring that to zero within a few seconds, before the container's whole thread pool (often 200 or so) is gone.

Lesson 2: Fault tolerance in a high-volume distributed system (2012), the design that became Hystrix#

Assumptions. By 2012 the API received over 1 billion calls a day, fanning out about 1 to 6 into several billion calls to dozens of subsystems, with peaks above 100,000 dependency requests per second, on thousands of EC2 instances. Teams owned their own protocols (XML, JSON, Thrift, Protocol Buffers) and shipped their own Java client libraries, so the API had to treat dependencies as black boxes. The key arithmetic: 30 dependencies at 99.99% each give 99.7% together, more than 2 hours of downtime a month, even if every dependency is excellent. And one latent dependency can fill every Tomcat request thread in seconds, taking the whole API down.

Production architecture: the DependencyCommand. Every network-bound call is wrapped in a command that combines four protections:

  1. Network timeouts and retries, set aggressively through work with client library owners.
  2. A separate thread pool per dependency. A latent dependency can fill only its own pool. Tomcat threads then time out or are rejected immediately instead of blocking. The same threads enable parallel calls and request collapsing (automatic batching), so the overhead also buys speed.
  3. Semaphores (try-acquire, never blocking) for calls that do no network I/O, such as in-memory cache lookups, where a thread hop costs too much. Semaphores also guard fallbacks, which run on the caller's thread and should never do network calls. If someone writes one that does, the semaphore limits how many threads it can block.
  4. Circuit breakers that trip at a threshold, for example 50% errors in 10 seconds, and reject everything until health checks pass. This sheds load from the struggling dependency and fails fast instead of waiting for timeouts.

Every failure or rejection, whatever triggered it, passes through the command's fallback, so the command can return something other than an error.

Fallbacks in order of user impact:

  1. Cache: serve local or remote cached data, even if stale.
  2. Eventual consistency: queue writes (for example in SQS) and apply them when the dependency recovers.
  3. Stubbed data: default values when personalised ones are unavailable.
  4. Empty response (fail silent): null or an empty list that the UI can ignore.

A worked timeout configuration from the post. A dependency has a 40 ms median. If it has no legitimate reason to reach its 99.5th percentile, the network timeout cuts the slow tail and retries once, expecting a median-latency answer, all inside a 300 ms thread timeout. If it does have a reason to be slow sometimes (for example a cache miss with lazy generation), the network timeout is set above that tail, around 325 ms with 0 or 1 retries, and the thread timeout higher still (350 ms or more). The pool is sized at 10 threads for a burst of 99th-percentile calls, but when healthy only 1 or 2 are busy. All of this can be changed at runtime without risking the app.

DependencyCommand("ratings")
  pool.size            = 10      # p99 burst, 1-2 busy when healthy
  thread.timeout       = 300ms   # outer guard, independent of client config
  net.timeout          = ~p99    # cut the tail, then
  net.retries          = 1       # retry expecting median (40ms)
  breaker.errorPercent = 50      # in a 10s rolling window
  fallback             = local cache -> stub -> empty   # no network calls, semaphore-limited

Overlooked constraints.

  • Two layers of timeout are both needed. The thread timeout protects the caller whatever the client library does. The network timeout stops slow calls from filling the dependency's own pool forever.
  • Black-box clients force isolation at the caller. You cannot assume each team's library has good timeouts, so the caller must enforce them.
  • Fallbacks are code that runs only during incidents. Untrusted fallbacks get their own guard because they are rarely exercised.

What Netflix sacrificed. A thread hop and a thread pool per dependency, which costs memory and context switches on every call. It also accepted complex per-dependency tuning. Netflix decided the isolation was worth it, and recovered part of the cost by making calls run in parallel.

Deep Dive: availability compounding and thread pool sizing with Little's lawShow

Compounding. If a request needs all n dependencies and each is up a fraction a of the time, independently, the request succeeds a^n of the time. With a = 0.9999 and n = 30: 0.9999^30 ≈ 1 − 30 × 0.0001 = 0.997. A month has about 43,200 minutes, so 0.3% is about 130 minutes, the post's "2+ hours". Isolation and fallbacks change the formula: if a failed dependency is replaced by a fallback that still lets the request succeed, that dependency drops out of the product. With fallbacks for 25 of the 30, only 5 remain critical: 0.9999^5 ≈ 0.9995, about 22 minutes a month.

Pool size. Little's law says the number of calls in progress = arrival rate × time in system. Suppose an instance calls a dependency 30 times per second (handbook's illustration). At the 40 ms median, 30 × 0.04 = 1.2 calls are in flight, which matches the post's "1 or 2 active threads". In a burst where every call takes the 300 ms timeout, 30 × 0.3 = 9 calls are in flight, which is why a pool of 10 is enough. If the dependency stops responding, the pool fills at once, and every further call is rejected in microseconds instead of blocking a Tomcat thread for 300 ms. The pool size is the bulkhead: it decides the most damage this dependency can do to the caller.

Retry budget. One retry after a tail cut turns a p99.5 call (say 250 ms) into a likely median call: 40 ms extra plus the cut-off time. Worst case: connect, read, retry connect, read. That can still exceed 300 ms, which is why the outer thread timeout exists.

Lesson 3: Eureka, a client-side service registry (2012)#

Assumptions. In AWS, servers come and go all the time, so a load balancer must register and deregister servers on the fly. In 2012 AWS had no middle-tier load balancer, and putting internal services behind an internet-facing ELB would expose them and lose the protection of security groups. Most Netflix mid-tier services are stateless and want non-sticky balancing, which fits autoscaling.

Production architecture.

  • Eureka Server is a REST service holding a registry of instances. The Eureka Client (Java) registers, renews and looks up instances, and includes a basic round-robin balancer. Inside Netflix a richer balancer wraps it, weighting by traffic, resource use and errors.
  • Leases. Instances send heartbeats every 30 seconds. An instance that misses several renewals is removed after about 90 seconds. Registrations and renewals are replicated to every Eureka node in the cluster.
  • Clients cache the registry and refresh it every 30 seconds. They call servers directly, which avoids two network hops through a proxy and keeps working even if every Eureka server is down.
  • One cluster per region, at least one server per zone. Regions do not talk to each other. Eureka is like internal DNS for one region, not a global naming system.
  • Not Route 53. DNS-based balancing can send traffic to servers that are unhealthy or gone, and it exposes mid-tier identities.
  • Other uses: Asgard deployments, fast rollback without relaunching hundreds of instances, rolling pushes, taking Cassandra nodes out of traffic for maintenance, listing EVCache nodes in a ring, and carrying service metadata. Non-Java services use REST or a Java "sidekick" process.
  • Partition handling. The post says the servers have built-in resiliency to avoid a large outage during a network partition between clients and servers.

Overlooked constraints.

  • The registry is eventually consistent by design. A dead instance can stay in clients' caches until its lease expires and the next fetch happens, so clients must retry on another instance.
  • Client-side balancing moves logic into every language. Non-Java services need a sidekick or their own client. That cost grows with the number of languages, and is one reason service meshes appeared later (Lesson 7 mentions Netflix's Envoy-based mesh).
  • Deregistration is part of deployment. Fast rollback and rolling pushes work because traffic can be switched by changing registry state, not by killing instances.

What Netflix sacrificed. Strong consistency of the registry, in exchange for availability: clients keep working on a cached, possibly stale view. It also gave up sticky sessions, which it did not want anyway.

Deep Dive: how stale can a Eureka view be, and what it means for retriesShow

Worst case for a crashed instance (handbook's illustration, from the post's timers): it crashes just after a renewal. The server evicts it about 90 s later. The eviction reaches clients at their next 30 s fetch, so a client may keep choosing it for up to about 120 s. With 100 instances and 1 crashed, a uniform balancer sends it 1% of calls for 2 minutes. At 10,000 calls per second, that is about 12,000 failed first attempts. With connection failures caught quickly (a refused connection returns in about 1 ms inside a region) and one retry to a different instance, the user sees only a tiny delay. That is why client-side discovery always goes with a retry-on-next-instance policy and a short connect timeout.

Compare a strongly consistent registry built on a consensus store (see ZooKeeper and etcd). It can show the change immediately when it is healthy. But during a partition, the minority side cannot read or write the registry, and clients there lose discovery entirely. For service discovery, a stale list that still mostly works beats an empty one, which is the choice Eureka makes. In CAP terms, Eureka is an AP system.

Lesson 4: Zuul, a programmable edge service (2013)#

Assumptions. The Netflix API supported over 1,000 device types and over 50,000 requests per second at peak. UI teams pushed server-side adapter scripts every day, new AWS regions and country catalogs kept arriving, and the edge needed to be quick to change, insightful and resilient.

Production architecture.

  • Filters. Zuul is a chain of filters, each with a type (the stage it runs in), an execution order, criteria and an action. Filters share state only through a per-request RequestContext.
  • Dynamic code. Filters are written in Groovy (any JVM language works). Their source sits in directories that Zuul polls. Changed filters are compiled into the running server and used for the next request, with no deploy.
  • Standard stages: PRE (authentication, choosing origin servers, debug logging), ROUTING (building and sending the origin request with Apache HttpClient or Ribbon), POST (headers, metrics, streaming the response back) and ERROR. Custom types are allowed, such as STATIC, which answers from Zuul without an origin.
  • Uses: authentication, insights, stress testing, canary testing, dynamic routing, load shedding, security, static responses and multi-region resiliency.
  • Built from Netflix OSS: Hystrix wraps origin calls to shed and prioritise traffic, Ribbon makes outbound calls and balances, Turbine aggregates real-time metrics, Archaius gives dynamic properties, Eureka finds instances, Servo provides metrics, and Astyanax stores filters in Cassandra.

Three uses worth copying.

  1. Surgical debugging. A SurgicalDebugFilter sends requests that match a pattern (for example certain device IDs, or one new web page) to an isolated debug cluster. Before Zuul, finding a few thousand bad requests meant a Hadoop query over billions of log lines. Now it was a small log file on a few servers, watched live. A real-time streaming log built on Zuul and Turbine could answer questions like "how many PS3 API requests are coming from São Paulo?"
  2. Squeeze testing. A filter steadily raises the share of traffic sent to a small cluster of origin servers, using dynamic Archaius settings. The team measures where performance breaks, which tells them how many instances are needed at peak, whether autoscaling needs retuning, and whether a build is fast enough to ship.
  3. Cross-region bridging. In the Isthmus project, Zuul bridged requests from the US West region to US East, giving the critical domains redundancy across ELBs in two regions.

The post's example filter shows the style: a PRE filter, order 5, that matches a malfunctioning device type and sleeps a random 0 to 20 seconds to spread that device's load on the origin.

Overlooked constraints.

  • Runtime code loading is a deployment system. Changing behaviour without a deploy is powerful and risky. It needs the same review, staging and rollback as code, the lesson Cloudflare's posts teach at length (see the Cloudflare page).
  • Filters share a mutable context. Order matters, and a filter that mutates the context can break later ones. Execution order is part of the contract.
  • A gateway sees everything, so it is the natural place for operations tools: debug routing, squeeze tests, traffic shaping. Teams that treat a gateway as a dumb proxy miss this.

What Netflix sacrificed. A thin, simple proxy. Zuul became a large platform with business logic at the edge, and every request paid for the filter chain.

Deep Dive: finding capacity with a squeeze testShow

Suppose a service runs on 100 instances at peak, serving 30,000 requests per second, so each instance normally takes 1% of traffic, or 300 requests per second (handbook's illustration). Pick a squeeze cluster of 3 instances and raise its combined share step by step: 3% (normal), then 4.5%, 6%, 7.5%. At 4.5% each squeeze instance takes 1.5%, or 450 requests per second; at 6%, 600.

Watch p99 latency and errors at each step. If p99 crosses the target at 600 but not at 450, safe capacity is roughly 500 requests per second per instance. Peak 30,000 ÷ 500 = 60 instances are enough for normal traffic. Add headroom for losing a region (Lesson 12): if another region's traffic can land here, size for that peak, not just your own. The same test run on every build catches performance regressions before release. The dynamic share is what makes this cheap: no synthetic load generator, just real traffic re-weighted, and the experiment ends by setting the share back.

Lesson 5: Zuul 2, the journey to asynchronous, non-blocking I/O (2016)#

Assumptions. Zuul 1 was built on the Servlet model: one thread per connection, blocking I/O. That works for hundreds of concurrent connections per instance. But when backends slow down or devices retry after errors, active connections and threads climb, and nodes can enter a death spiral, which is why Hystrix-style throttling existed. Netflix wanted persistent connections from devices, for push notifications and fewer requests, for more than 83 million members, each with several devices.

Production architecture.

  • Zuul 2 runs on Netty: about one event loop thread per CPU core, with requests handled by events and callbacks. A connection costs a file descriptor and a listener, not a thread. Data stays on one core, giving better CPU cache use and fewer context switches. Latency spikes and retry storms cost queued events rather than piles of threads.
  • Migration strategy: async filters first. Netflix rewrote the filter base classes and filters with RxJava, creating async filters for I/O and sync filters for pure logic. The same filters ran on both the blocking Zuul 1 and the Netty Zuul 2, so feature work and the new architecture shared one codebase.
  • The hard part was the ecosystem. Netflix libraries assumed blocking and stored request context in thread-local variables, which break when many requests share one thread. Engineers had to find hidden blocking calls (the Reactive-Audit tool helped), fix resource leaks, and fork or refactor core libraries.

Results, measured apples-to-apples.

  • The API-fronting cluster (metrics, logging, payload decryption, response compression) saw no efficiency gain. It is CPU-bound, and the two versions degraded at about the same throughput.
  • The logging cluster (large requests, small unencrypted responses, little work per request) saw about 25% more throughput and 25% less CPU.
  • The rule: the less CPU work a system does per request, the more async gains. The main win was connection scaling, which enables push and two-way communication. There was some resilience gain against retry storms, but only with effort and tuning.
  • Debugging got harder. Event-loop stack traces are meaningless for following a request, and edge cases lead to ByteBuf leaks, file descriptor leaks and lost responses.

Overlooked constraints.

  • Async does not make CPU work faster. If a request spends most of its time on CPU (crypto, compression, metrics), removing thread overhead saves little. Measure before migrating for efficiency.
  • Thread-locals are hidden coupling. Tracing, auth context and logging libraries often keep request state in thread-locals. An async migration has to find every one.
  • Brownfield costs more than greenfield. The post notes that a new system would have avoided much of this work. The value came from staying compatible with an ecosystem built for blocking.

What Netflix sacrificed. Simplicity of debugging, coding and testing, plus ongoing work to keep removing blocking assumptions from shared libraries. It accepted this for cheap connections and push.

Deep Dive: the memory and CPU arithmetic of threads versus event loopsShow

Memory per connection (handbook's illustration). A JVM thread typically reserves about 1 MB of stack (configurable), plus kernel structures. Holding 100,000 idle persistent connections with a thread each would reserve about 100 GB of address space and schedule 100,000 threads, which is not possible on one instance. With an event loop, each idle connection costs a socket, a file descriptor and a small buffer, a few KB to tens of KB. 100,000 connections × 20 KB = 2 GB, which fits. That is the whole case for Zuul 2: persistent connections at Netflix's scale need async.

CPU gain bound. Write per-request CPU as work W plus overhead O (thread scheduling, context switches, cache misses from moving between cores). Async removes most of O, so the best speed-up is (W + O) ÷ W. If O is 5% of the total, the gain is at most about 5%, which matches "no gain" on the CPU-heavy API cluster. If O is 25% because W is small, as on the logging cluster that just forwards messages, the gain is about 1 ÷ 0.75 ≈ 1.33, so up to 33% more throughput. The observed 25% fits that bound. The same reasoning tells you in advance which services are worth converting.

Lesson 6: Rethinking edge load balancing (2018), choice-of-2 plus server-reported utilization#

Assumptions. Zuul handled over a million requests per second, so even a low error rate hurt many members. Zuul had used Ribbon round-robin plus a blacklist for servers with many connection failures. The errors that remained came from cases where only some servers were overloaded: cold servers after start-up (red-black deploys and autoscaling), servers briefly stalled by staggered property or data updates or big GC pauses, and bad hardware or noisy neighbours that make some servers permanently slower.

Guiding principles. Work inside the existing load balancer framework so other teams can reuse it. Build on ideas already proven elsewhere (choice-of-2 and probation had been tried in other Netflix IPC stacks). Avoid distributed state. Avoid client-side configuration and manual tuning. For example, if Service X moves to a bigger instance type, Service Y's "max connections per host" setting should change too, and it usually gets forgotten. Prefer adaptive mechanisms, and when a static threshold is needed, have the server announce it at runtime.

The key idea. The best view of a server's latency is the client's. The best view of its utilization is the server's own. Combine both.

  • Why join-the-shortest-queue (JSQ) alone fails. Many load balancers each pick the least-loaded server and herd onto the same one, overload it, then herd onto the next. Choice-of-2 mostly fixes herding, but each balancer only counts its own in-flight requests. With tens to hundreds of balancers, server Y can look idle to balancer A while two other balancers are loading it. In large, low-traffic pools a balancer often compares zero with zero.
  • Server-reported utilization. Each server counts its in-flight requests as a percentage of its configured maximum and returns it in a response header: X-Netflix.server.utilization: <current>[, target=<target>]. This is passive, so it adds no load from N balancers polling M servers, and it reflects all balancers at once. CPU and load average were tried but caused oscillation because they are lagging averages.
  • Choice-of-2 compares three factors: client health (rolling rate of connection errors to that server), server utilization (last reported score) and client utilization (this balancer's in-flight count). Multiple factors guard edge cases. A failing server that rejects everything reports low utilization, since rejecting is fast, and would attract traffic if utilization were the only factor.
  • Filtering: before comparing, skip servers above conservative utilization or health thresholds, with N random attempts and then a fallback to unfiltered choice, to keep balancer CPU low.
  • Probation: a server that has not yet answered this balancer gets one in-flight request at a time.
  • Server-age warm-up: traffic to new servers ramps up over their first 90 seconds.
  • Stats decay: all stats decay linearly to zero over 30 seconds, so no server is blacklisted forever. An 80% error rate reads as 40% after 15 seconds without traffic.

Results. In a synthetic test (4,000 requests per second through 200 Zuul nodes to a 20-instance origin, then a second, deliberately slow 20-instance group added), the new balancer cut load shedding and connection errors by orders of magnitude and average and tail latency by about 3×. Server-reported utilization alone gave one order of magnitude of the error reduction and most of the latency gain. The slow group received about 15% of traffic instead of 50%. In production, during an incident where threads leaked a few per hour on each server, errors stayed evenly spread across servers of very different capacity, and new autoscaled servers took about twice the traffic of old ones.

Operational side effects.

  • Wider request distribution than round-robin. Canary analysis must compare RPS together with CPU, because a slow canary gets less traffic.
  • Outlier detection gets harder, since a bad VM now gets less traffic.
  • Rolling data updates work better. Data updates are deployed one region at a time, and applying one can cause a GC spike. If servers in a cluster apply it a few at a time, the balancer routes around them.
  • Alerting gaps. Error-rate alerts that used to fire when part of a cluster went bad now fired late or not at all, because the balancer hid the errors. Teams added alerts on utilization deviations.

Overlooked constraints.

  • A better balancer hides problems. Errors spread thin across the cluster no longer trip error alerts. Alert on utilization and capacity, not just errors.
  • Passive feedback needs traffic. The less often a balancer talks to a server, the staler its utilization data. At low RPS per server, active health-check polling can be better.
  • Fast failures look healthy. Any balancer that rewards low latency or low utilization must also track errors, or it will herd onto a broken server.

What Netflix sacrificed. The tight, even request distribution of round-robin, which made canaries and outlier detection simple, and some static thresholds it had wanted to avoid.

Deep Dive: why two random choices beat one, and what decay doesShow

The power of two choices. Throw n requests at n servers at random and the busiest server ends up with about ln n ÷ ln ln n requests. For n = 1,000, about 6.9 ÷ 1.93 ≈ 3.6, nearly four times the average. Pick two servers at random and send each request to the less loaded one, and the maximum drops to about ln ln n ÷ ln 2 + O(1). For n = 1,000, that is about 1.93 ÷ 0.69 ≈ 2.8 plus a small constant, and it barely grows with n. Michael Mitzenmacher's analysis, "The Power of Two Choices in Randomized Load Balancing" (2001), is the classic reference. Two choices also avoid herding: different balancers sample different pairs, so they do not all pick the same "best" server.

Decay arithmetic. With linear decay over 30 s, a stat value v becomes v × (1 − t ÷ 30) after t seconds without fresh data. A server that hit an 80% error rate and then got no traffic reads 40% at 15 s and 0% at 30 s. It is then picked again, and if it is still bad, a few requests re-raise its score. The cost of rediscovery is a handful of failed requests every 30 s per balancer. With 200 Zuul nodes that is about 200 probes per 30 s, roughly 7 per second, against a bad server, small next to the traffic it would get under round-robin (1/20 of 4,000 = 200 per second in the test scenario).

Warm-up. A linear 90 s ramp means a new server gets about a third of its full share at 30 s, two thirds at 60 s and all of it at 90 s. JIT compilation and cache filling usually finish inside that window, so cold-start errors drop sharply.

Lesson 7: Curbing connection churn in Zuul (2023), subsetting with a low-discrepancy ring#

Assumptions. Zuul was designed when connections were effectively free, before mutual TLS (mTLS). It runs one Netty event loop per core, and each loop has its own connection pool to every origin server, so a request stays on one thread for its whole life. The downside is multiplication: a 16-core Zuul connecting to an 800-server origin holds 12,800 connections, and 100 Zuul instances hold 1,280,000. When Zuul scales up during a spike, connections to origins grow with it. This became urgent when large streaming apps moved to mTLS and an Envoy-based service mesh, where every connection costs handshakes.

Production architecture.

  1. HTTP/2 multiplexing to origins. Zuul had proxied HTTP/2 but treated it like HTTP/1. It now creates a stream and immediately returns the connection to the pool so later requests share it. ALPN negotiates HTTP/2 and falls back to HTTP/1, so it could be enabled broadly. The mesh enabled ALPN by default, so service owners did nothing. But connection counts did not fall: with every loop connecting to every server of a large origin, each connection carried too few requests to multiplex.
  2. Subsetting. Each event loop connects to only a subset of the origin. Netflix based this on Google's Ringsteady algorithm, from an ACM paper by Peter Ward, Paul Wankadia and Kavita Guliani. It places servers on a ring using a binary Van der Corput sequence, a low-discrepancy sequence that stays evenly spread as servers are added, more evenly than a random consistent hash. Adding or removing a node changes one subset, typically creating or removing one connection, so there is no cascading reshuffle.
  3. Applied to event loops, not instances. Google computes subsets centrally. Netflix applies the ring to the event loops inside each Zuul, keeping decentralized client-side balancing. Eureka changes feed the ring as incremental deltas. Nodes are shuffled before insertion so different Zuul instances do not overlap or hot-spot. A request's event loop picks its subset, and the existing choice-of-2 (Lesson 6) balances inside it.
  4. Replicated subsets with an ideal size. The ideal subset is about 25 to 50 nodes. A 400-node origin gets 8 subsets of 50, and on a 32-core instance each subset is used by 4 loops (the replication factor). The subset count is recomputed rarely, because changing it reshuffles the ring. Between 200 and 400 nodes the subsets do not change at all. In one rollout the subset size went from 100 (400 servers ÷ 4) to 50 (÷ 8) as the origin grew.

Results. Peak connections fell by about 10× in all three AWS regions. TCP connection opens per second (churn) fell about 8× peak to peak, and pool connection creation went from thousands per second to about 60. Zuul CPU fell about 4%, heap about 15% and latency about 3%. On the streaming playback origins, some Zuul shards dropped 13 million connections at peak. Overall Netflix serves the same traffic with tens of millions fewer connections, with no loss of balance or resilience.

Overlooked constraints.

  • Per-thread pools multiply. Lock-free per-core pools are fast, but connections = cores × servers × instances. At mTLS cost that product matters.
  • Multiplexing needs concentration. HTTP/2 only reduces connections if each connection carries many requests. Spreading thin across a huge origin defeats it, which is why subsetting came first.
  • Subsets must stay balanced, or canaries lie. Even origin load is essential for canary analysis (Lesson 19) and for avoiding hot spots. Random subsets would have broken it.
  • Stability matters more than perfection. The subset count is changed rarely because each change causes churn.

What Netflix sacrificed. Some redundancy per loop: a loop sees 50 servers instead of 400, so a bad subset hurts its loops more. That is why subsets are replicated across loops and sized at 25 or more. It also took on algorithmic complexity in the hottest path of the edge.

Deep Dive: the Van der Corput sequence and connection arithmeticShow

The sequence. Write n in binary, mirror its digits around the binary point, and read the result as a fraction. For n = 1, 2, 3, 4, 5, 6, 7: 1 → 0.1₂ = 0.5; 10 → 0.01₂ = 0.25; 11 → 0.11₂ = 0.75; 100 → 0.001₂ = 0.125; 101 → 0.101₂ = 0.625; 110 → 0.011₂ = 0.375; 111 → 0.111₂ = 0.875. Each new point lands in the largest remaining gap. With 4 subsets covering [0, 0.25), [0.25, 0.5), [0.5, 0.75) and [0.75, 1), the positions 0, 0.5, 0.25, 0.75 fill one subset each, then 0.125, 0.625, 0.375, 0.875 fill one more each. After any 4k insertions every subset has exactly k nodes. A random hash gives no such guarantee: with 50 nodes in 4 subsets, the expected spread is about √(50 × 0.25 × 0.75) ≈ 3 nodes around the mean of 12.5, so some subsets get 9 and others 16. Balance from a low-discrepancy sequence is exact by construction.

Connections before and after. One 32-core Zuul and a 400-node origin: without subsetting, 32 × 400 = 12,800 connections. With 8 subsets of 50, each loop holds 50, so 32 × 50 = 1,600, an 8× cut, matching the post's "divide by the number of subsets". Across 100 Zuul instances that is 1.28 million down to 160,000. With HTTP/2 each of those connections can carry many concurrent streams, so throughput headroom is kept.

Churn. When the origin autoscales by 40 nodes, each new node joins one subset, used by 4 loops per Zuul: about 4 new connections per Zuul instance, or 400 across 100 instances. Without the stable ring, a random reshuffle could rebuild a large share of 1.28 million connections, each needing an mTLS handshake costing a millisecond or more of CPU.

Lesson 8: EVCache, ephemeral volatile caching in the cloud (2012 and 2013)#

Assumptions. Moving from Netflix's own data center to AWS meant moving from session-based apps to stateless services, backed by NoSQL stores such as Cassandra, SimpleDB and S3. Those stores could take several hundred milliseconds at p99, which gave a jumpy experience. A cache had to be fast, shared and scalable. The name states the contract:

  • Ephemeral: data lives only for its TTL.
  • Volatile: data may be evicted at any time (LRU).
  • Cache: an in-memory key-value store.

Production architecture.

  • memcached plus a Java sidecar on each server. The sidecar registers with discovery (Eureka), monitors memcached and reports metrics. Apps use a Java client built on spymemcached.
  • Sharding by Ketama consistent hashing across the nodes of a cluster, so losing one node loses only its share of keys.
  • One copy per availability zone. Each zone has a full cluster. Writes go to every zone (set and delete), reads go to the local zone (get, getBulk, getAndTouch). Local reads are fast and avoid cross-zone data transfer fees. On a miss, the client can fall back to another zone's copy, which is still much faster than the source of truth.
  • Zone failure handling. If one zone's cluster loses instances, it can be set to write-only and reads moved to another zone, so hit rate and latency hold.
  • Keys are non-null strings, values are under 1 MB, and an optional cache name acts as a namespace.
  • Consistency is best effort. Speed was chosen over consistency. TTLs clean up short-lived inconsistencies, and consistency checkers repair long-lived data.

Numbers from 2012. More than 25 use cases, over 200,000 requests per second at peak, average latency 1 to 5 ms, p99 around 20 ms, and hit rates above 99% (above 99.9% for the Similars service, which recommends similar titles). Capacity could be added within a minute, with data rebalanced and warmed within minutes.

The read-through pattern, from the Similars case study. A web app asks EVCache for the similar titles of a movie. On a miss it calls the Similars app, which reads SimpleDB or, if the data was never computed, computes it and writes it back to EVCache. This is cache-aside with a compute fallback.

Overlooked constraints.

  • The cost of a cache is the cost of its misses. The post points out that misses to SimpleDB, S3 or Cassandra are the real expense. A cache sized too small saves little.
  • Every zone holds a full copy. Three zones means three times the RAM. That is the price of zone isolation and local reads.
  • Best effort means apps must cope. Every caller must be written for stale or missing data, which is easier when the data is derived and can be recomputed.

What Netflix sacrificed. Consistency (writes to zones are independent, with no transactions) and memory efficiency (one full copy per zone). In return it got local-zone latency and survival of a whole zone.

Deep Dive: what a 99% hit rate means for the database, and why replicas per zone pay offShow

Suppose a service makes 100,000 cache reads per second (handbook's illustration). At a 99% hit rate, 1,000 reads per second fall through to the database. At 99.9%, only 100. Going from 99% to 99.9% cuts database load by 10×, and losing the cache entirely multiplies it by 100. That is why a cache fronting a slow store becomes a dependency of the store's capacity plan.

Zone fallback changes the arithmetic of a node failure. With 3 nodes per zone, losing one node in zone A makes a third of zone A's keys miss locally. Without fallback, a third of zone A's reads (say 11,000 per second if zone A serves 33,000) go to the database, an 11× rise over the 1,000 per second baseline. With fallback to zone B, those reads cost one extra cross-zone hop, about 1 ms inside a region, and the database sees nothing new. Consistent hashing is what keeps the damage to one node's share: with modulo hashing, changing the node count from 3 to 2 would remap about two thirds of all keys.

Lesson 9: Caching for a global Netflix (2016), cross-region replication through Kafka#

Assumptions. By 2016 EVCache handled more than 30 million requests per second at peak, stored hundreds of billions of objects on tens of thousands of memcached instances, and served just under 2 trillion requests a day. Netflix ran in three AWS regions (Northern Virginia, Oregon, Ireland) and had just launched in 130 more countries. Members are served from the closest region, but traffic moves for failures and for Chaos Kong region failover exercises, so any region must be able to serve any member. Two cache uses needed replication:

  1. Caches fronting databases. Without replication, traffic moved to a new region finds a cold cache, and the misses overwhelm the databases: a thundering herd.
  2. Memoized computed data not stored anywhere else, such as recommendations, must be present in every region.

Explicit non-requirements. No strong global consistency (Ireland and Virginia may briefly show different recommendations), no global locking, quorums or transactions. Replication must be asynchronous and must never slow local cache operations. Latency only has to be "acceptable".

Production architecture: a SET, step by step.

  1. The app calls set() on the EVCache client, which writes to the local region's cache.
  2. The client also writes metadata only (the key, not the value) to a Kafka topic.
  3. A Replication Relay cluster in the local region reads the topic. There is one Relay cluster per destination region, so a slow region cannot delay the others.
  4. The Relay reads the value from the local cache.
  5. The Relay sends the SET to the Replication Proxy in the remote region. This is the only cross-region hop.
  6. The Proxy writes to its local cache using the normal EVCache client, which handles sharding, retries and zone copies.

DELETE and TOUCH follow the same path without reading the value. Apps never see other regions.

Why only the key goes through Kafka. Kafka stays small and cheap, since it does not have to hold all cache data. For some caches, a write in one region only needs an invalidation in the others: send a DELETE, and the other region takes a miss on the next read. That is cheaper when few reads in region A are for data written in region B.

Numbers and tuning. p99 end-to-end replication latency is under 1 second for most caches and about 400 ms for the busiest, where buffers fill and flush fast. Persistent connections between Relay and Proxy avoid TCP and TLS handshakes. Batching several messages per request to fill a TCP window raises throughput at a small latency cost. The system handles over a million RPS of replication daily, and more than 1.5 million messages per second at peak.

Lessons from a year in production.

  • Packets-per-second limits. Before VPC, instances had hidden packet-rate limits. Crossing them caused TCP timeouts and drops. The fix was more, smaller instances: two "large" can beat one "extra large" at the same cost. VPC raised the limits.
  • Per-hop latency metrics: app to Kafka, Relay reading Kafka, Relay to remote Proxy, Proxy to cache, plus end-to-end.
  • Kafka does not scale elastically. Adding partitions means matching consumer threads and resizing Relays, which can cause duplicate sends and more skew.
  • A lost remote cache instance slows everything, because the Proxy keeps trying it and the Relay waits for each batch.
  • Detecting missing messages means comparing broker message counts with replicated counts per topic, and alerting on maximum latency rather than average, since one slow partition hides in an average.
  • If a region is down for a long time, Kafka's retention fills and old messages are dropped. Apps are built to tolerate this.

Overlooked constraints.

  • Reading the value at relay time means the relay ships whatever is in the cache now, not what was written. That is fine for "last writer wins" caches, and it naturally merges repeated writes to the same key.
  • Separate relays per destination are bulkheads. One slow region only builds its own backlog.
  • Average latency hides partition problems. Use maximum per partition.
  • Instance packet limits are a real ceiling for chatty replication traffic. Bandwidth is not the only network limit.

What Netflix sacrificed. Consistency across regions (sub-second lag, and messages may be lost in a long regional outage) and simplicity (Kafka, Relay and Proxy clusters to run). It gained warm caches everywhere at RAM speed without slowing local writes.

Deep Dive: sizing the replication path and when invalidation beats replicationShow

Bandwidth (handbook's illustration). Suppose a cache takes 200,000 SETs per second with 2 KB values, and must replicate to 2 other regions. Full replication sends 200,000 × 2 KB × 2 = 800 MB/s across regions, about 6.4 Gbit/s. The Kafka topic only carries keys and metadata, say 100 bytes each: 20 MB/s, 40 times less, which is the post's point about keeping Kafka small.

Invalidate or replicate? Let w be the write rate in region A, and f the fraction of those keys that are later read in region B before being rewritten. Replication costs w value transfers. Invalidation costs w small deletes plus f × w misses in region B, each falling to the source (perhaps 5 to 10 ms and database load) or to recomputation. If f is 1%, invalidation turns 200,000 value transfers per second into 2,000 misses per second in region B, a clear win. If f is 50%, region B takes 100,000 misses per second, a thundering herd. That is why the choice is per cache: personalised data read where the member lives can invalidate, while data needed everywhere must replicate.

Kafka retention. If the Relay to region B is down for an hour at 200,000 messages per second, the backlog is 720 million messages × 100 bytes = 72 GB, easily held on disk. A multi-day regional outage could exceed retention, and messages would be dropped. This only works because regional evacuation (Lessons 12 and 13) moves traffic away from the broken region, and caches there are rebuilt or warmed (Lesson 11) when it returns.

Lesson 10: From RAM to SSD (2018), Moneta and memcached extstore#

Assumptions. EVCache had become a tier-0 service: petabytes of data, hundreds of billions of items, trillions of operations per day and thousands of servers in three regions. The Global Cloud (Lesson 13) tripled the data each region had to cache. RAM is expensive, but SSDs are fast: RAM random reads were rarely over 1 microsecond, and SSD random reads take 100 to 500 microseconds. EVCache's SLA was about 1 ms, with a 20 ms default timeout, at around 100,000 RPS per cluster. Tests on i3.2xlarge instances reached over 200,000 IOPS of 1 KB items with latency rarely over 1 ms.

First try: EVCache Moneta. All data lived on SSD in RocksDB, with hot data in memcached RAM. Clusters shrank by over 60% compared with RAM-only. It worked well for personalization, where batch jobs periodically recompute everyone's recommendations. But large online, customer-facing clusters hit throughput problems when overwriting data caused compactions, and sometimes broke the SLA. And because FIFO compaction could only delete an old item after it was rewritten, disks could be used to only 50% of capacity, holding both old and new copies.

Second try: memcached extstore. memcached's external storage keeps keys and metadata in RAM and values on flash. There are no duplicate copies, so the disk is used fully. Most EVCache clusters became limited by network, not storage. Reads were mostly about 100 microseconds or less, consistently better than Moneta. The lru_crawler metadump command can list every key in an instance, which enables cache warming (Lesson 11) and periodic snapshots for disaster recovery. All Moneta clusters moved to extstore, and some big RAM clusters moved to much smaller extstore clusters.

Overlooked constraints.

  • LSM trees and overwrite-heavy caches do not mix well. Compaction is the cost of RocksDB's write path (see storage engines). A cache with many overwrites pays it all the time.
  • Metadata still lives in RAM. With extstore, RAM per item is roughly key plus metadata. Billions of small items can still need a lot of memory.
  • The new bottleneck is network. Once storage is cheap, the instance's network limit decides cluster size, so pick instance types by network as well.

What Netflix sacrificed. Some latency (about 100 µs instead of about 1 µs per read, still well within a 1 ms SLA) and the operational simplicity of a pure RAM cache. It gained much lower cost per terabyte and the ability to dump and warm caches.

Deep Dive: when SSD caching is good enough, with latency budgetsShow

The network round trip inside an availability zone is a few hundred microseconds, and a memcached request with serialization costs similar. So a RAM cache read costs about 300 to 500 µs end to end, of which the RAM access is 1 µs. Replacing RAM with NVMe adds about 100 µs, about 20% to 30% more end-to-end latency, still well under a 1 ms SLA. If the cache were in-process, adding 100 µs to a 1 µs read would be a 100× slowdown. SSD caching works because the network already dominates.

Cost example (handbook's illustration, relative prices). Assume RAM costs roughly 10 to 20 times more per GB than NVMe flash on cloud instances. A 100 TB cache in RAM needs about 100 TB of memory across, say, 400 instances with 256 GB usable. With extstore, if keys and metadata take 10% of item size, RAM needs about 10 TB, and the 100 TB of values fit on about 60 instances with 1.7 TB of NVMe each, or more if network is the limit. Moneta's 50% disk utilization would have doubled the flash. IOPS check: 100,000 reads per second spread over 60 instances is under 2,000 IOPS each, far below the 200,000 the post measured.

Lesson 11: Cache warming (2018), agility for a stateful service#

Assumptions. EVCache had thousands of nodes in hundreds of clusters, serving signup, personalization, search and playback, and clusters had to scale for growth and the holidays. The old way to scale was to create a new empty cluster, dual-write to old and new, and wait for the old data to expire by TTL. That cost two clusters for the length of the TTL, did not work for items without expiry or that were never rewritten, and replacing nodes still caused misses as they filled naturally.

Goals. Limit network impact on current clients, use little memory and disk on cache nodes, warm fast, and work at any time, including peak.

Approaches rejected.

  • Replaying the replication Kafka stream (Lesson 9) meant storing keys for the whole TTL, up to a few weeks, and had deduplication problems, especially with invalidations.
  • Key dumps to S3, then fetching values from live replicas competed with real clients for the same network, so it needed a rate limiter and could not run at peak.

Production architecture.

  • Controller: the orchestrator. It picks the source replica (the one with the most items, unless told otherwise), creates a dedicated SQS queue, starts dumps on the source nodes, creates a Populator cluster, waits until the queue is empty, then tears everything down.
  • Dumper: part of the EVCache sidecar on each node. Phase 1: list keys with memcached's LRU crawler into key-chunk files. Phase 2: for each key, read value and metadata locally and write a data-chunk file. When a chunk is full, upload it to S3 and post its URI to SQS. Chunk metadata (warm-up ID, host, URI, format, key count) lets each chunk be used independently, so populating starts before the dump finishes. Parallelism depends on disk, sidecar heap and cores.
  • Populator: reads SQS, downloads chunks and writes them to the destination replicas using add (insert only if absent), so it never overwrites a key changed during warming. It autoscales on queue depth.
  • Instance warmer: when a node restarts or is replaced, it signals the Controller. If any node in that replica has less than its fair share of items, warming starts, using a different replica as the source. Because EVCache uses consistent hashing with virtual nodes, a node's keys are spread across all nodes of the other replicas. So every node dumps, but only keys that hash to the target node.

Numbers. Two new replicas were warmed from one existing replica of about 500 million items and 12 TB in about 2 hours. The largest warm-up was 700 TB and 46 billion items across 380-node replicas, in about 24 hours with 570 populator instances. One replaced instance was warmed with 15 million items and 2.2 GB in under 15 minutes. The warmer is used for caches whose TTL is longer than a few hours. The main bottleneck at large sizes is S3 throughput being throttled, and EBS volumes shared between dumper and populator were being considered.

Overlooked constraints.

  • Moving data off-box removes network contention. Reading values on the node and shipping files through S3 keeps the cache's client network free, which is why warming can run at peak.
  • Use insert-if-absent when copying a live dataset. A plain set would overwrite fresh values with older ones copied earlier.
  • Virtual nodes spread a node's keys everywhere. Warming one node touches every node of the source replica, just lightly.
  • A cache that takes 24 hours to rebuild is effectively a database. Its loss is a capacity event for whatever is behind it, so it needs backup and warm-up tooling.

What Netflix sacrificed. Simplicity (a controller, sidecar dumpers, SQS, S3 and a populator fleet) and some disk and CPU on cache nodes during dumps. In return, scaling and node replacement no longer cost TTL-long double clusters or hit-rate drops.

Deep Dive: warm-up throughput and the cost of a cold cacheShow

Throughput. 12 TB in 2 hours is 12,000,000 MB ÷ 7,200 s ≈ 1.7 GB/s, or about 69,000 items per second (500 million ÷ 7,200). The 700 TB warm-up in 24 hours is about 8.1 GB/s overall, or about 14 MB/s per populator instance with 570 instances. That is a modest per-instance rate, consistent with the post's observation that S3 throttling, not compute, was the limit.

Cold-cache cost (handbook's illustration). Suppose a replica serves 1 million reads per second at a 99% hit rate. Replacing it with an empty replica, the hit rate starts near 0% and recovers as keys are re-read. If the backing store can take 50,000 reads per second, an empty replica would send it 20 times its capacity. Even with zone fallback, other replicas absorb 1 million extra reads per second and double their load. Dual-writing for a week-long TTL costs a whole extra cluster for a week. Warming it in 2 hours costs a populator fleet for 2 hours. For any cache with TTLs longer than a few hours, warming wins clearly.

Lesson 12: Active-Active for multi-regional resiliency (2013)#

Assumptions. Failure rates grow with scale and with velocity of change, and Netflix had both. Its internal availability goal was 99.99%. A full regional AWS outage was unlikely, but Netflix's own changes sometimes broke critical services in a region. The principles were isolation (a failure in one region must not affect another, and a network partition must not hurt either) and redundancy. The project followed Isthmus, which had protected against a region-wide ELB outage.

Requirements for active-active across US-East-1 (Virginia) and US-West-2 (Oregon).

  1. Services must be stateless, with all replication in the data tier.
  2. Every resource must be used in-region, including S3 and SQS, so apps that publish to S3 now publish to a bucket per region.
  3. No cross-region calls on the user's path. Replication is asynchronous.

Production architecture.

  • DNS with Denominator. Users are geo-routed about 50/50. UltraDNS provides directional routing for parts of North America, which Route 53 did not support, and latency-based routing was rejected because it could move traffic unpredictably. A Route 53 layer between UltraDNS and the ELBs makes switching fast and reliable through its API: moving a CNAME, not editing directional groups. Denominator is a client library and CLI that controls several DNS providers.
  • Zuul enhancements: detect misrouted requests (not matching the geo records), so one device session does not span regions, and either proxy them to the right region (Isthmus mode) or redirect. A region can be set to failover mode, serving misrouted requests locally. A maximum traffic level can be set, above which requests are shed to protect services that are still scaling up or whose caches are cold.
  • Cassandra replicates across regions asynchronously. Netflix had run multi-region clusters (US-East-1 and EU-West-1) with LOCAL_QUORUM and ONE, but data was mostly read where written. To test timeliness, it wrote 1 million records in one region and read them 500 ms later in the other, under production load. All were read.
  • EVCache remote invalidation. Rather than build multi-master memcached replication, the client sends an SQS message to the other region to invalidate the key on every write. The next read there recomputes or falls through to Cassandra. (Lesson 9 shows the later Kafka-based replication.)
  • Multi-region deployment with Mimir, a workflow tool built on the Glisten workflow language, plus automated canary analysis and rollback. Environments had grown from two to six (Test and Prod in three regions), so manual deployment had to go. Teams wait many hours between regions to catch problems before they are everywhere.
  • Bigger chaos. Chaos Gorilla removes a whole availability zone. Split-brain cuts connectivity between regions, so each must keep working while replication queues up. Chaos Kong moves most traffic out of a region: in the test, traffic stayed in US-West-2 for over 24 hours before going back to 50/50. Traffic was moved more gradually than in an emergency so services could scale and caches could warm. Latency Monkey injects latency and errors at a chosen rate.
  • A real failover came even before Kong validation: a middle-tier system in one region degraded until most of its cluster stopped responding, and moving users to the healthy region restored service quickly. The team then fixed the problem without time pressure and moved traffic back.

Overlooked constraints.

  • Each region needs spare capacity for the other. At 50/50, failover means one region takes 100%. Either keep about 2× capacity, or scale up fast and shed load while doing it, which is why Zuul got a maximum traffic level.
  • Cold caches are the real failover risk. Moving traffic to a region whose caches never saw those users floods the databases. That drove EVCache replication (Lesson 9).
  • A global configuration push defeats regional isolation. Waiting hours between regions is what keeps a bad deploy from breaking both.
  • "Data is replicated in 500 ms" is a test result, not a guarantee. The post itself says the test was not exhaustive.

What Netflix sacrificed. Cost (duplicate deployments and S3 buckets, spare capacity), consistency across regions (asynchronous replication and invalidation-based caches) and deployment speed (hours between regions). It got survival of a whole region's failure.

Deep Dive: capacity for failover and the arithmetic of a gradual traffic shiftShow

Headroom. With two regions at 50/50 and peak traffic P, each region normally carries P ÷ 2. To absorb a full failover without scaling, each needs capacity P, so the fleet is twice the peak. With three regions at about a third each (Lesson 13), a failed region's third can be split across the other two, so each needs P ÷ 3 + P ÷ 6 = P ÷ 2: 1.5× the peak in total, not 2×. That is one reason the later Global Cloud splits evacuated traffic across both remaining regions.

Scaling while shifting (handbook's illustration). Suppose a region runs at 60% utilization and autoscaling adds about 10% capacity every 5 minutes (new instances need time to boot and warm). Moving 50% of global traffic onto it at once would ask for 200% of current capacity: shedding or failure. Moving it in steps of 10% of global traffic every 5 minutes lets capacity grow alongside it, finishing in about 25 minutes. Chaos Kong deliberately moved more slowly than an emergency would. Later work (Lessons 14 and 15) aimed to make emergency shifts fast without causing this overload, by pre-scaling and by changing how traffic is moved.

Cassandra lag. Reading 1 million records 500 ms later and finding all of them suggests cross-region replication delay was under 500 ms at p100 for that test. A cross-country round trip is about 70 ms, so normal replication is probably well under that, with the 500 ms covering queues and load. Apps reading their own recent writes after a region switch can still see older data, so writes that must be visible immediately need to go back to their home region or be read with stronger consistency.

Lesson 13: Global Cloud, active-active and beyond (2016)#

Assumptions. After 2013, members in the Americas were protected by active-active, but European members still depended on a single region, EU-West-1. As international membership grew, Netflix decided to serve any member from any of its three regions. Work started in summer 2014.

Production architecture.

  • Merging data islands. When Europe launched in 2012, Netflix deliberately kept separate regional data islands for most member data. For example, what a member watched in Europe was not merged with what they watched in the Americas, on the theory that few members cross the Atlantic and isolation limits outages. To serve EU members from the US, the EU Cassandra data had to be replicated to US-East-1 and US-West-2. Separate keyspaces would have been cheaper, but merging fit the goal of serving anyone anywhere. Some datasets merged as a simple union. The Cloud Database Engineering team added parallel writes to two keyspaces to the Astyanax Cassandra client, and built a forklift tool to copy data between clusters. Others, such as viewing history, needed custom merge tools, and a couple of datasets had unexpected inconsistencies that needed analysis to decide which values to keep.
  • EVCache now supports both full replication and invalidation per cache (Lesson 9).
  • Personalization. Recommendations were precomputed in a member's home region and replicated. During a traffic migration, interactions in another region did not trigger updates, which was accepted at first because precomputation also runs on a clock. Later, the triggering events were delivered to all three regions, which also let the compute load move to wherever capacity was available.
  • Misrouted traffic. Different app-level redirect mechanisms had caused confusion. Netflix replaced them with the same Zuul-to-Zuul proxying used for failover, then, once every region could serve everyone, simply served misrouted traffic locally. Teams deleted old redirect code and were told to serve the best answer possible with local data.
  • Evolving Chaos Kong. In an early real production issue in US-East-1, traffic went first to US-West-2 and later to EU-West-1, while global stream starts tracked the previous week. Later tools could evacuate a region to both remaining regions at once, split by available capacity. For example, US-East-1 traffic went mostly to EU-West-1 with some to US-West-2. Similar evacuations were run for each region.

Overlooked constraints.

  • Data islands are cheap to create and expensive to merge. Each dataset needed its own merge rule, and hidden inconsistencies appeared.
  • Event-driven precomputation must follow the member. If only the home region recomputes, members served elsewhere see stale personalization.
  • Uniform routing logic beats special cases. Using one Zuul proxying path for both misrouting and failover removed a class of confusing bugs.

What Netflix sacrificed. The isolation of regional data islands, which limited the reach of a data problem, plus storage and replication cost for full copies in every region. It gained the ability to evacuate any region.

Deep Dive: splitting an evacuation by capacityShow

Suppose peak traffic is split 40% US-East-1, 25% US-West-2 and 35% EU-West-1, and each region is provisioned at 1.4× its normal share (handbook's illustration). Spare capacity in global-traffic units is then 0.4 × 0.4 = 16% in US-East-1, 0.4 × 0.25 = 10% in US-West-2 and 0.4 × 0.35 = 14% in EU-West-1.

To evacuate US-East-1 (40%), the other two must absorb 40% between them, but they have only 10% + 14% = 24% spare. They must scale up by another 16% of global traffic, shed low-priority work (Lessons 16 and 17), or both. Split in proportion to spare capacity, EU-West-1 takes 14 ÷ 24 ≈ 58% of the moved traffic, about 23% of global, and US-West-2 takes about 17%. That matches the post's pattern of "mostly to EU-West-1", although time of day matters too: when the US is at peak, Europe is in its evening or night, so EU-West-1 has more spare capacity. Sending everything to one region would need 40% spare there, almost three times what any single region has.

Lesson 14: Evolving regional evacuation (2019), predicting per-service demand#

Assumptions. By 2019 Netflix had more than 150 million members streaming over 100 million hours a day. It used an N+1 architecture: each AWS region is a fault domain, and the remaining regions must absorb one failed region. Services autoscale to current demand, so they are right-sized for now, not for the surge an evacuation brings. Before moving traffic, Netflix must pre-scale services in the healthy regions. The 2013 pre-scaling machinery rested on two assumptions:

  1. Every service's regional demand tracks stream starts per second (SPS), Netflix's key business metric (Lesson 21).
  2. All services in a healthy region can be scaled by the same ratio during an evacuation.

Both held in 2013, when a few monoliths did most of the work and members used devices in similar ways across regions. Both broke later.

What broke.

  • Decomposition broke assumption 1. Player logging, authorization, licensing and bookmarks had been one monolith whose demand followed SPS. Split into purpose-built services, each had its own demand curve. Even Zuul was sharded by function: combined Zuul demand roughly tracked SPS for most of the day, but individual shards strayed widely.
  • Device mix broke assumption 2. Playback licensing (DRM) depends on the device type: TVs and other consumer electronics (CE), Android and iOS use different DRM platforms. The CE-to-mobile ratio differs by region (mobile is more popular in South America), so evacuating South America into North America does not grow CE DRM and Android DRM by the same ratio. Playback authorization, used by every device, scales roughly with total regional demand.

Production architecture.

  • Service-specific demand metrics. Services were a mix of Java (Governator or Spring Boot with Ribbon or gRPC) and Node.js (NodeQuark), so no single metric fit everyone. Netflix built a self-service, configuration-driven way to attach demand metrics to each service, scoped per shard and region, with history pulled from Atlas (Lesson 23).
  • Demand by device type, from tracing. Metrics did not break demand down by device, so sampled distributed traces (Lesson 22) were used to split each service's regional demand into device groups (CE, Android, PS4 and others), and to see how that split changes through the day.
  • Device evacuation ratios. Historical evacuations show how much each device type's traffic in the receiving region grows when another region is evacuated: the demand scaling ratio, evacuation traffic divided by nominal traffic, for that time of day.
  • Device-weighted scaling ratio per service = the sum over device types of (the service's share of demand from that device × that device's evacuation ratio). Compared with the old SPS ratio, some services were predicted about the same, some were over-provisioned and some under-provisioned.

Overlooked constraints.

  • Decomposing a monolith breaks capacity models built on it. A proxy metric that fit one big service fails for twenty small ones.
  • The traffic mix moves, not only the volume. Evacuated users bring their device mix and habits.
  • The new model is still an approximation. It assumes all traffic of one device type has a similar shape, for example Android logging and Android playback, which may not be true.

What Netflix sacrificed. Simplicity and computation: per-service metrics, trace processing and per-device ratios instead of one SPS ratio. It gained safer evacuations (fewer under-scaled services) and cheaper ones (less over-scaling).

Deep Dive: computing a device-weighted evacuation ratioShow

Take a fictional licensing service in US-East-1 at 20:00 (handbook's illustration). Its demand by device is 50% CE, 30% Android, 15% iOS and 5% browser. History shows that when US-West-2 is evacuated at this hour, US-East-1's CE traffic grows 1.6×, Android 2.3×, iOS 1.9× and browser 1.5×.

Weighted ratio = 0.50 × 1.6 + 0.30 × 2.3 + 0.15 × 1.9 + 0.05 × 1.5 = 0.80 + 0.69 + 0.285 + 0.075 = 1.85.

If SPS in US-East-1 grows 1.7× in the same evacuation, the old method would pre-scale this service by 1.7× and leave it about 8% short (1.85 ÷ 1.7 ≈ 1.09). A service whose demand is mostly CE (ratio 1.6) would be over-scaled by about 6%. Small errors per service matter because an evacuation stresses everything at once, and the under-scaled service becomes the bottleneck. The time-of-day dimension is essential: the device mix of evacuated traffic at 20:00 Pacific differs from that at 09:00.

Lesson 15: Project Nimble (2018), region evacuation in under 10 minutes#

Assumptions. With 117 million members watching 140 million hours a day, even short or partial outages hurt many people. A region failover took about 50 minutes. The goal was under 10 minutes, cost-neutral, with minimal changes to core infrastructure and no extra work for other teams.

Where the 50 minutes went.

StepTimeWhy
Decide to fail overabout 5 minThe failover itself made huge numbers of EC2 changes that could confuse a healthy region, so it was a risky choice
Provision capacity3 to 5 minCompute how much each service needs, then scale destination regions
Service start-upabout 25 minBoot, start, download resources, connect to backends, register with Eureka, apply Archaius configuration, register with ELBs
Proxy traffic through Zuul10 min or moreZuul tunnels traffic between regions to work around DNS TTLs, in steps, so new instances can warm up (JIT compilation)
DNS cut-overabout 5 minDNS updates take seconds, but device TTLs mean most devices move within about 5 minutes

The long pole was start-up. If instances could be ready instantly, failover would just be a DNS change.

Rejected options.

  • Pin capacity high. Teams autoscale on their own signals. Running every group "cold" would mean either centrally overriding teams' autoscaling signals or changing hundreds of policies.
  • Abandon autoscaling and pin to a computed size. That would hide performance regressions inside a huge evacuation buffer.

The solution: dark capacity.

  • Shadow ASGs. Netflix bakes AMIs (machine images with everything installed), so a copy of each service can boot fully ahead of time. Dark instances live in a shadow auto scaling group with the same launch configuration as the service they shadow.
  • Detach and attach. AWS lets you detach an instance from one ASG and attach it to another. An orchestrator moves dark instances into the live ASG on failover, so it looks as if new instances appeared instantly.
  • Tracking changes. Edda (cloud resource history) and Spinnaker (deployment) are used to follow red/black deploys and rollbacks and keep shadow groups cloned from the current production configuration.
  • Sizing. The number of dark instances per service and region comes from time of day and the expected failover traffic (the model in Lesson 14).
  • Invisibility. The base AMI team helped dark instances set the same environment variables as the service they shadow, early in boot. ELBs never see them, because they are in a different ASG. A platform library keeps them in Eureka's STARTING state, so Ribbon never sends traffic. Atlas metrics are disabled until activation, so dark instances do not skew dashboards or autoscaling. On the signal, they register UP and take traffic.

Result. Failover dropped from 50 to 8 minutes. A team of two built it in about six months. Every streaming-path service is enabled by default, and it "just works" for any service without cross-region dependencies. Ideas for the future: emergency capacity for one service on demand, and faster autoscaling using pre-warmed instances.

Overlooked constraints.

  • Immutable images make dark capacity possible. A service configured after boot by configuration management could not be pre-booted this safely.
  • "Ready" means ready in every system. An instance must be hidden from load balancers, service discovery and metrics, or it distorts autoscaling and alerts.
  • Cost neutrality has to be designed in. The post presents Nimble as cost-neutral, which suggests dark capacity takes the place of evacuation capacity that would otherwise have been bought anyway. It does not explain the accounting in detail.
  • DNS TTL sets the floor. Once start-up is solved, the remaining minutes come from device DNS caching.

What Netflix sacrificed. Some complexity in the control plane (shadow groups and an orchestrator that must track every deploy) and keeping booted but idle instances around. In return, failover dropped from 50 minutes to 8.

Deep Dive: what 42 minutes of failover time is worthShow

Suppose a regional problem affects a third of global traffic and streams start at a rate S per second in that region (handbook's illustration: 10,000 per second at peak). With 50-minute failovers, the failed starts number roughly 10,000 × 3,000 s × an average failure fraction. If half the starts fail on average while traffic slowly moves, that is 15 million failed play attempts. With 8 minutes, it is about 2.4 million. The difference is the business case for Nimble.

Why could start-up not just be made faster? The 25 minutes are the sum of many small dependency steps: instance boot (1 to 3 minutes), JVM start and class loading, downloading data such as caches or ML models, opening connection pools, Eureka registration (the client and server refresh caches every 30 seconds or so, Lesson 3), and ELB health checks. Then JIT warm-up means a new JVM runs slower for minutes, which is why Zuul moved traffic in steps. Each step could be shaved, but only removing them from the critical path, by doing them before the failover, changes the order of magnitude.

Lesson 16: Prioritized load shedding at the gateway (2020)#

Assumptions. Failures that overload Netflix come from retry storms from misbehaving clients, an under-scaled backend, a bad deploy, a network blip or the cloud provider. All of them had stopped members from pressing play at some point. Netflix had on/off circuit breakers but no progressive way to shed load. Goals: prioritize requests consistently across mobile, browser and TV, throttle progressively by priority, and validate with chaos testing.

A request taxonomy. Requests are judged by throughput, functionality and criticality:

  • NON_CRITICAL: does not affect playback or experience, such as logs and background requests. Usually high volume, so a big share of load.
  • DEGRADED_EXPERIENCE: affects experience but not the ability to play, such as pause markers, player language selection and viewing history.
  • CRITICAL: affects the ability to play. If it fails, the member sees an error on pressing play.

Production architecture.

  • Zuul computes a priority score from 1 to 100 for every request at the start of processing, based on its attributes. Normally the score is ignored. Under stress, Zuul behaves like a priority queue with a moving threshold and drops requests below the current threshold.
  • Two places to throttle. Service throttling applies when one backend is in trouble, detected by that backend's error rate and concurrent requests. Global throttling applies when Zuul itself is in trouble, detected by CPU, concurrent requests and connection count. Global throttling is aggressive, because if Zuul falls over, nothing gets through.
  • A cubic curve maps overload to the threshold. Overload is measured as how far load sits between the throttling threshold and the maximum capacity. The threshold barely moves at first: at 35% overload it is still in the mid-90s, at 80% it is 50, at 95% it is 10. Beyond that, everything is throttled.
  • Retry back-pressure. When Zuul sheds a request, it tells the device how many retries it may make and over what window. Higher-priority requests are allowed to retry more aggressively. This stops retry storms much faster:
{ "maxRetries": 2, "retryAfterSeconds": 30 }
  • Validating the taxonomy. A FIT (Failure Injection Testing) injection point in Zuul can shed any priority range for a chosen device or member, so engineers can see what a member experiences. Because requests thought non-critical can quietly become critical, ChAP (Lesson 18) runs 45-minute A/B experiments: a small group of members has a range of priorities throttled, and playback KPIs per device are compared with a control group. The first experiment found a race condition on Android and iOS, where a low-priority request caused sporadic playback errors. The experiments now run periodically to catch regressions.

Results. In 2019, before this existed, an outage stopped a sizable share of members from playing. In 2020, days after rollout, a similar incident hit, Zuul shed traffic by priority until the system was healthy, and SPS stayed flat: members kept playing.

Overlooked constraints.

  • Most load is not critical. Telemetry and logs are high volume, so shedding them frees a lot of capacity while hurting no one.
  • Priority labels go stale. A request can become critical through a client change, which is why the taxonomy needs continuous experiments.
  • Shedding without retry control is incomplete. Rejected clients that retry immediately bring back the load, so the response must tell them when to retry.

What Netflix sacrificed. During overload, features: pause markers, history and logging silently stop working, and telemetry is lost. It also has to maintain the taxonomy and the experiments. In return, playback survives overload.

Deep Dive: the shape of the shedding curveShow

The three published points (35% overload gives threshold about 95, 80% gives 50, 95% gives 10) fit a curve of the form threshold = 100 × (1 − x³), where x is overload from 0 to 1. Check: at x = 0.35, x³ ≈ 0.043, giving 95.7; at x = 0.8, x³ = 0.512, giving 48.8; at x = 0.95, x³ ≈ 0.857, giving 14.3. This is the handbook's fit, not a published formula, but it shows the design intent: barely shed at mild overload, then shed fast as the system nears collapse.

Why cubic and not linear? Suppose scores are spread so that non-critical traffic (60% of requests) sits at 1 to 60, degraded traffic (30%) at 61 to 90 and critical traffic (10%) at 91 to 100, and within each band the scores order requests by how much they matter, for example browser telemetry below TV telemetry (handbook's illustration). A linear curve, threshold = 100 × (1 − x), would reach 90 at only 10% overload and start shedding degraded features while the system is barely stressed. The cubic curve stays above 95 until about 35% overload, so mild overload is handled by trimming the least important traffic, and then rises steeply: at x = 0.8, threshold 49 sheds most non-critical traffic, and only near total collapse does it reach the critical band.

The general lesson: the curve and the score distribution must be designed together. The same curve sheds very different amounts depending on where each class of traffic sits on the 1 to 100 scale. Test the pair by replaying a realistic traffic mix and checking which classes are dropped at each overload level, and keep critical traffic in a narrow band at the top so that it is touched last.

Lesson 17: Service-level prioritized load shedding (2024)#

Assumptions. Gateway shedding (Lesson 16) cannot see inside a service, cannot protect backend-to-backend calls that never pass through Zuul, and forces teams to split clusters to isolate request types. The 2024 work moved prioritization into services, owned by service teams.

PlayAPI, the motivating case. PlayAPI handles manifest and license requests needed to start playback. It sees two kinds:

  • User-initiated (critical): the member pressed play.
  • Pre-fetch (non-critical): sent speculatively while the member browses, to cut start-up latency if they do press play. Failure only makes start-up slightly slower.

A plain concurrency limiter rejected both kinds equally. So a spike in pre-fetch traffic cut availability for user-initiated requests, and high backend latency cut both equally even when there was enough capacity for every user-initiated request. Sharding into two clusters isolates them, but costs more compute and duplicates CI/CD, autoscaling, metrics and alerts.

Production architecture.

  • A partitioned concurrency limiter from the open-source Netflix concurrency-limits library. The user-initiated partition is guaranteed 100% of throughput, and pre-fetch gets only excess capacity. User-initiated requests can take capacity from pre-fetch whenever they need it. Nothing is throttled in steady state.
  • It runs as a servlet filter that reads an HTTP header set by the device, so a rejected request costs almost no CPU (its body is never parsed):
Filter filter = new ConcurrencyLimitServletFilter(
    new ServletLimiterBuilder()
        .named("playapi")
        .partitionByHeader("X-Netflix.Request-Name")
        .partition("user-initiated", 1.0)
        .partition("pre-fetch", 0.0)
        .build());
  • Testing. FIT injected 2 seconds of latency into pre-fetch calls (normally under 200 ms at p99) on one baseline instance with the old limiter and one canary with the new one. On the baseline, both kinds lost availability. On the canary, only pre-fetch did; user-initiated stayed at 100%.
  • A real incident. Months later, after an infrastructure outage was fixed, Android devices sent a 12× spike in pre-fetch requests (a backlog of queued requests). Pre-fetch availability fell to 20%, while user-initiated stayed above 99.4%, even when over 50% of all requests were throttled. Without it, that spike could have caused a second outage.

A generic library with four buckets, inspired by Linux traffic control (tc-prio) levels:

BucketMeaningWhen shed
CRITICALCore functionOnly in complete failure
DEGRADEDHurts experienceProgressively as load rises
BEST_EFFORTNot visible to the userMay be shed progressively even in normal operation
BULKBackground workRoutinely shed

Services can inherit the caller's priority or map requests to buckets from headers or the body.

  • CPU-based shedding. Most services autoscale on CPU, so shedding starts only above the autoscaling target, which keeps the scale-up signal alive. Example: target 60% CPU, then shed lower buckets progressively above it while new instances arrive. In a test, a service that normally targets 45% CPU was prevented from scaling, configured to shed non-critical traffic above 60% CPU and critical above 80%, and hit with more than 6× its normal volume. It shed non-critical, then critical traffic, while p99 latency stayed reasonable and successful throughput stayed flat.
  • IO-based shedding, for services limited by a backend rather than CPU. Services can set per-endpoint target and maximum latencies. Storage services behind the Data Gateway (such as the KeyValue abstraction, Lesson 24) report SLO utilization: the percentage of requests slower than the target and slower than the maximum, plus storage and compute use, per namespace:
utilization(namespace):
  overall = 12
  latency:  slo_target = 12   (12% slower than the 10 ms target)
            slo_max    = 0    (0% slower than the 500 ms maximum)
  system:   storage = 17, compute = 10

A daily batch writer can be shed when storage utilization nears capacity. A file origin service for Open Connect accepts writes of new files and serves reads to the CDN. Writes must never be shed, but less important reads can be. It was configured to shed those reads when KeyValue reported target latency utilization above 40%. In a stress test at about 2,000 reads per second of roughly 4 MiB files (over 50 Gbps), the backend became overloaded, and only low-priority reads were shed. CPU on the service stayed under 10%, so only an IO-based limiter could have protected it.

Two anti-patterns.

  1. No shedding. Latency rises for everyone instead of a fast, retryable rejection for some. One unhealthy instance pushes load onto others, a death spiral that finishes before autoscaling can react.
  2. Congestive failure. Shedding so hard that successful throughput falls below what it was before shedding began. In the post's example, a service sustaining 240 RPS dropped far below that once shedding started. This happens with fixed concurrency limits or when the shedding itself uses too much CPU.

Overlooked constraints.

  • Shed below the autoscaling target, and you blind autoscaling. Starting above the target keeps the scale-out signal intact.
  • Rejecting must cost much less than serving. Use headers, not bodies, or shedding turns into congestive failure.
  • CPU is the wrong signal for IO-bound services. Latency SLO utilization from the backend gives an earlier, truer signal, with less tuning than fixed concurrency limits, which either shed too early or too late.
  • One cluster with priorities can replace two clusters. It is cheaper, but failure isolation is now in software, so bugs in the limiter matter.

What Netflix sacrificed. Physical isolation (critical and non-critical requests now share a cluster and its failure modes), plus a dependency on clients setting priority headers correctly. It gained lower cost, priorities owned by service teams, and protection for backend-to-backend traffic.

Deep Dive: why a partitioned limiter protects critical traffic, with numbersShow

Suppose a PlayAPI instance can handle 200 concurrent requests at good latency (handbook's illustration). Normal load is 60 user-initiated and 80 pre-fetch requests in flight: 140, no throttling.

A plain limiter during a 12× pre-fetch spike. Pre-fetch demand becomes 960 in flight, user-initiated stays at 60, so 1,020 compete for 200 slots. If rejections are spread evenly, about 200 ÷ 1,020 ≈ 20% of each kind is served. User-initiated availability is about 20%, and members cannot press play.

A partitioned limiter. User-initiated requests get their 60 slots first. Pre-fetch gets the remaining 140 out of 960, about 15%. User-initiated availability is 100% and pre-fetch is about 15%, close to what the post reported (above 99.4% and 20%).

Little's law check. At 50 ms average latency, 200 in flight equals 4,000 requests per second per instance. If backend latency doubles to 100 ms, the same 200 slots handle only 2,000 per second. A plain limiter would then reject half of all traffic, including user-initiated. A partitioned limiter still serves all 60 user-initiated in flight (now 600 per second) and gives pre-fetch the remaining slots. This is the second problem in the post: latency, not traffic, can fill a concurrency limiter, and partitioning keeps the important work flowing.

Lesson 18: ChAP, the Chaos Automation Platform (2017)#

Assumptions. Chaos Monkey (instances) and Chaos Kong (regions) cover big failures, but availability is also threatened by failures between microservices. FIT injected microservice failures in production by decorating requests, but it had limits. ChAP was built to make microservice chaos safer, more frequent and broader. Experiments run in production, in line with the Principles of Chaos Engineering, so the question is: what is the smallest experiment that still gives a confident answer?

Problems with FIT.

  • Signal lost in noise. FIT's affected requests were mixed into whole-system metrics. To see an effect, users ran bigger and longer experiments, putting more members at risk.
  • Results go stale. Netflix sees many hundreds of deploys a day, so a result from last month may no longer hold.
  • Diffuse failures. FIT-decorated requests were spread across all production capacity, so extra load was absorbed by normal headroom and circuit breakers never tripped. Fine for checking that fallback logic is correct, but not for checking behavior when many requests fail.

Production architecture.

  • ChAP reads the service's deployment pipeline (Spinnaker) and launches an experiment cluster and a control cluster, both copies of the production service. It sends a small, equal slice of traffic to each and applies a FIT scenario only to the experiment cluster.
  • A Mantis streaming job computes KPIs (such as SPS) only for the members and devices in each cluster, so divergence is easy to see even with a small population.
  • An automatic circuit breaker stops the experiment if it exceeds a predefined error budget. Ongoing analysis uses the same system as canary analysis (Lesson 19).
  • Continuous runs. ChAP is integrated with Spinnaker, so experiments run regularly and catch regressions in resilience.
  • Concentrated experiments. Clusters are scaled to the population being studied. For 0.5% of traffic on a service with 200 instances, the experiment and control clusters get one instance each. Because only experiment traffic reaches the experiment cluster, 100% of its calls to the failing dependency are affected, exposing thresholds a diffuse experiment never reaches:
    • thread pools exhausted by a slow dependency;
    • fallbacks that cost more CPU than the normal path;
    • lock contention in logging when errors are logged as exceptions;
    • retry storms that become a self-inflicted denial of service.

Example. To test how the API handles failure of the Ratings service (thumbs up and down), ChAP launches one-instance API clusters, routes the control and experiment populations to them, and fails all experiment calls to Ratings. ChAP has found mistuned retry policies, CPU-heavy fallbacks and unexpected interactions between circuit breakers and load balancers.

Overlooked constraints.

  • A control group turns chaos into a statistics problem you can actually win at small sizes.
  • Diffuse failure tests logic; concentrated failure tests capacity. Both are needed.
  • Resilience regresses with every deploy, so chaos must be automated and continuous, not a one-off game day.

What Netflix sacrificed. A small number of real members experience real failures, bounded by the error budget and the population size, and it runs extra clusters. In return it catches resilience bugs before an outage does.

Deep Dive: why a control group shrinks the experiment you needShow

Suppose a playback error rate is normally 0.5% with random noise, and a broken fallback raises it to 0.8% for affected members (handbook's illustration).

Diffuse (FIT-style). If 1% of all traffic is affected, the global error rate rises from 0.5% to 0.503%. Global metrics naturally move by more than 0.003 percentage points minute to minute, so this is invisible. To see it, you must affect perhaps 20% of traffic, putting many members at risk.

Controlled (ChAP). Compare 0.5% vs 0.8% between two equal groups. For a two-proportion test with 95% confidence and 80% power, the required sample per group is about (1.96 + 0.84)² × (p1(1 − p1) + p2(1 − p2)) ÷ (p2 − p1)², which is 7.84 × (0.004975 + 0.007936) ÷ 0.000009 ≈ 11,200 play attempts per group. At 0.5% of a region's traffic, with a start rate of, say, 5,000 per second, each group sees 25 starts per second, and reaches 11,200 in about 7.5 minutes. A small population, compared directly against a matched control, reaches a confident answer in minutes, which is what makes automated, frequent experiments safe.

Lesson 19: Automated canary analysis with Kayenta (2018)#

Assumptions. A canary release sends a small share of traffic to the new version and compares it with the old. Manual canary analysis (engineers comparing graphs of HTTP status codes, latency, exceptions and load) took hours per canary, limited deploys to once or twice a week and missed subtle differences. Netflix's first automated canary analysis was more than five years old by 2018. Kayenta, open-sourced with Google, is its successor and is tightly integrated with Spinnaker.

Production architecture.

  • Three clusters, not two. Production (unchanged, any size) takes most traffic. A baseline cluster runs the current version, typically 3 instances. A canary cluster runs the new version, also 3 instances. Baseline and canary usually join the production load balancer pool. Comparing a fresh canary with the long-running production cluster would be unfair: long-running processes have warm caches, memory growth and other effects. A fresh baseline removes that bias.
  • Spinnaker creates and destroys baseline and canary, runs one or more analysis rounds, and decides to continue, roll back or ask a human.
  • Metric retrieval. A configuration lists metric queries, combined with a scope (cluster and time range). Sources include Prometheus, Stackdriver, Datadog and Atlas, and can be mixed in one analysis.
  • Judgment in four steps.
    1. Data validation: mark a metric NODATA if either side is empty.
    2. Data cleaning: handle missing values by metric type. For example, a missing error count becomes zero, while missing samples of other metrics are dropped.
    3. Metric comparison: classify each metric as Pass, High or Low, using confidence intervals from the Mann-Whitney U test.
    4. Score: the percentage of metrics that pass (9 of 10 gives 90%). It is deliberately simple to understand. Spinnaker compares the score with thresholds.
  • Reports. A canary report breaks the score down by metric and shows the input data (for example, a 58% score with several metrics High), which builds trust.
  • Archived results let new judges be tested on old data. Metric sources, judges and storage are pluggable. A REST API means Kayenta can run without the rest of Spinnaker, needing only Redis.
  • In 2018 Kayenta ran about 30% of Netflix's production canary judgments, about 200 a day, with full migration planned.

Overlooked constraints.

  • The control must be equally fresh. Without a new baseline, the canary "fails" for reasons that have nothing to do with the code.
  • Traffic must be evenly spread across baseline and canary (Lesson 7), or differences come from load, not from code.
  • Metric choice is the real configuration. A canary passes on the metrics it watches. A bug in an unwatched behavior ships.

What Netflix sacrificed. Two short-lived clusters per deploy, and some statistical risk: with small clusters and short windows, subtle regressions can pass and noisy metrics can fail a good build. It gained frequent, safe deploys without people staring at graphs.

Deep Dive: why Mann-Whitney, and what a canary score can missShow

Mann-Whitney U (a rank test, from Mann and Whitney, 1947) asks whether values from one group tend to be larger than values from another, without assuming a normal distribution. Pool all samples, rank them, and sum the ranks of the canary samples. If the canary's latency points mostly rank above the baseline's, U is extreme and the difference is significant. Latency and error metrics are skewed and have outliers, so a rank test is more robust than a t-test on means. A confidence interval on the shift tells Kayenta not only whether there is a difference but how big it is, so a tiny, harmless shift can still pass.

Example (handbook's illustration). Over a 30-minute window with 1-minute samples, each cluster yields 30 values per metric. If the canary's p50 latency is about 4% higher with low noise, the test flags it High. If one metric in 10 is High, the score is 90%. A pipeline that passes at 90% or higher ships it. So a single critical regression can still pass if the score treats all metrics equally. This is why teams mark key metrics (errors, crashes) as critical, which fail the canary on their own, and why the post plans semantic defaults for metric types such as "error" and "resource usage".

Power. With 3 instances per side, a slow memory leak or a problem that only shows under peak traffic may not appear in a short window. Netflix pairs canaries with hours between regions (Lesson 12) and with Nimble and evacuations as a fallback.

Lesson 20: Scryer, predictive autoscaling (2013)#

Assumptions. Amazon Auto Scaling (AAS) is reactive: it adds or removes instances when a metric such as load average crosses a threshold. Netflix found it effective, but it missed some cases:

  • Fast spikes. Instance start-up took 10 to 45 minutes, and existing servers were exposed during that time.
  • Outages followed by retry storms. Traffic drops during an outage, so reactive scaling scales down, then the retry storm arrives when the problem is fixed, and the fleet is too small.
  • Different patterns at different times. Some periods see a fast rise from a small fleet (20% of maximum) and others a slow rise from a large one (80%), so one policy cannot fit both.

Scaling up aggressively causes oscillation, and over-provisioning is expensive. But Netflix's traffic is highly predictable: the same daily curve, similar from one week to the next, barring outages and special events.

Production architecture. Scryer predicts demand ahead of time from past patterns and turns the forecast into scheduled scaling actions through AWS APIs, with each step sized to follow the curve closely. It runs alongside AAS: Scryer handles the predictable curve, and AAS is the safety net for surprises. Results: better cluster performance, better availability and lower EC2 costs. The post promised follow-ups on the algorithms and possible open-sourcing.

Overlooked constraints.

  • Reactive scaling reads an outage as low demand. Scaling down during an outage sets up the next failure. A forecast is not fooled by the drop.
  • Lead time is the whole point. With 10 to 45 minutes to start, scaling must happen before the demand, not in response to it.
  • Forecasts fail on unusual days (launches, holidays, outages), so a reactive floor is still required.

What Netflix sacrificed. Some capacity bought ahead of time that may not be needed, and a forecasting system to maintain. It got capacity ready before the evening peak and protection against retry storms after outages.

Deep Dive: how much a forecast saves over reactive scalingShow

Suppose a cluster needs 1 instance per 1,000 RPS and the evening ramp rises from 100,000 to 300,000 RPS in 2 hours, about 1,700 RPS per minute, and new instances take 20 minutes to be useful (handbook's illustration).

Reactive only. The policy notices load rising and adds instances, but each takes 20 minutes. To avoid overload, the fleet must always have 20 minutes of growth in hand: 20 × 1,700 = 34,000 RPS, about 34 extra instances, kept as headroom all day, since the policy cannot know when the ramp will come. That is 34% extra at the 100,000 RPS trough.

Predictive plus reactive. Scryer schedules the fleet to be ready about 20 minutes before each point on the forecast curve. Headroom is now only for forecast error, say 5% (15 instances at peak), plus the reactive layer for surprises. Over a day, average excess drops from about 34 instances to about 10. Across thousands of instances in hundreds of clusters, that saving is large, and so is the protection against an outage that would have shrunk the fleet just before a retry storm.

Lesson 21: SPS, the pulse of Netflix streaming (2015)#

Assumptions. Around 2008 engineers watched hundreds of metrics by hand. That worked for tens of servers and thousands of devices, not for thousands of servers and millions of devices. Netflix needed one simple signal that everyone, technical or not, could understand, and that closely tracks its most important activity: viewing.

The signal. A server-side count of stream starts per second (SPS), people pressing play, has a regular, predictable pattern, and moves sharply when there are UI, device or server problems. In each region it follows one cycle a day: peaks in the evening, troughs in the early morning, more daytime viewing on regional holidays. Because the pattern is so regular, expected SPS can be predicted for any time of the week, and deviations from the prediction indicate trouble. SPS became the company's language: incidents are "SPS impacting" or not, and availability is measured as expected versus actual SPS. It is the same signal used to judge evacuations (Lesson 13), load shedding (Lesson 16) and chaos experiments (Lesson 18).

Detection methods.

  • Static thresholds suit metrics that should not exceed a level (CPU), but not an oscillating signal like SPS.
  • Exponential smoothing (an exponential moving average) gives a bound that moves with the signal. It weighs all past observations with decaying weights and needs only the latest value to update, which suits real-time alerting.
  • Double exponential smoothing (DES) adds a trend term to follow the daily rise and fall, and is what Netflix uses for SPS bounds. Triple smoothing (with seasonality) was not needed, because alerts look at short windows without a strong seasonal component. Parameters were estimated from data, motivated by Gardner's review of exponential smoothing, and reused across signals with similar daily shapes, such as SPS per device. DES catches drops well, but after a sharp recovery it lags and gives false alarms for a short time.
  • Bayesian methods such as switchpoint detection with Markov Chain Monte Carlo (MCMC) can be non-parametric and evolve with data, but they are far more compute-heavy and hard for people to interpret, so they could not run in real time on many metrics. Netflix was also exploring stream mining (drift detection) and Robust PCA for high-cardinality data.

Overlooked constraints.

  • One business metric beats hundreds of technical ones for deciding "is this an incident?". Technical metrics then explain why.
  • Detection must match the signal's shape. A threshold fit for CPU is useless for a daily wave.
  • Interpretability and cost matter in alerting. A model no one can explain, or one too slow to run on every metric, will not be trusted or used.

What Netflix sacrificed. SPS only sees problems that affect playback starts. Problems after play begins (rebuffering, quality drops) or in browsing need other signals. DES also gives false alarms after sharp recoveries. In return, the whole company shares one clear health signal.

Deep Dive: double exponential smoothing, step by stepShow

DES (Holt's linear method) keeps two numbers: a level L and a trend T. For each new value y:

  • new L = α × y + (1 − α) × (old L + old T)
  • new T = β × (new L − old L) + (1 − β) × old T
  • forecast for the next step = new L + new T

Alert if the actual value falls below the forecast by more than k standard deviations of recent forecast error.

Example (handbook's illustration). α = 0.5, β = 0.3. SPS samples each minute during the evening ramp: L = 10,000, T = 50. The next value is 10,060. New L = 0.5 × 10,060 + 0.5 × (10,000 + 50) = 10,055. New T = 0.3 × (10,055 − 10,000) + 0.7 × 50 = 16.5 + 35 = 51.5. Forecast is 10,055 + 51.5 ≈ 10,107. If errors usually have a standard deviation of 150, a band of 3 standard deviations sets the lower bound at about 9,657. A sudden drop to 8,000 crosses it immediately: an alert.

Why recovery causes false alarms. During the drop, L falls toward 8,000 and T becomes strongly negative. When SPS jumps back to 10,000, the forecast still includes the negative trend, so the model takes several steps to catch up. Meanwhile the error band, widened by the drop, can trigger alerts in the other direction or misreport when recovery happened. That is the weakness the post describes, and why recovery is also judged against the same time last week.

Lesson 22: Distributed tracing for troubleshooting, Edgar (2020)#

Assumptions. A member asks, "Why doesn't this show play on my phone?" Before Edgar, on-call engineers rebuilt a streaming session by hand from account data and logs pulled from the app, the CDN and many backend services. If every session had an ID, distributed tracing could rebuild the session automatically: the service topology, retries, errors and the latency of every call. Joining traces with account data and logs would give the full context.

Production architecture.

  • Instrumentation. Netflix started with its own Java tracing libraries about four years before the post. By 2017 it adopted Open-Zipkin, which fitted its Spring Boot runtime best, with B3 HTTP headers for context propagation. The platform team guaranteed propagation in the "paved road" Java and Node runtimes, including legacy code. Teams on other stacks (Python, Node, Ruby on Rails) chose their own tracers under the "freedom and responsibility" principle. Runtimes add infrastructure tags automatically: service name, ASG and container ID. These let Edgar join traces with logs and deep-link to monitoring and deployment tools.
  • Sampling. Sampling heavily makes traces useless for troubleshooting, since the request you need may not be kept. Sampling nothing costs CPU, memory and network in every service, plus a bigger pipeline. Netflix chose hybrid head-based sampling: 100% of traces for a configurable set of requests (mission-critical streaming services) and random sampling elsewhere (for example, offline batch jobs). Teams retuned services to absorb the tracing overhead.
  • Stream processing with Mantis, Netflix's back-pressure-aware stream platform. Agents publish spans via the Mantis Publish library. A first job buffers spans for a time window to assemble whole traces. A second job applies tail-based sampling and writes to storage. The chained jobs scale independently, and engineers can query the live stream ad hoc with MQL in the Raven tool.
  • Storage: from Elasticsearch to Cassandra. Elasticsearch's flexible queries were attractive, but as trace volume grew exponentially, indexing at a high write rate slowed both reads and writes. Cassandra with simple lookup indexes handled heavy writes with acceptable read latency. To make storage cost grow slower than data:
    • EBS volumes instead of SSD instance storage, so disks can grow without adding nodes.
    • Tuned Time Window Compaction Strategy (TWCS), which reduced SSTable writes and merges, and so reduced EBS I/O and replication traffic.
    • Zstd block compression, which halved file sizes.
    • Together: 71% lower cost while storing 35× more data.
    • Rule-based tail filtering. Edgar users looked at under 1% of traces. The storage job keeps traces with warnings, errors or retries and samples the rest, cutting volume by 20% with no loss to users.
    • Next: new Edgar features could need 10× more data, so a tiered data gateway would keep the last few hours in Cassandra and move compacted files to S3.
  • Other uses of traces: Telltale health monitoring infers the service topology from traces and correlates it with Atlas metrics. Chaos engineers check that FIT failures were injected correctly. Demand Engineering uses device mix per service for evacuation pre-scaling (Lesson 14). Data science estimates the infrastructure cost of an A/B test from traces tagged with test names.

Overlooked constraints.

  • Troubleshooting needs completeness, not statistics. Head sampling at 1% is fine for latency analysis but fails "show me this member's session". Hence 100% for critical paths.
  • Tail sampling needs the whole trace first, which means buffering spans in the pipeline for a window.
  • Search indexes are expensive on write-heavy data. If the lookup is by ID, a key-value store with a simple index is cheaper.
  • Users read very little of what is stored, which justifies aggressive filtering and tiering.

What Netflix sacrificed. CPU and memory in every critical service for 100% tracing, rich ad hoc search over stored traces (gone with Elasticsearch), and some traces filtered out by rules. It gained complete session reconstruction at a storage cost that grows sub-linearly.

Deep Dive: sizing trace storage and the effect of each optimizationShow

Suppose critical services handle 2 million requests per second at peak, each request fans out to 20 spans of 500 bytes (handbook's illustration). That is 2,000,000 × 20 × 500 B = 20 GB/s of spans, about 1.7 PB a day before compression. Even a few days of retention is far too much, which explains every step in the post:

  • Zstd halves it to about 0.86 PB a day.
  • Tail filtering removes 20%, to about 0.69 PB a day.
  • Short hot retention (hours in Cassandra, the rest in S3) keeps the expensive tier small: 6 hours is about 170 TB, with older data on S3 at a fraction of the cost per GB.

TWCS works well for traces because they are written once and expire by time: SSTables group by time window, and whole windows are dropped at expiry, with no tombstones and no merging of old and new windows. This is the same idea as dropping time slices in the TimeSeries abstraction (Lesson 25).

Lesson 23: Atlas, the primary telemetry platform (2014)#

Assumptions. In the data center, Netflix's home-grown tool Epic (built on RRDTool) let engineers send any time series and query it, but it struggled at about 2 million distinct series. Global expansion and more devices needed 10× or more (20 million and beyond). Atlas was built in 2012 and fully in production by early 2013. Epic features to keep: normalization and consolidation, flexible legends, math with NaN for missing data, Holt-Winters alerting, visualization options and deep links. Atlas also had to cover third-party data such as CloudWatch.

Production architecture.

  • Scale. During failover exercises, with all North American traffic in one region, Atlas sustained over 1.2 billion time series, which means billions of data points published per minute.
  • Dimensional identity. Old metric names packed dimensions into one long string, such as a request counter with the UI version, device type ID, client version and country encoded in it. Querying needed regular expressions, conventions varied by team, and a 255-character limit meant there was no room for, say, availability zone. In Atlas, a metric's identity is a set of key-value tags. The client library adds server, zone, ASG, cluster, application and region automatically, and users add their own, with essentially unlimited values per key.
  • A composable query layer. Isolated regional deployments plus a global layer that merges results across regions. Aggregations run down the fan-out tree, close to the data. The query layer can sit over multiple backends, which eases future backend changes.
  • A stack language in the URL. Every graph is a GET request, so charts can be linked, embedded in email and wikis, and tweaked by the recipient. It has few special symbols, and covers query (and, or, equal, regex, has key, not), aggregation (sum, count, min, max, group by), consolidation over time, math, boolean comparison and graph settings.
  • In-memory storage. After trying many backends, nearly all queryable data is kept in memory, on or off the JVM heap.
  • Performance at high fan-in. A 3-hour graph at 1-minute resolution has 180 output points. With 100 nodes, the intermediate set is about 18,000 points. One service broke requests down by device (thousands) and country (about 50), about 50,000 series per node, so the same 3-hour line needed about 900 million points. Atlas routinely fetches and graphs billions of points per second. Cardinality should be limited by cost and value, not by technology.
  • Resilience rules: data loses value fast with age; restoring service matters more than preventing data loss; degrade gracefully. Data is split into clusters by age. The 6-hour clusters keep data and index in memory on each node, so each instance is self-contained. Several mirrors run, one per zone. Publish nodes shard incoming data across mirror instances using slots from Edda, and cache the Edda response so publishing continues if Edda is down. Older clusters (for example under 4 days, under 16 days) can fail separately: a week-over-week chart still shows data, with a gap.
  • Persistence and cost. Mirrors flush to S3 at full resolution. Hadoop (EMR) merges mirror data, generates reports and computes rollups for the historical clusters. Historical clusters, reloadable from S3, usually run one replica. Because of autoscaling and red/black deploys, under 50% of distinct series overlap from one day to the next. Rollups drop dimensions such as node name, which matter less once the node is gone, and this shrinks the index a lot. Deep dives can still use Hadoop.
  • Ecosystem: UI, dashboards, alerts, inline aggregation before storage, off-heap and Lucene storage, a percentile backend, SNMP and health-check pollers, client integration with Servo, local rollups, metric volume reports, automated canary analysis (Lesson 19), outlier detection and automated culling of outlier servers.

Overlooked constraints.

  • Monitoring must be up when everything else is down. Self-contained nodes, cached Edda data and zone mirrors keep it working when dependencies fail.
  • Cardinality is driven by churn. Instance names change every deploy, so a new set of series appears every day. Rollups that drop those tags are what keep the index manageable.
  • Recent data is the priority. Losing yesterday's data is acceptable; being blind right now is not.

What Netflix sacrificed. Cost (RAM for all queryable data), long-term detail (rollups drop dimensions) and durability of the freshest data (an instance lost before flushing can lose part of one shard). It gained fast dimensional queries over billions of points and monitoring that survives failures.

Deep Dive: memory for in-memory telemetry, and why rollups matterShow

Suppose 1.2 billion active series at 1-minute resolution, each point stored as an 8-byte double, for 6 hours: 360 points × 8 B × 1.2 billion ≈ 3.5 TB of values per mirror, plus the index (tag sets), which can be as large again (handbook's illustration). With 2 mirrors, that is 10 to 15 TB of RAM for the hot tier alone, which is why Atlas splits data by age and limits replicas for older data.

Rollup example. A service with 100 nodes reporting 50,000 series each has 5 million series. Dropping the node tag merges them into 50,000 series, a 100× reduction. Since under 50% of series survive from one day to the next, a week at full detail could hold over 3 times as many distinct series as any single day. With node-level tags rolled up, that churn disappears. The cost is that you can no longer ask, "which node was slow last Tuesday?" without going back to S3 and Hadoop.

Lesson 24: The Key-Value data abstraction layer (2024)#

Assumptions. Netflix ran many online databases, Cassandra above all, for sign-ups, viewing history, real-time analytics and live streaming. As new key-value stores and use cases arrived, problems repeated:

  • Developers struggled to reason about consistency, durability and performance across a global, multi-store deployment.
  • Every team relearned data modeling and access patterns: tail latency, idempotency, wide partitions with many rows, fat columns with single large values, and slow pagination.
  • Services were tightly coupled to native database APIs, which changed, sometimes incompatibly, forcing company-wide migrations.

The fix was a set of abstraction services on the Data Gateway Platform. The most mature is the Key-Value (KV) Data Abstraction Layer.

Data model: a two-level map. The first level is a hashed string record ID. The second is a sorted map of byte keys to byte values. Simple maps (one item with an empty key), sets (items with empty values), structured records and time-ordered events all fit.

HashMap<String, SortedMap<Bytes, Bytes>>
Item = key (bytes), value (bytes), metadata, chunk number
 
Cassandra mapping:
CREATE TABLE ns.table (
  id text, key blob, value blob, value_metadata blob,
  PRIMARY KEY (id, key)
) WITH CLUSTERING ORDER BY (key ASC);

On Cassandra, the record ID is the partition key and the item key is the clustering column. The abstraction also runs over EVCache, DynamoDB and RocksDB.

Namespaces set where and how data lives: one or more backends (for example Cassandra plus an EVCache layer with a 180-second TTL), consistency scope (local or global), consistency target (such as read-your-writes) and latency targets. "Developers provide their data problem, not a database solution."

APIs.

  • PutItems: an upsert of one or more items with an idempotency token. Large values are written as staged chunks and then committed.
  • GetItems: with a predicate (all items, specific keys or a range), a selection (page size in bytes, item limit, and include or exclude large values) and signals (client capabilities such as compression and chunking). Returns items and a next-page token.
  • DeleteItems: record, range or item deletes. On Cassandra, record and range deletes write a single tombstone. Item deletes would create many tombstones, so they are done as TTL expiry with random jitter, spreading compaction load while keeping pagination safe.
  • MutateItems and ScanItems for multi-item and multi-record work.

Design choices.

  • Idempotency tokens for hedging and retries. A token holds a client-side monotonic generation timestamp plus a 128-bit random UUID. Clock drift on EC2 Nitro instances measured under 1 ms. Servers reject tokens with large drift: one far in the past would be silently discarded by last-write-wins, and one far in the future would create an undeletable "doomstone". When stronger ordering is needed, tokens can come from ZooKeeper or transaction IDs.
  • Transparent chunking. Items under 1 MiB are stored directly. Larger items keep ID, key and metadata in the main table, with data split into chunks in a separate store (which can also be Cassandra, partitioned differently). The idempotency token ties the chunks into one atomic write. Latency grows linearly with size.
  • Client-side compression saves server CPU, network and disk. A search deployment saw 75% smaller payloads.
  • Byte-based pagination gives predictable SLOs, for example single-digit milliseconds for a 2 MiB page. Ten items can be 10 KiB or 10 MiB, so item counts do not. Most stores page by row count, so KV queries with a row limit, keeps reading until it reaches the byte budget, discards the excess and returns a token.
  • Adaptive pagination. The page token stores the observed average item size, and the server caches an estimate per namespace for first requests, so row limits match the data and read amplification falls.
  • Early return near the SLO. For a 2 MiB page with a 500 ms deadline on a record of thousands of tiny items, the server tracks elapsed time and returns a partial page with a token before breaching the SLO, instead of failing. gRPC clients with deadlines stop when there is no time left.
  • Signaling. On start-up and periodically, the client does a handshake. The server sends back target and maximum latency SLOs, so clients adjust timeouts and hedging without redeploying. Each request carries the client's capabilities.

Uses: streaming metadata, user profiles, messaging push registry and real-time impression analytics. Planned: lifecycle management, summarizing records with many items, new engines and dictionary compression.

Overlooked constraints.

  • Hedging is only safe with idempotency. Sending a duplicate write to cut tail latency could otherwise apply it twice or out of order.
  • Deletes are writes in LSM stores. Without care, tombstones make reads slow and compaction heavy.
  • Item-count pagination has unbounded latency. Bytes are the right unit for an SLO.
  • Clocks are part of correctness in last-write-wins systems, so bound and check drift.

What Netflix sacrificed. Access to each database's full native feature set, an extra network hop through the gateway, and a platform team to build and run it. It gained one data API across stores, built-in best practices and the freedom to change backends.

Deep Dive: hedged requests and the tail-latency mathShow

Hedging sends a second copy of a request if the first has not answered by some delay, and uses whichever answers first (Dean and Barroso, "The Tail at Scale", Communications of the ACM, 2013). Suppose a read's latency is 5 ms at p50, 10 ms at p90 and 100 ms at p99 because of occasional GC pauses or compactions (handbook's illustration). Hedge at the p90 point, 10 ms. A request is slow only if both copies are slow. If slowness is independent, the chance that the first exceeds 10 ms is 10%, and the chance that the hedge (started at 10 ms) is also slow is about 1% for its own p99. So a 100 ms tail becomes roughly 10 ms plus the hedge's normal latency, about 15 to 20 ms at p99. The cost is about 10% extra requests.

KV's signaling makes this practical: the server publishes the target latency (the hedge point) and the maximum (the timeout), and clients adopt them without redeploying. Idempotency tokens make the duplicates safe for writes: if both copies of a PutItems arrive, they carry the same token and timestamp, so last-write-wins resolves them as one write.

Byte pagination example. A record holds items of 1 KiB to 1 MiB. With a 100-item page, a page could be 100 KiB or 100 MiB, latency anywhere from 2 ms to 2 seconds. With a 2 MiB page, latency stays in single-digit milliseconds. The server may need several backend queries to fill a page of small items, which adaptive limits reduce.

Lesson 25: The TimeSeries data abstraction (2024)#

Assumptions. Netflix produces huge volumes of immutable temporal events: video plays, asset impressions, service traces. Requirements: up to 10 million writes per second, petabytes of data, primary-key reads in low double-digit milliseconds, search and aggregation on secondary attributes, global reads and writes with tunable consistency, per-dataset configuration, bursts during launches and failovers, and lower cost per byte and per operation. It is not a metrics database. Metrics stay in Atlas (Lesson 23).

Data model. An event item is a key-value pair (such as device type = iOS). An event is a set of items at a client-supplied event time with an event ID (such as a UUID). Time and ID together form the idempotency key. A time series ID (such as a device ID) holds all events for its retention period, append-only. A namespace is a whole dataset, with its own settings.

APIs. WriteEventRecordsSync (durable acknowledgement), WriteEventRecords (fire and forget, for logging and tracing, which tolerate small loss), ReadEventRecords (by series ID, time interval and optional filters, newest first, low milliseconds), SearchEventRecords (by criteria, eventually consistent) and AggregateEventRecords (for example distinct values, eventually consistent, can take seconds).

Primary store: Cassandra, partitioned three ways.

  • Time slices, each a separate Cassandra table covering a time range, joined without gaps (start inclusive, end exclusive). Retention is done by dropping whole tables, not with row TTLs, which would create many tombstones and slow range scans. The trade-off: data may be kept a little longer than needed, until a whole slice is past retention. Retention can also be extended instantly in the control plane, which TTLs cannot do.
  • Time buckets inside a slice, so a query only touches buckets that overlap its range. Long-range reads scan many partitions in parallel (scatter-gather), but most reads ask for recent, narrow ranges.
  • Event buckets inside a time bucket, to spread a burst of writes for one series across partitions.
  • The partition key is (series ID, time bucket, event bucket), and the clustering key keeps events sorted by time on disk, the order in which they are read. A metadata table records each slice's settings, so future slices can be re-partitioned based on what was observed (partition histograms).

Index store: Elasticsearch, for searches and aggregations on configured fields. Depending on volume, it is used as a reverse index (results fetched from Cassandra) or holds the full documents. Users never touch Elasticsearch or Cassandra directly.

Control plane vs data plane. The data plane reads and writes. The control plane sets namespace configuration and talks to the sharded Data Gateway control plane. Anything that needs schema consensus stays out of the data path. An example namespace for tracing, in words: 36-hour time slices (129,600 s), 1-hour time buckets, 4 event buckets, writes coalesced for 1 s in a 4 MiB buffer, local and eventual consistency, an accept limit of 36 hours, slices closed after 15 days and dropped after 16, and an Elasticsearch index with mapped fields and a 60-second refresh. Provisioning turns "workload desires" into infrastructure (described in an ApacheCon talk by Joey Lynch). Scaling is horizontal, vertical, by growing EBS, or by re-partitioning future slices.

Design principles.

  • Idempotent mutations (event time, event ID and item key), so clients can retry and hedge.
  • SLO-based hedging: for example, read target 0.5 s (hedge there) and max 1 s (time out), write target 10 ms and max 50 ms.
  • Partial returns around the SLO, keeping newest-first order, for callers like real-time frequency capping, where a late answer is useless and an approximate one is fine.
  • Adaptive fan-out: reads start scanning 8 buckets in parallel, and the service lowers that for dense series (most reads are answered by the first buckets) or raises it for sparse ones.
  • A limited write window (accept limit): events older than, say, 4 hours are rejected, so older ranges become immutable and can be cached, compressed and compacted. Raised temporarily for backfills.
  • Buffered writes: events coalesce for seconds in in-memory queues, are grouped by partition key and are batch-written, with batch sizes per backend (smaller for Cassandra, bigger for Elasticsearch). This raised GC pressure, and moving to JDK 21 with ZGC cut tail latency by 86%. Because a crash loses queued events, buffering is only for loss-tolerant data such as tracing. Durable or read-after-write namespaces flush almost immediately.
  • Dynamic compaction once a slice leaves the write window: recompact with better strategies, and shrink or split shards.

Numbers. Writes in low single-digit milliseconds, stable point-read latency, and close to 15 million events per second at peak globally. Uses: tracing, user interaction tracking for recommendations, feature rollout analysis, asset impressions, and billing and subscription history. Planned: tiered storage on object stores, dynamic event bucketing (Cassandra 4.x reads wide partitions much better), caching immutable ranges, and counts, which led to the distributed counter (Lesson 27).

Overlooked constraints.

  • Retention by table drop beats row TTLs for time series, in both performance and flexibility.
  • Immutability is a feature you can create. An accept limit turns "recent" data into "closed" data that can be optimized aggressively.
  • Bursts for a single key need sub-partitioning (event buckets), not just more nodes.
  • Durability is a per-dataset choice. Buffering is great for traces and wrong for billing.

What Netflix sacrificed. Read amplification (scatter-gather across buckets), late events (rejected after the accept limit), some data loss for buffered namespaces, and slightly longer retention than configured. It gained very high write throughput at low cost with predictable reads.

Deep Dive: choosing time bucket and event bucket sizesShow

Suppose a device ID writes 2 events per second at peak, each 300 bytes, and is read for "the last 6 hours" (handbook's illustration).

  • With 1-hour time buckets and no event buckets, a partition holds 2 × 3,600 × 300 B ≈ 2.2 MB per hour per device. That is fine for Cassandra (partitions of tens of MB are fine). A 6-hour read touches 6 partitions in parallel.
  • A hot series, such as a tracing namespace keyed by service, might take 50,000 events per second. One hour in one partition would be 50,000 × 3,600 × 300 B = 54 GB, far too big, and all writes would hit the same 3 replicas. With 4 event buckets and 1-minute time buckets, each partition gets 12,500 events per second and holds 12,500 × 60 × 300 B ≈ 225 MB per minute bucket, still large. So hot namespaces need smaller time buckets and more event buckets, while sparse ones need fewer.

That is why bucket settings are per namespace and per time slice, and why the future plan is dynamic event bucketing: only split the series that need it, so sparse series do not pay for read amplification.

Retention by slice. With 36-hour slices and 15 days of retention, about 11 slices hold data. Data is dropped up to 36 hours late, about a 10% storage overhead, in exchange for zero tombstones.

Lesson 26: Scaling time-series storage, viewing history (2018)#

Assumptions. Members watched over 140 million hours a day, and each viewing generates records used for bookmarks (where you stopped) and recommendations. Viewing history grows along three dimensions: time, number of members and hours per member. Netflix grew to over 100 million members in its first 10 years of streaming.

Version 1: one wide row per member in Cassandra. Reasons: Cassandra models time series well (rows with a dynamic number of columns), the workload is about 9 writes per read, which suits Cassandra's write path, and the team chose availability over strong consistency (AP in CAP terms, see CAP theorem). The row key was the customer ID. Starting play added a new column, and pausing or stopping updated it, a fast single-column write.

Why it slowed down. As members watched more, rows grew. Reading a whole row, or a time range of it, meant reading many SSTables plus memtables. Pagination helped avoid timeouts but raised total latency. Compaction, read repair and full column family repair got slower as rows widened.

The cache. An EVCache layer stored a compressed copy of each member's history, keyed by customer ID. On each Cassandra write, the cache entry was looked up and merged if present. Reads went to the cache first, and a miss read Cassandra, compressed the result and filled the cache. This worked for years, until in 2012 the cluster was one of Netflix's largest and needed to double.

Version 2: live plus compressed.

  • LiveVH: a few recent records, updated often, uncompressed. Frequent compaction, small gc_grace_seconds and frequent repair.
  • CompressedVH: many older records, rarely updated, compressed into a single column per member. Rare manual compaction, consistency checked at write time, so no read repair or full repair needed.
  • API: "recent history" reads only LiveVH. "Full history" reads both in parallel.
  • Rollup: when a LiveVH read sees more records than a threshold, a background task compresses them into a new version in CompressedVH, reads it back to verify, and only then deletes the old version. There is no locking, and rare duplicate rollups are resolved by last-write-wins. The last couple of days stay in LiveVH so heavy viewers are not rolled up constantly. A version column points to the latest rollup.
  • Chunking for heavy users. If compressed data exceeds a threshold, it is split into chunks under keys of the form customer ID, version and chunk number, spread across nodes and written in parallel. A metadata row (version, chunk count, size) is written after the chunks succeed. In the common case, metadata and data share one row. So reads and writes take one round normally, and two for heavy users. The EVCache layer chunks large entries the same way, with metadata in the first chunk.

Results: about 6× less data, about 13× less time on Cassandra maintenance, about 5× lower average read latency and about 1.5× lower average write latency, with room for growth.

Overlooked constraints.

  • Unbounded rows are a time bomb. A design keyed by user with no limit on growth works until heavy users make it slow for everyone.
  • Hot and cold data want different tuning. Separate tables let each use the right compaction and repair settings.
  • Write the pointer last. Writing chunks first and metadata second makes a partial rollup invisible, without locks or transactions.

What Netflix sacrificed. Simplicity (two tables, background rollups and chunking), and some write work (rollups and verification). Full-history reads need parallel reads of two tables. In return it got bounded latency for every member and a much smaller footprint.

Deep Dive: how compression and chunking bound latencyShow

Suppose a heavy viewer has 20,000 viewing records of 200 bytes each: 4 MB as wide-row columns (handbook's illustration). Reading 4 MB of columns spread over many SSTables can take hundreds of milliseconds and stress the nodes.

After rollup, assume compression of about 6× (in line with the reported 6× data reduction): about 670 KB. With a chunk threshold of, say, 256 KB, that becomes 3 chunks on different nodes, read in parallel after one metadata read. Latency is roughly two round trips, about 2 × 5 ms, whatever the history size. A member with 200 records (40 KB, about 7 KB compressed) reads one row. The common case stays one read, and the rare case is capped at two, which is the "upper bound" the post describes.

Why read back before deleting the old version? If the new rollup were partly written (a node failed mid-write) and the old version already deleted, the history would be lost. Writing a new version, verifying it, switching the pointer and then deleting the old one is a copy-on-write pattern: at every moment, a complete version exists.

Lesson 27: The distributed counter abstraction (2024)#

Assumptions. Netflix counts many things: user interactions, how often a feature or experience is shown, and many facets of A/B tests. These needs fall into two groups. Best-effort counts need very low latency and low cost, but can be slightly wrong or lost. Eventually consistent counts must be accurate and durable, and can accept a few seconds of delay and more cost. Both need high throughput and high availability. The service handled close to 75,000 count requests per second globally, with single-digit millisecond latency on every endpoint. It is built on the TimeSeries abstraction (Lesson 25).

The API. Counters live in namespaces. Each namespace sets the counter type, a TTL and the expected cardinality (how many distinct counters). The calls are modelled on Java's AtomicInteger:

  • AddCount / AddAndGetCount: add a delta, which can be negative, and optionally return the new value.
  • GetCount: read the value.
  • ClearCount: reset to zero.

Writes can carry an idempotency token made of an event ID and a generation time. With it, a client can retry or hedge (send a duplicate request after a delay, see Lesson 24) without counting twice.

{
  "namespace": "my_dataset",
  "counter_name": "counter123",
  "delta": 2,
  "idempotency_token": { "token": "some_event_id", "generation_time": "2024-10-05T14:48:00Z" }
}

Type 1: best-effort regional counter. This is just EVCache: increment or decrement a cache key built from namespace and counter name, with a TTL. Clearing deletes the key from all replicas. It is very fast and cheap, since many tenants share one cluster. The costs: increments are not replicated across regions, there is no consistency guarantee, and there is no idempotency, so a retry or hedge may double count. It suits short-lived A/B experiments where "about right" is enough.

Why not HyperLogLog or Count-Min Sketch? HyperLogLog estimates how many distinct items were seen. It cannot add or subtract an arbitrary delta for a key. Count-Min Sketch can add amounts per key, but neither sketch supports reset or per-key TTL without extra structures. Netflix preferred to build on stores it already ran at scale, and the EVCache version is a few lines of code, at the cost of a little memory per key.

The design space for accurate global counts. The post walks through four approaches, each fixing the last one's flaw:

ApproachIdeaWhy it is not enough
1. Single row per counterRead, add, compare-and-swap one rowNo idempotency; heavy contention on hot counters. Splitting into buckets helps, but the right bucket count per counter is hard to pick across millions of counters
2. Per-instance aggregationEach server sums in memory and flushes with jitterLoses in-memory counts on crash or deploy; resets cannot be agreed in time; idempotency would need sticky routing and leader election
3. Durable queueLog increments to Kafka, partition by counter key, aggregate in Kafka Streams or FlinkHot partitions lag; partitions must be rebalanced as counters grow; pre-aggregation makes auditing and recounting impossible
4. Event log of incrementsStore every increment with event time and event IDReads scan all increments; threads repeat the same work; wide partitions; large footprint

Netflix's approach: event log plus background rollup. It combines 3 and 4. Every increment is stored as an event in TimeSeries, and a background process keeps adding up the events into a stored total.

  • Event store. TimeSeries (on Cassandra) stores each mutation. Time buckets and event buckets break up wide partitions. Event time, event ID and an item key form the idempotency key, so a retry overwrites instead of double counting. Events are sorted newest first, which makes resets easy to find. Retention deletes events once they are rolled up and archived for audit.
  • Immutable window. Counting events while writes still arrive could miss late events. So the rollup only counts events older than a safe lag. TimeSeries has an acceptLimit that rejects events with timestamps too far in the past, so a window older than that limit can no longer change. The rollup pushes its boundary back a little more to allow for clock skew. As a result the count lags real time by a few seconds.
  • Rollup store. The result, the last rollup count and its timestamp, is saved in Cassandra per dataset. The next rollup starts from this checkpoint and only scans new events.
  • Last write timestamp. Every write also records the counter's last write time as a column, using Cassandra's USING TIMESTAMP so last-write-wins is predictable. The rollup uses it to decide whether a counter has caught up.
  • Rollup cache. The count and its checkpoint timestamp are cached together in EVCache as one value, so they can never be mismatched.

Write path. Add or clear writes durably to TimeSeries and updates the last-write timestamp. If the acknowledgement is lost, the client retries with the same token. After durability, a fire-and-forget rollup trigger is sent.

Read path. GetCount returns the last rolled-up value with a fast point read, which may be a few seconds stale. It also triggers a rollup. This keeps the checkpoint moving forward and self-repairs a count whose earlier rollup failed.

The rollup pipeline. This is where the hard work is.

  • Light rollup events. A rollup event names only the namespace and counter, not the delta. It just says "this counter changed". So the rollup never scans the whole dataset, only counters that were touched.
  • In-memory queues. Each rollup server runs a set of in-memory queues. This keeps provisioning simple and cheap, at the risk of losing rollup events if a server crashes. That causes stale counts until the next read triggers a rollup.
  • Same counter, same queue. A fast non-cryptographic hash (XXHash) maps each counter to one queue, so work is not duplicated. A separate rollup stack runs fewer, larger instances for the same reason.
  • No locks. Several rollup servers may roll up the same counter at once, and they simply overwrite each other. This is safe because each one sums an immutable window. Their idea of "now" may differ slightly, so the value can move back and forth briefly, but it converges.
  • Rebalancing and deploys. Changing the queue count is a config change plus a redeploy. On deploy, queues drain before shutdown, and a brief overlap of old and new servers is safe for the same immutable-window reason.
  • Coalescing. Events are drained into a set, so a counter touched 1,000 times in a window is rolled up once.
  • Batching and back-pressure. A consumer rolls up a batch of counters in parallel. It adjusts how many time partitions it scans to the counters' cardinality, and waits between batches based on how long the last batch took. This is adaptive back-pressure, so the TimeSeries store is not overwhelmed.
  • Convergence. Low-cardinality counters stay in constant circulation so they never fall far behind. High-cardinality ones would use too much queue memory that way, so the server checks the last write timestamp and re-queues a counter only until its rollup has caught up with its writes.

Experimental "accurate" counter. Same design, but a read also computes the delta since the last rollup in real time: current count = last rollup count + delta. For counters read often, the delta window is small and cheap. For rarely-read ones it can be a large scan.

Control plane. One namespace config ties the layers together. It sets the shared EVCache cluster for the cache; the Cassandra rollup store; the counter type and cardinality; queue settings (for example 8 queues per instance, a 10-second coalesce, 16 MB per queue, 32 counters per batch); and the TimeSeries event store (4 event buckets, 600-second buckets for low cardinality, 1-day slices, a 5-second accept limit, and 7-day event retention). Each layer runs as a container on the same host and reads only its own part of the config. Provisioning is automated from the user's workload and cardinality inputs.

Future work. (1) Regional rollups: cross-region replication problems can cause missed events, so each region could keep its own rollup table and a global table could sum them. The hard part is propagating a clear across regions. (2) Stale counts: lost rollup events or failed rollups hurt rarely-read counters most. Durable queues, rollup handoffs and better error detection are planned.

Overlooked constraints.

  • Auditing and recounting are requirements, not extras. Storing only totals is cheaper, but you can never explain or fix a wrong total. Keeping individual events (for a retention period) buys auditability.
  • Idempotency must be in the data model. An external dedup store adds latency and races. Making the event's own key the dedup key is simpler and always correct.
  • "Accurate" is relative. In a distributed system, a count is "accurate" only up to a time boundary. Netflix chose to state the lag (seconds) instead of pretending it was zero.

What Netflix sacrificed. Freshness (counts lag by seconds), storage (every increment is kept for a week), and some rollup durability (in-memory queues). It also accepted that two rollup servers may do duplicate work. In return it got idempotent retries, no locks, safe deploys, audit trails and single-digit millisecond reads at 75,000 requests per second.

Deep Dive: why the immutable window makes lock-free rollups safeShow

Let A be the accept limit (5 seconds) and S a skew margin (say 2 seconds, handbook's illustration). At wall time T, a rollup counts events with times in the window from the last checkpoint to T − A − S. Any event written after T must have a time later than T − A, or TimeSeries rejects it. So no new event can ever land in the counted window, which makes it immutable.

Now suppose two rollup servers, R1 at wall time T1 and R2 at T2 where T2 is later. Both start from the same checkpoint C. R1 computes count(C to T1 − A − S), R2 computes count(C to T2 − A − S). Whichever writes last wins. If R1 writes last, the stored value is slightly older, but it is still the exact count of an immutable window, and the next rollup moves forward from there. The value never contains a double-counted or half-counted event; it can only lag. That is why "overwrite without locks" is safe here, while it would be unsafe for a classic read-modify-write counter.

Cost of coalescing. Suppose a hot counter gets 5,000 increments per second (handbook's illustration). Without coalescing, 5,000 rollups per second would each scan the same events. With a 10-second coalesce window, there is one rollup per 10 seconds per counter, scanning about 50,000 events. Grouped into 4 event buckets and 600-second time buckets, that scan touches about 4 partitions in parallel, which is low milliseconds. That is a 50,000× reduction in rollup calls for that counter.

Delta reads for the accurate counter. If a counter is read every second, the delta window is about A + S + 1 seconds, roughly 8 seconds of events. At 5,000 increments per second that is 40,000 small events, which is too many for a per-read scan. So "accurate" mode works best for counters with moderate write rates and frequent reads, which is why it is still experimental.

Lesson 28: A resilient data platform with a write-ahead log (2025)#

Assumptions. At Netflix scale, the same few failures kept causing incidents, bespoke fixes and technical debt:

  • accidental data loss or corruption in a database;
  • entropy between two stores, for example Cassandra and Elasticsearch drifting apart;
  • updating several partitions together, such as maintaining a secondary index on a NoSQL store;
  • replication within and across regions;
  • retries for real-time pipelines at scale;
  • bulk deletes that ran Key-Value nodes out of memory.

One incident shows the stakes. A developer ran an ALTER TABLE that corrupted data. Recovery was possible only because a cache sat in front of the data (its TTL was extended quickly) and the app also wrote its mutations to Kafka. Without those, the data would have been lost for good. The data platform team wanted to give every critical app that safety by default.

What a WAL is here. In a database, a write-ahead log is a record of each change written before the change is applied, so a crash can be replayed (see storage engines). Netflix's WAL is the same idea as a service: capture a change durably first, then deliver it to targets reliably.

The API is one call: WriteToLog. A request has:

  • a namespace, which picks the queue type and settings;
  • a lifecycle, the delay and the original write time;
  • a payload (bytes);
  • a target (where to deliver).

The response has a trilean "durable" field (yes, no or unknown) plus a message. Unknown is honest: after a timeout, the client cannot know whether the write landed. Delivery is at-least-once, so targets must handle duplicates.

Namespaces give WAL different "personas" with no code change:

  1. Delayed queue. Backed by SQS. Product Data Systems uses it to retry failed Kafka messages later, with a dead-letter queue, a 10-second poll interval and up to 100 messages per poll.
  2. Cross-region replication. Backed by Kafka, with a target per region (for example, us-east-1, us-east-2, us-west-2 and eu-west-1) for an EVCache cluster.
  3. Multi-partition mutations. Backed by Kafka plus a durable store (a Key-Value namespace), which together give two-phase-commit-like behaviour.

Under the hood.

  • Producers and consumers are separate. Producers accept messages and enqueue them, and consumers dequeue and deliver them. Each side scales on its own, and teams can bring their own producer or consumer.
  • Every namespace gets its own queue and a dead-letter queue (DLQ) by default, because some errors are transient and some are permanent. Kafka namespaces handle normal processing. SQS namespaces add delays, with custom logic to go past SQS's default delay and size limits.
  • Pluggable targets: Cassandra, Memcached, Kafka or an application.
  • For Key-Value users, WAL is a flag. Toggling it gives all of this without learning the internals.

Deployment. WAL runs on the Data Gateway platform, so it inherits mTLS, connection management, authentication and config. Each use case usually gets its own shard (a group of instances), so Ads Events and the Gaming Catalog never share hardware and cannot be noisy neighbours. A shard holds many namespaces (logical configs), and each namespace has its own queues; operators add queues on the fly if one becomes a bottleneck. Namespace configs live in a globally replicated relational database. Producer and consumer groups autoscale separately on CPU and network, and WAL uses Netflix's adaptive load-shedding libraries and Envoy to shed excess load (Lesson 17). Each region runs its own deployment.

One architecture, many problems.

  • Data loss prevention: if the database is down, WAL keeps the mutations and replays them when it returns. The cost is eventual consistency instead of immediate.
  • Generic replication: stores without built-in replication, such as Memcached-based EVCache and RocksDB, get it through WAL.
  • Entropy and multi-partition writes: write to WAL first and let the consumer apply each mutation with retries and backoff, instead of running repair jobs later.
  • Corruption recovery: restore the last good backup, then replay WAL skipping the bad mutation.

Why not just use Kafka or SQS directly? WAL is an abstraction: the queue underneath can be swapped through the control plane with no app changes, and the API hides retry, DLQ and delay settings.

Use 1: delay queue. The Live Origin (which serves live video segments, Lesson 47) stores data in Key-Value on Cassandra and EVCache. After a live event it deletes a lot of data. A burst of deletes hurt Cassandra and caused timeouts for live reads and writes. Now Key-Value sends each delete to WAL with a random delay plus jitter, and WAL sends it back later, so deletes arrive as a flat curve instead of a spike. Many Kafka users (Ads, Gaming, Product Data Systems) also hand failed produce or consume calls to WAL for delayed retry, so they no longer write their own backoff code.

Use 2: cross-region replication. EVCache keeps a cluster per region with the same data. The client in the writing region sends each write or delete to that cluster's WAL. Since the EVCache client is the producer, WAL deploys only consumer groups: one per target region, reading the Kafka topic and calling a writer group in that region, which applies the change locally. This replaces the replication design in Lesson 9. The big gain is moving the most latency-sensitive users, such as Live Origin, to single-tenant consumers and writers, which shrinks the blast radius and removes noisy neighbours, while less sensitive users stay multi-tenant.

Use 3: multi-table mutations (MutateItems). A Key-Value MutateItems call can hold several puts and deletes across different IDs and namespaces (tables). A success reply promises that every mutation will eventually apply. Large mutations may be split into ordered chunks.

  • Synchronous option, rejected: the client retries until everything succeeds. But the stores do not have transactions, latency across replica sets is unpredictable, the whole chain must be retried, and a partial failure leaves data inconsistent unless you build rollback.
  • Asynchronous option, chosen: Key-Value is stateless and cannot track progress itself. So for each request it forwards every put or delete to WAL with a sequence number, then sends a completion marker. The WAL producer saves content, state and order in the durable store, and puts only the completion marker on the queue. The consumer takes the marker, reads all the stored pieces, orders them by sequence and applies them. If any fails, the marker is re-queued for a retry.

Lessons the team lists. Make the architecture pluggable by config. Reuse existing building blocks (control plane, Key-Value). Separate producing from consuming so each scales on its own. And remember WAL has failure modes too: traffic surges, slow consumers and permanent errors, handled with partitioning and back-pressure. Planned next: secondary indexes in Key-Value via WAL, and guaranteed fan-out to several stores (for example, a database plus a backup, or a database plus a queue).

Overlooked constraints.

  • A "durable" answer can be unknown. Designing for a three-valued result, and making retries safe, is more honest than pretending timeouts are failures.
  • Deletes are load too. Bulk cleanup can hurt live traffic more than writes do. Spreading it out with a delay queue is a cheap form of traffic shaping.
  • The marker pattern keeps queue messages small. Big payloads go to the durable store, and the queue only carries "this request is complete, process it". This keeps Kafka fast and makes retries cheap.

What Netflix sacrificed. Immediate consistency (mutations apply later), an extra hop and an extra system on the write path, and at-least-once delivery, which pushes idempotency onto every target. In return it got one reusable answer to six recurring problems.

Deep Dive: WAL multi-mutation versus two-phase commit and the outbox patternShow

Classic two-phase commit (2PC) has a coordinator ask every participant to prepare (lock and promise), then tell them all to commit. It gives atomicity, so all changes appear at once, but it needs every participant to support prepare, holds locks across network round trips, and blocks if the coordinator dies between phases.

Netflix's WAL design is not true 2PC. Phase 1 is "durably record the full intent" (all mutations plus a completion marker in the durable store and queue). Phase 2 is "apply each mutation, retrying until done". There are no locks and no prepare, so readers can see a partly applied request for a short time. What it guarantees is eventual completeness, not atomic visibility. This trade fits Cassandra, which has no cross-partition transactions.

Compared with the transactional outbox: an outbox writes the business row and an "event to publish" row in one local transaction, and a relay publishes it later (see microservices patterns). That needs a database with local transactions. WAL instead makes the log itself the first durable write, so it works on stores with no transactions at all.

Why sequence numbers matter. Suppose one MutateItems call holds "put item X = 1" (seq 1) and then "delete item X" (seq 2). Applied in the wrong order, X would survive. Storing the sequence numbers lets the consumer apply them in order even if the pieces reached the producer out of order or over different connections.

Delete smoothing in numbers. Suppose a live event leaves 10 million segment rows to delete (handbook's illustration). Sent at once, a cluster sized for 50,000 extra writes per second would take 200 seconds at full saturation, hurting live reads. With a random delay spread over 6 hours, the rate is about 460 deletes per second, under 1% of that headroom. The data stays a few hours longer, which costs some disk but no reliability.

Lesson 29: Kafka inside the Keystone pipeline (2016)#

Assumptions. Keystone is Netflix's unified pipeline for publishing, collecting and routing events, for both batch and streaming use. In 2016 it ran 36 Kafka clusters with more than 4,000 brokers, taking in more than 700 billion messages a day. There are two kinds of cluster. Fronting Kafka collects messages from virtually every application instance and buffers them. Consumer Kafka holds the subset of topics that a Samza router forwards for real-time consumers. Netflix was moving from Kafka 0.8.2.1 to 0.9.0.1. (For Kafka basics, see Kafka.)

Design principle: accept a little loss, never block the app. Lossless delivery at this volume on EC2 was judged too expensive. Netflix agreed with its users on an acceptable loss rate and achieved under 0.01% daily loss, with metrics on dropped messages. Producers send asynchronously, and if a message cannot be delivered after retries, the producer drops it so the application and the member's experience stay healthy. The chosen settings show this:

  • acks = 1: only the partition leader must confirm. It is faster, but a message is lost if the leader dies before followers copy it.
  • block.on.buffer.full = false: when the producer's buffer is full, drop instead of blocking the app thread.
  • unclean.leader.election.enable = true: if no in-sync replica is available, let an out-of-date replica become leader. Messages it never received are lost, but the partition becomes writable again at once.

Producer side. Most apps use a Java client library. Each instance runs several producers, one per fronting cluster, for sink-level isolation. Topic routing is dynamic config, so traffic can be redirected or topics moved between clusters with no restart. Non-Java apps can post to REST endpoints that relay to fronting Kafka. Messages are not keyed, which gives flexibility, and rough ordering is rebuilt later in Hive or Elasticsearch, or by the router. No app may consume directly from fronting Kafka, so its load stays predictable.

Why Kafka struggled in the cloud. Kafka was built at LinkedIn for data centres. In the cloud, instances die at any time and networks blip. That is fine for stateless services but hard for a stateful system that depends on ZooKeeper and a single controller.

  • Outlier brokers cause most problems. Uneven load, bad hardware or noisy neighbours make one broker slow, with TCP timeouts and retransmits. Producers sending to it fill their buffers waiting, then must drop. The 0.8.2 producer had no timeout for buffered messages, which made this worse.
  • Replication spreads the pain. A slow broker slows replication, followers lag, leaders must read old data from disk to serve them, the leaders slow down, and more producers drop. This is a cascade.
  • A ZooKeeper incident once made producers drop many messages to a cluster with hundreds of brokers, and debugging that many brokers quickly was not realistic.

The response was: make clusters less stateful, detect outliers, and be able to start over clean fast.

Deployment strategy.

  • Many small clusters, not one giant one. The largest had under 200 brokers.
  • Under 10,000 partitions per cluster. Controller work and some request latencies grow with partition count.
  • Even replica distribution per topic, which simplifies capacity planning and makes an outlier stand out.
  • A dedicated ZooKeeper cluster per Kafka cluster, so one ZooKeeper problem hits one Kafka cluster (see ZooKeeper and etcd).

Failover to a clean cluster. Each fronting cluster has a cold standby: the right launch config but tiny capacity, no topics, its own ZooKeeper, and replication factor 1 so it cannot inherit replication trouble. Failover steps: (1) resize the standby; (2) create topics and start routing jobs in parallel; (3) optionally wait for partition leaders, to reduce initial drops; (4) switch producers by dynamic config. It takes under 5 minutes. Then the broken cluster can be debugged at leisure, or destroyed and rebuilt. Netflix also uses failover for maintenance and upgrades, which avoids rolling upgrades and protocol-version juggling.

Tools Netflix built.

  • Sticky partitioner. Since messages are unkeyed, the producer sticks to one partition for a while and then picks another at random. Combined with linger (waiting briefly to fill a batch), this gives bigger batches and less broker load. The same idea later became Kafka's default partitioner for unkeyed messages (KIP-480, Kafka 2.4).
  • Rack-aware replica assignment. Every cluster spans three availability zones, and an AZ is treated as a rack, so a partition's replicas land in different zones. This survives a zone outage, and also the loss of several brokers on one physical host. Netflix contributed it as KIP-36.
  • Metadata visualizer. A UI over the ZooKeeper metadata with broker, topic and cluster views, search across clusters, broker-ID-to-instance mapping, and colour-coded in-sync replica (ISR) state.

Monitoring. A dedicated service checks whether each broker is registered in ZooKeeper. It acts as both producer and consumer of heartbeat messages to measure real end-to-end latency. It also checks that every partition of old consumer groups is consumed, and that Samza routers' committed offsets keep up with the brokers' log end, so routers are neither stuck nor lagging.

Plans then. Kafka 0.9 (new consumer API, producer message timeouts, quotas), a move to VPC for better networking, and tiered SLAs: topics that tolerate a little loss could use one replica, saving replication bandwidth and controller state, with message timeouts and possibly EBS volumes reducing the loss.

Overlooked constraints.

  • Replication is not free resilience. It couples brokers, so one slow broker can hurt many.
  • The producer buffer is the real failure boundary. When it fills, data is lost no matter how healthy the cluster is overall.
  • Clean-slate failover beats in-place repair when debugging a sick stateful cluster would take hours.

What Netflix sacrificed. Durability (acks = 1, unclean leader election, drop on full buffer, about 0.01% loss), ordering (unkeyed messages), and efficiency (idle standby clusters and many small clusters). In return it protected application availability and gained a five-minute escape hatch for any cluster.

Deep Dive: what acks, ISR and unclean election really tradeShow

Each partition has a leader and followers. The in-sync replica set (ISR) is the set of followers caught up within a lag limit.

  • acks = 0: the producer does not wait. Fastest; a broker crash or network drop loses data silently.
  • acks = 1: the leader writes to its log (page cache) and replies. If the leader dies before any follower copies the message, it is lost. Latency is one leader round trip, typically a few milliseconds in-region.
  • acks = all with min.insync.replicas = 2: the leader replies only when at least 2 replicas have it. No acknowledged message is lost on one broker failure, but latency follows the slowest ISR member. One outlier broker in the ISR makes every produce wait, which is exactly the problem Netflix had with outliers.

Unclean election. Suppose the leader has offsets up to 1,000 and the only live replica, now out of sync, has up to 950. With unclean election enabled, that replica becomes leader; offsets 951 to 1,000 are lost, and new writes reuse those offsets. With it disabled, the partition stays unavailable until an in-sync replica returns, which could be minutes or forever. For event logging, Netflix chose loss over unavailability. For payment events, you would choose the opposite. Since Kafka 0.11 the default is disabled.

Loss budget in numbers. At 700 billion messages a day, 0.01% is up to 70 million messages a day. That sounds big, but for analytics such as viewing metrics it is statistically invisible, and Netflix measured it. The lesson for interviews: state the loss rate your users can accept, then pick acks and election settings to match, rather than defaulting to "zero loss" everywhere.

Sticky partitioning in numbers. Suppose a producer sends 10,000 messages per second over 100 partitions, with a 10 ms linger (handbook's illustration). Round-robin spreads each 10 ms window's 100 messages over 100 partitions: batches of about 1 message, so about 100 requests per window. Sticking to one partition for that window gives 1 batch of 100 messages. Fewer, larger batches mean far fewer requests and better compression.

Lesson 30: Keystone as a stream processing platform (2018)#

Assumptions. By 2018 Netflix served 130 million subscribers in 190+ countries, and Keystone processed trillions of events and petabytes of data a day. It offered two services. The Data Pipeline combines a streaming Routing Service and a Kafka-based Messaging Service, and moves all microservice events in near real time. Stream Processing as a Service (SPaaS) lets teams run their own managed streaming apps. A separate platform, Mantis, targets operational use cases.

Challenges.

  1. Scale: trillions of events a day, still growing.
  2. Diverse use cases. Routing jobs are embarrassingly parallel (no shuffles), with optional filters and projections, and deliver at-least-once to a sink, with users picking their latency and duplicate trade-offs. SPaaS jobs vary much more:
    • State: from none to tens of TB of local state.
    • Shape: from simple chains to complex graphs with several shuffles and sessionization.
    • Windows: from a few seconds to hours-long user sessions.
    • Traffic: bursty or steady, at GB per second.
    • Recovery: some need recovery in seconds even with large state and shuffles.
    • Replay: some need backfill from a batch source or a rewind to a checkpoint.
    • Bottlenecks: a job may be limited by CPU, network or memory.
    • Semantics: different duplicate-versus-latency preferences; most need no strict ordering but some do; some tolerate loss while others need exactly-once state.
    • Users: from distributed-systems engineers to business analysts.
  3. Multi-tenancy: thousands of jobs need runtime and operational isolation with little shared overhead.
  4. Elasticity: most streams are steady, but spikes come from a popular launch or a failure, and the system must adapt automatically.
  5. Cloud-native resilience: survive everything from network blips and instance loss up to zone, cluster and region failure, plus back-pressure between services.
  6. Operations: too many jobs for the platform team to manage by hand, so users declare lifecycle and the platform automates it.
  7. Agility: deploy many times a day, and let users do the same.

Design principles.

  • Enablement: users focus on business logic; the platform does the hard parts and offers self-service tools and insight into cost and performance.
  • Building blocks: composable operators; jobs can feed other jobs ("Managed Datasets"); deep reuse of Netflix's container runtime, dynamic config and injection framework.
  • Tunable trade-offs: expose knobs for latency versus duplicates, consistency versus availability, and strict versus loose ordering.
  • Failure as a first-class citizen: assume the network is unreliable; trust the runtime but add self-healing; isolate jobs; shrink the blast radius; reconcile automatically; propagate back-pressure.
  • Separation of concerns: users declare a goal state, and the platform moves toward it. The control plane orchestrates and the data plane does the work. Each component owns its state and lifecycle. Jobs run on Titus containers.

The core idea: declarative reconciliation. The user declares the desired job (via UI or API). One durable source of truth (on AWS RDS) holds every goal state. Every other component treats its own view as "current state" and keeps reconciling toward the source of truth. If a Kafka cluster is lost because its ZooKeeper state is corrupt, it can be rebuilt entirely from the source of truth. Because commands converge to a goal instead of performing one-off steps, they are naturally idempotent: a failed instruction does no lasting harm, because the next reconcile fixes it. (This is the same pattern Kubernetes controllers use.)

Deployment. The control plane deploys through Spinnaker, which drives Titus. Each job gets its own Flink cluster (job managers plus task managers) for full isolation; the only shared services are ZooKeeper and S3 for checkpoints. On redeploy, a stateless job picks a workflow that favours latency (start new before stopping old, risking duplicates) or no duplicates (stop then start, adding a gap). A stateful job resumes from a checkpoint or savepoint, or starts fresh.

Self-service. For routing, a user picks a stream, optional filters and projections, and a sink (Elasticsearch, Hive or a real-time Kafka topic). The UI turns that into goal states, hiding details such as which Kafka cluster is used. For custom SPaaS jobs, a CLI generates a Flink project template with CI. Each check-in builds a Docker image and registers it with the platform.

Engines and connectors. Keystone focuses on Apache Flink for analytics, with plans to extend Mantis for operational work. Managed connectors (Kafka, Elasticsearch, Hive) hide wire formats, serialization, batching and throttling. Dynamic source and sink operators switch inputs or outputs at runtime without rebuilding. Managed operators include filter, projection and data hygiene, with a simple DSL.

Config. Defaults and user settings live in properties files, can be overridden by environment variables, and again through the UI, and reconciliation applies them.

Self-healing. Components are isolated, and reconciliation fixes drift. Inside each Flink cluster, a health monitor acts on four cases:

  • task manager drift: Flink's view of containers persistently disagrees with Titus's view, so the affected containers are terminated;
  • stalled job manager leader: no leader is elected and the cluster is "brainless", so the job manager is fixed;
  • unstable containers: a task manager restarts periodically, so it is replaced;
  • network partition: a container loses connectivity, so it is terminated.

Backfill and rewind. For data also stored in the warehouse, a job can switch its source to the batch copy without code changes, which is recommended only for stateless jobs. Otherwise, rewind to an earlier automatic checkpoint.

Monitoring and testing. Every job gets its own dashboard and alerts. The platform pushes unit tests, integration tests, operational canaries and data parity canaries (comparing a new version's output with the old one's), while noting that testing streaming systems is still hard. Future items: schemas, a service layer, streaming SQL, ML use cases and event sourcing for microservices.

Overlooked constraints.

  • State size drives recovery time. A job with tens of TB of state cannot recover in seconds by reloading from S3. The checkpoint size, not the code, sets the recovery SLA.
  • Isolation per job costs resources. A Flink cluster per job wastes idle capacity compared with a shared cluster, but one tenant's bug or memory leak cannot hurt others.
  • One source of truth is also a single dependency. If RDS is down, users cannot change goal states, but running jobs keep going, because the data plane does not need the control plane to process events.

What Netflix sacrificed. Resource efficiency (one cluster per job), immediate control (changes take effect when reconciliation catches up), and generality in some places (backfill by source switching only for stateless jobs). In return it got a self-healing, self-service platform that a small team could run for thousands of jobs.

Deep Dive: latency versus duplicates during a redeployShow

A stateless routing job reads Kafka and writes to a sink, committing offsets every checkpoint interval, say every 30 seconds (handbook's illustration).

  • Stop-then-start (favour no duplicates). The old job checkpoints and commits offset N, then stops. The new job starts and resumes from N. Nothing is processed twice, but events pile up during the gap, say 60 seconds. At 100,000 events per second that is a 6-million-event backlog, drained at whatever headroom the job has. With 2× headroom, catching up takes another 60 seconds, so end-to-end delay peaks at about 2 minutes.
  • Start-then-stop (favour latency). The new job starts while the old one still runs, so both read the same partitions for a moment. Or the old one dies without a final commit, and the new one resumes from the last commit, up to 30 seconds back. Either way up to 30 seconds × 100,000 = 3 million events may be delivered twice, but the sink never stops receiving data.

Exactly-once for stateful jobs comes from Flink's checkpointing, which is based on the Chandy-Lamport snapshot idea (Chandy and Lamport, "Distributed Snapshots", 1985). Barriers flow through the stream; each operator snapshots its state when the barrier passes; on failure, every operator restores the same consistent snapshot and replays from the matching Kafka offsets. Internal state is then exactly-once. End-to-end exactly-once also needs a sink that is idempotent or transactional, such as Kafka transactions committed when the checkpoint completes.

Lesson 31: Distributed delay queues on Dynomite (2016)#

Assumptions. Netflix's Content Platform Engineering runs business processes as asynchronous orchestration of microservice tasks: ingesting content from partners in IMF (a studio packaging format), setting up new titles, and encoding and deploying content to the CDN. Queues sit at the heart of this. The old recipe was a queue in Cassandra with ZooKeeper locks. Queues are a known Cassandra anti-pattern (every dequeue is a delete, and deletes leave tombstones that slow later reads). A global lock while polling also allowed only one consumer at a time per queue or shard. A new orchestration engine (Conductor, Lesson 32) needed something better.

Requirements: distributed; no external locks; highly concurrent; at-least-once delivery; no strict FIFO; delayed messages (invisible until a future time); and priorities within a shard.

Why Dynomite and Redis. Dynomite is Netflix's Dynamo-style layer that adds sharding, peer-to-peer replication and multi-datacenter replication on top of single-node stores such as Redis (see Redis). Redis provides the data structures needed for a queue and in-memory speed, and Dynomite adds high availability and a consistency mode suited to queues.

The recipe. Each queue uses three Redis structures:

  1. a sorted set of message IDs, scored by delivery time and priority;
  2. a hash from message ID to payload;
  3. an un-ack sorted set of messages handed to a consumer but not yet acknowledged.
  • Push: compute the score from the delay and the priority, add the ID to the sorted set, and store the payload in the hash.
  • Poll: take "now" as the maximum score and fetch IDs with scores from 0 to now. For each, add it to the un-ack set and remove it from the queue set. Only if that succeeds, read the payload.
  • Ack: remove the ID from the un-ack set and the payload from the hash.
  • Redelivery: a background job moves messages that stay in un-ack past a per-queue timeout back into the queue. This gives at-least-once delivery.

Zone awareness and sharding. The Java client Dyno is token-aware and prefers nodes in the local availability zone, failing over if they are down. The queue uses this for sharding: each queue has one shard per AZ, a sorted set keyed by queue name plus zone. Pushes pick a shard round-robin, so shards balance out over time.

Consistency: DC_SAFE_QUORUM. Reads and writes go synchronously to a quorum of nodes in the local data centre and asynchronously to other regions. Every write is acknowledged by a majority.

No global locks, by design.

  • Each broker node talks to the Redis nodes in its own zone.
  • Redis runs commands on one thread. Dynomite accepts thousands of connections, but two concurrent polls on one Redis node execute one after the other, so no lock is needed on the broker side.
  • During failover, two brokers might grab the same message through different Dynomite connections. The quorum write to the un-ack set succeeds for only one of them; the other gets a failure and moves on to the next message. The un-ack add acts as a claim.

Maintenance. A rebalance operation for uneven shards, or when a zone is added or removed. The un-ack monitor handles crashed consumers.

Extensions. Multiple consumers: subscribe by message type and deliver to every interested consumer, a form of pub/sub. Ephemeral queues: give messages a TTL so they disappear if not consumed in time.

Alternatives considered.

OptionWhy not chosen
KafkaGreat for streams with at-least-once delivery, but priority and time-based delivery are hard; many partitions plus a broker in front would add complexity
Amazon SQSViable for some cases, but no priority, and delays capped at 15 minutes
DisqueRedis-like distributed queues, but still in beta at the time
Cassandra + ZooKeeper locksZooKeeper becomes a bottleneck as clients grow; queues are a Cassandra anti-pattern

Setup. The performance tests used a Dynomite cluster across 3 regions, with the broker using its own region's cluster. Latency was measured server-side only. The recipe was open-sourced as dyno-queues.

Overlooked constraints.

  • "No strict FIFO" is what makes it scale. Allowing order to bend across shards removes the need for one global sequence and one lock.
  • The claim step must be a single atomic, quorum-backed write. Splitting "read" and "claim" into separate steps without that guarantee would let two workers run the same task.
  • Memory is the limit. Redis holds the whole queue in RAM, so a big backlog of large payloads costs real money. That is fine for task IDs and small payloads, not for bulk data.

What Netflix sacrificed. Strict ordering, exactly-once delivery (consumers must be idempotent), and durability beyond what quorum replication of in-memory Redis offers. In return it got lock-free, highly concurrent, delayed and prioritized queues across zones and regions.

Deep Dive: encoding priority and delay in one scoreShow

A sorted set orders by one number, so delay and priority must share it. One simple scheme (handbook's illustration): score = deliver-at time in milliseconds × 100 + priority, with priority 0 (highest) to 99. Messages due at different milliseconds sort by time, and messages due at the same millisecond sort by priority. A poll fetches scores from 0 to now × 100 + 99. Messages scheduled in the future have bigger scores and stay invisible, which is the delay.

Atomic claim. The poll's "move from queue to un-ack" must not let two consumers both win. On a single Redis node, a short Lua script (or a MULTI block) that runs ZREM on the queue set and ZADD on the un-ack set is atomic, because Redis runs one command or script at a time. The ZREM's return value says whether this caller removed the item; only a caller that got 1 proceeds. Across replicas during failover, Netflix relies on the quorum write to the un-ack set to decide the single winner.

Why the ack timeout must exceed the work time. If a task takes 90 seconds at p99 but the un-ack timeout is 60 seconds, about 1 in 100 tasks or more will be redelivered while still running, and two workers will do the same encode. Set the timeout above the p99.9 task time, or let workers extend their lease (a heartbeat that bumps the un-ack score). This is the same "visibility timeout" idea SQS uses.

Throughput intuition. A Redis node does on the order of 100,000 simple operations per second. A poll plus ack is about 5 operations, so one shard handles on the order of 20,000 messages per second, and three AZ shards around 60,000, before replication overhead. That is ample for orchestration tasks, which number in the thousands per second, not millions.

Lesson 32: Conductor, a microservices orchestrator (2016)#

Assumptions. Content Platform Engineering runs business processes as asynchronous tasks across microservices, and some run for days: studio partner integration, IMF content ingest, setting up new titles, and ingest, encode and deploy to the CDN. These had been glued together ad hoc with pub/sub, direct REST calls and a database for state. As services and process complexity grew, nobody could see a workflow end to end. In its first year Conductor ran more than 2.6 million process flows, from simple linear ones to complex dynamic ones lasting days.

Why not choreography? In choreography, each service listens for events and decides on its own what to do next; no one is in charge. Netflix found it hard to scale with business complexity:

  • the process flow is embedded in the code of many apps;
  • services are tightly coupled through assumptions about each other's inputs, outputs and SLAs;
  • there is almost no way to answer "what is still left before this movie's setup is done?"

Orchestration puts one engine in charge of the flow, with visibility and control, while still reusing existing services. (See multi-step processes for the general pattern.)

Requirements:

  • a blueprint in a JSON DSL;
  • tracking and management of runs;
  • pause, resume and restart;
  • a UI to visualize flows;
  • synchronous processing when needed;
  • millions of concurrent flows;
  • a queue hidden from clients;
  • HTTP, and later gRPC.

Architecture.

  • Decider: the heart is a state-machine service. On every event (task done, task failed), it combines the blueprint with the run's current state, works out the next state, and schedules tasks or updates the workflow status.
  • Queue: scheduled tasks go on dyno-queues (Lesson 31).
  • Workers: tasks run in worker apps, which either expose a REST endpoint or, more often, poll for pending tasks. Workers should be idempotent, stateless functions. Polling gives natural back-pressure (workers take only what they can handle), and the queue depth, which Conductor exposes per task type, drives autoscaling.
  • Storage: Dynomite holds state, and Elasticsearch indexes executions for search. Storage is pluggable, so an RDBMS or Cassandra could be used instead.

Key concepts. A workflow definition lists tasks, each either a control task (fork, join, decision, sub-workflow) or a worker task. Definitions are versioned, so running instances keep the version they started with. A task definition sets timeouts and retries. Inputs are mapped from workflow input or from earlier task outputs, so an encode task's output location can feed a publish task.

{
  "name": "encode_task",
  "retryCount": 3,
  "timeoutSeconds": 1200,
  "timeoutPolicy": "TIME_OUT_WF",
  "retryLogic": "FIXED",
  "retryDelaySeconds": 600,
  "responseTimeoutSeconds": 3600,
  "inputKeys": ["sourceRequestId", "qcElementType"],
  "outputKeys": ["state", "skipped", "result"]
}

Here the task retries 3 times, 10 minutes apart. responseTimeoutSeconds (1 hour) is how long a worker may hold a task without reporting back before it is considered lost and rescheduled. timeoutSeconds (20 minutes) caps one attempt, and the timeout policy fails the whole workflow if it is exceeded. System tasks include Decision, Fork, Join, Sub-workflow and HTTP, and an SPI allows custom ones.

Example: encode and deploy. Three worker tasks (content inspection, encode, publish to CDN) plus an error-handling control task. Each is done by a different worker polling for work. After each completion, the Decider checks the run against its blueprint version and schedules the next step, or completes the workflow.

The UI is the main monitoring tool. Search runs by input or output, see the blueprint and the path taken, and for every task: scheduled, picked-up and completed times, failure reason, retry count, host, and input and output.

Alternatives. Amazon SWF was tried first, but it needs programmatic deciders (code, not a blueprint), has no flow-visualization UI, is purely message-based, cannot index and search inputs and outputs, and needs a separate store for workflow events. AWS Step Functions had just launched with some of the wanted features, and Conductor might adopt its states language later. Future ideas: Lambda-style tasks, container autoscaling integration, per-task execution logs, editing blueprints in the UI.

Overlooked constraints.

  • Visibility is a requirement. "What is left for this title?" is a business question that choreography cannot answer cheaply.
  • Idempotent workers are mandatory, because at-least-once queues and response timeouts will rerun tasks.
  • Versioned blueprints let a days-long run finish on the old definition while new runs use the new one.

What Netflix sacrificed. A central engine is a shared dependency and potential bottleneck: if the Decider or its store is unhealthy, all workflows stall. Services also lose some autonomy, since the flow lives in Conductor, not in them. In return it got visibility, restartability and one place to reason about long processes.

Deep Dive: orchestration versus choreography, and why polling helpsShow
DimensionChoreography (events)Orchestration (Conductor)
Who knows the flowNobody fully; it is spread across servicesThe blueprint
Adding a stepChange several servicesChange the blueprint
"Where is run X?"Join logs from many servicesOne query
CouplingEvent schemas, hidden ordering assumptionsTask inputs and outputs
Failure pointNone central; failures hide in gapsOrchestrator must be highly available
Best forSimple fan-out notificationsLong, multi-step business processes

Polling and back-pressure. If the engine pushed tasks to workers by HTTP, a slow encode farm would get more requests than it could handle, and the engine would need to track capacity and retries per worker. With pull, an overloaded worker simply polls less often, the queue grows, and queue depth becomes the scaling signal. Suppose encode tasks arrive at 200 per minute and each takes 10 minutes on one worker slot (handbook's illustration). Little's Law (items in system = arrival rate × time in system) says about 2,000 slots must be busy to keep up. If only 1,500 exist, the queue grows by about 50 tasks a minute, and an autoscaler watching depth adds capacity. A push model would show the same overload as timeouts and retries instead.

Durable execution, the next step. Engines like Temporal (see Temporal and workflow engines) store an event history and replay workflow code to rebuild state, so workflows can be written as ordinary code instead of JSON blueprints. Conductor's JSON keeps the flow declarative and visible, at the cost of less expressive logic.

Lesson 33: Maestro, the data and ML workflow orchestrator (2024)#

Assumptions. Maestro runs data and ML workflows: ETL, ML training, A/B test pipelines, and moving data between stores. It is Workflow-as-a-Service for thousands of users. In the year before the post, executed jobs grew 87.5%. It launches thousands of workflow instances and runs about half a million jobs a day on average, with about 2 million on busy days. Hundreds of thousands of workflows were migrated to it with little disruption. A key belief: since all of Netflix's tables live in one data warehouse and workflows are deeply interconnected, one orchestrator should run them all, rather than splitting workflows across clusters and adding coordination between them. So Maestro must be horizontally scalable, both in the number of workflows and in jobs per workflow.

What makes it different. Business logic can be Docker images, notebooks, bash, SQL, Python and more. Unlike classic DAG-only orchestrators (Airflow-style), Maestro supports both acyclic and cyclic workflows, plus reusable patterns: foreach, subworkflow and conditional branch.

Workflow definition (JSON). Two parts:

  • Properties: owner, author, run strategy, concurrency, triggers, alerts. These are kept across versions, and ownership can change without a new version.
  • Versioned workflow: ID, name, tags, timeouts, criticality (low, medium, high). Each change creates a new version, so you can track and roll back. Steps are the graph nodes (a job, a subworkflow or a foreach), each with parameters, dependencies, retry policies by error type and a failure mode.

Run strategies decide whether a newly triggered instance runs:

StrategyBehaviourGood for
Sequential (default)FIFO, one at a time; the next starts when the last ends, success or notOrdinary scheduled pipelines
Strict sequentialFIFO, but a failure blocks later runs until someone restarts or unblocks itBusiness-critical, time-insensitive pipelines that must be reviewed
First-onlyIf one is running, drop new triggersAvoiding idempotency problems from queued duplicates
Last-onlyIf one is running, stop it and run the newestAlways processing the latest full snapshot
Parallel with limitRun many at once up to a capBackfills

Parameters and SEL. Parameters carry state between workflows and steps and control execution. Allowing user code injection in parameters is powerful but dangerous: an infinite loop that keeps appending to an array could crash the server with out-of-memory. Pushing all logic into user code would couple business logic to the workflow. So Netflix built SEL (Simple, Secure and Safe Expression Language), a subset of Java's syntax with:

  • validation while parsing the syntax tree;
  • runtime limits on loop iterations, array sizes and object memory;
  • the Java Security Manager to restrict what code can access.

Output parameters come back through Maestro's REST API, so step code never touches Maestro's database.

Static, dynamic and parameterized workflows. Static workflows are simple, but get duplicated for small changes and cannot share state. Fully dynamic ones are hard to debug and reuse. Parameterized workflows are the middle ground: they are built step by step at runtime from parameters, flexible but still understandable, which is ideal for backfills.

Execution patterns, built into the engine.

  • Foreach: each iteration runs as a separate workflow instance, so a loop with hundreds of thousands of iterations (backfills, model tuning) scales like any other workflow. The foreach step collects their statuses.
  • Conditional branch: a SEL condition on upstream output decides whether later steps run.
  • Subworkflow: "workflow as a function". Some workflows contain hundreds of subworkflows owned by different teams.
  • Composites: for example, an auto-recovery workflow: subworkflow (ETL plus audit), then a status check, then either finish or run a recovery job, then rerun the same subworkflow.

Step runtime. Each step type implements start, execute and terminate, and tracks a runtime state plus an execution result (artifacts and a timeline). Parameter merging builds each step's parameters in a fixed order, so later layers override earlier ones:

  1. reserved defaults such as workflow instance ID and step attempt ID, which users cannot set;
  2. parameters injected by the step type's schema, which can evolve without Maestro code changes;
  3. typed defaults, such as a foreach's loop parameters and loop index;
  4. workflow and step info;
  5. new parameters the user adds at start or restart;
  6. the step definition's parameters;
  7. run and restart overrides, last.

Signals and dependencies. A step can wait on signals: messages carrying parameter values, published by step outputs or by external systems (SNS, Kafka). This works as both trigger and pub/sub dependency: one signal can unblock many steps. Matching can use a subset of fields and operators like greater-than or less-than. For example, an ETL step updates a table and signals it, which unblocks downstream workflows waiting for that partition. Signal lineage lets users browse historic signals and who published or consumed them. Signal triggering guarantees exactly-once execution of the subscribing workflow.

Operability features.

  • Breakpoints: like an IDE breakpoint, a step pauses until resumed. In a foreach, one breakpoint pauses every iteration at that step, and resuming one resumes only that one.
  • Timeline: every state change and the reason for it.
  • Retries: fixed or exponential backoff, separate for platform errors and user errors. Retries can be set to zero for non-idempotent steps.
  • Aggregated view: after a restart from the failed step, the view merges the earlier run's successes with the new run's statuses.
  • Rollup: counts leaf steps by status across nested subworkflows and foreach steps (a 3-step workflow with a 5-step subworkflow shows 7 leaf steps). It is computed from a base plus the current state, so it is eventually consistent.
  • Events: internal events drive Maestro itself, and an event processor turns some into external events on SNS or Kafka (workflow changes, instance status changes) for downstream services.

Overlooked constraints.

  • Users write code inside configs. Any expression language in a multi-tenant control plane is an attack and stability surface, so it needs a sandbox and resource limits.
  • Run strategy is a correctness setting. First-only and last-only are really idempotency and freshness decisions, not scheduling preferences.
  • Rollups of nested workflows are recursive and eventually consistent. Showing a "7 of 7 succeeded" view is non-trivial at scale.

What Netflix sacrificed. One giant orchestrator means a large blast radius and demanding scaling work, accepted to avoid cross-cluster coordination. SEL restricts what users can express. In return it got one place for all data workflows, reusable patterns and safe parameterization.

Deep Dive: choosing a run strategy for a daily pipelineShow

A daily job builds a "titles watched yesterday" table, and each run takes 2 hours (handbook's illustration).

  • A normal day: the trigger fires at 01:00 and the run finishes at 03:00. Every strategy behaves the same.
  • The upstream table is late and three triggers pile up (day 1, 2 and 3), each run depending on its own date. Sequential runs them in order over 6 hours, which is correct. Last-only would cancel day 1 and 2 and leave holes in a date-partitioned table, which is wrong here. First-only would drop day 2 and 3, also wrong.
  • The job rebuilds a full snapshot each time (for example, "current catalog"). Then last-only is right: older triggers are obsolete, and running them wastes 4 hours of compute.
  • Day 2's run fails on bad data. With sequential, day 3 runs anyway on top of a broken day 2, and downstream jobs may consume garbage. With strict sequential, day 3 waits until a human checks day 2, which is slower but safe for a finance or royalty table.
  • A 2-year backfill: 730 daily partitions. Parallel with limit 20 finishes in 730 / 20 × 2 hours ≈ 73 hours, versus about 61 days sequentially, while capping warehouse load.

The strategy is therefore a choice between completeness, freshness, safety and speed, and it belongs in the workflow's properties, where Maestro keeps it stable across versions.

Lesson 34: Scaling the API with GraphQL federation (2020)#

Assumptions. Netflix offers UI developers one API aggregation layer at the edge rather than hundreds of microservices. As developers and domains grew, building that layer became the bottleneck. The case here is Studio: hundreds of apps covering pitching, casting, deals, production, post-production, VFX, subtitling and dubbing, with deeply connected data spread across many services.

Before: two patterns, both painful.

  1. Single-use aggregation layers: each team wrote its own data-fetching and aggregation code, in a BFF (Backend for Frontend) or a mid-tier service. Lots of duplication.
  2. Materialized views of other teams' data: fast, but always somewhat stale. Inconsistent data across Studio apps was the top support issue in Studio Engineering in 2018.

Then: one curated graph, Studio API. A central team built a GraphQL API over the shared data (see API styles). Every field resolves through one piece of fetching code, so apps stopped disagreeing. It was a "runaway success", until it became a new bottleneck:

  • the central team was far from the domain expertise, which hurt schema quality;
  • wiring new backend data into the graph was manual, which clashed with fast-moving microservices;
  • one small team carried an ever-growing operational and support load.

The goal became "unified but decoupled, curated but fast moving": keep one schema, but let domain teams implement their parts. In early 2019 Apollo released the GraphQL Federation specification. Netflix tested it, worked with Apollo on it, and built Studio Edge around it.

How federation works. Take three entities owned by three teams: Movie, Production (where and how it is shot) and Talent (actors, directors). In the old design, one team owned all resolvers. In federation, the Movie DGS owns the Movie type, and the Production and Talent services extend Movie with their own fields. Movie becomes a federated type, and the gateway delegates each field to its owner.

# Movie DGS
type Movie @key(fields: "movieId") {
  movieId: ID!
  title: String
}
type Query { movies: [Movie] }
 
# Production DGS extends Movie
extend type Movie @key(fields: "movieId") {
  movieId: ID! @external
  production: Production
}
 
# Talent DGS extends Movie
extend type Movie @key(fields: "movieId") {
  movieId: ID! @external
  actors: [Talent]
}

Components.

  • Domain Graph Service (DGS): a spec-compliant GraphQL service owned and run by a domain team. It can be an existing microservice converted, or a new one.
  • Schema registry: stores every DGS schema and its changes. It exposes CRUD APIs used by tools and CI/CD, validates each schema, composes the unified schema, and hands it to the gateway.
  • GraphQL gateway: takes a client query, builds a query plan of sub-queries, runs them against the right DGSs (in sequence or in parallel), and merges the results.

Schema composition checks on every push: is the new schema valid GraphQL? Does it compose with all others? Is it backward compatible? Only then is it checked in. This turns "you broke another team's client" into a CI failure.

Query planning. For "first 10 movies with title, production and actors": the gateway sends query 1 to the Movie DGS for IDs and titles. Then it sends queries 2 and 3 in parallel to Production and Talent, passing 10 representations (objects holding just the movie ID). Then it merges the results. Planning and execution add about 10 ms in the worst case, including building the plan and deserializing and re-serializing responses.

Entity resolution. For the gateway to join Movie across services, all of them must agree on a primary key using the @key directive (here, movieId), and each DGS implements a generic _entities query that takes representations and returns the matching entities. This resembles Relay's object identification, except _Entity is a union (not an interface) and keys can be any name, type or composite, not one opaque ID.

Result. 70 DGSs live with hundreds of developers. The architecture moved from microservices plus ad hoc aggregation, to a central graph, to a federated graph, each step aiming to shorten the time from idea to implementation.

Overlooked constraints.

  • Consistency of meaning beats speed of access. Materialized views were fast, but six apps showing six versions of a movie's status was the bigger cost.
  • A central schema team becomes Conway's law in reverse. It must understand every domain. Federation lines ownership up with domain teams.
  • Every federated join is a network hop. A careless query can fan out into many sequential sub-queries, so query plans need watching.

What Netflix sacrificed. Some latency (about 10 ms worst case plus extra hops), a new critical component (the gateway and the registry), and the discipline of schema governance across 70 teams. In return it got one consistent graph with distributed ownership.

Deep Dive: the N+1 problem and why _entities is batchedShow

A naive resolver for "10 movies with their actors" calls Talent once per movie: 1 + 10 = 11 calls, the N+1 problem. With 100 movies and 3 extended fields, that is 301 calls. Federation's _entities takes a list of representations, so the gateway makes one call per DGS per level: 1 + 2 = 3 calls regardless of N.

Latency. Suppose each DGS call takes 20 ms at p50 (handbook's illustration). Federated: 20 ms (Movie) + max(20, 20) (Production and Talent in parallel) + about 10 ms of gateway overhead = 50 ms. Naive per-movie calls done in parallel are also about 40 ms, but with 10× the requests, and the tail grows with fan-out. If each call has a 1% chance of exceeding 200 ms, the chance that at least one of 20 parallel calls is slow is 1 − 0.99^20 ≈ 18%, against 1 − 0.99^2 ≈ 2% for two batched calls. Batching protects the tail as well as the request count.

Inside a DGS, a DataLoader (per-request batching and caching of key lookups) does the same thing for the DGS's own downstream calls, so _entities for 10 IDs becomes one database query with an IN-list.

Lesson 35: Migrating critical traffic with no downtime, part 1: replay testing (2023)#

Assumptions. Hundreds of millions of members expect uninterrupted streaming while the backend keeps changing. Migrations happen at every level of the call graph: edge API to devices, edge to mid-tier, and mid-tier to data stores. APIs may be stateless and idempotent or stateful. Netflix splits a migration into two phases. Before: validate functional correctness, scalability, performance and resilience. During: move traffic gradually while watching device QoE (quality of experience), SLAs and business KPIs. Part 1 covers the main pre-migration tool, replay traffic testing.

What replay testing is. Copy real production requests and send the copy to the new system (and often also the old one) on a separate path, then compare. Benefits:

  • sandboxed testing at scale without affecting members;
  • the full diversity of real inputs (thousands of device types and app versions, high-cardinality parameters, rare combinations);
  • functional correctness and load testing from the same traffic;
  • behaviour over long periods and real traffic shifts;
  • a chance to have metrics, logs and alerts ready before cut-over.

There are two parts: duplicate and correlate (clone traffic, record both responses with a shared ID), then compare and report.

Three ways to generate replay traffic.

OptionHowProsCons
Device-drivenDevice calls both paths in parallel, discards the replay response; same correlation ID on bothCovers the full path from the deviceWastes device resources; risks QoE on weak devices; tied to slow device release cycles; exposes untested server paths to the internet
Server-drivenAn upstream service calls old and new in parallel and records both asynchronouslyNo device cost; fast to changeReplay code lives next to business code; replay bugs can hurt production
Dedicated serviceRequests and responses are already logged to a stream; Mantis replays them against the new service, adjusting as needed, and records bothFully isolated; independent release cycleNot real-time; needs good request logging

Analysis. Responses go to cheap cold storage (Apache Iceberg tables), and batch jobs compare them.

  • Normalization first: ignore timestamps, sort unordered lists, and transform expected format changes (for example, a list that became key-value pairs) so intended differences do not show as mismatches.
  • Comparison: a summary of total responses on each side, how many joined by ID, matches, mismatches and pass or fail counts per side. Mismatches are stored with raw and normalized responses and the diff, so engineers fix the causes and repeat until the mismatch rate is acceptable.
  • Lineage: responses often depend on data that changes between the two calls. For example, a playback response lists available streams, and a new encode or language may appear between production and replay. Each response records a lineage, the versions or checksums of all dependency data used. Pairs with different lineage are discarded as noise.

Live comparison is an alternative for simple payloads or off-critical-path services: the forking service compares inline and logs only mismatches.

Load testing with replay. By controlling how much traffic is replayed and how big the new cluster is, teams see how availability, latency, CPU, memory and GC change with load. This exposes memory leaks, deadlocks and caching bugs, and lets them tune thread pools, connection pools and timeouts, set scaling policies and estimate cost.

Stateful systems are harder: the two paths need separate, identical data stores, every request type that changes state must be replayed, and the comparison must cover state, not just responses. Netflix often uses other techniques for these (part 2).

Uses. A large re-architecture of the playback edge APIs, and a mid-tier migration from REST to gRPC.

Overlooked constraints.

  • Non-determinism is the main source of false mismatches. Without normalization and lineage, the signal drowns in noise.
  • Replay must not have side effects. Replaying a write (a charge, an email) to a shared store would be a real action, which is why stateful replay needs isolated stores.
  • Where you fork decides your blast radius. Device forking risks members, server forking risks the service, and offline replay risks nothing live.

What Netflix sacrificed. Extra cost (duplicate compute, storage of both responses, batch jobs), and engineering time on normalizers. In return it found subtle issues before members did.

Deep Dive: how much replay traffic is enough?Show

Suppose you want to be 95% confident the new path's mismatch rate is under 0.1% (handbook's illustration). If you see zero mismatches in n requests, the "rule of three" says the 95% upper bound on the true rate is about 3 / n. To push that bound below 0.001 you need n ≥ 3,000. But real input space is huge: if a rare device or parameter combination appears in 1 in 1,000,000 requests, you need several million replayed requests to see it even a few times. At 10,000 replayed requests per second, 5 million takes under 10 minutes, but rare time-based behaviours (daily cache expiry, weekly batch refresh) need days of replay. That is why replay runs over extended periods, and why the dedicated-service approach, which is cheap to keep running, won out.

Mismatch triage. Suppose the first run shows a 4% mismatch rate. Group mismatches by the JSON path of the diff. Typically a few paths dominate: for example, 3% in an unordered list (fix: normalize), 0.7% in fields whose lineage differs (discard), and 0.3% real bugs. Fixing iteratively drives the rate toward the noise floor.

Lesson 36: Migrating critical traffic with no downtime, part 2: canaries, A/B tests, dials and stores (2023)#

Assumptions. After replay testing, changes still need a controlled rollout that limits risk and measures impact continuously. Part 2 adds four techniques, in order of increasing exposure.

1. Sticky canaries. A normal canary creates two new clusters, a baseline with the current version and a canary with the new one, and sends a small share of traffic to both, comparing metrics (Kayenta, Lesson 19). But some features are a lifecycle of calls across services. Playback, for example, means getting stream URLs, downloading from the CDN, getting a license from another service, and sending start-play telemetry to yet another. Service-level metrics alone can miss an end-to-end break. A sticky canary picks a pool of devices and routes them consistently to canary or baseline for the whole experiment, so end-to-end customer metrics (for example, play starts) can be compared across the pool. The risk: a device stuck on a bad canary keeps hitting it through retries, so the framework watches KPIs and stops the experiment on persistent deviation. Canaries run for hours to days.

2. A/B tests for migrations. When a change is expected to affect device QoE or business KPIs, or when it changes the device contract, Netflix uses its A/B framework (Lesson 37). Membership is decided in the device or the backend, and only a share of members get the new path. A/B tests can run weeks or months, enough to measure, for example, whether better playback quality leads to more plays. They can be restricted by geography, platform or device version, analysed by those dimensions to catch harm to a segment, and resized mid-test. Not every migration needs one.

3. Dialing traffic. The last step. A dial samples each request with a distribution function and routes it to the new path if the result falls under a target percentage. That percentage is a global dynamic property that can be changed instantly. Sampling uses a fixed request attribute: a random number or timestamp for request-level randomness, or the device ID when a device must stay on one path. Dials can live in the device app, a server or the API gateway.

  • Traffic moves in discrete steps, with stakeholders informed and service, device, operational and business metrics watched at each.
  • If anything trends badly, the dial goes back down at once.
  • Steps can be scoped to one data centre first, making side-by-side comparison with other regions easy.
  • Longer steps surface issues that hit only small groups of members.

4. Migrating persistent stores. Netflix uses this method when the data model is simple, self-contained and immutable, with no relations, no need for strict consistency and no transactions. The steps:

  1. Initial ETL load from the old store into the new model, with custom queries to check completeness.
  2. Dual writes, guarded by a dial. All state-changing requests for an entity go to both stores, with the dial made sticky to the entity so an entity's history is either fully dual-written or not at all. The dial is raised gradually, and can also switch off all writes to the new store.
  3. Continuous verification on read: read both stores and compare, live or offline. In live mode, return the new store's record when they match.
  4. Completeness checks: periodic dumps of both stores to cold storage are compared, and gaps are filled by ETL.
  5. Cut-over and clean-up: stop dual reads and writes, remove client code, use only the new store.

(See online data migrations for the wider set of strategies, including CDC-based approaches.)

Clean-up matters. Remove dials, A/B tests and replay hooks, revert temporary config, and document issues and fixes so the next migration is easier. Leftover migration code is tech debt.

Overlooked constraints.

  • Stickiness has two edges. It makes end-to-end metrics measurable, but it also concentrates harm on the same devices, so you need automatic stop conditions.
  • The sampling key decides correctness. Random sampling for a stateful flow can send one device's "start" to the new path and its "stop" to the old one.
  • Dual writes need an entity-level dial. Sampling per request would split an entity's writes across stores and break parity.

What Netflix sacrificed. Time (weeks of staged rollout), double write cost during migrations, and code complexity that must be cleaned up later. In return, most migrations had minimal to no downtime.

Deep Dive: a dial schedule and what each step can detectShow

Suppose a service handles 100,000 requests per second, and an issue affects 1 in 10,000 requests for one device family (handbook's illustration).

Dial stepNew-path trafficAffected requests per hourDetectable?
1% for 1 hour1,000 per second360Barely, for a per-device-family error metric
5% for 4 hours5,000 per second7,200Yes
25% for 1 day25,000 per second216,000 per dayClearly
50%, 100%Only regressions too small to see before

At each step, the members harmed are the dial share times the bug rate, so starting low caps the damage while the signal is weak. Running longer at a low dial gives the same statistical power as running shorter at a high dial, but with less harm per hour. That is the trade-off behind "longer steps surface issues for small groups".

Sticky entity dials for dual writes. Hash the entity ID: hash(entityId) mod 100 below the dial means dual-write. Raising the dial from 10% to 20% adds new entities, which must then be backfilled by ETL, because their earlier history was never dual-written. That is why the initial ETL load and the periodic completeness checks are part of the method, not extras.

Lesson 37: The experimentation platform, it's all A/Bout testing (2016)#

Assumptions. Every product change goes through an A/B test before becoming the default: UI redesigns, the personalized homepage, adaptive streaming and CDN algorithms, and even title artwork (sometimes 20% to 30% more viewing for a title). The point is that data, not the loudest opinion, decides. The platform handled 150,000 to 450,000 requests per second with autoscaling. Fetching existing allocations took about 8 ms with a cold cache and under 1 ms warm. Real-time evaluation averaged about 50 ms. The architecture dates from 2010, when Netflix streamed in 2 countries to 10+ million members on dozens of devices. By 2016 it was 190+ countries, 80+ million members and thousands of devices.

Concepts. An experiment has a control and one or more treatment groups called cells. A member is in exactly one cell per test, and the default cell is the control, which gets the same experience as non-members of the test. Metrics are typically streaming hours and retention. A member is in several tests at once, as long as they do not conflict (two tests changing the same UI area differently). ABlaze, the front end, shows a test schedule to find conflicts.

Two ways to allocate members.

  • Batch: an analyst's query picks a fixed set of members. It is very flexible, but cannot include brand-new members, cannot react to real-time behaviour, and does not ensure allocated members ever see the feature (say, an iPhone test for a member who never uses an iPhone).
  • Real-time: rules are evaluated as members use the service, and eligible members not in a conflicting test are allocated on the spot. This fixes the batch drawbacks but adds latency to the calling app, often hidden by running in parallel with other calls. It also makes it hard to predict how long a test takes to fill.

Call flow (an artwork test on a PS4).

  1. The PS4 app calls the Netflix API with session and device context.
  2. A PS4-specific script in the API's client adapter layer handles it (each device team owns its scripts and endpoints). The script calls the A/B client library.
  3. The A/B client gathers more context about the member and device from other services, then calls the A/B server.
  4. The server fetches the member's existing allocations. Batch tests are already known; for real-time tests it evaluates the rules and allocates if eligible. It returns all tests and cells. The app does not know or care whether the member joined weeks or microseconds ago.
  5. The script acts on the relevant tests, here picking the image for the chosen cell from the title-metadata service. The platform does not implement the experience; the owning service does.

Storage. Test metadata and allocation rules live in Cassandra, and so do member allocations, fronted by EVCache with a 3-hour TTL. On a new allocation, the server writes Cassandra and invalidates the member's cache entry, so the next read misses and reloads.

Stratified sampling. Cells must be alike on key dimensions, chiefly country and device type. Pure random assignment can, by chance, put more Australian game-console users in one cell and bias the result. Stratified sampling balances each stratum across cells.

Data flow. Allocation events go to Kafka, then to Hive for ad hoc analysis and Ignite, the internal analysis tool where owners read results. Spark Streaming writes to Elasticsearch so ABlaze can show near-real-time allocation counts.

Pressures in 2016. On mobile, real-time allocation did not work: unreliable bandwidth meant the app could not wait for the server while the member stared at a loading screen, so mobile used batch allocation. Adaptive-streaming tests run in hours and need fast results, unlike UI tests that run for weeks. Plans: faster real-time evaluation, better mobile handling, and forecasting allocation rates from the Spark stream so analysts can plan test durations. (See design an experimentation platform for a full design including hashing-based assignment.)

Overlooked constraints.

  • Allocation latency is on the critical path of the UI. 50 ms per real-time evaluation is fine on a TV and too much on a flaky mobile connection.
  • "Allocated" is not "exposed." Batch allocation dilutes the measured effect with members who never saw the change.
  • Cache invalidation is part of correctness. If a stale cache served an old allocation, a member could see two cells' experiences and contaminate the test.

What Netflix sacrificed. Latency (real-time evaluation), statistical power (batch allocation includes unexposed members), and engineering effort for stratification. In return, every decision is backed by evidence.

Deep Dive: why stratification matters, in numbersShow

Suppose 10% of a test's population are game-console users, whose baseline streaming is 30% higher than average (handbook's illustration). With 2,000 members per cell, random assignment gives each cell a console share with a standard deviation of √(0.1 × 0.9 / 2,000) ≈ 0.67 percentage points. A 2-standard-deviation imbalance (cell A 11.3%, cell B 8.7%) shifts the cells' average streaming by about 2.6 × 0.3 ≈ 0.8%. That is the same size as many real treatment effects, so it could create a false winner. Stratifying by device type (and country) forces each cell's share to match closely, removing that noise and increasing the test's power.

Why exposure matters. If only 40% of batch-allocated members ever open the app on the tested device, a true 2% lift among the exposed shows up as about 0.8% overall. Detecting an effect 2.5× smaller needs about 2.5² ≈ 6× the sample, since the required sample size grows with 1 / effect². Real-time allocation at the moment of exposure avoids that dilution, which is why it exists despite its latency cost.

Lesson 38: Tudum, from CQRS with Kafka to CQRS with RAW Hollow (2025)#

Assumptions. Tudum.com is Netflix's fan site: interviews, first looks, behind-the-scenes video, guides. It draws over 20 million members a month. Traffic is read-heavy. Editors write rarely, but when they do they want to preview the change in seconds. The whole published dataset is small, megabytes rather than terabytes. Visitor reads can tolerate seconds of staleness. Editor previews cannot.

The first design, end of 2021. The team wanted a configuration-driven site and picked server-driven UI (SDUI). In SDUI the server decides the structure and content of each screen, and web, mobile and TV clients just render what they are sent. So a layout can change without shipping a new app. Underneath, they chose a pattern close to CQRS (Command Query Responsibility Segregation: separate models for writing and for reading; see event sourcing and CQRS). That fits Tudum's two very different users:

  • Editors (the write side). Pages and the content elements inside them come from a third-party CMS. The write store keeps everything an editor needs: internal comments, revisions, version history, asset metadata and publishing schedules.
  • Visitors (the read side). They only need the latest published version, in a read-optimised form, and personalised.

The read model is denormalised and resolved. Where the CMS stores an internal asset ID, the read store holds a CDN image URL. Where the CMS holds a placeholder for a title, the read store holds the real title, synopsis and cast names. Because the read model is derived, the team can regenerate all of it on demand, for example after a global navigation or branding change.

The pipeline:

  1. An editor saves through the CMS's REST API.
  2. The CMS calls a webhook on the Tudum Ingestion Service.
  3. Ingestion queries every section it needs, applies page templates, validates data and assets, transforms the content, and produces each content element to a Kafka topic.
  4. A Data Service Consumer reads Kafka, writes to Cassandra (a highly available store), and serves an API to Page Construction and other Tudum services.
  5. A Page Data Service fronts the key-value store with a near cache, an in-process cache on every app node, so page construction can do its many key lookups from memory.

Where eventual consistency hurt. Scaling worked. Previews did not. Every edit had to pass through five waits: CMS save, webhook, ingestion processing, Kafka consumption and the database write, and then the cache refresh. Profiling pointed at that last step. The near cache held the whole dataset, to turn page construction's N+1 key lookups into memory reads. (N+1 means one lookup for the page, then one for each of its N elements.) It refreshed in the background on a cycle that walked the keys. The post's illustration: with 60 keys and a 60-second refresh interval, the cache refreshes one key per second. So an edit becomes visible only when the refresher reaches that key. As Tudum's content grew, the cycle grew too, and previews took minutes.

This is the classic lesson that a cache added to fix slow reads becomes the source of staleness. The cache was not wrong. It was the wrong tool for read-your-writes.

RAW Hollow. Netflix's Hollow is a library that ships an entire dataset to every consumer as a compact, in-memory, read-only snapshot. RAW Hollow (Read After Write) extends it into an in-memory, co-located, compressed object database:

  • The whole dataset lives in the memory of every application process in the cluster. There is no network hop per read.
  • Compression lets it scale to about 100 million records per entity.
  • It is eventually consistent by default, with strong read-after-write consistency on request, per individual request. So an editor's preview can ask for strong reads while visitor traffic uses the cheap default.
  • It targets small to medium datasets that change infrequently, and it removes cache synchronisation and external dependencies.

The revised design. Tudum adopted RAW Hollow while it was still pre-GA internally. It removed the Page Data Service, the key-value store and the Kafka infrastructure. The read-path services (page construction, search, personalisation) embed the Hollow client and look up any record in O(1) time, synchronously, from local memory.

Results.

  • Previews in seconds instead of minutes. Visitors still get high availability and in-memory speed.
  • Memory footprint. Three years of unhydrated data (raw records, not yet joined into pages) takes 130 MB, about 25% of its uncompressed size in an Iceberg table.
  • Latency. Home page construction, excluding TLS, authentication, logging and WAF filtering, fell from about 1.4 s to about 0.4 s, because every read-path service now reads from memory instead of doing I/O.

The authors' lessons. CQRS is powerful for scale if you can tolerate some eventual consistency. Minimising sequential operations cuts response time, and I/O is usually the main enemy. Cache invalidation is hard, and holding the entire dataset in memory removes that whole class of problems.

Overlooked constraints.

  • Preview is a different consistency requirement from serving. One user (the editor) needs read-your-writes, and 20 million users do not. A design that offers per-request consistency serves both from one store.
  • "Small dataset" is a design input, not an accident. Full replication to every process works only because the data fits in 130 MB. A catalogue of user-generated content could not do this.
  • Embedding a data client couples schemas to deployables. The authors warn that sharing the in-memory client with other teams could limit schema changes and deprecations, because every consumer process now holds the data model in memory.

What Netflix sacrificed. Independence of the read side. Kafka-based CQRS let the read store and write store scale and evolve separately, with a durable log in between. With Hollow, every read-path node carries the full dataset and its schema, deploys are coupled to the data model, and the dataset must stay small. They also bet on a pre-GA internal technology. In exchange they got fewer moving parts (three systems removed), seconds-fast previews and roughly 3.5× faster page builds.

Deep Dive: why a full-dataset near cache refreshes slowly, and what replication costsShow

Refresh-cycle staleness. Suppose a near cache refreshes its keys round-robin at r keys per second over K keys. The time to revisit any one key is K / r. An edit lands at a random point in the cycle, so the average wait is K / 2r and the worst case is K / r. With the post's 60 keys at 1 key per second, the average is 30 s and the worst is 60 s. If the content grows to 3,000 elements and the refresher can afford 10 keys per second without hammering the store, the worst case becomes 300 s, five minutes (handbook's illustration). The delay grows linearly with dataset size. That matches the post's observation that refreshes got slower as Tudum grew.

Change-driven replication instead. Hollow-style systems invert this. The writer publishes a delta (only what changed) and every consumer applies it. Staleness becomes "time to publish plus time to fetch the delta", independent of dataset size. Strong read-after-write on a single request can be done by having that read check with the writer, or wait until the local copy has applied a version at least as new as the write. That is the same idea as a session token or log position in other databases.

Memory cost. 130 MB per process across, say, 100 read-path instances is 13 GB of RAM in total (handbook's illustration), which is cheap. The real cost is that the dataset size is now multiplied by the instance count. For a 50 GB dataset, 100 copies is 5 TB of RAM, and the design stops being sensible. That is why RAW Hollow targets small to medium, slowly changing data.

Latency arithmetic. If page construction needs about 30 sequential lookups at 30 ms each through a facade and a KV store, that is about 0.9 s of I/O. In-memory lookups at microseconds each are negligible (handbook's illustration). The post's measured drop, from 1.4 s to 0.4 s, is consistent with removing roughly 1 s of sequential I/O.

Lesson 39: Event sourcing for Netflix downloads, episode 1 (2017)#

Assumptions. Early in 2016, Netflix asked: what would it take for members to download titles and watch them offline? The feature had to launch to all members worldwide at once, with millions of existing users, in about nine months. It shipped in late November 2016. For the Playback Licensing team, the hard part was that licensing had always been stateless, and downloads needed state.

How streaming licensing works. To play a title, the device first fetches a Playback Context: metadata such as images and the stream URLs. The streams are protected by DRM (Digital Rights Management: encryption that only licensed devices can decrypt). Before playing, the device asks for a license that lets it decrypt that title. For streaming, the license is short-lived and single-use: once the member finishes watching, it is consumed.

Netflix supports several DRM technologies, each in its own microservice with its own scaling and deployment. The licensing tier has no fallback. Many Netflix services can degrade gracefully, but if licensing is down, nothing plays. That is why it had been kept stateless: stateless services are easy to scale and to replace.

How downloads differ. The device still gets a Playback Context. Then it asks for a license. The back end runs business checks to see whether this member may download this title, and if so returns a license plus what is needed to play offline. Only then does the device download the encrypted bytes. The download license is different: it is persisted on the device for longer and reused across many playback sessions.

The lifecycle. Each offline play queues session events on the device, which are uploaded the next time it is online. After a per-title duration, the license expires. Depending on the content, the device may ask for a renewal, which is validated against the same business rules. When the member deletes the title, the license is released, securely closed so the content can no longer play.

A maze of restrictions. Studio contracts for downloads are more complex than for streaming and vary a lot between studios:

  • How long a title can be watched after download.
  • Caps on the number of downloads per device or per member.
  • Limits on how many times a title can be downloaded or watched within a time period.
  • Netflix's own rules, such as the number of devices that may hold downloads.

Every download or renewal must be checked against all applicable rules, using the member's past download interactions across all titles. A failure returns the reason to the device.

The decision. Validation happens at license-request time. So the stateless licensing services needed a new stateful service to consult. The team chose an event-sourced storage microservice (see event sourcing and CQRS): store every download, renewal and release as an immutable event, and compute a member's current state by replaying them. The series says later episodes cover data versioning and snapshotting for flexibility and scale. Those episodes are not in this handbook's fetched set, so this lesson stops at the design motivation.

Overlooked constraints.

  • No fallback means state must not reduce availability. Adding a stateful dependency to a tier that has no degraded mode is risky. The new service had to be as available as licensing itself.
  • Requirements were "yet to be defined". Studio rules were still being negotiated while the system was being built. An event log keeps the raw facts, so a rule added later can be evaluated against history that was recorded before the rule existed.
  • Offline devices report late. Session events arrive whenever the device comes back online, so the server's view is always behind and events arrive out of order.

What Netflix sacrificed. The simplicity of stateless licensing. They took on a stateful, event-sourced store with its own durability, replay and snapshot concerns, on a tight deadline, in a tier where failure stops playback. In return, rules can change without migrating state, and every decision has an audit trail.

Deep Dive: why event sourcing suits rule-heavy entitlement checksShow

State versus facts. A conventional design might store counters such as downloads_this_year = 7. When a studio adds "no more than 3 downloads of the same title in 30 days", that counter cannot answer the question, so you need a backfill. With an event log, you store facts such as "member M, device D, title T, licensed at time t", and each rule is a function over the events. A new rule is a new function, and it can be evaluated immediately against existing history.

Worked check. Member M asks to download title T at time t. The rules are: at most 4 devices with active downloads, at most 100 active downloads per member, and for this studio at most 3 licenses of T per 365 days (handbook's illustration). The service loads M's events, folds them into a small state (active devices, active downloads, licenses of T in the window) and evaluates each rule. With a few hundred events per member, the fold is microseconds of CPU. The cost is reading the events, which is why the series moves on to snapshotting: store the folded state at a known event position and replay only newer events.

Concurrency. Two devices can request licenses at the same moment and both pass the "4 devices" check. An event store usually prevents this with an expected-version append: "append only if the latest event for M is still version v". The loser re-reads and re-evaluates. That is optimistic concurrency, and it is what makes event sourcing safe for limits.

Cost of the choice. Reads are a fold, not a lookup. Schemas of events live forever, so they need versioning (the other topic the series names). And the log grows without bound unless old, irrelevant events are compacted into snapshots.

Lesson 40: Content popularity for Open Connect (2017)#

Assumptions. Open Connect is Netflix's own CDN. Its servers, Open Connect Appliances (OCAs), sit inside ISP data centres ("ISP servers") and at internet exchange points ("IX servers"). The catalogue is far bigger than the disk of most ISP clusters. Traffic is predictable day to day, and content can be pushed during off-peak hours (proactive caching). The goal is to serve each byte over the shortest network path.

What popularity means here. For the CDN team, popularity is how many times a piece of content is watched, computed as total bytes streamed from an asset divided by the asset's size. A half-watched film counts as half a view.

Three uses of a popularity ranking.

  1. Minimise network distance. Clusters close to users (ISP clusters) cannot hold the whole catalogue, so they hold only the most popular content.
  2. Organise server tiers. Large locations use two tiers: high-throughput flash servers, up to 100 Gbps, for very popular content, and high-capacity storage servers, 200 TB or more, for the long tail.
  3. Decide replication inside a cluster. A title is replicated over N servers, with N roughly proportional to its popularity.

Why keep several copies? Two things already reduce hot spots: routing by network proximity spreads regional demand across the network, and popular files are locked in memory, so disk I/O is never the bottleneck. Copies still matter for two reasons:

  • Balance (rocks versus pebbles). Content is spread over a cluster's servers with consistent hashing (see consistent hashing). Even with a good hash, if each hugely popular file lives on one server, the absolute traffic variance between servers is large. The authors' analogy: filling buckets with big rocks rarely yields equal weights, but filling them with pebbles does. Splitting a popular file into several copies turns one rock into pebbles. Balanced servers all hit peak load at the same total traffic, which maximises what the whole cluster can serve.
  • Resilience. If a server fails, its traffic should stay inside the same cluster rather than travel to a more distant location. So the most popular content always has several replicas in the cluster. Some mid-tier content is also replicated as insurance against sudden spikes, such as a celebrity going viral.

How much there is to place. Each title is encoded in many encoding profiles (some for iOS, some for a class of smart TVs), separate video, audio and subtitle profiles, several bitrates per profile, and multiple languages. So each combination of title, profile, bitrate and language becomes one or more files. One episode of The Crown needs about 1,200 files.

How effectiveness is measured.

  • Caching efficiency. For a cluster serving a traffic segment, the share of that segment's bytes the cluster itself served. It is measured per ISP network (what partners care about) and per cluster (for Netflix's own tuning). Higher efficiency close to users means fewer hops, better streaming quality, and lower transit cost for both ISPs and Netflix.
  • Content churn. How much content must be updated day over day. Updates happen off-peak, but less churn still means lower cost for ISPs and Netflix. It is a secondary metric.

How it is predicted. Future viewing is predicted from past viewing. Using only yesterday would be short-sighted and would cause unnecessary churn as popularity fluctuates, so several days of history are smoothed into the next day's prediction.

Granularity.

  • Title level. All files of a title are ranked together, so every bitrate and audio track of one session is guaranteed to be on one server. The cost is storing unpopular bitrates and profiles next to popular ones.
  • File level. Each file is ranked on its own. Files from one title end up in different parts of the ranking, and caching efficiency improves significantly. In 2016 most clusters moved from title level to file level and reached the same caching efficiency with 50% of the storage.
  • Regional. Popularity is also computed per region, on the assumption that members in the same country have similar tastes.

New titles. A title with no history is predicted from internal and external forecasts, normalised against organic predictions, sometimes adjusted for how heavily it will be marketed, and sometimes pinned high by human judgement to guarantee capacity on launch day.

Overlooked constraints.

  • The metric is bytes, not plays. Two titles with the same plays can have very different byte demand (4K versus mobile bitrates), and the CDN cares about bytes.
  • Prediction error has asymmetric cost. Under-predicting a launch means streams go to a distant cluster on the busiest night. Over-predicting just wastes a little disk. Hence human pinning for big launches.
  • Smoothing trades reactivity for stability. It reduces churn but reacts slowly to a sudden hit, which is why mid-tier content gets extra replicas.

What Netflix sacrificed. Session locality and reactivity. File-level ranking means one session's files may come from different servers. Smoothing means day-one surprises are absorbed by spare replicas rather than by the ranking. They accepted more complex placement to halve storage for the same efficiency.

Deep Dive: rocks and pebbles, and why file-level ranking halves storageShow

Variance of load. Put F files on S servers by hashing, and let file i draw traffic t_i. Server load is a sum of the t_i of the files it received. With random placement, the variance of one server's load is roughly (1/S)(1 − 1/S) × Σ t_i². The total traffic Σ t_i stays the same, but Σ t_i² is dominated by the biggest files. Split a file with traffic t into k copies of traffic t/k each, and its contribution to Σ t_i² falls from t² to k × (t/k)² = t² / k. So k replicas cut that file's variance contribution by a factor of k. That is the rocks-to-pebbles effect in one line.

Worked example. A cluster of 10 servers, each with 10 Gbps of headroom. One title draws 8 Gbps at peak, and the other traffic totals 60 Gbps, spread finely (handbook's illustration). With one copy, the server holding the title carries about 8 + 6 = 14 Gbps and is overloaded, while the others carry 6. With 4 copies, it adds 2 Gbps to each of 4 servers, so they carry 8 and the rest 6. Every server stays under 10 Gbps, and the cluster can serve all 68 Gbps.

Why file level wins. Popularity within a title is very skewed. Most streams of a title use a few bitrates and one or two audio languages, and many files (rare languages, old profiles) are almost never fetched. Title-level ranking forces every file of a popular title into the scarce near tier. Suppose a title's top 20% of bytes by file carry 80% of its traffic (handbook's illustration). File-level ranking can then fill the near tier with only the hot files of many more titles. Netflix's measured result, the same efficiency at half the storage, is what you would expect from that kind of skew.

Lesson 41: Distributing content to Open Connect, Heterogeneous Cluster Allocation (2017)#

Assumptions. Placement is recomputed daily. A cluster contains servers of different generations and types, and some have failed drives that have been disabled automatically, so even identical models end up with different usable disk. The popularity ranking from Lesson 40 is the input.

Placement goals. Put the most popular content on the cluster, load-balance it across servers, keep the allocation stable day over day and stable when servers join or leave, and keep the computation affordable.

Uniform consistent hashing. Imagine a ring of hash values. Each server ID is hashed onto the ring 1,000 times (1,000 "slices" or virtual nodes), and each server owns the arc before each of its points. Each content ID is hashed onto the ring and assigned to the owner of the arc where it lands. For R replicas, walk the ring to the next R distinct owners. This keeps churn low:

  • Adding or removing a title only touches the server that must download or delete it.
  • A new server adds 1,000 slices and takes content roughly equally from every other server. A removed server's 1,000 slices disappear, and its content spreads roughly equally to the rest.

Why uniform is not enough. Netflix runs two kinds of servers:

TypeDisksCapacityThroughput
StorageMostly spinning disks200 TB or moreAbout 40 Gbps
FlashAll SSDUp to 18 TBUp to about 100 Gbps

Small and medium ISP sites get storage servers only. IX and large ISP sites have a flash tier for most traffic and a storage tier that holds the whole catalogue. Newer revisions must serve alongside older ones. Uniform hashing gives every server equal weight, which goes wrong in two ways:

  • Different storage leaves "content holes". Take four 100 TB servers and one 50 TB server. Each gets one fifth of the ranked catalogue. The small one is full at the 250 TB mark of the ranking, so from 250 TB to 500 TB about one fifth of the content is simply not stored. A content hole can make a title unavailable from that cluster.
  • Different throughput cannot be mixed. The 2016 flash servers did 100 Gbps on 18 TB. Most production flash servers did 40 Gbps on 12 TB. Traffic follows storage under uniform hashing, a 3:2 ratio, but the servers' capacity ratio is about 5:2. So the new box would idle while the old one saturated.

Heterogeneous Cluster Allocation (HCA). Keep consistent hashing, but give each server a weight, implemented as the number of slices it puts on the ring. A single set of weights can match storage or throughput, not both. So HCA uses two rings:

  1. Stage 1 places the ranking from the top down to a cutoff depth D, the popular content, with one set of weights.
  2. Stage 2 places everything below D, the tail, with another set of weights.

Given each server's storage and throughput, the region's popularity curve and a candidate D, HCA solves an optimisation problem: either it finds weights for both rings that fill every server's disk without holes and draw traffic in proportion to throughput, or it reports that D is infeasible. In practice a wide range of D is feasible. Among them, HCA picks the D* that causes the least churn: a file near the cutoff can cross it from one night to the next, move to the other ring and change server. D* is the cutoff where that crossing is least likely.

Reconfiguration. Adding or removing an OCA can change D* or the weights and cause churn. Because only the ratio of slice counts matters, HCA can scale each ring's slice counts up or down to the values that cause the least movement.

Results. Content holes were substantially reduced and load balance improved significantly in clearly heterogeneous clusters.

Overlooked constraints.

  • Disk failures make every cluster heterogeneous. Even a fleet of one model drifts as drives are disabled, so a uniform scheme degrades silently over time.
  • Two objectives need two degrees of freedom. Weighted hashing has one knob per server. Matching storage and throughput needs two, hence the two rings.
  • The cutoff itself causes churn. Any boundary in a ranking that changes daily creates movement, so the boundary's position is part of the optimisation.

What Netflix sacrificed. Simplicity. Placement became an optimisation solved per cluster per day, with two rings and a tuned cutoff, instead of one ring with equal weights. They also accepted that some cluster and popularity combinations have no feasible configuration. In return, mixed hardware generations can share a cluster at full utilisation.

Deep Dive: solving a two-ring HCA by handShow

Two flash servers: A has 18 TB and 100 Gbps, B has 12 TB and 40 Gbps. Together they hold the top 30 TB of the ranking. Suppose the top 10 TB of that draws 80% of the cluster's traffic (handbook's illustration). Try cutoff D = 10 TB.

Let a1 be A's share of ring 1 and a2 its share of ring 2, so B gets 1 − a1 and 1 − a2.

  • Storage of A: 10 × a1 + 20 × a2 = 18.
  • Traffic of A: 0.8 × a1 + 0.2 × a2 = 100 / 140 ≈ 0.714.

From the first equation, a2 = 0.9 − 0.5 × a1. Substituting: 0.8 a1 + 0.18 − 0.1 a1 = 0.714, so 0.7 a1 = 0.534, giving a1 ≈ 0.763 and a2 ≈ 0.519.

Check B: storage 10 × 0.237 + 20 × 0.481 ≈ 12.0 TB, and traffic 0.8 × 0.237 + 0.2 × 0.481 ≈ 0.286, which is 40 / 140. Both shares lie between 0 and 1, so D = 10 TB is feasible. As slices, A could have 763 points on ring 1 and 519 on ring 2, with B at 237 and 481. Only the ratios matter.

Infeasible cutoffs. Repeat with D = 2 TB, where the top 2 TB draws 30% of traffic. The equations are 2 a1 + 28 a2 = 18 and 0.3 a1 + 0.7 a2 = 0.714. From the first, a2 = (18 − 2 a1) / 28. Substituting gives 0.3 a1 + 0.45 − 0.05 a1 = 0.714, so a1 ≈ 1.06, which is above 1. A cannot take more than all of ring 1, so this D is infeasible: too little traffic is concentrated above the cutoff to steer A's extra throughput. That is the feasibility check HCA performs for each candidate.

Uniform hashing for comparison. One ring with weights 18:12 would give A 60% of traffic, 84 Gbps of 140, against its 100 Gbps capacity, and B 56 Gbps against 40, so B saturates first and caps the cluster at about 100 Gbps instead of 140.

Lesson 42: Serving 100 Gbps from one Open Connect Appliance (2017)#

Assumptions. OCAs run FreeBSD and serve large media files with NGINX using the asynchronous sendfile() system call, which moves file pages straight into the network stack without copying them to user space. Clients hold tens of thousands of concurrent TCP connections per box. Most bytes come from disk. Only the hottest 10 to 20% of titles are served from RAM (Lesson 40). The goal, set in summer 2015: one server, 100 Gbps, on new 100GbE NICs and NVMe flash. The starting point was flash appliances that were CPU-limited at about 40 Gbps on a single-socket Xeon E5-2697v2.

This post is a case study in a method: measure, find the one bottleneck, remove it, repeat. Every step below was found with a profiler (pmcstat, flame graphs, DTrace lockstat, Intel PCM, Intel VTune), not guessed.

StepSymptomFixResult
1. Fake NUMAServing only from RAM dropped from 40 to 22 Gbps. Lockstat showed time spent waiting on the inactive page queue lockTell the kernel there is one NUMA domain per 2 CPUs, so there is one queue and one lock per pair52 Gbps, limited by the PCIe Gen3 x8 slot, with idle CPU
2. PbufsNew hardware (E5-2697v3, x16 slots, NVMe) stuck near 60 GbpsRaise kern.nswbuf, then make the vnode pager use the normal zone allocator instead of a global locked listAbout 70 Gbps
3. Proactive page scanningAbout twice a minute, memory ran out and every NGINX process slept while the pageout daemon worked, sometimes for secondsRun the pageout code lightly, several times a second per domain, inside the sendfile allocation pathAbout 80 Gbps, no stalls
4. RSS-assisted LROLRO aggregation rate about 1.1 packets because traffic came from tens of thousands of connectionsBatch received packets and sort by RSS hash (then arrival time) before LROAggregation over 2; over 90 Gbps unencrypted
5. TLS memory bandwidthTLS-only traffic stuck at 58 Gbps, CPU rising almost exponentially near the limit, no hot spot in flame graphsDiagnosed as memory-bandwidth bound with PCM and a copy benchmarkRe-focused on bytes moved
6. Non-temporal storesISA-L encryption read destination buffers too (32-byte AVX writes against 64-byte cache lines forced read-modify-write)ISA-L build with non-temporal stores; also DDR4-2400 instead of DDR4-186665 Gbps, then 76 Gbps
7. Cache-line dietVTune showed misses on rarely used struct fieldsRe-pack TCP structs, shrink 1980s-era longs; avoid reading ext_arg2 (usually NULL, alone on the third mbuf cache line) via a flag in the first lineAbout +1 Gbps from the mbuf trick alone
8. Stop measuring so hardExporting the full TCP table to count connections; detailed TCP stats on every connection used 5 to 10% CPUPer-CPU lockless counters per TCP state; detailed stats on a small sample of connections, under 1% CPU+3 to 5 Gbps
9. Mbuf page arraysAbout 8 million mbufs per second in flightNew mbuf type carrying up to 24 pages plus TLS header and trailer, so a TLS record goes from 6 mbufs to 1Under 1M mbufs per second, +7 Gbps

Where it ended in 2017. 90 Gbps of 100% TLS with the default FreeBSD TCP stack. With the more advanced RACK and BBR congestion-control stacks it was still a little short. Next ideas: tune the new TCP code, improve LRO further, and encrypt closer to the data path (from disk, or at the NIC) to exploit Intel DDIO (which lets devices write directly into the CPU's last-level cache) and save memory bandwidth.

The trap in step 1. Serving everything from RAM made things slower. Because NGINX told sendfile() that the pages would be needed again, almost every released page went to the inactive queue, one list per NUMA domain behind one mutex. The free-page pool already had a per-CPU cache, but the inactive queue could not simply be made per-CPU, because the system must find a page again later, and pages hash to per-domain queues predictably. The fix used that same hashing: create more domains, and therefore more locks.

The trap in step 3. The memory picture looked healthy at 15, 10 and 5 GB free, then fell to zero and the box served 0 Gbps while the pager ran. It got worse with more NUMA domains: each domain's pageout daemon tried to clear the global deficit, so with 16 domains each tried to clean the full amount. Doing a little work continuously, in one unlucky NGINX process at a time, turned a periodic stop-the-world into background noise.

The trap in step 8. Observability is not free. A connection count needed by the load balancer was produced by copying the whole TCP hash table under a lock. At tens of thousands of connections, the monitoring was competing with the serving.

Overlooked constraints.

  • Bottlenecks move. Each fix exposed the next: CPU, then PCIe slot, then locks, then memory bandwidth. A capacity plan based on the first bottleneck is wrong.
  • Memory bandwidth is the real budget for TLS. Encryption touches every byte at least twice (read plaintext, write ciphertext), so 100 Gbps of TLS needs about 25 GB/s of page traffic before any overhead.
  • Changing a core data structure touches every driver. Unmapped page-array mbufs panic any code that uses mtod() to access mbuf data directly. Netflix had to add accessors across the stack, teach busdma about the new type, and audit every NIC driver in its fleet.

What Netflix sacrificed. Using a stock kernel. They carried deep kernel changes (Fake NUMA, allocator changes, new mbuf types, custom LRO), many contributed upstream to FreeBSD, plus vendor-specific work with Mellanox and the Intel ISA-L team. They also gave up full per-connection TCP statistics, keeping only a sample. In return, one box replaced two or more, at a huge saving in rack space, power and ISP goodwill.

Deep Dive: the mbuf arithmetic at 100 GbpsShow

Bytes. 100 Gbps is 12.5 GB/s of payload. With TLS, every page is read once to encrypt and written once as ciphertext, so about 25 GB/s of 4 KB pages move through memory.

Mbufs per second. 25 GB/s divided by 4 KB per page is about 6.1 million page mbufs per second, which the post rounds to 6.25 million. TLS records are up to 16 KB, so 12.5 GB/s is about 0.78 million records per second. At 2 extra mbufs per record for header and trailer, that adds about 1.6 million per second. The total is about 8 million mbufs per second.

Cache traffic just for metadata. At about 2 cache lines (128 bytes) touched per mbuf, at each layer that handles it (allocate, free, crypto, TCP, socket buffer, driver), 8M × 128 B is about 1 GB/s (8 Gbps) of metadata traffic, multiplied by the layers. On a box whose limit is memory bandwidth, that is real throughput lost.

After page arrays. One mbuf carries up to 24 pages plus the TLS header and trailer, so a 16 KB record of 4 pages is 1 mbuf instead of 6. Traffic falls to under 1 million mbufs per second, about 8× less metadata, and the measured gain was about 7 Gbps.

The 32-byte write problem. A CPU writes memory in 64-byte cache lines. A 32-byte AVX store to a line that is not in cache forces the CPU to read the full line first (read-modify-write), even though the next instruction will overwrite the other half. For an encryption output buffer, that adds a 64-byte read for every 64 bytes written, which matches the "half again as much reading as writing" seen in VTune. Non-temporal stores write around the cache and skip the read, worth 58 to 65 Gbps here.

Lesson 43: High-quality video encoding at scale (2015)#

Assumptions. Netflix receives high-quality sources from its own productions and from content partners, and must produce the best stream for each device and bandwidth. Throughput needs to grow with the business: more titles, more encodes, and faster time to launch (some titles go live hours after their original broadcast). Compute is elastic: the pipeline runs on EC2 Linux with no special hardware, and borrows idle capacity from an internal spot market of instances that are not in use by autoscaled services at that moment.

The pipeline. Ingest the source, inspect it, encode it in many codec profiles at several quality levels each, package, deploy to the CDN, and let the client switch between quality levels during playback with adaptive bitrate.

Reject bad sources instead of repairing them. A source can carry artefacts from earlier transcoding, corruption in transfer or storage, or human error in production. Garbage in means garbage out. Netflix chose to reject and request redelivery rather than conceal errors after ingest, for four reasons:

  1. The best possible source enters the system. Repair techniques often only half work.
  2. The ingest pipeline is not burdened with complex algorithms that a better upstream process would make unnecessary.
  3. Problems are caught early, with a specific, actionable error.
  4. Partners are pushed to fix the root cause in their own pipelines, so future deliveries improve.

The preferred format is Interoperable Master Format (IMF), and ProRes, DPX and MPEG (for older material) are also supported. Inspection does three things: checks conformance to the relevant specs, detects content that would look bad to viewers, and generates metadata the encoders need. A failed inspection automatically notifies the partner with the issues.

Chunking makes big files tractable. A modern 4K source can be larger than the local disk of a typical EC2 instance. So the first step only indexes the file (byte offsets for frame-accurate seeking, resolution, frame count). Then chunks are inspected in parallel on different instances, with bitstream-level and pixel-level analysis that also produces temporal and spatial fingerprints. An aggregator combines the results. A 4K source is inspected in under 15 minutes, and because longer sources simply have more chunks, the time does not grow with duration.

Parallel encoding. In 2015 the profiles were VC1, H.264/AVC Baseline, H.264/AVC Main and HEVC, for members ranging from under 0.5 Mbps cellular to over 100 Mbps broadband, at bitrates from 100 kbps to 16 Mbps. Encoding also works on chunks:

  • Each chunk is verified as soon as it finishes, so problems are triaged (or transient failures resubmitted) without waiting for the whole video.
  • An assembler stitches the chunks.
  • The assembled stream's fingerprints are compared with the source's, to catch parallelism bugs: chunks in the wrong order, or frames dropped or duplicated at chunk boundaries.
  • Full-reference quality metrics (comparing each encode with the source) are computed for every stream, to monitor quality at scale, find bugs and improve encoding recipes.

Results.

  • Before chunking, a 1080p film could take days to encode, and a failure late in the run cost even more. Now a title is inspected and encoded, with automatic QC, in a few hours, and the target was 30 minutes or less for 1080p.
  • Before automated checks, problems such as corrupt pictures, inserted black frames, frame-rate conversion errors, interlacing artefacts or frozen frames could go unnoticed until members reported them to Customer Support, and triage bounced between many teams. With automated inspection, problems are caught early, whatever the cause (bad delivery, a code bug or a glitchy cloud instance).
  • For sources that pass inspection, encode reliability is 99.99% or better. Each problem that slips through becomes a new inspection.

The same pipeline, plus spot-market capacity, runs large experiments: codec comparisons, recipe tuning and quality-metric design.

Overlooked constraints.

  • Spot capacity can vanish. Small tasks mean an abruptly terminated instance loses only a little work, which is then rescheduled. Chunk size is set by how much lost work you can tolerate, not only by parallelism.
  • Parallelism creates its own bugs. Chunk boundaries are where frames get lost or duplicated, so the pipeline needs an end-to-end check (fingerprints) that is independent of the chunking logic.
  • Upstream quality is a people problem. The reject-and-redeliver policy works only because Netflix has the leverage to make partners redeliver.

What Netflix sacrificed. Time to launch for bad sources (a redelivery can take days) and compute efficiency (inspection, verification, fingerprints and quality metrics on every chunk cost extra CPU on top of encoding). In return, failures surface in minutes with a clear owner, instead of weeks later through member complaints.

Deep Dive: why chunking turns days into hours, and what it costsShow

Latency. A 2-hour 1080p film encodes at, say, 0.25× real time on one instance, so one profile and bitrate takes 8 hours. Ten bitrates across four profiles is 40 encodes, 320 instance-hours (handbook's illustration). Done linearly on one machine, that is 13 days. Split into 2-minute chunks, there are 60 chunks per encode, 2,400 tasks of about 8 minutes each. With 1,000 spot instances, that is 3 waves, roughly 30 minutes plus inspection, assembly and QC. The total CPU is the same. What changes is the critical path.

Cost of chunking. Each chunk needs a few seconds of overlap or a fresh key frame at its start, which costs a little compression efficiency at boundaries, and there are seek, upload and scheduling costs per task. With 2-minute chunks and 1-second overhead per chunk, the overhead is under 1% (handbook's illustration). Very small chunks raise both overhead and boundary artefacts.

Failure cost. Suppose each instance-hour has a 2% chance of being reclaimed by the spot market. A monolithic 8-hour encode then has 1 − 0.98⁸ ≈ 15% chance of being interrupted, and on average loses about 4 hours when it is. An 8-minute task has about a 0.3% chance and loses about 4 minutes. Chunking makes preemptible compute usable, which is the economic reason the pipeline can live on the internal spot market.

Reliability arithmetic. At 99.99% encode reliability and, say, 10,000 encodes a day, about 1 encode a day fails after inspection, and that one becomes the next inspection rule.

Lesson 44: Rebuilding the video processing pipeline with microservices, Reloaded to Cosmos (2024)#

Assumptions. The pipeline went live with streaming in 2007. Since then it has grown from SDR standard definition to 4K and HDR, from centralised linear encoding to distributed chunk-based encoding (Lesson 43), from a fixed pool of dedicated instances to the internal trough left by autoscaled microservices, and added per-title and per-shot encoding optimisation, integration with studio content systems (which enabled things like interactive storytelling), and studio use cases whose latency and resilience needs differ from streaming. The team changes its algorithms often, so the cost of a change matters more than raw throughput.

Reloaded, the third-generation platform (2014). Reloaded was stable, scalable and reasonably flexible, and many encoding innovations were built on it. But it was designed for one use case: turn studio mezzanines (high-quality master files) into compressed streaming assets. It was one monolithic system in which several media teams and the platform team shared one codebase. As use cases piled on, three problems grew:

  • Coupled functionality. Adding a new module and wiring it into orchestration was a lot of work, so people extended existing modules instead. Example: video quality calculation lived inside the encoder module, so recomputing quality without re-encoding was extremely hard.
  • Monolithic structure. Modules shared a repository, so code-isolation rules were easy to ignore. Unintended reuse across what should have been strong boundaries created tight coupling, which then forced all modules to deploy together.
  • Long release cycles. A joint deploy was scary, because debugging and rolling back something that big is hard. So there was a release train: every two weeks a snapshot of all modules became a release candidate, then about two weeks of exhaustive testing. A merged change took two to four weeks to reach production.

Over time the rate of new features fell and promising ideas were abandoned because the architecture made them too expensive.

Cosmos (from 2018). Cosmos is a computing platform for workflow-driven, media-centric microservices. It keeps Reloaded's scalability and stability and adds strong decoupling between services, per-service workflow support for complex media logic, and abstractions so that algorithm developers work on signals, not infrastructure.

Finding service boundaries. The team mapped every processing step from creation to ingest to delivery and grouped steps by domain. The test case was Reloaded's encoder, which bundled five steps: split the input into chunks, encode each chunk, compute VMAF (Netflix's perceptual video-quality metric) for each chunk, assemble the chunks, and aggregate the scores. The output callers care about is the assembled encode. Chunking exists only to meet latency and resilience goals, so it is an implementation detail. Quality measurement is a different function. So the bundle became two services: the Video Encoding Service (chunking and assembly hidden inside) and the Video Quality Service.

The same analysis across the pipeline produced these services (the post notes there are more, which are Netflix-specific):

ServiceInputOutput
Video Inspection Service (VIS)MezzanineMetadata from every layer; flags invalid or unexpected metadata with actionable feedback upstream
Complexity Analysis Service (CAS)MezzanineContent-complexity data, using VES for pre-encodes and VQS for scores, stored for reuse
Ladder Generation Service (LGS)Codec family, e.g. H.264 or AV1A full bitrate ladder of encoding recipes, optimised from CAS data
Video Encoding Service (VES)Mezzanine + recipeEncoded video; options to trade latency against throughput
Video Validation Service (VVS)Encode + list of expectationsDiscrepancies against the recipe and the codec specification
Video Quality Service (VQS)Mezzanine + encodeVMAF score

Separating LGS from CAS splits the ladder-optimisation algorithms (per-title, mobile, per-shot and optimised 4K work) from the creation and management of complexity data, so the algorithms can be experimented with freely.

Orchestration per use case. Each use case has its own workflow orchestrator:

  • Streaming Workflow Orchestrator. Assets will be watched millions of times, so it uses almost every service: VIS to reject non-conformant or poor mezzanines, LGS for recipes, VES to encode and VQS for quality, whose data also feeds analytics and monitoring. It also calls audio, timed-text and packaging services.
  • Studio Workflow Orchestrator. Marketing clips and daily editorial proxies are latency-sensitive: someone may be waiting for a proxy to plan the next day's shoot. It optimises for fast turnaround, calling VIS for metadata and VES with predefined recipes. It is the only user of some features, such as forensic watermarking and timecode or text burn-in.

Migration. The new pipeline ran alongside Reloaded in production for a few years. The team migrated every needed function, shifted traffic one use case at a time, and completed the switchover in September 2023 (the same strangler approach as Lessons 35 and 36).

Payoff. The ad-supported plan launched in November 2022. Ad creatives come in very different media formats from films and series, with new business-driven processing requirements. Cosmos's modularity let the team iterate the pipeline quickly enough to keep up with changing requirements for the launch.

Overlooked constraints.

  • Boundaries should follow what callers need, not how the work is done. Chunking is how encoding meets its latency goal. Exposing it as a service would have leaked an implementation detail into every caller.
  • Different users need different orchestration, not different services. Streaming wants maximum quality, and studio wants speed. Sharing services while splitting orchestrators avoids a single workflow full of if-statements.
  • The monolith's release train was a symptom. Two to four weeks of lead time came from shared deploys, which came from coupling. Splitting the deploy unit fixed the lead time only because the coupling was removed first.

What Netflix sacrificed. Years of running two pipelines in parallel. Network hops and serialisation between services that used to be in-process calls. And a platform team's investment in Cosmos itself. They traded those for independent deploys, the ability to recompute quality without re-encoding, and feature velocity. See microservices patterns for the general trade-off.

Deep Dive: what a release train costs, and a test for a service boundaryShow

Lead time. With a snapshot every 2 weeks and 2 weeks of testing, a change merged just after a snapshot waits 2 weeks for the next one and then 2 weeks of testing: 4 weeks. A change merged just before a snapshot waits about 2 weeks. The average is about 3 weeks. If an engineer needs 5 iterations to tune a new encoding idea in production, that is about 15 weeks, a full quarter (handbook's illustration). With independent services deploying daily, the same 5 iterations take about a week. That difference is why "promising ideas were abandoned".

A boundary test drawn from the VES and VQS split. Ask of each candidate step:

  1. Does a caller want its output on its own? Quality scores without a re-encode: yes, so VQS is a service. Encoded chunks: no, so chunking stays inside VES.
  2. Does it change for a different reason or at a different rate? Ladder algorithms change with research, and complexity data changes with content, so LGS and CAS are separate.
  3. Does it have different scaling or latency needs? Encoding is CPU-heavy and parallel. Validation is a lighter pass, but it must always run, so VVS stands alone.
  4. Would two use cases call it with different settings? VES serves both streaming and studio, with latency and throughput options, rather than two encoders.

A step that fails all four stays inside its neighbour. This is a practical version of the domain-driven idea of a bounded context: draw lines where the language and the reasons for change differ.

Lesson 45: Three years of Live at Netflix, the foundations (2025)#

Assumptions. Live started with one question three years earlier: how would Netflix do a format as old as television? The first target was the comedy special Chris Rock: Selective Outrage (2023), nine months away. Since then there have been hundreds of live events, from comedy and NFL Christmas games to record-breaking boxing and WWE. The service has over 300 million subscribers. Live is unlike on-demand in every way that matters to infrastructure: content cannot be pre-positioned overnight (Lesson 40), demand arrives as a spike at the start time, every viewer wants the same few seconds of video at once, and there is no time to debug during the event.

The guiding principle. Netflix builds for one product and controls the whole lifecycle, from production to screen. That lets it choose each piece for its own needs instead of for a generic broadcaster.

The pillars.

  1. Dedicated broadcast facilities. Events happen in venues with poor connectivity. Feeds go to well-connected Broadcast Operations Centers with gear for signal ingest and inspection, closed captions, graphics and ad management. Heavy automation means the only event-specific setup is the link from the venue to the broadcast centre. Everything after it is reused.
  2. Cloud transcoding and packaging, redundant. The cloud gives elastic scale, flexible configuration and easy integration with DRM, content management and delivery services that already run there. AWS MediaConnect and AWS MediaLive acquire and transcode the feed into a per-show bitrate ladder. Netflix built its own packager and its own Live Origin, which has strict read and write SLAs (Lessons 46 and 47).
  3. Delivery over Open Connect. Segments travel from a few AWS locations to devices over Open Connect: 18,000+ servers in 6,000+ locations, at IXs or inside ISPs, linked to 5 AWS regions by the dedicated Open Connect Backbone. That builds on over $1 billion of investment over 12 years. Sharing servers between on-demand and live raises utilisation, and keeping past live segments on the same servers gives catch-up viewing almost for free.
  4. Playback tuned for compatibility. Netflix chose HTTPS-based live streaming over UDP-based protocols. UDP could offer ultra-low latency, but HTTPS works on practically every device and with existing delivery and encoding systems. Codecs are AVC and HEVC, with quality levels from SD to 4K, and 2-second segments balance compression efficiency, infrastructure load and latency. Latency from camera to device is at industry standard and improving.
  5. Discovery and playback control in the cloud. Dozens of services (playback configuration, personalisation, metrics) see disproportionate load at start time. The cloud scales them, and because live demand is regional, load is spread across several AWS regions.
  6. Real-time metrics. Netflix controls ingest, encoding, CDN and players, so it sees almost the whole path. Atlas, Mantis and Lumen (internal) plus Kafka and Druid process up to 38 million events per second during the largest events, with insights in seconds. A dedicated Control Center room brings the key metrics to the operations team.

The manifest trick. At play start, the player gets a manifest with bitrates and CDN servers to use. It comes from the cloud, not the CDN, so it can be personalised per device. Instead of listing segments (which would force players to re-fetch the manifest every few seconds), it contains a segment template: a rule that maps wall-clock time to a segment URL on the CDN. No polling means fewer network dependencies, less CDN load and less work for weak devices like smart TVs. During playback the player keeps choosing bitrate and CDN server from measured network performance.

Lessons learned.

  • Testing without real traffic. On-demand had a steady flow of traffic for canaries and A/B tests. Live traffic often is not there, at least not at launch scale. So Netflix built internal test streams for integration, regression and smoke tests, and synthetic load of up to 100,000 starts per second, using two methods: replaying modified past live traffic (real device and request diversity) and virtualised Netflix devices hitting CDN or cloud endpoints. It also runs automated failure injection: missing or corrupt segments, loss of a cloud region, network drops and server timeouts.
  • Regular practice. Nothing beats production. A regular schedule of varied live content lets the team run A/B tests, chaos tests and operational drills, and train operators, with bounded member risk.
  • Viewership prediction. Forecasts pre-provision cloud and CDN capacity and are shared with ISPs and cloud partners in advance. Reactive scaling of sign-up, login, discovery and playback covers the excess. Real-time forecasts during the event let operators act before more members are affected.
  • Graceful degradation. Viewership has exceeded predictions. Levers include service-level prioritised load shedding (live traffic beats non-critical work such as prefetch), then lightening the experience: less personalisation, no bookmarks, and a lower maximum streaming quality. Load tests deliberately under-scale systems to check that these levers work.
  • Retry storms. At capacity, the danger is retries making it worse. Members also retry by hand: a viewing interruption of as little as 30 seconds produced 10× the load from stream restarts. Responses: server-guided backoff for device retries, prioritised shedding at the Cloud Edge Gateway, and re-balancing between regions.
  • Contingency planning. There is no time to troubleshoot. Big events get in-person launch rooms with owners of critical systems, a small set of early-indicator metrics, extensive runbooks, and Game Day rehearsals. The runbooks go beyond engineering: escalation to executives and coordination with Customer Service, Production, Communications and Social.
  • After the show. Data & Insights analyses each event. A/B tests cut latency by about 10 seconds without hurting quality or stability.

Overlooked constraints.

  • The start time is a synchronised thundering herd. Millions press play within a minute, and every dependency (login, discovery, manifest, license) sees the peak at once.
  • Humans are part of the retry loop. Device retry policy is not enough, because a frustrated member restarting the app is a retry the server cannot shape, except by recovering fast and guiding the client.
  • You cannot canary a one-off event. The first time a system sees real load is the event itself, so test streams, replay and synthetic devices have to stand in for canaries.

What Netflix sacrificed. Lowest-possible latency. They chose HTTPS segments over UDP for reach and stability, accepting broadcast-like delay. They also accepted degrading features (personalisation, bookmarks, top quality) to keep streams up, and bore the cost of dedicated facilities, launch rooms and rehearsals. The reward is reusing a decade of on-demand delivery investment for a completely different traffic shape.

Deep Dive: segment templates and retry-storm arithmeticShow

Template maths. With a constant segment duration d = 2 s, availability start time T0 and start number N0, the segment a player should fetch at wall-clock time t is N = N0 + floor((t − T0) / d). Its URL is the template with N filled in. A player 20 s behind the live edge fetches N − 10. Nothing has to be polled, and every player, OCA and the origin compute the same N for the same moment. That is also what lets the origin and CDN reject requests for segments that cannot exist yet (Lesson 47).

Why polling would hurt. With 10 million viewers each refreshing a manifest every 2 s, that is 5 million manifest requests per second just to learn the next segment number (handbook's illustration). With templates, that load is zero.

Retry storm. Steady state: 20 million viewers each fetch one segment per rendition every 2 s, about 10 million segment requests per second at the edge (handbook's illustration). A 30-second interruption makes, say, a third of viewers restart, so about 6.7 million new playback starts arrive in a minute instead of a trickle. Each start needs a manifest, a license and other calls. If the normal start rate is 10,000 per second, the post's 10× load is easy to reach.

Server-guided backoff. If the server tells each client to wait a random time between 0 and W before retrying, the retry rate is about (failed clients) / W. With 6.7 million clients and W = 60 s, that is about 110,000 per second, which capacity can absorb, instead of millions in the same second. Jitter turns a spike into a ramp. See resilience patterns for retry budgets and backoff.

Lesson 46: Building a reliable cloud live streaming pipeline (2025)#

Assumptions. When Live began there was no broadcast infrastructure for acquiring, inspecting, processing and delivering feeds, and it was not even clear how or where feeds would arrive. The pipeline had to reach as many Netflix devices as possible on day one and meet industry standards for quality and latency. With many unknowns, the team preferred tools already on Netflix's paved path or familiar to them.

Acquisition in the cloud. The team built acquisition and processing in the cloud, assuming feeds would somehow get there. For the first comedy special, the venue had two diverse dedicated internet access (DIA) circuits, carrying a UHD mezzanine feed in HEVC at 50 Mb/s. That direct venue-to-cloud path worked for the first shows but did not scale, because every venue is different. So they moved to hub and spoke: production feeds are gathered at a well-connected broadcast facility, which then sends them to the cloud.

Redundancy at ingest. Cloud ingest runs in two regions, each fed through two separate managed network paths (not the open internet). That is four independent copies of the feed. SMPTE 2022-7 seamless protection switching merges two paths packet by packet, choosing the best packet in real time. If one path loses packets or fails completely, the output does not glitch. This has worked flawlessly in practice. AWS Elemental MediaConnect handles the 2022-7 processing, redundancy, failover and monitoring.

Encoding. The cloud encoder produces segmented streams with an adaptive bitrate ladder. The Video Algorithms team tunes the ladder by resolution, frame rate and content complexity: high-motion events like WWE get more bits, to match on-demand quality. Outputs cover old and new devices: video in AVC and HEVC, audio in HE-AAC and Dolby Digital Plus 5.1 at several bitrates, multiple audio languages, and captions in WebVTT and TTML/IMSC.

Epoch locking and REaP. Two pipelines are only useful if their outputs are interchangeable: segment 1234 from pipeline A must start and end on exactly the same frame as segment 1234 from pipeline B, so the origin can serve either. Netflix follows ISO/IEC 23009-9, DASH Part 9: Redundant Encoding and Packaging for Segmented Live Media (REaP). The two pipelines never talk to each other. Instead:

  • Encoder and packager use the same constant average segment duration.
  • The venue's contribution encoder stamps UTC timecode into every frame using SEI (Supplemental Enhancement Information) messages.
  • The cloud encoder maps frames to segments deterministically from those timecodes ("epoch locking"), so both pipelines cut at the same frames.

A custom packager, for three reasons.

  1. Device compatibility. Netflix supports millions of devices across hundreds of categories, vendors and software versions. Getting stream formats right for them took years of adjustments and large field tests. Reusing the on-demand (SVOD) packager's proven formula in the live packager avoided repeating those tests.
  2. Captions. Devices consume IMSC or WebVTT text segments in Netflix-specific ways that third-party packagers did not support.
  3. DRM. The SVOD packager was already integrated with Netflix's security back end for key generation, segment encryption and packager authentication, and the live packager reuses that.

The packager also produces the segment template metadata and submits it to PlayAPI, which builds the personalised manifests (Lesson 45). So live needed no major change to the manifest back end.

Origin, first version. Segments first went to static storage buckets, one per AWS region. Each packager cross-published to both buckets, giving four candidates per segment, and the CDN applied its own fallback order. Problems appeared quickly:

  • Latency variance. Publish latency sometimes reached seconds, which is terrible when a segment lasts 2 s.
  • Throttling. With concurrent events and over 100 RPS per event, publishes were throttled, and sometimes failed in both regions at once.
  • Blind choice. Often one copy was fine and the other was defective, but a plain bucket cannot tell them apart.

That led to a media-aware Live Origin built with the Data Storage team on the key-value platform (Lesson 47).

Orchestration. A small team meant automating everything. An orchestration service configures pipelines per event from content and production requirements: Selective Outrage in UHD at 30 fps, and back-to-back NFL Christmas games in HD at 59.94 fps, with four audio languages, ads, and an automatic move of viewers from one game to the next. It configures ingest, encoders, packagers, origin and monitoring, which removes human error. It creates redundant pipelines in separate regions for each event, chosen by production location, and guarantees identical configurations so segments are interchangeable. It provisions and deprovisions instances by the event schedule, which saves cost. It spins up test events with new ladders, codecs or components (such as Netflix's own captions service). Some real-time actions go through it too: setting lookback and DVR windows, timing transitions between events, and manual encoder operations during incidents.

The control plane is hub and spoke. A central hub manages resources, permissions and storage. Each component (encoder, packager, origin) is a spoke with its own tasks. State is tracked by pub-sub plus polling. The control plane runs in several regions, and each regional deployment can orchestrate the whole global footprint.

Control Room. Off-the-shelf tools did not scale, and at first the developers themselves ran the events, so they built Control Room, a UI over the orchestrator. An event has three phases: pre-event setup, encoding (including on-air), and post-event clean-up. Early on, setup and teardown were manual in Control Room, because the live event schedule was a new concept with no mature metadata, unlike on-demand. During the transmission window (the broadcast plus time beforehand for signal checks), one action starts the pipelines in both regions. Operators see venue and cloud feeds side by side, and can fail over to the healthy region within a few seconds. Because live events have no fixed end, the operator starts the end sequence by hand: clients are told to exit the player, and the end of the DVR window is marked for later on-demand viewing.

Overlooked constraints.

  • Redundancy without coordination needs determinism. Two pipelines that talk to each other share failure modes. REaP keeps them independent by making their outputs identical by construction, through timecodes and a fixed segment cadence.
  • Device compatibility is accumulated knowledge. Years of field tests are encoded in the packager. Buying a generic packager would have meant relearning them under a nine-month deadline.
  • Generic object storage is not a live origin. It meets its uptime SLA but not a 2-second latency budget, and it cannot judge media quality.

What Netflix sacrificed. Build versus buy. They wrote their own packager, origin, orchestrator and Control Room, and paid for four-way redundant ingest and two full pipelines per event, roughly double the encoding cost. They also kept some manual operation (event end, failover) because live is unpredictable. In return, one broken path, region or encoder does not reach viewers.

Deep Dive: how much redundancy four paths and two pipelines buyShow

Ingest. Suppose each managed path independently has a 1% chance of a serious problem during an event (handbook's illustration). With 2022-7 merging two paths, a region loses its feed only if both fail: 0.01² = 0.0001. With two regions, the event loses ingest only if all four fail: 0.01⁴ = 10⁻⁸. Real failures are correlated (same facility, same uplink provider), which is why the paths are diverse, and why the venue-to-facility link remains the single point that cannot be fully duplicated.

Seamless versus switch-over. 2022-7 is not failover after detection. It is packet-level selection: for each packet sequence number, take whichever copy arrives intact. So there is no switch-over gap. Ordinary failover needs detection time (say 1 to 3 s) plus a resync, which is one or two lost 2-second segments.

Epoch locking. At 59.94 fps, a 2-second segment holds about 120 frames. If pipeline A cut at frame 120 and pipeline B at frame 119, segment N from A followed by segment N+1 from B would duplicate or skip a frame, and the player would glitch. Deterministic cuts from UTC timecodes keep segment boundaries identical, so the origin can mix sources segment by segment.

Cost. Two full encode pipelines, each producing perhaps 10 video renditions in two codecs plus audio and captions, roughly double the per-event cloud bill, and four managed paths cost more than one internet link. For an event watched by tens of millions, avoiding even a minute of outage is worth it.

Lesson 47: Netflix Live Origin (2025)#

Assumptions. The origin sits between the cloud packagers (upstream) and Open Connect (downstream) and decides what content reaches the CDN. Segments are 2 seconds long, so a write that takes a second is a crisis. The peak so far was 65 million concurrent streams for the Tyson vs Paul fight in 2024. Each event has many renditions: several video formats each with its own ladder, many audio options (languages, formats, bitrates), and versions with and without ads. Several events can run at once.

The interface is plain HTTP. The packager PUTs each segment to a URL. Open Connect GETs the same URL. The origin is a multi-tenant microservice on EC2. Two earlier design decisions shape it. Epoch locking (Lesson 46) means the origin can pick a segment from either pipeline, so failover happens on the server and clients stay simple. Segment templates with a constant duration mean the origin can predict when every segment should arrive.

Choosing between pipelines. Live streams have defects, because contribution feeds are unpredictable and publishing deadlines are strict:

  • Short segments: missing video frames or audio samples.
  • Missing segments: the whole segment never arrives.
  • Timing discontinuities: a wrong Track Fragment Decode Time, the timestamp that tells the player where the segment sits on the timeline.

A template-based manifest has no way to tell clients about a discontinuity, so a defect can break playback. The two pipelines are independent, so simultaneous defects are rare. The packager does lightweight media inspection and attaches the defect information as metadata when it publishes. On a GET, the origin checks candidates in a deterministic order and serves the first valid one. If both are bad, which is rare, it passes the defect information downstream so the client can conceal the error.

Working with Open Connect. Open Connect had been tuned for on-demand for years: nginx on FreeBSD, and assets pre-positioned on OCAs rather than filled on demand, which makes it more a distributed origin than a classic CDN. A separate on-demand fill path, with its own nginx server block and hostnames, served small objects such as artwork and client downloads. Live fit neither model, so Netflix extended nginx's proxy caching:

  • Reject impossible requests at the edge. OCAs receive the same segment templates as part of the Live Event Configuration. From the availability start time and initial segment number, an OCA knows the valid segment range at every moment, and drops anything outside it before it climbs the fill hierarchy.
  • Cacheable 404s. If a request for a not-yet-published segment reaches the origin, the origin returns 404 with an expiry that lets Open Connect cache the 404 until just before the segment is due.
  • Hold-open at the live edge. For the very next segment, the origin does not return 404. It holds the request open and answers as soon as the segment is published, which removes a lot of early-request chatter.
  • Millisecond caching. HTTP Cache-Control works in whole seconds, which is long when segments arrive every 2 s. Netflix added millisecond-grain caching to nginx.

Event notifications in headers. The pipeline gives the origin event notifications, which the origin adds as HTTP response headers on segments from that point on. They are cumulative. Each OCA extracts them into an in-memory structure keyed by event ID, and attaches the latest notifications to every response it serves, even for segments behind the live edge. So every client learns about stream events whatever its playback position, in a highly scalable way.

Invalidation and masking.

  • Whole-event flush. A version number in the cache key can be bumped to "flush" every object of an event. This resets the network to a clean state between pre-event tests.
  • Targeted invalidation. Each segment records which pipeline produced it and which region it was requested from. Operators can invalidate a range of segment numbers only from encoder A, or only from encoder A as fetched via region X.
  • Origin masking. The origin can exclude a segment range from one pipeline when serving Open Connect. Together with targeted invalidation, known-bad segments are hidden from millions of clients for the whole DVR window.

Storage, first S3, then a database. S3 met its uptime guarantees, but live's 2-second retry budget, where every write is critical, called for something closer to a global, low-latency, highly available database. The requirements:

RequirementTarget
HA writesClose to full write availability in a region, replication to other regions within seconds; any write failing within 500 ms is a bug to be triaged and prevented
ThroughputHundreds of MiB per second replicated across regions
Large partitionsWrites of about a MiB each, about 10,000 keys per partition, about a GiB per event
Strong consistencyRead-your-writes in-region, so a published segment is readable in under 1 s
Origin stormGigabytes per second of reads in the worst case, without affecting writes

Netflix's KeyValue abstraction over Apache Cassandra already did chunked storage of MiB- or GiB-sized values. It was first built for game cloud saves. Live pushed it on write availability, partition size and read throughput.

  • Writes. The chunking and compression algorithm splits each value into parts that can each be idempotently retried and hedged (sent twice, keeping the faster answer), and spreads them over the whole cluster. Cassandra's LOCAL_QUORUM keeps writes available even through the loss of a whole availability zone, and its LSM engine is write-optimised (see storage engines). The result: the new system's P99 matched the old system's P50, with cross-region replication handled behind the scenes. It is significantly more expensive (SSD-backed databases cost more), and that was accepted, because cost was not the goal.
  • Reads. In an origin storm, dozens of top-tier OCAs may fetch several MiB segments at once, and the team's estimate was on the order of 100 Gbps. Careful chunk-access tuning got Cassandra to serve at line rate, but concurrent writes suffered. The fix was a write-through cache of chunks in EVCache (memcached-based). Almost all reads hit the cache, reaching 200 Gbps and beyond with no impact on writes: read-write separation.
  • Clean-up. Old segments are removed through the WAL's delay queue (Lesson 28).

Scaling without an origin shield. Many CDNs put an origin shield (a mid-tier cache) in front of the origin. Netflix instead made the origin itself scale, for tighter end-to-end cache-consistency control and a simpler system. The origin connects directly to top-tier Open Connect nodes at several sites, and only designated nodes per rendition per site may fill from it, which caps fan-in. EC2 autoscales, but storage capacity and AWS-to-Open Connect backbone bandwidth do not. So the origin protects itself:

  • Publishing isolation. Publishing is predictable, and CDN retrieval can surge. They get separate EC2 stacks, separate KV clusters for reads and writes, and at the bottom separate paths: EVCache for reads, Cassandra for writes. A retrieval storm cannot slow publishing.

  • Priority rate limiting. Under storage stress, live-edge requests beat DVR requests, using the platform's priority rate limiter. Live edge versus DVR is decided from the segment template cached in memory, so classifying a request needs no datastore access, which matters exactly when the datastore is stressed. Rejected low-priority requests get HTTP 503 with max-age=5s, so Open Connect caches the rejection and does not retry identical requests for 5 seconds. In tests, only the low-priority class saw failures while P99 latency stayed under control.

  • 404 storms. Requests for segments that do not exist are handled using the hierarchy event, then rendition, then segment:

    • Unknown event: 404.
    • Known event, but the timing does not match the publishing schedule: 404 with a TTL up to the expected publish time.
    • Segment never produced, or past its retry deadline: 410 Gone, so clients stop asking.

    Metadata lives in a separate control-plane datastore that deliberately has no distributed cache, to avoid inconsistency. Each origin instance caches event and rendition metadata in memory, with a hit ratio over 90% during 404 storms. This complements the media cache.

Overlooked constraints.

  • Not every request matters equally. A viewer at the live edge notices a failure at once. A DVR viewer can retry 5 seconds later. Encoding that difference in the rate limiter is what keeps the live edge up during a storm.
  • Non-existent content is a load source. Clients ahead of the edge, or asking for skipped segments, would hammer storage. Predictable schedules turn most of those into cheap, cacheable answers.
  • Consistency of metadata beats speed. The control-plane store skips a shared cache on purpose. A stale "segment not yet published" answer would be worse than a slower lookup, and per-instance memory caching gets most of the speed anyway.

What Netflix sacrificed. Cost and simplicity of storage. S3 became Cassandra plus EVCache plus a chunking protocol, which is clearly more expensive. They built instead of adopting an origin shield, so they own all fan-in control. And they made DVR viewers second-class under stress. In return, write P99 equals the old P50, reads scale past 200 Gbps, and bad segments can be hidden surgically.

Deep Dive: origin-storm numbers and why 503 with max-age worksShow

Publishing load. One event with 3 video formats × 8 ladder rungs, 6 audio variants and 2 ad versions has about (24 + 6) × 2 = 60 renditions (handbook's illustration). At one segment per rendition every 2 s, that is 30 PUTs per second per pipeline, 60 with both, and a few hundred with concurrent events. That is consistent with the post's "over 100 RPS" per event once manifests and metadata are added. At about 1 MiB per segment, that is tens to hundreds of MiB per second of writes to replicate across regions.

Retrieval storm. If 40 top-tier OCA sites each fetch all 60 renditions' latest segment, about 2 MiB each, within the same second after a cache flush, that is 40 × 60 × 2 MiB ≈ 4.8 GiB, about 40 Gbps in one second. With several designated nodes per site, the post's O(100 Gbps) worst case follows (handbook's illustration). Without designated fill nodes, every OCA in a site would fetch separately, multiplying that by the node count.

Why a cached 503 dampens storms. Suppose 2,000 low-priority request keys each get retried by the CDN every 100 ms during an overload, which is 20,000 requests per second. Returning 503 with max-age=5s means each key reaches the origin at most once per 5 s: 400 requests per second, a 50× reduction, with no client-side change. It is load shedding plus negative caching, chosen to be short enough that DVR viewers recover quickly.

Hold-open versus 404 polling. A client that arrives 300 ms early and gets a 404 might retry after 500 ms, adding latency and a request. With hold-open, it waits about 300 ms on one open request and gets the segment the instant it lands, which is lower latency and fewer requests. The cost is one open connection per early request at the origin, which is bounded because only the next segment is held.

Lesson 48: Edge authentication and token-agnostic identity propagation (2021)#

Assumptions. Netflix has 200 million+ members, millions of monthly active devices, over 2,000 device types, and serves more than 2.5 million requests per second, most of which need some form of authentication. Several security protocols and token types coexist: cookies over HTTPS, MSL (Message Security Layer, Netflix's own protocol for devices that need application-level encryption and authentication), partner tokens and more. Services are written in Java and, increasingly, JavaScript.

How it grew messy. Netflix began as a website for a DVD queue, added streaming, then streaming devices, and over time more and more website functions moved onto devices. Each service behind those functions had to understand several tokens and protocols just to know who the user and device were. The login flow showed the problem:

  1. The client sends credentials plus the device's ESN (Electronic Serial Number, the device ID) to Zuul, the edge gateway.
  2. Zuul forwards to the API's /login endpoint.
  3. The API orchestrates back-end systems to authenticate the user.
  4. On success, the API returns a cookie holding the customer ID, the ESN and an expiry.
  5. Zuul passes the cookie back to the client.

What was wrong.

  • External tokens were minted deep in the stack and carried all the way up, so they could be logged or mishandled on the way.
  • Upstream systems re-opened tokens to learn who had logged in, and kept parallel identity structures that could drift out of sync.
  • Tokens were consumed and sometimes changed by several systems. Identity moved around as primitives in API calls, request-context headers, even URL parameters, with no integrity checks.
  • Every one of the 2.5 million requests per second triggered an API call to authenticate its claims.
  • The edge was moving to EdgePaaS, where front-end teams run their own backend-for-frontend (BFF) services in Node.js ("NodeQuark"; see API gateway and BFF). Terminating something as complex as MSL in each JavaScript BFF, and copying all the token logic there, would have been hard and wasteful.

The fix: authenticate once, at the edge. Netflix moved protocol termination and token handling into Zuul, run by one specialised team, and replaced tokens inside the network with an integrity-protected, token-agnostic identity object called the Passport.

Edge Authentication Services (EAS) is both the idea (authenticate users and devices at the cloud edge) and a suite of services, one per token type. In practice EAS is a chain of Zuul filters:

  • The EAS Inbound Filter inspects the client's tokens. Most are valid and unexpired, and Zuul handles them itself. The few that are missing, expiring or invalid are delegated to the matching EAS service for key exchange and token creation or renewal.
  • The Passport Injection Filter builds the Passport and attaches it to the request going downstream.
  • The EAS Outbound Filter, on the response path, asks EAS for any new or updated tokens to return to the device.

Tokens never cross the edge. MSL is terminated in Zuul. Inside the network only Passports travel.

Resilience. If Zuul sees a cookie that is valid but expired, and the renewal call to EAS fails or is slow, the filter is lenient: it lets the resolved identity through and marks the renewal to be retried on the next request. A failing token service degrades token freshness, not availability.

The Passport. A short-lived identity structure, created at the edge for each request and living only as long as that request, purely internal to Netflix. It is a Protocol Buffer carrying a header (which service created it), user info, device info, and an integrity block for each of the user and device parts. A simplified sketch of its shape:

// Simplified sketch of the Passport shape described in the post
message Passport {
  Header header = 1;            // which service minted it
  UserInfo user_info = 2;       // customer id, created, expires, source, level, actions
  DeviceInfo device_info = 3;   // ESN, device type, created, expires, source, level, actions
  Integrity user_integrity = 4; // version, key name, HMAC-SHA256 bytes
  Integrity device_integrity = 5;
}
enum PassportAuthenticationLevel {
  LOW = 1;      // untrusted transport
  HIGH = 2;     // secure tokens over TLS
  HIGHEST = 3;  // MSL or user credentials
}
  • Source records which kind of claim produced the identity (cookie, insecure cookie, MSL, partner token and so on), so the protocol and validating service are known.
  • Authentication level is how much the claim is trusted. Downstream services write authorization and experience rules against it, for example "changing the email address requires HIGH or above", instead of re-implementing per-token trust rules.
  • Integrity is an HMAC (a hash-based message authentication code: a hash over the data mixed with a secret key, so it proves both that the data is unchanged and that it came from a key holder). Version 1 uses SHA-256, and the block has a version and key name so algorithms and keys can rotate.
  • The Passport is opaque. Services read it through a Passport Introspector library (getters for customer ID, account owner ID, ESN, device type), which can verify integrity before any field is used.
  • Passport Actions are explicit signals from downstream services that identity has changed (a login, a profile switch, a device link). EAS turns them into new or updated external tokens on the way out. Downstream services never mint tokens themselves.

Results, from the main API service.

  • 30% less CPU per request and 40% lower load average. Part of this came from consolidation: MSL used to be decrypted twice per request, once at the edge to route and once downstream for rich termination, and now it is processed once.
  • 30% lower average latency and 20% lower p99.
  • Much lower GC pressure and stop-the-world pause times.
  • Developer velocity. Auth changes happen once, in one set of specialised services.
  • Debuggability. When an identity looks wrong, the Passport records who created it, and it can be opened and validated from logs. Passing primitives around made "who changed the customer ID between service A and service D?" unanswerable.

Next steps the team named. Multi-factor authentication through a new service, Resistor, which adds a second factor (OTP by email or phone, push to mobile, authenticator apps) only for connections that ML models flag as suspicious, with opt-in MFA a possibility. Plus a Product Access Strategy (PACS) for authorization built on the verified identity. PACS already powered access control for StreamFest, a free-Netflix weekend in India. See authentication and authorization.

Overlooked constraints.

  • Authentication at 2.5M RPS is a capacity problem, not just a security one. Removing an auth call per request and a duplicate MSL decryption freed a third of the API's CPU.
  • Internal identity needs integrity too. A mutable structure passed between services lets any compromised or buggy service change "who" a request is for. HMAC makes changes detectable.
  • Leniency must be explicit. Allowing an expired-but-valid cookie when renewal fails is a deliberate security trade-off, bounded by retrying on the next request.

What Netflix sacrificed. Edge simplicity and concentration of risk. Zuul became security-critical: a bug in an EAS filter affects every request, and the HMAC keys are high-value secrets. Downstream services lost direct access to raw tokens and must trust the edge. And during renewal failures they accepted slightly stale tokens. In return: one place to fix auth, a third less CPU downstream, and identity with provenance.

Deep Dive: what edge termination saves, and HMAC versus signaturesShow

CPU arithmetic. Say MSL decryption plus token validation costs 0.5 ms of CPU per request, and the old design did it twice: at the edge to route, downstream to read (handbook's illustration). At 2.5 million RPS, if 40% of requests are MSL, that is 1 million × 2 × 0.5 ms = 1,000 CPU-seconds per second, about 1,000 cores. Doing it once saves about 500 cores. Removing the separate per-request authentication call saves a network round trip and the auth service's own capacity. The measured 30% CPU-per-request drop at the API fits this shape.

HMAC or digital signatures? With an HMAC, every verifier holds the same secret key as the minter. That makes it fast (a SHA-256 over a few hundred bytes takes microseconds) but means any service that can verify could, in principle, forge. With asymmetric signatures (such as Ed25519 or ECDSA), verifiers hold only a public key, so they cannot forge, but verification is about 10 to 100× more expensive. Inside a trusted network, with keys managed centrally and named in the key_name field for rotation, Netflix chose HMAC's speed. A design that sends identity tokens across organisational boundaries usually picks signatures, as JWTs signed with RS256 or ES256 do.

Why per-request, short-lived identity? A Passport that lives only for one request cannot be replayed later or leaked into a long-lived cache entry. The expiry fields in user and device info bound it even if it is logged. Contrast with forwarding the external cookie, which is valid for weeks.

Lesson 49: Sequential A/B testing for software canaries (2023)#

Assumptions. Every Netflix client release goes through a canary: a randomised experiment in which a small group gets the new software (treatment) and a matched group keeps the old one (control). One key metric is play-delay, the time from pressing play to video starting. Any increase is treated as a serious regression that blocks the release. The canary is part of a semi-automated release process, so a false alarm stops a release and sends engineers hunting for bugs that do not exist.

Three requirements.

  1. Detect regressions as fast as possible, to limit harm to members in the treatment group.
  2. Strictly control false positives, to protect release velocity.
  3. Detect any change in the distribution, not just the mean or median. A release can leave the median unchanged while making the upper quantiles worse, which hurts exactly the members on slow or unstable connections who already wait longest.

Why the usual tests fail. The t-test, Kolmogorov-Smirnov and Mann-Whitney are fixed-n tests: collect a pre-set amount of data and analyse once. If you run them repeatedly as data arrives ("peeking"), the false-positive guarantee is lost. In Netflix's simulation of 100 A/A tests (no real difference), Mann-Whitney applied repeatedly up to 10,000 observations per group falsely declared a difference at some point in 66 of 100, against a nominal 5%. Kolmogorov-Smirnov behaves the same way. (The risks of peeking are discussed by Johari et al., "Peeking at A/B Tests", KDD 2017.) Staying with fixed-n leaves a bad choice: test early and miss small regressions, which then pile up over many releases, or test late and leave members exposed to big regressions for longer than needed.

The fix: any-time valid inference. Sequential tests may be checked after every new data point, with a false-positive guarantee that holds over all time. The idea goes back to Abraham Wald's Sequential Tests of Statistical Hypotheses (1945). Netflix's approach is in "Rapid Regression Detection in Software Deployments" (Lindon, Sanden, Shirikian and colleagues, KDD 2022). Netflix has since published related papers on count data, linear models, design-based confidence sequences and dependent observations.

How it works.

  • At any moment, estimate the empirical quantile function (the value below which a fraction p of observations fall, for every p) for treatment and control.
  • A fixed-time confidence band around a distribution function comes from the DKWM inequality (Dvoretzky-Kiefer-Wolfowitz-Massart). To get bands valid uniformly over time, Netflix uses the any-time valid confidence sequences of Howard and Ramdas (2022).
  • Build a time-uniform band on the difference of quantile functions, treatment minus control, across all quantiles. If at any time the band excludes zero at any quantile, the distributions differ, and the test stops.
  • A sequential p-value is computed as well. The moment the 95% band leaves zero is the same moment the sequential p-value drops below 0.05, so intervals and p-values agree, as they do in fixed-n tests.
  • Error control is simultaneous across all quantiles, all treatment groups and all joint sample sizes. The groups do not even need equal sizes.

Case study. A client change raised several play-delay quantiles: the median by at least 0.5% and the 75th percentile by at least 1%. The sequential test rejected "no change" at the 0.05 level after about 60 seconds of canary traffic. The system is fully automated and part of every client release. It has stopped several serious bugs, and because developers trust it, they release more often. (Lesson 19 covers Kayenta, Netflix's automated canary analysis for server deployments, and Lesson 37 the A/B platform.)

Overlooked constraints.

  • Peeking is how canaries are used. Engineers watch dashboards continuously, so a test that is only valid when checked once is unsafe by design. The statistics must match the behaviour.
  • Averages hide tail regressions. The members hit by a tail regression are the ones already having the worst experience.
  • False positives have a cost. In an automated gate, every false alarm blocks a release, so alpha must hold under continuous monitoring, across many quantiles and many releases.

What Netflix sacrificed. Some statistical power at a fixed sample size. Time-uniform bands are wider than fixed-n bands at the same n, because they pay for the right to look at every moment. A small effect therefore takes somewhat longer to detect than a perfectly timed single test would need. In return, big regressions stop in about a minute, and the error rate is honest no matter how often anyone looks.

Deep Dive: why peeking inflates error, and how time-uniform bounds fix itShow

Peeking. Under no true difference, a fixed-n p-value is uniformly distributed at each look. But checking it after every batch gives many correlated chances to dip below 0.05. With k roughly independent looks, the chance of at least one false alarm approaches 1 − 0.95^k: 23% for 5 looks and 64% for 20. Correlated looks grow more slowly, but they grow without bound: by the law of the iterated logarithm, a running z-statistic under the null crosses any fixed threshold eventually with probability 1. Netflix's 66% at 10,000 observations is that effect in action.

Ville's inequality. The key tool behind any-time valid tests: if M_t is a non-negative supermartingale with M_0 = 1 (for example a likelihood ratio of "regression" against "no regression" under the null), then P(M_t ever reaches 1/α) ≤ α. So "reject as soon as the evidence ratio exceeds 20" has a 5% false-alarm rate over all time, however often you look. Wald's sequential probability ratio test (1945) is the classic special case.

Width cost. DKWM gives a fixed-n band on a distribution function of half-width ε = √(ln(2/α) / (2n)). At n = 10,000 and α = 0.05, that is √(3.69 / 20,000) ≈ 0.0136. Time-uniform bands have half-widths that grow like √(log log n / n) times a constant, roughly 1.5 to 2× wider at practical n (handbook's illustration of the order of magnitude). So the price of continuous monitoring is roughly needing 2 to 4× the data to detect the smallest effects, while large effects are caught almost immediately.

Why 60 seconds was enough. Play-delay events arrive at thousands per second even from a small canary. With, say, 50,000 observations per group in a minute, a 1% shift in the 75th percentile is well outside a band that is a fraction of a percent wide (handbook's illustration).

Lesson 50: Building in-video search (2023)#

Assumptions. Editors making trailers, social reels and promotional videos need to find specific moments across hundreds of thousands of films and episodes: a car exploding in The Gray Man, every character shouting "Merry Christmas" across the catalogue, an actor's most dramatic shots for a birthday reel. Without search they scrub through whole films. Queries are free text and often about things no fixed label covers. Users are internal, so the query rate is modest, but the index is huge and must include new assets quickly.

Why classic computer vision failed. Object detection with general labels was at once too limiting and too specific, yet not specific enough. Every show has its own important things (the Demogorgon in Stranger Things) that a generic label set does not cover. Action recognition had the same problem.

The approach: contrastive learning of text and video. Train two encoders, one for images or video and one for text, so that matching pairs land close together in a shared embedding space of hundreds or thousands of dimensions. This is the approach popularised by OpenAI's CLIP (Radford et al., "Learning Transferable Visual Models From Natural Language Supervision", 2021).

  • In-batch contrastive loss. In a batch of N image-caption pairs, push up the cosine similarity of the N correct pairs and push down the other N² − N pairings. Similarities are treated as logits with a symmetric cross-entropy: classify the right caption for each image and the right image for each caption, weighted equally.
  • One model learns objects, scenes, emotions and actions together.
  • At query time, the text is embedded and the nearest visual embeddings are returned, even for phrases that never appeared in training.

From images to shots. Video is a sequence of frames, so a shot or scene needs one embedding. For short units like shots, simple mean pooling of frame embeddings worked better than adding learned parameters. Netflix then fine-tuned the image-text model on in-house data pairing shots of different lengths with rich text descriptions, improving video retrieval by 15 to 25%, depending on the base model and metric. Training was scaled on Ray Train, with a faster video-decoding library.

Reuse beyond search.

  • Netflix has many clip classifiers for specific attributes (close-up shots, caution elements). Starting from shot embeddings gives them a large head start over training from scratch, beyond what the base image-text model gives.
  • The embeddings show strong zero-shot and few-shot performance on other content-understanding tasks.
  • Shot embeddings also power video-to-video search: "find more shots like this one", which is very useful when cutting trailers.

Infrastructure.

  • Shot embeddings are precomputed, stored in the media feature store, and replicated to Elasticsearch for real-time nearest-neighbour queries (see vector databases).
  • The media feature system automatically triggers embedding jobs when new assets arrive, so search covers the latest content.
  • Split CPU and GPU work. Shot segmentation of a full film is CPU-heavy, and embedding needs GPUs. Running both on GPU machines would leave expensive GPUs idle during segmentation. So segmentation runs in parallel on multi-core CPU machines and writes shots to S3 as mp4. A prefetching, preprocessing data loader then streams them straight to the GPUs, which stay busy. This improves throughput and cost.
  • At query time, the text encoder turns the query into a vector, and a nearest-neighbour search runs over selected shows or the whole catalogue.

Outcome. Creatives iterate faster and try more ideas, and the system is relatively simple to maintain. See ML system design and feature stores for the general pattern of precomputed embeddings served from a feature store.

Overlooked constraints.

  • The label vocabulary is open. Any fixed taxonomy fails on show-specific things, so the model must map arbitrary text into the same space as video.
  • GPU cost is dominated by idle time. The CPU-GPU split is mainly an economics decision. The model is the same either way.
  • Freshness is a pipeline property. Search is only as current as the trigger that embeds new assets. Without auto-triggering, new titles would be invisible to editors exactly when marketing them matters most.

What Netflix sacrificed. Precision and explainability. Embedding search returns "similar" results ranked by cosine score, not exact matches, and it cannot say why a shot matched. Mean pooling throws away the order of events within a shot. And the system depends on curated in-house training descriptions. In return, one model covers objects, actions, emotions and show-specific concepts, and the same embeddings serve many other tasks.

Deep Dive: sizing an in-video search indexShow

How many shots? Films average a shot every few seconds. Say 3 s on average, so a 2-hour film has about 2,400 shots and a 50-minute episode about 1,000. A catalogue equivalent to 50,000 hours of video has about 60 million shots (handbook's illustration).

Index size. At 512 dimensions in float32, each embedding is 2 KB, so 60 million shots is about 120 GB of raw vectors. Quantising to int8 cuts that to 30 GB, and product quantisation to about 64 bytes per vector cuts it to under 4 GB, with some loss of recall. An HNSW graph index adds roughly 100 to 200 bytes per vector for links. That fits comfortably in a modest Elasticsearch cluster with kNN support.

Query cost. Brute-force cosine over 60 million 512-dimension vectors is about 30 billion multiply-adds, perhaps 1 to 3 seconds on a CPU node and well under that on a GPU. HNSW answers in milliseconds by visiting only a few thousand vectors, at about 95% recall. Filtering to "selected shows" shrinks the candidate set, but filtered ANN needs care, because a strict filter can leave the graph search with too few valid neighbours, and engines then fall back to exact search over the filtered subset.

The contrastive loss in one line. For a batch of N pairs with normalised embeddings u_i and v_i, logits s_ij = (u_i · v_j) / τ, where τ is a learned temperature. Loss = ½ × [cross-entropy over rows (image to text) + cross-entropy over columns (text to image)], with the diagonal as the correct class. Larger batches give more negatives (N² − N), which is why these models train with batches in the thousands and need distributed training such as Ray Train.

Lesson 51: Recurring patterns across fifty-one posts#

Assumptions. Read one Netflix post and you learn one system. Read fifty-one and the same handful of moves keep coming back, in 2011 and in 2025, in the gateway and in the video pipeline. This lesson names those moves, so you can reuse them as a checklist when you design your own systems.

The patterns.

PatternWhat it meansWhere it appears
Expect failure, bound the damageEvery remote call has a timeout, a fallback and a limit on how many threads or requests it can holdLessons 1, 2, 16, 17, 47
Isolate by priority, shed the least valuable work firstWhen capacity runs out, drop prefetches and logging before playback startsLessons 16, 17, 45, 47
Put an abstraction in front of storageTeams use a key-value, time-series, counter or WAL API, and the platform team picks and tunes the enginesLessons 24, 25, 27, 28
Cache everything that is read often, and plan for the cache to be statefulCaches get replication, warming and SSD tiers because losing one is an outageLessons 8, 9, 10, 11, 38
Prove changes with real traffic before trusting themReplay testing, canaries with statistics, chaos experiments with a small blast radiusLessons 18, 19, 35, 36, 49
Predict first, react secondPrecompute capacity and content placement from forecasts, and keep reactive controls as the safety netLessons 14, 20, 40, 41
One business metric as the health signalStream starts per second tells you more than CPU graphs, so alerts and experiments use itLessons 15, 18, 21
Async and event-driven at the edgesNon-blocking gateways and streams decouple producers from consumersLessons 5, 29, 30, 31
Orchestrate long flows explicitlyWorkflows with state, retries and timeouts instead of chains of hidden callsLessons 32, 33, 44
Version 2 replaces version 1, with a migration planZuul 1 to 2, Reloaded to Cosmos, Kafka-based CQRS to Hollow, every move came with shadow traffic and dialsLessons 5, 34, 35, 38, 44
Build when scale makes buying wrong, buy when it does notOpen Connect appliances and Hollow were built; AWS, Cassandra, Kafka and Elasticsearch were adoptedLessons 8, 29, 42, 50

Overlooked constraints.

  • Patterns cost people. Each one needs a team to own it: Hystrix, Eureka, EVCache, Atlas and Kayenta all had owners. A small company copying all of them at once would spend its whole roadmap on platform work.
  • The patterns depend on each other. Region evacuation (Lesson 15) only works because caches are replicated (Lesson 9) and capacity is predicted (Lesson 14). Taking one without the others gives you the cost without the benefit.
  • Most posts describe the second or third design. The first designs were simpler and were replaced when they stopped working. The lesson is to plan the migration path, not to start with the final design.

What Netflix sacrificed. Across all fifty-one posts the same trade appears: Netflix gave up simplicity and some consistency to get availability, and gave up engineer time to get operational control. It runs many custom systems that a smaller company would never build. Those systems make sense only because a minute of lost streaming at Netflix's scale costs more than a platform team does.

Deep Dive: when is a platform abstraction worth building, with numbersShow

Use a simple break-even test (handbook's illustration). Suppose 40 product teams each run their own Cassandra cluster. Each spends about 0.3 engineer-years a year on tuning, upgrades, schema mistakes and incidents. That is 40 × 0.3 = 12 engineer-years a year of scattered storage work.

A platform abstraction such as the key-value layer (Lesson 24) needs, say, a team of 8 to build and run it. If it removes 80% of the per-team work, teams now spend 40 × 0.06 = 2.4 engineer-years. Total cost = 8 + 2.4 = 10.4 engineer-years, against 12 before. That is only a small saving in people. The bigger win is in incidents. If each team causes one storage incident a year and the platform halves the rate and the time to fix, the yearly incident minutes fall by about 75%.

Now run the same test with 5 teams: 5 × 0.3 = 1.5 engineer-years of scattered work, against a platform team of 8. The abstraction loses badly. The pattern therefore has a threshold. It pays when the number of teams using the same kind of storage is large, when mistakes are costly, and when the platform team can enforce good defaults such as idempotency tokens and chunking. Below that threshold, a shared runbook and a managed database service give most of the benefit at a fraction of the cost.

Cross-cutting: the reference toolbox seen through Netflix#

The reference lists for this handbook name a standard toolbox for distributed systems: heartbeats, service discovery, consensus, distributed locks, gossip, circuit breakers, disaster recovery, distributed tracing, caching for read-heavy data, CDN and edge computing, hot-key handling, write queues for bursts, load shedding, and scaling persistent connections. Netflix's posts show almost every item in production. This section maps each tool to the lesson that shows it, and notes where Netflix chose not to use it.

ToolHow Netflix used itLessonHandbook page
Heartbeats and leasesEureka clients renew every 30 s; missing renewals evicts an instance after about 90 s3Leader election and coordination
Service discoveryClient-side registry with local caching, chosen over a strongly consistent store so discovery survives partitions3Microservices patterns
Consensus and coordinationDeliberately avoided on the hot path; ZooKeeper only for rare ordering needs such as idempotency token generation24ZooKeeper and etcd
Distributed locksAvoided: rollups overwrite immutable windows, viewing-history rollups write the pointer last26, 27Distributed transactions
Circuit breakers and bulkheadsHystrix: per-dependency thread pools, timeouts, fallbacks, breakers1, 2Resilience patterns
Disaster recoveryActive-active in three regions, evacuation in under 10 minutes, predicted per-service demand12 to 15Disaster recovery
Distributed tracingEdgar joins traces, logs and request context for one member's session22Observability
Caching read-heavy dataEVCache with replication, warming and SSD; Hollow puts the whole dataset in memory8 to 11, 38Distributed caching
CDN and edge computingOpen Connect appliances inside ISPs; Zuul and Passport at the cloud edge4, 40 to 42, 48CDN
Hot keys and hot contentPopularity prediction places hot titles on more appliances; file-level placement spreads load40, 41Consistent hashing
Write queues for burstsKeystone and Kafka absorb event bursts; the WAL queues writes when a database is slow28, 29Pattern: Scaling Writes
Load sheddingPriority-based shedding at the gateway and inside services; live origin returns fast 503s by priority16, 17, 47Rate limiting
Persistent connection scalingZuul 2 moved to non-blocking I/O for push; subsetting curbed connection churn5, 7Pattern: Pushing Realtime Updates
Search with cachingIn-video search embeds frames once, stores vectors in Elasticsearch, and caches query embeddings50Elasticsearch

Gossip is the one gap. None of the fifty-one posts describes a gossip protocol as a Netflix-built system. Cassandra, which Netflix runs at large scale, uses gossip internally for membership, so the technique is in Netflix's stack, but the posts treat it as part of the database. The handbook covers gossip on the Cassandra page.

Queue the burst or shed it. Two tools in the table look like rivals: write queues and load shedding. Netflix uses both, and the choice follows a simple rule about the work, not about the system.

Work typeCan it wait?Netflix moveLesson
Telemetry and analytics eventsYes, minutes are fineQueue in Kafka, process later29, 30
Writes to a slow databaseYes, seconds are fine, if order is keptQueue in the WAL with retries and backoff28
Delayed jobs and timersYes, by designDelay queue on Dynomite31
Prefetch and non-critical API callsNo, a late answer is uselessShed first, by priority16, 17
Playback start and live segment requestsNo, and they are the most valuableProtect, shed everything else first16, 47
Device retries after an outageNo, they multiplyShed with retry-after hints and backoff45, 47

Three rules come out of the posts:

  1. Queue only work whose value survives the delay. A queued prefetch that arrives after the user has scrolled away is wasted capacity, so it is shed, not queued.
  2. Every queue needs a limit and a plan for when it is full. Kafka in Keystone was sized for hours of retention; the WAL has dead-letter queues. A queue without a limit just moves the outage to memory.
  3. Shed early and cheaply. A rejection at the gateway costs microseconds; a rejection after the request reached a database has already spent the expensive part. That is why Lesson 16 sheds at Zuul, and Lesson 17 adds shedding inside services only for traffic the gateway cannot classify.
Deep Dive: sizing a write queue versus shedding, with numbersShow

Suppose a service normally handles 20,000 writes per second, and the database can take 25,000 (handbook's illustration). A regional evacuation (Lesson 15) moves traffic so the service sees 40,000 writes per second for 10 minutes.

Queue it. The excess is 40,000 − 25,000 = 15,000 writes per second. Over 600 seconds that is 9 million writes in the queue. At 1 KB each, that is 9 GB, which a Kafka topic or WAL handles easily. After the burst ends, traffic drops back to 20,000, so the database drains the backlog at 25,000 − 20,000 = 5,000 per second. Draining 9 million takes 1,800 seconds, or 30 minutes. If the writes are viewing-history updates, a 30-minute lag is fine. If they are "continue watching" bookmarks a member expects to see on another device in a minute, it is not.

Shed it. If the writes are low-value, for example impression logging, shedding 37.5% of them at the gateway keeps the database at 25,000 with no backlog. Nothing lags, but the data is gone.

Mix them. Netflix's real answer is usually a mix. Protect the critical writes with reserved capacity, queue the important but delayable ones, and shed the rest. With 20% critical, 50% delayable and 30% sheddable, the burst of 40,000 splits into 8,000 critical, 20,000 delayable and 12,000 sheddable. Shed the 12,000 and you have 28,000 per second against a limit of 25,000. Only 3,000 per second goes to the queue, so it holds 1.8 million writes after 10 minutes and drains in 6 minutes. That is the case for priority classes: the same hardware gives a 6-minute lag instead of a 30-minute lag, and the most valuable writes never wait.

When to Use It#

Study the Netflix posts when:

  • You are designing for very high availability, where a few minutes of downtime costs real money or trust. Lessons 1, 2, 12 to 17 show how to make failure routine rather than rare.
  • Your system is read-heavy and global. The caching lessons (8 to 11, 38) and the Open Connect lessons (40 to 42) show how to serve most reads close to the user.
  • You run many microservices and need discovery, an edge gateway, tracing and safe deploys. Lessons 3 to 7, 19 and 22 cover the control plane.
  • You need data platforms that many teams share. Lessons 24 to 28 show how to put one abstraction in front of several storage engines.
  • You are preparing for interviews on streaming, video, feeds or resilience. Netflix examples are familiar to interviewers and come with real numbers.
  • You are planning a big migration. Lessons 35, 36, 38 and 44 show replay testing, dials and rollback for moving critical traffic.

When NOT to Use It#

  • Do not copy the scale. Netflix runs three AWS regions active-active and its own CDN. A product with 10,000 users needs one region, a managed database and a commercial CDN.
  • Do not copy systems whose reason has gone. Hystrix is in maintenance mode; Netflix itself moved toward adaptive concurrency limits and service meshes. Learn the ideas, then pick today's tools such as Resilience4j or Envoy.
  • Do not use it as a guide for strong consistency. Netflix mostly chooses availability and accepts eventual consistency. For payments, ledgers or inventory, study the Stripe page and the distributed transactions page instead.
  • Do not treat a blog post as a full specification. Posts describe the interesting parts and skip the hard operational detail. Treat the numbers as one company's point in time.

How to Implement It#

Apply the lessons in this order. Each step builds on the ones before it.

  1. Add timeouts, fallbacks and bulkheads to every remote call (Lessons 1 and 2). Size each pool with Little's law from the real call rate and p99 latency.
  2. Use client-side discovery with health-based balancing (Lessons 3 and 6). Short connect timeouts and retry on a different instance hide most crashes.
  3. Put a programmable gateway at the edge (Lessons 4 and 5). Do authentication, routing and shedding there, and use non-blocking I/O if you hold persistent connections.
  4. Pick one business health metric (Lesson 21), such as orders per second or stream starts per second, and alert on its deviation from forecast.
  5. Classify traffic by priority and shed from the bottom (Lessons 16 and 17). Decide the classes before an incident, not during one.
  6. Cache read-heavy data with replication and warming (Lessons 8 to 11). Treat a cold cache as an outage risk.
  7. Put storage behind an abstraction once several teams need it (Lessons 24 to 28), with idempotency tokens, chunking and a write-ahead log.
  8. Make deploys safe with canaries and statistics (Lessons 19 and 49), and test resilience with small chaos experiments (Lesson 18).
  9. Run active-active only when the business needs it (Lessons 12 to 15), and practise evacuation regularly.
  10. Migrate with replay, dials and rollback (Lessons 35 and 36). Never switch critical traffic in one step.

A priority shedding rule, in the style of Lessons 16 and 17, as configuration:

shedding:
  signal: cpu_utilization        # or concurrent requests, or queue latency
  priorities:
    - name: critical             # playback start, login, payment
      shed_above_cpu: 95
    - name: degraded             # personalisation, artwork
      shed_above_cpu: 85
    - name: best_effort          # logging, prefetch
      shed_above_cpu: 70
    - name: bulk                 # backfills, batch jobs
      shed_above_cpu: 60
  rejection:
    status: 503
    headers:
      Retry-After: 5
  retries:
    client_backoff: exponential_with_jitter
    max_attempts: 3

Technology choices.

NeedNetflix choiceModern alternativesWhen each fits
Circuit breakingHystrixResilience4j, Envoy outlier detection, adaptive concurrency limitsLibrary for one language; mesh for many languages
DiscoveryEurekaConsul, Kubernetes services, AWS Cloud MapKubernetes services if you already run Kubernetes
Edge gatewayZuul 2Envoy, NGINX, Spring Cloud Gateway, AWS API GatewayManaged gateway for small teams; Envoy for custom filters
CacheEVCache on memcachedRedis, Memcached, ElastiCache, MomentoRedis when you need data structures; memcached for simple, huge caches
Event streamingKafka in KeystoneKafka, Amazon Kinesis, Redpanda, PulsarManaged Kafka unless you need to run your own
Stream processingFlinkFlink, Kafka Streams, Spark Structured StreamingFlink for stateful, low-latency jobs
Wide-column storeCassandraCassandra, ScyllaDB, DynamoDBDynamoDB to avoid operations; ScyllaDB for tail latency
OrchestrationConductor, MaestroTemporal, AWS Step Functions, AirflowTemporal for service workflows; Airflow for data pipelines
TelemetryAtlasPrometheus, Grafana Mimir, DatadogPrometheus for most teams; managed SaaS for small teams
Canary analysisKayentaArgo Rollouts, Flagger, Spinnaker with KayentaArgo Rollouts on Kubernetes

Trade-offs#

Choice Netflix madeWhat it boughtWhat it cost
Availability over consistency (AP discovery, async replication)Service survives partitions and region lossMembers may briefly see stale data across regions
Active-active in three regionsEvacuation in minutes, no cold standbyRoughly a third extra capacity held in reserve and complex data replication
Building its own CDNLower cost per byte, control over hardware, peering inside ISPsHardware teams, ISP relationships, global logistics
Async, non-blocking edgeCheap persistent connections and pushHarder debugging, testing and library compatibility
Platform abstractions over storageFewer incidents, safe defaults, engine changes hidden from teamsExtra hop, platform team cost, lowest common denominator APIs
Precomputing and caching aggressivelyLow latency at huge read volumeStaleness, warm-up work, memory and SSD cost
Testing in production with chaos and canariesFinds real failures before members doSmall, controlled member impact and heavy tooling
Custom tools for most problemsFits Netflix's exact scale and needsMaintenance burden; some tools later replaced or archived

Common Pitfalls#

  • Copying Hystrix's thread pools everywhere. Thread-per-dependency isolation costs memory and context switches. Use semaphores or adaptive limits for cheap calls, as Lesson 2 itself advises.
  • Retrying without budgets. Retries during an outage multiply load. Lessons 45 and 47 show retry storms from devices; always use backoff with jitter and server-sent retry-after hints.
  • Caching without a warm-up plan. Losing a cache cluster sends all its reads to the database at once. Lesson 11 exists because this happened.
  • Shedding without priorities. Random shedding drops playback starts as often as logging. Decide classes in advance.
  • Active-active without testing evacuation. A failover you have never run will fail. Netflix practises it regularly, and Lesson 15 made it fast enough to do often.
  • Assuming canary graphs are enough. Looking at a canary dashboard repeatedly inflates false alarms. Lesson 49 shows 66 of 100 A/A tests falsely rejected when peeking; use sequential tests.
  • Building a platform too early. Lesson 51's break-even example shows a storage abstraction losing money with only a handful of teams.
  • Treating one blog post as current truth. Several systems in the 2012 to 2016 posts were later replaced. Check the dates.

Real-World Examples#

  • Netflix itself. The whole page is drawn from its posts, covering 2011 to 2025: Hystrix, Eureka, Zuul, EVCache, Atlas, Kayenta, Keystone, Conductor, Maestro, Open Connect, Cosmos and the Live Origin.
  • Resilience4j and Envoy. Resilience4j took up Hystrix's ideas when Hystrix went into maintenance mode, and Envoy brings outlier detection and circuit breaking to service meshes in any language.
  • Spinnaker and Kayenta. Netflix built Spinnaker for continuous delivery and released it as open source. Kayenta, the canary analysis service built with Google (Lesson 19), plugs into it, so other companies can run the same automated canary judgement.
  • Spring Cloud Netflix. Spring wrapped Eureka, Ribbon, Hystrix and Zuul for Java users, which spread these patterns widely before Kubernetes made built-in discovery common.
  • Other companies' edge appliances. Google Global Cache and Meta's network appliances in ISPs follow the same idea as Open Connect: put caches inside the ISP to save backbone traffic.

In the Interview#

Deep Dive: designing a small streaming service with Netflix's lessons, with numbersShow

Problem. A regional streaming service with 2 million members, a peak of 200,000 concurrent streams, a 5,000-title catalogue, and a target of 99.95% playback availability (handbook's illustration).

Bandwidth. At an average 4 Mbps, peak egress is 200,000 × 4 Mbps = 800 Gbps. That is too much to serve from cloud storage at cloud egress prices, so a CDN is required. At this scale, a commercial CDN is the right call; building appliances like Open Connect only pays at many terabits per second.

Content placement. Following Lesson 40, popularity is very skewed. If the top 10% of titles carry 80% of views, then the top 500 titles at an average of 30 GB across all encodes come to 15 TB. Ask the CDN to pre-warm those 15 TB each night, and let the long tail fill on demand.

Control plane. Peak API traffic is about 10 calls per stream start plus background calls. With 2,000 stream starts per second at peak and 30,000 background calls per second, the gateway sees about 50,000 requests per second. Shed by priority (Lessons 16 and 17): playback start and license calls are critical, artwork and recommendations are degraded, logging is best effort.

Caching. Catalogue metadata for 5,000 titles at 50 KB each is 250 MB. That fits entirely in memory on every API instance, like Hollow in Lesson 38, refreshed every minute. Per-member data such as viewing history goes in a Redis cluster with replicas.

Availability math. 99.95% allows about 22 minutes of downtime a month. A single region with three zones gives roughly 99.9 to 99.95% in practice, which is borderline. Instead of full active-active, run a warm standby region with replicated metadata and a tested failover of under 15 minutes. That meets the target at about a third of the cost of a second active region.

Safety. Deploy with canaries on 1% of traffic for 30 minutes, judged by a sequential test on stream starts per second (Lessons 19 and 49), and run a monthly game day that fails one zone (Lesson 18).

What we did not copy. No custom CDN, no three-region active-active, no in-house telemetry platform and no custom storage abstraction. Each would cost a team, and at 2 million members none passes the break-even test from Lesson 51.

Key Takeaways#

  • Netflix treats failure as normal: timeouts, fallbacks, bulkheads and circuit breakers on every call, starting with Hystrix in 2011 and 2012.
  • Priority decides who suffers under overload. Shed logging and prefetch first, and protect playback, from the gateway to the Live Origin.
  • Caches are stateful systems at Netflix's scale. They need replication, warming and SSD tiers, and losing one is an outage.
  • Availability beats consistency for most streaming data. Active-active across three regions and fast evacuation are built on asynchronous replication.
  • Put the bytes near the user. Open Connect places popular content inside ISPs ahead of demand, using popularity forecasts and careful hardware tuning.
  • Abstractions over storage let many teams share safe defaults, such as idempotency tokens, chunking and a write-ahead log, but they pay only at scale.
  • Prove changes on real traffic with replay testing, canaries judged by sequential statistics, and small chaos experiments.
  • Queue work whose value survives delay, and shed work whose value does not. Size every queue and plan for when it fills.
  • Copy the ideas, not the scale. Most companies need a few of these patterns, chosen with a break-even test.