Summary#
Meta (Facebook, Instagram, WhatsApp, Messenger and Threads) serves more than three billion people. Its workload is unusual in three ways. Reads vastly outnumber writes. The data is one huge, densely connected social graph that does not split cleanly into shards. And product teams change the load every week. Meta's engineering posts show how it turned an open-source cache into a distributed system serving billions of requests per second, built a graph store on top of MySQL, and rebuilt storage, logging, queuing, load balancing and finally whole data centres for AI training.
This page studies about forty posts, plus the NSDI 2013 memcache paper that one of them links to, in seven families:
- Caching: memcache, mcrouter, cache consistency with Polaris, CacheLib.
- The social graph and storage: TAO and RAMP-TAO, Haystack and cold storage, Tectonic, RocksDB and MyRocks, MySQL Raft, ZippyDB, Akkio and Delos.
- Data movement: Wormhole, LogDevice, Scribe, FOQS, async computing and Beringei.
- Fleet and traffic: Shard Manager, Twine, Katran, OWL and configuration management.
- Products: News Feed ranking, Instagram Explore, live video, WhatsApp multi-device and Threads.
- Outages: 2010 and October 2021.
- AI infrastructure: GenAI clusters, LLM training at scale and keeping AI capacity healthy.
Why It Exists#
A news-feed design in an interview usually has a feed service, a cache and a database. Meta's posts show what that hides:
- The read path is the system. One page load fetched an average of 521 cached items in 2013, and some fetched more than 1,700. A cache miss is a database query, so the cache is not an optimization but a requirement.
- The graph does not partition. Friends, likes and comments connect everything to everything. Any sharding scheme sends some queries to many shards, and a few celebrity objects get orders of magnitude more traffic than average.
- Consistency is measured, not assumed. Meta treats the chance of reading stale data as a tunable parameter and then measures it to ten nines.
- Storage is enormous and mostly cold. Photos and videos are written once, read heavily for days, then rarely. Storing them all on the same hardware wastes money.
- Everything is a fleet problem. Millions of servers, tens of thousands of services and constant hardware failure mean that placement, configuration, load balancing and capacity are systems in their own right.
- AI changed the hardware. Training large language models needs tens of thousands of GPUs working in lockstep, so one slow or failed GPU stalls the whole job.
The textbook pages (distributed caching, news feed case study, social graph case study, storage engines) explain each idea alone. Meta's posts show the same ideas at the scale of the world's largest social network, with their costs.
For each post the page asks:
- Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
- Production architecture. What did Meta actually build?
- Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
- Sacrifice. What did Meta give up to get the benefit?
How It Works#
The diagram shows where each family sits on the path of a request. A user's request reaches an edge PoP through Katran, Meta's layer-4 load balancer, and then a web server. The web server reads the social graph through TAO and other data through memcache via mcrouter. Writes go to MySQL (MyRocks storage, Raft replication), whose changes flow through Wormhole to invalidate caches and feed other systems. Media goes to blob storage (Haystack, then Tectonic, then cold storage). Logs and events go through Scribe and LogDevice into data warehouses and ML training. Shard Manager and Twine place all of these services on millions of machines. Configuration flows to every server in seconds.
The lessons follow the seven families in order. Each covers one post, or a few closely linked posts, and ends with what the design gave up.
Family 1: Caching
Lesson 1: Scaling memcache, from 800 servers to billions of requests per second (2008 to 2013)#
Assumptions. Users read an order of magnitude more than they write. Data comes from many sources: MySQL, HDFS and backend services. A page needs hundreds of items. Meta treats the probability of reading briefly stale data as a parameter to tune, like latency, and accepts a little staleness to protect the databases. Operations matter as much as speed.
The 2008 starting point. Facebook began using memcached in August 2005, when page loads were slowing because of growing database queries. By 2008 it ran more than 800 memcached servers with over 28 TB of memory. Thousands of web servers, each with a hundred or more Apache processes, held hundreds of thousands of TCP connections to memcached. The 2008 post (Paul Saab) describes fixes at the operating-system level:
- Per-connection buffers wasted gigabytes per server. A per-thread shared buffer pool for TCP and UDP sockets reclaimed that memory for data.
- UDP for gets cut network traffic and allowed application-level flow control for multi-gets of hundreds of keys. Linux UDP performed badly under load because many threads sent through one socket and fought over its lock. The fix was a separate reply socket per thread.
- One core saturated by network soft interrupts. A mix of interrupt-driven and opportunistic polling I/O (polling whenever entering the network driver and from the scheduler's idle loop, with aggressive interrupt coalescing) spread network work across all cores.
- Global locks on 8-core machines. Stats collection behind a global lock used 20 to 30% of CPU, so stats moved per thread and were aggregated on demand. The network device's transmit queue lock caused contention, so dequeues were batched.
Results: 200,000 UDP requests per second at 173 µs average latency, up from 50,000 with stock Linux and memcached. 300,000 per second was possible, but the latency at that rate was too high to be useful.
The 2013 architecture (Nishtala et al., "Scaling Memcache at Facebook", NSDI 2013). The paper describes three scales: one cluster, one region and many regions.
Look-aside, demand-filled caching. A web server asks memcache for a key. On a miss it reads the database or service and sets the value. On a write it updates the database and then deletes the key rather than updating it, because deletes are idempotent. Memcache is not authoritative and may evict anything. See Caching strategies.
In a cluster: latency.
- Batching by dependency graph. The web application builds a DAG of data dependencies and fetches everything that can be fetched in parallel. The average batch is 24 keys and the 95th percentile 95.
- Stateless clients. Memcached servers never talk to each other. Routing, serialization, compression, error handling and batching live in the client, either a library or mcrouter, a proxy that looks like a memcached server.
- UDP for gets, TCP for sets and deletes. Gets go directly over UDP, bypassing mcrouter. Lost or reordered packets count as errors and are treated as misses (0.25% of gets at peak), and clients skip refilling after an error to avoid adding load. Sets and deletes go over TCP through a local mcrouter, which pools connections. UDP gave about 20% lower latency.
- Incast control. A page touching hundreds of servers can get all replies at once and overflow rack switches. Clients use a sliding window of outstanding requests that grows on success and shrinks on timeouts, like TCP congestion control but across all destinations. Too small a window serializes fetches; too large causes congestion.
In a cluster: load.
- Leases. On a miss, memcached gives the client a 64-bit lease token bound to the key. The client must present it when setting the value. If a delete arrived in the meantime, the token is invalid and the set is rejected, which prevents stale sets (an old value written after a newer delete, similar to load-link/store-conditional). To stop thundering herds, the server issues at most one token per key every 10 seconds. Other clients are told to wait briefly and retry, by which time the leaseholder has usually filled the key. On one set of herd-prone keys, peak database queries fell from 17,000 per second to 1,300.
- Stale values. A deleted item moves briefly to a recently-deleted structure. A get can return a lease or a value marked stale, so applications that can tolerate it continue without waiting.
- Pools. Workloads with different churn hurt each other: low-churn valuable keys were evicted before high-churn keys no one wanted any more. A default wildcard pool, plus separate pools (small for cheap-to-miss hot keys, large for expensive-to-miss rare keys), fixes that.
- Replication within a pool. When an application fetches many keys at once, the whole set fits on one or two servers, and the request rate exceeds one server, replicate instead of splitting. Splitting 100 keys across two servers still sends every request to both. Replication halves per-server load.
- Gutter. About 1% of a cluster's servers form a Gutter pool. When a get gets no reply, the client retries in Gutter and fills it with short-lived entries. This reduced client-visible failures by 99%. Rehashing keys onto the remaining servers was rejected, because one key can carry 20% of a server's load and would overload its new home.
In a region: replication. Adding servers to one cluster makes incast and hot keys worse, so a region holds several frontend clusters (web plus memcache) sharing one storage cluster.
- Invalidation from the database. SQL statements that change data are annotated with the memcache keys to delete. mcsqueal daemons on every database read the commit log and broadcast deletes to every frontend cluster in the region. They send batches to dedicated mcrouters in each cluster, which unpack them, giving an 18-fold improvement in deletes per packet. Because invalidations come from a reliable log, lost ones can be replayed, which web-server invalidation could not do.
- Regional pools. Large, rarely read items are stored once per region and shared by all frontend clusters, saving memory at the cost of crossing cluster boundaries, which have 40% less bandwidth.
- Cold cluster warmup. A new or emptied cluster reads misses from a warm cluster instead of the database, cutting recovery from days to hours. A race could leave stale data, so deletes in the cold cluster use a two-second hold-off that rejects adds. A failed add tells the client to read the database.
Across regions: consistency. One master region holds the primary MySQL databases; other regions have read replicas fed by MySQL replication. Invalidations travel with the replication stream, so a replica region never invalidates before the data arrives. For writes from a non-master region, a remote marker is set in a regional pool before the write. On a later miss, a reader that sees the marker reads from the master instead of the possibly stale local replica. This trades extra latency on a miss for a lower chance of stale reads.
Single-server work. Fine-grained locking tripled hit throughput from 600,000 to 1.8 million items per second. An adaptive slab allocator moves memory between size classes to balance the age of their oldest items, approximating one global LRU. A transient item cache evicts short-lived keys proactively, cutting one key family's memory share from 6% to 0.3%. Keeping cache data in System V shared memory lets a server be upgraded without losing its contents, because refilling a cold server takes hours.
Overlooked constraints.
- The network is the bottleneck, not memory. All-to-all traffic between web and cache servers causes incast and packet-rate limits. That is why UDP, batching, sliding windows and batched deletes matter.
- Failures move load to the database. Without leases and Gutter, a lost cache server or a popular key's invalidation turns into a database spike.
- Invalidations must come from a durable log. Web servers sending deletes cannot replay a lost or misrouted one; commit-log daemons can.
What Meta sacrificed. Strong consistency (best-effort eventual consistency, with stale reads possible during races and lag), memory (replicated pools and clusters) and simplicity in clients, in exchange for billions of reads per second with sub-millisecond latency and databases protected from load.
Deep Dive: Lease arithmetic, the replication-versus-sharding choice, and incast windowsShow
Thundering herd with and without leases. Suppose a hot key gets 5,000 reads per second and is invalidated by a write. Refilling takes 5 ms from the database. Without leases, every read during the refill window misses: 5,000 times 0.005 is 25 database queries per invalidation. If the key is written 20 times a second, that is 500 queries per second for one key, and a popular object with many such keys produces the paper's 17,000 queries per second. With one lease per 10 seconds, the database sees at most one query per key per write burst. The others wait a few milliseconds and hit the refilled value. The paper's measured drop was from 17,000 to 1,300 per second.
Why replicate instead of shard. The paper's example: a server holds 100 items, handles 500,000 requests per second, and each request wants all 100 keys. Getting 100 keys costs about the same as 1. To reach 1 million requests per second, sharding across 2 servers splits each request into 2 requests of 50 keys. Both servers still see 1 million requests per second, so nothing improves. Replicating all 100 keys on 2 servers sends each request to one replica, so each sees 500,000. The cost is that every delete goes to every replica.
Incast window intuition (handbook's illustration). A page needs 500 keys across 200 servers. With a window of 500, all replies arrive within about 100 µs, roughly 500 KB of data into one top-of-rack switch port with perhaps 100 KB of buffer, so packets drop and gets fail. With a window of 50, replies arrive in 10 waves. Each wave fits the buffer, at the cost of 10 sequential round trips of about 200 µs, or 2 ms. The optimum sits where the queueing delay from small windows equals the error cost of large ones, which is what Figure 4 of the paper measured.
Gutter sizing. If 1% of servers form Gutter and up to 1% of main servers fail, Gutter absorbs the failed servers' traffic with short TTLs. Measured Gutter hit rates exceed 35% within 4 minutes of a failure, so roughly a third to half of that traffic never reaches the database.
Lesson 2: mcrouter, a memcached protocol router (2014)#
Assumptions. Traffic: close to 5 billion requests per second at peak, across thousands of cache servers in dozens of clusters worldwide. Compatibility: any client that speaks the memcached ASCII protocol must work unchanged. Operations: pools change constantly, hardware is tested with real traffic, and clusters are brought up empty.
What it is. mcrouter (pronounced "mick-router") sits silently between clients and memcached. To a client it looks like a memcached server; to a server it looks like a client. Meta open-sourced it under a BSD licence in 2014. Instagram ran it on Amazon Web Services before moving to Meta's infrastructure, and Reddit tested it in production.
Features, grouped by purpose:
- Distribution: connection pooling (many clients share outgoing connections), several hash schemes including a consistent hash called furc_hash, hostname hashing to give each client a stable replica, and prefix routing (keys starting with "foo" to one pool, "bar" to another, everything else to a wildcard pool).
- Replication and availability: replicated pools (writes go to all replicas, each client reads from one), destination health checks with automatic failover, and background probes that switch back once a host recovers. Soft errors such as timeouts may happen a few times; hard errors such as connection refused mark a host down immediately.
- Operations: shadowing a full or partial copy of production traffic to test new hardware or pool sizes; online reconfiguration by reloading config files on a background thread with no added latency; cold cache warm-up that fills a new pool from a warm one; broadcast operations by key prefix; one config for every cluster, interpreted by location; rich stats and debug commands ("which host would this key go to?").
- Consistency: a reliable delete stream that logs deletes to disk when a destination is unreachable and replays them later, while always reporting success to the client.
- Protection and convenience: rate limits per operation type at host, pool or cluster level; splitting and re-joining large values that would not fit a slab; local-then-remote multi-level caches; IPv6 and SSL, including SSL between chained mcrouters.
Route handles. Configuration is a graph of small modules called route handles, each with one interface: route a request and return a reply. They compose freely:
- AllSync sends to all children and waits for all replies.
- AllAsync sends to all without waiting.
- AllMajority waits for a majority.
- Failover tries children in order until one succeeds.
- Warm-up reads from a cold pool and falls back to a warm one.
Moving a warm-up handle higher in the tree warms an entire cluster from another cluster.
Implementation. C++ (C++11), some C, protocol parsing in Ragel, Folly and fbthrift for asynchronous networking. Each thread runs an event loop (libevent), and each request runs in a lightweight fiber built on boost::context. Configuration is JSON.
Overlooked constraints.
- A proxy adds a hop. Meta still sends gets over UDP directly from clients in the hottest paths (Lesson 1), and uses mcrouter for sets, deletes and connection pooling.
- Configuration is now critical. One bad routing config can send all traffic to the wrong pool, which is why reloading is atomic and debug commands exist.
- Reporting deletes as successful when they are only logged gives bounded staleness, not immediate consistency.
What Meta sacrificed. Some latency and a component in every path, in exchange for routing, failover, shadowing and warm-up that applications never have to implement. Twitter's twemproxy made a similar choice.
Deep Dive: Composing route handles, and what shadowing buysShow
Composition as configuration. A route handle tree is like a small program: Failover(AllSync(replica1, replica2), Gutter). A write goes to both replicas and waits; if that fails, it goes to Gutter. Because each handle is independently testable, complex behaviour is built from parts with known semantics, the same idea as middleware chains in HTTP servers or Envoy filter chains.
Shadowing for capacity tests (handbook's illustration). To test whether new servers with twice the memory can replace 100 old ones with 50 new ones, shadow 10% of the key space to a 5-server test pool, rehashed for the new size. Within a day you see the hit rate, the latency and CPU at real request mixes, without any user seeing the test pool. A synthetic benchmark misses the real key-size distribution, which spans from tens of bytes to hundreds of kilobytes in Meta's pools.
Warm-up cost. A cold 100-server cluster serving 5 million gets per second at a 0% hit rate would send 5 million queries per second to databases, which is impossible. With warm-up, misses go to a warm cluster with a 95% hit rate, so the databases see 5% of 5 million, 250,000, falling as the cold cluster fills. Warm-up is switched off once the hit rate stabilises, because the cross-cluster reads cost bandwidth.
Lesson 3: Cache made consistent, Polaris and consistency tracing (2022)#
Assumptions. Traffic: TAO serves more than one quadrillion queries a day. At a 99% hit rate that is still more than 10 trillion cache fills a day, so logging every cache change is impossible. Consistency target: as close to perfect as can be measured. Correctness of measurement: zero false positives, or engineers will learn to ignore the alarm.
Why caches with invalidation are hard. A cache does not hold the truth; something else (a client or a pub-sub system) must tell it about each change. The classic race: the cache asks the database for x and gets 42. Before that reply arrives, x changes to 43 and the invalidation for 43 arrives and is applied. Then the late fill reply sets x back to 42, and the cache is wrong indefinitely. Versions help, since older data must never overwrite newer data. But if the entry "x=43 version 2" is evicted before the late fill arrives, the cache no longer knows a newer version exists. A dynamic cache like TAO or memcache changes data on both the read path (fills) and the write path (invalidations), which creates races a database, which changes data only on writes, never sees.
Why it matters. From a user's view, a stale cache entry can look like data loss. A messaging service stored the mapping from user to primary message store in TAO and moved users between regions to keep storage close to them. After Alice's store moved from region 2 to region 1, Bob's message went to region 1 via a correct TAO replica, but Mary's went to region 2 via an inconsistent one. Neither region had all of Alice's messages, which is a split brain caused by a cache.
Step 1: measure with Polaris. Polaris checks client-observable invariants, because an anomaly no client can see does not matter. It acts as a client and knows nothing about the service's internals, so it is generic; Meta has dozens of integrations. For caches, the invariant is "the cache should eventually match the database". Polaris pretends to be a cache server and receives invalidation events. On "x=4 version 4", it queries all cache replicas. If one returns "x=3 version 3", it flags it and requeues the check against the same host.
It reports at timescales: one minute, five minutes and ten minutes. A sample still inconsistent after one minute counts as a one-minute inconsistency. Multiple queues give efficient backoff and retries and avoid false positives from in-flight invalidations.
Ambiguous replies are the hard case. If the cache says x does not exist, either the cache is wrong or a version 5 delete has already happened. Only the database can tell, and cache-bypassing reads are expensive and risky. Polaris therefore checks the database only when a sample crosses a reporting timescale. Most transient mismatches resolve on retry, so few database reads are needed.
Polaris's query carries a flag asking whether the cache host has already processed the invalidation. That separates transient lag from "permanent" inconsistency, where a stale value persists after the invalidation was processed.
The output is a metric of the form "N nines of cache writes are consistent within M minutes". For TAO at five minutes it went from 99.9999% to 99.99999999%, fewer than 1 in 10 billion writes inconsistent after five minutes. Polaris runs as a separate service so it scales independently; more nines need only more Polaris throughput or longer windows.
Step 2: trace only where bugs live. From one cache server's view, only three questions matter: did it receive the invalidation, did it process it correctly, and did the item become inconsistent afterwards? After a write, there is a short window in which fills and invalidations race. Outside it, the cache is effectively static. Meta's stateful tracing library logs cache mutations only inside that window, including evictions. It keeps an index of recently modified keys to decide what to log, so the absence of a log entry reveals that an invalidation never arrived. It also records the code path. It is embedded in major cache services and along the invalidation pipeline.
A real bug it found. The cache showed "metadata=0 version 4" while the database had "metadata=1 version 4", indefinitely. A rare transaction updated a metadata table and a version table together. The steps were:
- The cache filled the old metadata.
- The transaction committed.
- The cache filled the new version, interleaved with the transaction.
- The invalidation hit a rare transient error, and the error handler called "drop the item if its version is less than 4".
- The cached item already had version 4 with stale metadata, so the drop did nothing.
Polaris alarmed immediately, and tracing let on-call engineers find the bug in under 30 minutes. Similar bugs once took weeks to find, if they were found at all.
Future work. Consistency for disaggregated secondary indexes, measuring consistency at read time, and a high-level consistency API for distributed systems, something like C++'s std::memory_order.
Overlooked constraints.
- Evictions erase the evidence. Versioning alone fails when the newer version is evicted, so fills must carry enough information to be rejected, such as leases (Lesson 1) or a version check against a durable source.
- Error handlers are where consistency bugs hide. The race was handled; the transient-error path was not.
- Monitoring needs its own invalidation path. If Polaris shared the cache's network path, a partition would hide inconsistencies.
What Meta sacrificed. A separate service and a tracing library to maintain, and some database reads for verification, in exchange for a trustworthy, quantitative consistency metric and fast root-causing.
Deep Dive: What ten nines means, and how to sample itShow
Scale of ten nines. If TAO processes 10 billion cache writes (invalidations and versioned updates) a day, ten nines means at most one inconsistent write a day after five minutes. At six nines it was 10,000 a day. The improvement is not a percentage tweak but four orders of magnitude fewer user-visible anomalies.
Sampling to measure it (handbook's illustration). To estimate a rate near 1 in 10 billion, you need to observe at least tens of billions of writes, or aggregate over long windows. Checking every write costs one read per cache replica per write. With 10 replicas and 10 billion writes a day, that is 100 billion check reads a day, about 1.2 million per second, a small fraction of TAO's billions of reads per second. A cheaper option is to check a 1% sample over 100 days, which gives the same statistical power over a longer window. That is why Polaris can "add nines" by adding throughput or widening the window.
Why the race window matters for tracing. If the race window is about 100 ms after each write and a key is written once an hour, the window covers about 0.003% of the time. Tracing only inside it cuts trace volume by a factor of tens of thousands while capturing the moments when inconsistencies can be introduced.
The general rule. Any cache filled from a source that changes needs three things: a way to reject stale fills (lease or version check), a durable invalidation source that can replay, and an independent checker that reads like a client. Uber's CacheFront (in the Uber blog page) added the same version check with a Lua script for the same reason.
Lesson 4: CacheLib, a shared caching engine (2021)#
Assumptions. Each team building its own cache duplicates work on the same problems: concurrency, eviction, memory efficiency, deployment and warm restarts. DRAM is getting more expensive and power-hungry to scale, so caches must also use flash (NVM and SSD drives) as a cheaper second tier. New caching heuristics need a shared place to land and be tested.
What it is. CacheLib is a C++ library for in-process caches, with a simple API for building concurrent caches that span DRAM and flash. It is used in more than 70 large systems at Meta, including the social graph, the CDN, storage and look-aside key-value caches. Because so many systems share it, one optimization benefits all of them. Meta open-sourced it in 2021, together with CacheBench, a benchmarking tool that replays production-like workloads.
Hybrid DRAM and flash. Hot items stay in DRAM; less popular items move to flash, which is much cheaper per gigabyte but slower (tens to hundreds of microseconds against under one) and wears out with writes. Deciding what deserves DRAM, what deserves flash and what should not be cached at all is the research problem CacheLib aims to centralise.
Ecosystem. Twitter was integrating CacheLib into its Pelikan cache to put objects on SSD. Pinterest was evaluating it for ML serving. Researchers at Carnegie Mellon, Princeton and Yale use CacheLib and CacheBench to test ideas on industry-like workloads. Meta worked with Intel, KIOXIA, Samsung and Western Digital on SSDs suited to caching, now part of the Open Compute Project NVMe Cloud SSD specification.
Overlooked constraints.
- Flash endurance limits the admission rate. Writing every DRAM eviction to flash would wear out SSDs quickly, so a hybrid cache needs an admission policy.
- In-process caches die with the process. Warm restarts, like memcache's shared memory trick in Lesson 1, matter for any large in-process cache.
- A shared engine means shared bugs. One defect affects 70 systems, which raises the bar for testing.
What Meta sacrificed. Freedom for each team to tune a bespoke cache, in exchange for one engine where every optimization and hardware improvement pays off many times.
Deep Dive: The economics of a flash tierShow
Cost per gigabyte (handbook's illustration). Suppose DRAM costs about 3 dollars per GB and data-centre flash about 0.10 dollars per GB. A 1 TB working set costs 3,000 dollars in DRAM or about 100 in flash. If 20% of requests go to the hottest 5% of items, and 60% to the next 45%, then 50 GB of DRAM plus 450 GB of flash can serve 80% of requests from cache for about 195 dollars, against 1,500 dollars for 500 GB of DRAM.
Latency budget. A DRAM hit costs about 1 µs inside the process; a flash hit about 100 µs; a miss to a backend 1 to 10 ms. With 20% DRAM hits, 60% flash hits and 20% misses at 5 ms, the average is 0.2 µs plus 60 µs plus 1,000 µs, about 1.06 ms. Without flash, the misses rise to 80%, about 4 ms. The flash tier cuts average latency fourfold even though each flash hit is 100 times slower than DRAM.
Endurance. An SSD rated for 1 drive write per day on 2 TB can absorb 2 TB of writes daily. A cache that admits every eviction at 50,000 objects per second of 4 KB writes 200 MB per second, about 17 TB a day, more than 8 times the rating. Admission filters that only write items seen at least twice cut this drastically, and that is the kind of policy CacheLib centralises.
Family 2: The social graph and storage
Lesson 5: TAO, a graph-aware cache over MySQL (2013)#
Assumptions. Traffic: more than a billion reads and millions of writes per second in 2013. By 2021, the RAMP-TAO paper reports over ten billion reads and tens of millions of writes per second, on petabytes of changing data. Latency: a page must be built on the fly in a few hundred milliseconds, because feeds are too personalised and change too fast to precompute. Consistency: eventual by default, with users seeing their own writes with high probability. Maintenance: product engineers must change schemas without operator work.
Why memcache plus MySQL was not enough. Two mismatches with the workload:
- InnoDB's buffer pool assumes spatial locality. It caches pages of rows that sit next to each other on disk. Facebook's workload has creation-time locality instead: recently created items are the ones read.
- Many requests ask about relations that do not exist. "Does this user like this story?" is false for most stories in a feed. Pulling kilobytes of disk pages into a block cache to answer "no" pollutes the cache.
Memcache fixed memory efficiency, but product engineers had to manage two data models (relational tables and flat key-value pairs derived from SQL), which led to bugs, inconsistencies and slow schema changes.
Objects and associations. In 2007 engineers defined a graph API in PHP on the web servers:
- Objects are typed nodes with a dictionary of fields (users, check-ins, comments).
- Associations are typed, directed edges grouped into lists by their origin, each with a time attribute.
Likes, pages and events were built entirely on it. The client-side version had four flaws:
- A small edge-list update invalidated the whole cached list.
- Range queries pulled entire lists to web servers even when the result was tiny.
- Consistency was hard to maintain.
- Preventing thundering herds needed distributed coordination that memcache lacked.
Work on TAO ("The Associations and Objects") began in early 2009 as a dedicated service. The full design is in Bronson et al., "TAO: Facebook's Distributed Data Store for the Social Graph", USENIX ATC 2013.
Data model and API. Together, the objects and associations form a labelled, directed multigraph. Each association type can declare an inverse type, such as "likes" and "liked by". When one edge is written, TAO writes the inverse edge automatically, which keeps mutual relations intact and makes traversal fast in both directions. Object schemas can gain fields or deprecate them without operational work. Reads on associations come in three shapes:
- Point query: does the edge (id1, type, id2) exist, and what is its data?
- Range query: the most recent edges of (id1, type), ordered by time, such as "the 50 latest comments", with cursors for paging.
- Count query: how many edges of (id1, type) exist, kept up to date and answered in constant time.
TAO deliberately offers no complex traversals, pattern matching or server-side set intersection. Intersections run in a client library through point and range queries. Because the graph has so little clustering, doing it on the server would cost about the same network and CPU.
Implementation.
- Separate storage and cache clusters. Persistent clusters run MySQL; caching clusters keep data in RAM and flash. They scale independently.
- Hundreds of thousands of shards. Objects and associations in the same shard live in the same MySQL database and on the same cache servers. Shards can be migrated or cloned to spread load spikes, for example a celebrity photo that appears in tens of millions of feeds at once. Applications may choose a shard at creation time to colocate related data.
- Two cache tiers per region. Clients talk to followers. A follower miss goes to a leader, which talks to MySQL. All writes go through follower to leader, and caches are updated as the successful reply passes back down (write-through). Leaders keep the region consistent, act as a second cache (optionally on flash) and protect MySQL during outages.
- One primary region per shard. Secondary regions forward writes to the shard's primary region, and MySQL replication carries updates outwards. The write-through path gives read-after-write consistency even for writes made from a secondary region. Moving a shard's primary to another region is automated and is the normal response to a failed MySQL instance.
Consistency choice. Meta chose eventual consistency because failures and partitions, even inside one data centre, are certain. For most products, losing consistency briefly is less harmful than losing availability. A few use cases opt into strong reads, paying extra cost and some availability.
Overlooked constraints.
- Inverse edges live on different shards, because edges are sharded by their source. Keeping both sides in sync is a cross-shard write, which Lesson 6 returns to.
- The API's simplicity is a constraint on product teams. Anything beyond point, range and count queries must be composed by the client or precomputed elsewhere, such as in search indexes.
- Hot objects need shard cloning, not more shards. One celebrity object is one key, so spreading load means replicating it.
What Meta sacrificed. Arbitrary queries, joins and strong consistency by default, in exchange for a simple API that hides caching and sharding from thousands of engineers and serves billions of reads per second.
Deep Dive: Why a graph cache beats a block cache for this workloadShow
The negative-lookup problem. Suppose a feed of 100 stories asks "has the viewer liked story X?" for each one, and the viewer liked 3. In a block cache, each lookup pulls a 16 KB page of the likes index. 97 of those pages are read only to learn "no", so 1.5 MB of cache is filled with near-useless data per feed load. TAO caches the viewer's association list for type "likes", sorted by time, plus its count. Most negative answers come from one in-memory list. If the list is complete in cache, absence in the list means the edge does not exist, so no disk read is needed.
Creation-time locality. Range queries such as "the 50 latest comments" read the head of a time-ordered list. TAO can cache just the most recent part of a large list. A post with 100,000 comments might keep only the newest 1,000 edges in RAM and fall back to MySQL for deep pagination, which few users reach.
Follower and leader arithmetic (handbook's illustration). Suppose a region has 50 follower clusters each with a 95% hit rate, and the leader tier has a 90% hit rate on follower misses. Of 1 billion reads per second, 50 million reach leaders and 5 million reach MySQL. Without the leader tier, 50 million queries per second would hit MySQL, ten times more. The leader tier also deduplicates: if 50 followers miss on the same hot key at once, the leader fetches it once.
Read-your-writes from a secondary region. A user in Europe writes a comment to a shard whose primary is in the US. The write goes follower to leader in Europe, then to the US leader and MySQL. On success, the reply travels back down through the European leader and follower, which update their caches. A read by that user a moment later hits the updated European follower, even though MySQL replication to the European replica has not happened yet. When replication arrives, its invalidation is harmless because the cache already holds the same version.
Lesson 6: RAMP-TAO, atomic read transactions on an eventually consistent store (2021)#
Assumptions. Traffic: over ten billion reads and tens of millions of writes per second; fewer than 3% of writes are transactional. Latency: transactional reads must match normal TAO reads, with most finishing in one round trip to the local cache. Consistency: add atomic visibility without weakening availability. Maintenance: opt-in, rolled out to a few applications at a time over years, and with minimal changes to a mature system.
The problem. Applications increasingly use Ent, a higher-level query framework over TAO, and want transactional semantics. The paper (Cheng et al., "RAMP-TAO: Layering Atomic Transactions on Facebook's Online TAO Data Store", VLDB 2021) separates two needs:
- Failure atomicity (all or none of a write transaction persists). TAO already provides it in three ways: single-shard MultiWrites using MySQL transactions; cross-shard write transactions using two-phase commit with persisted progress, two-phase locking and one logical timestamp per transaction; and bidirectional associations, edge pairs that are 52% of association types and 56% of association writes. Most pairs commit in one round without the first phase of 2PC, and a background fixer repairs failures.
- Atomic visibility (a reader sees all or none of a transaction's writes). TAO lacks it. Shards replicate independently and asynchronously, so a batched read can see part of a committed transaction. This anomaly is called a fractured read.
The paper's example: Alice composes and records a song, and the app writes four edges together (compose, composed by, record, recorded by). Bob, reading during replication, might see the sheet music but not the recording.
Measurement before design. Meta mirrored production-shaped write transactions to test shards, injected the production changeset failure rate (2.22%, an upper bound) and generated batched reads from 30 days of Ent query profiles. Ent queries average 2.4 operations and 2.2 items, but range up to 587 operations and 162 items, across 1 to 10 shards. Findings:
- 6,433 fractured reads out of 10.1 million read batches, about 1 in 1,500 (0.06%).
- 45% were transient: reads within 500 ms of a successful write transaction, resolved by retry within seconds.
- 55% lasted up to 13 seconds (30 seconds in the worst case), because the overlapping write needed 2PC failure recovery.
- Up to 2.0% of bidirectional associations needed fixing after failure, and in hot spots they took minutes to settle.
At TAO's scale, 0.06% means millions of anomalous reads, rare and nondeterministic, which makes them hard to reproduce.
Choosing the isolation level.
- Read Committed still allows fractured reads.
- Snapshot isolation needs large dependency sets and multiversioning, and often forces cross-region reads, which breaks TAO's local, cacheable reads.
- Read Atomic isolation, between the two, guarantees atomic visibility and only needs the write sets of the transactions involved.
The RAMP protocols (Bailis et al., "Scalable Atomic Visibility with RAMP Transactions", SIGMOD 2014) provide Read Atomic isolation, but they have three problems for TAO:
- They verify every read, not just transactional ones.
- They need metadata replicated everywhere.
- They assume multiversioning, which TAO lacks. With one version per item, a needed version can be overwritten again and again, so a reader might never finish.
The key insight. Once a transaction is fully replicated, a naive read is atomically visible. Only recent, transactionally updated data needs checking.
The RefillLibrary. TAO already had a RefillLibrary, a buffer of about 3 minutes of recent writes from all regions. It is fed by the same at-least-once Wormhole stream as the cache and was originally built for cache consistency. RAMP-TAO extends it in three ways:
- A transactional bit per write. It costs no memory, because items are allocated by size class and one bit does not change the class.
- Transaction metadata: a 16-byte transaction ID and the write set, with keys of at most 24 bytes and usually fewer than 10 keys. Only transactional items carry it, and an item in an unusually large transaction may store only the bit.
- Multiple recent versions of transactional items.
The buffer's retention (3 minutes) exceeds the longest measured 2PC recovery plus replication lag (146 seconds), so anything evicted is already fully replicated.
The protocol.
- Read all items in parallel from TAO, along with their RefillLibrary entries.
- If no item was updated by a transaction recently, return immediately. This fast path is one round.
- If an item is missing from the buffer, compare its timestamp with the buffer's low watermark (the oldest entry). Older items were evicted and are fully replicated, so they are safe. Newer items mean the local buffer is behind, so fetch metadata from the database.
- For transactional items, compute the latest timestamp each key should have from the write sets (a RAMP-Fast style check). If some item is older than its transaction partner, request the needed version with an at-or-after read.
- Optimization: instead of chasing the newest versions, return slightly older versions that are atomically consistent, which the buffer almost certainly holds. Applications already tolerate staleness, so an older atomic result beats more round trips.
- If the buffer cannot help (needed version not yet replicated and older ones evicted), read the database. If that still fails, retry with backoff and finally fail the transaction. Fractured results are never returned.
For bidirectional pairs, both sides carry identical data and timestamp, so the newer side repairs the older one locally. Pair reads always finish in one round.
Results (prototype). Over 99.93% of read transactions finish in one round. The p99 is under 114 ms, close to TAO's p99 read latency of 105 ms on a similar workload, even though the prototype still fetched metadata from the database. The memory overhead is 0.42%: 3% of writes are transactional, and at most 14% extra versions are needed within the retention window.
Overlooked constraints.
- Write unavailability becomes read unavailability. A stalled 2PC can block an atomic read, which is why reads may fall back to older versions or time out instead of waiting.
- Read-your-writes tickets interact badly with transactions. FlightTracker attaches recent write metadata to reads for read-your-writes. It can demand a version that a stalled transaction has not made available. The paper's suggested remedy is to abort that transaction.
- Read Atomic is not a snapshot. It does not prevent read-write conflicts and cannot give a point-in-time view for analytics.
What Meta sacrificed. Full isolation (no snapshot or serializable reads) and guaranteed termination (rare reads fail with a timeout), in exchange for atomic visibility at almost no cost to non-transactional traffic.
Deep Dive: The atomic visibility check, step by stepShow
The check. For a read set R, collect each item's timestamp and, for transactional items, the write set of the transaction that produced that version. For each key k mentioned in any write set, compute latest[k], the maximum timestamp of any transaction in the result that wrote k. If any returned item has a timestamp below latest[k], the read is fractured. This is the RAMP-Fast idea: metadata on the items you did see tells you which versions you should have seen.
Worked example. T1 writes x and y at timestamp 1; T2 writes x and y at timestamp 2. A reader gets x at 1 and y at 2. y's metadata says T2 wrote x and y, so latest[x] = 2, but x is at 1, so the read is fractured. RAMP would fetch x at 2. RAMP-TAO may also choose x at 1 and y at 1 if the RefillLibrary still has y at 1, since both satisfy atomic visibility.
Why the low watermark eliminates false positives. If a key is absent from the RefillLibrary, either it was never written recently or it was written so recently that the local buffer has not received it. The buffer's oldest entry has timestamp W. If the key's cached version has a timestamp below W, any write to it would have been in the buffer, so it was not written in the window and is safe. Without the watermark, every buffer miss would need a database check.
Overhead arithmetic. Suppose a TAO host holds a RefillLibrary of 10 GB (handbook's illustration). With 3% of writes transactional and each needing at most 0.14 extra versions on average, extra versions add 3% times 14%, about 0.42% of entries. That matches the paper. Transaction metadata adds roughly 16 bytes plus 2 to 10 keys of 24 bytes, so about 64 to 256 bytes per transactional item, again only on the 3%.
The general pattern. The lessons section names it: in a read-optimised, geo-replicated system, stronger guarantees reduce to a cheap local staleness check with few false positives, followed by rare, incremental repair from remote data. FlightTracker uses the same shape for read-your-writes.
Lesson 7: Haystack, f4 and cold storage, matching storage to photo temperature (2009 to 2015)#
Assumptions. Traffic in 2009: over 15 billion photos, each stored in 4 sizes (60 billion images, 1.5 PB), growing by 220 million photos (25 TB) a week, with 550,000 images served per second at peak. Photos are written once, never modified, rarely deleted, and read most in their first days. Durability matters more than latency for old photos.
The NFS problem. The original stack had an upload tier, a photo-serving tier and NFS on commercial storage appliances. Every image was its own file. Directory and inode metadata far exceeded what the NFS tier could cache, so one photo read took several disk I/Os just to find the data. Facebook leaned on CDNs and added a profile-image cache (Cachr) and an NFS file-handle cache, but the metadata bottleneck remained.
Haystack (Vajgel, Beaver and Sobel; paper: Beaver et al., "Finding a Needle in Haystack: Facebook's Photo Storage", OSDI 2010). The goal was one disk read per photo, reading only photo data.
- Hardware. 2U blades with 2 quad-core CPUs, 16 to 32 GB RAM, a RAID controller with 256 to 512 MB of NVRAM write-back cache, and 12 or more 1 TB SATA drives. RAID-6 gives about 10 TB usable. Reads are random, so the NVRAM is reserved for writes, and disk caches are off for crash safety.
- Filesystem. XFS, which is extent-based, so a large preallocated file's block map fits in its inode. Block-based filesystems would need indirect blocks and extra reads.
- The store file. An append-only log of needles after an 8 KB superblock. Each needle has a header, data and a footer, and is identified by offset, key, alternate key and cookie.
- The index file. One record per needle, in order, used only to load metadata quickly at startup. It is usually under 1% of the store's size and can be rebuilt from the store.
- Writes append needles synchronously, then write index records asynchronously. On a crash, recovery truncates partial needles and rebuilds missing index records. A modification writes a new needle with the same key, and the needle at the largest offset wins.
- Deletes set a flag in the needle. Space comes back only through compaction, which copies live needles to a new file and swaps it in online.
- Photo Store server. Keeps an in-memory index of all needle offsets, using Google's sparse hash at about 2 bits of overhead per entry. A photo gets a 64-bit key and a random cookie, shared by its 4 sizes, with the size in the alternate key. The cookie makes URLs unguessable. A read looks up the offset in RAM and does one read of the whole needle, verifying key, cookie, checksum and the delete flag.
- HTTP is a simple libevent evhttp server, since the workload is I/O-bound.
f4, warm storage. The Tectonic paper explains the next step (f4 itself is Muralidhar et al., "f4: Facebook's Warm BLOB Storage System", OSDI 2014). Haystack's ideal effective replication factor was 3.6 (3 copies times 1.2 for RAID-6). As drives grew larger without getting more IOPS, Haystack became IOPS-bound. Extra drives bought for IOPS pushed the effective factor to 5.3. Older blobs moved to f4, which used Reed-Solomon RS(10,4) coding in two data centres for an effective factor of 2.8, accepting lower throughput for its lower request rate.
Cold storage (2015). Two billion photos were shared daily. Old photos could keep a lower replication factor in hot storage if a highly durable copy lived elsewhere. Instead of tape libraries, Meta redesigned the whole stack, building on the Open Vault OCP specification:
- The building. A data hall with under one-sixth of the power of a normal hall, holding up to one exabyte, with no UPS and no generators because it serves no live traffic. Facilities opened in Prineville, Oregon and Forest City, North Carolina.
- The rack. Only one drive per tray powered on at a time, enforced in drive-controller firmware so a software bug cannot blow fuses. Fans dropped from 6 to 4 per node, power shelves from 3 to 1, power supplies from 7 to 5 and bus bars from 3 to 1. A rack holds 2 PB on 4 TB drives at one-quarter the power of normal storage. With 480 drives it weighed over 1,100 kg and crushed the castors.
- Software principles.
- Durability at every layer, with data that describes itself so the system can recover even without its metadata service.
- Batching commands and trading latency for efficiency, because drives power on only within a duty cycle derived from their mean time between failures.
- A system that gets better as it grows.
- Erasure coding. Reed-Solomon coding, for example 10 data plus 4 parity chunks from which any 10 recover the file, stores backups of 1 GB in 1.4 GB. A re-encoding service can change parameters as media reliability changes.
- Bit rot. Checksums live next to the data. An anti-entropy scanner reads every drive about every 30 days. A separate repair process rebuilds lost pieces on other drives, cutting reconstruction from hours to minutes.
- Rebalancing. New capacity is treated as always present: the rebalancer moves old data onto new hardware while respecting power cycles, so migration is built in.
- Production surprise. Filesystems handled frequent mounts and unmounts badly, so drives moved to raw disk with no filesystem.
Overlooked constraints.
- IOPS per terabyte falls every year. Drive capacity grows but seek rates do not, so a hot tier on large drives becomes IOPS-bound and wastes capacity. This drove f4 and later Tectonic.
- Ephemeral media breaks age-based tiering. Content deleted before it ages into warm storage spends its whole life at the expensive replication factor.
- Power-limited hardware changes the software. Duty cycles, batched commands and filesystem mount behaviour become design constraints.
What Meta sacrificed. Haystack gave up POSIX files, in-place updates and immediate space reclaim to get one I/O per read. Cold storage gave up read latency (minutes to spin up a drive), power redundancy and general-purpose hardware for a fraction of the cost and power.
Deep Dive: Metadata per photo, and the replication factor arithmeticShow
Why NFS needed three I/Os. Reading one file can need a directory lookup (one I/O if the directory block is not cached), an inode read (one I/O) and the data read (one I/O). With billions of files, directory and inode blocks cannot all be cached. Each photo then costs about 3 random reads at about 10 ms each on SATA disks. A disk doing 100 random IOPS serves about 33 photos per second instead of 100.
Haystack's index size. A Photo Store node with 10 TB holding photos averaging 50 KB has about 200 million needles. If each in-memory entry needs about 10 bytes (key, offset and size compressed), that is 2 GB of RAM, comfortably inside 16 to 32 GB. Storing full filesystem inodes (256 bytes or more each) would need over 50 GB.
Effective replication factors.
- Haystack: 3 copies on RAID-6. If RAID-6 uses 10 data disks plus 2 parity, the overhead is 1.2, so 3 times 1.2 is 3.6.
- f4: RS(10,4) has overhead 1.4 in one data centre. Two data centres would be 2.8.
- Cold storage: 1.4 for the coded backup.
For 100 PB of logical photos, 3.6 times means 360 PB of raw disk, 2.8 times 280 PB, and 1.4 times 140 PB. Each step down saves tens of petabytes, worth tens of millions of dollars.
Tolerance of RS(10,4). Any 4 of the 14 chunks can be lost. If each chunk sits in a separate failure domain with a 1% chance of being down at a given moment, the chance that 5 or more are down at once is about C(14,5) times 0.01 to the 5th power, roughly 2,002 times 1e-10, about 2e-7. Three-way replication fails when all 3 copies are down, 1e-6 at the same 1%. RS(10,4) is both cheaper and more available than 3 replicas, at the cost of reading 10 chunks to rebuild one.
Scrub cadence. Scanning every drive every 30 days on a 4 TB drive at 100 MB per second takes about 11 hours of read time per drive per month, under 2% duty. That fits a one-drive-per-tray power budget only because scans are scheduled through the same duty cycle as normal reads.
Lesson 8: Tectonic, one exabyte-scale filesystem per data centre (2021)#
Assumptions. Capacity: exabytes per cluster, billions of files, one cluster per data centre. Tenants: about ten, including blob storage and the data warehouse, serving hundreds of applications. Latency: blob storage needs low latency, while the warehouse needs throughput (reads of several MB, writes of tens of MB). Maintenance: one system to run instead of Haystack, f4 and tens of HDFS clusters per data centre.
Why consolidate. Pan et al., "Facebook's Tectonic Filesystem: Efficiency from Exascale", FAST 2021, gives two reasons:
- Stranded resources. Haystack had spare disk capacity but no IOPS; f4 had spare IOPS but no capacity.
- HDFS limits. Each HDFS cluster has one metadata node, which caps it at tens of petabytes. Data sets larger than one cluster had to be split, and placing data sets into clusters was a two-dimensional bin-packing problem on capacity and throughput.
Architecture.
- Chunk Store. A flat object store of chunks, which grows linearly with storage nodes and knows nothing of blocks or files. Each node has 36 hard drives and a 1 TB SSD, used for XFS metadata and a hot-chunk cache managed by an endurance-aware cache library.
- Blocks. The unit of durability, made of chunks in different fault domains, either replicated or Reed-Solomon coded per block.
- Metadata Store. Three disaggregated layers, each hash-partitioned and stored in ZippyDB (Lesson 11), which runs RocksDB with Paxos-replicated shards:
- The Name layer maps a directory to its children.
- The File layer maps a file to its blocks.
- The Block layer maps a block to its disks, plus a reverse index from disk to blocks used for repair.
- Expanded keys. A directory listing is stored as one key per entry (d1,foo), (d1,bar) rather than one big list, so creating a file does not rewrite a list of millions.
- Client Library. Orchestrates everything at chunk granularity, so each application can tune its reads and writes per call. It talks to storage nodes directly, with no proxy hop for terabytes per second of data. Remote clients go through a stateless proxy in the cluster's data centre.
- Stateless background services. Garbage collectors between layers, a rebalancer and a repair service working per shard and per disk, a stats service, a disk inventory and health checks.
Consistency without cross-shard transactions. ZippyDB offers only in-shard transactions. Tectonic therefore guarantees read-after-write for data operations, for single-object operations and for moves within one directory, since a directory's files live in its shard.
- Cross-directory moves are two-phase (link at the new parent, then unlink the old) with a back pointer to stop concurrent moves.
- A rename racing with a create-overwrite of the same name is handled by a within-shard transaction that checks the name still points to the same file ID.
- Single-writer semantics. Each file has a write token; a new writer overwrites the token and seals the old writer's blocks.
Hash partitioning versus range partitioning. Azure Data Lake Store range-partitions its metadata layers, which colocates related directories and creates hot spots. Hash partitioning spreads them. About two-thirds of metadata operations hit the Block layer, and hashing spreads them evenly. Over three days, about 1% of Name-layer shards hit the 10,000 QPS per-shard limit because of very hot directories; those requests were retried after backoff. Tectonic also co-designed with the warehouse: list-files returns file IDs, so workers open files by ID without querying the directory shard again.
Multitenancy.
- Storage capacity is a non-ephemeral resource with strict per-tenant quotas, changed manually.
- IOPS and metadata QPS are ephemeral, managed per TrafficGroup (about 50 per cluster) instead of per application. Each group has a TrafficClass: Gold (latency-sensitive), Silver (normal) or Bronze (background).
- Spare capacity goes first to the same tenant's groups by class, then to other tenants. Borrowed traffic takes the lower of the two classes, so the class mix on a node stays the same.
- Enforcement happens at the client, with a modified leaky bucket over near-real-time distributed counters, so requests are delayed or rejected before wasting a trip. Nodes add a weighted round-robin scheduler.
- Protecting Gold requests on disks. Lower-class requests may cede a turn to Gold requests. Non-Gold I/Os in flight per disk are capped. Non-Gold scheduling stops if a Gold request has waited too long, since disks reorder their queues.
- Access control uses tokens per layer, verified in memory in tens of microseconds.
Tenant-specific write paths.
- Warehouse: write once, read many, files visible only when closed. Clients buffer full blocks, RS-encode in memory and write blocks in parallel: RS(9,6) for long-lived data, RS(3,3) for short-lived shuffle data. Hedged quorum writes send reservations to 19 nodes, write to the first 15 that accept, and acknowledge at 14 of 15. This improved p99 of 72 MB block writes by about 20% at 80% load without extra data transfer.
- Blob storage: tens of trillions of blobs packed into log-structured files. New blobs are replicated partial-block quorum appends (acknowledged after 2 of 3 replicas). The writer commits the new block size and checksum to metadata before acknowledging, so readers see everything up to that size. Sealed blocks are later re-encoded to RS(10,4) with one large I/O per target node, instead of 14 small I/Os per append.
Production results.
- One representative cluster: 1,590 PB of capacity, 1,250 PB used, 10.7 billion files, 15 billion blocks and 4,208 storage nodes, shared about half and half by blob storage and the warehouse. The warehouse's daily peaks needed 0.54 to 0.60 of the cluster's disk time against a standalone supply of 0.51, about 17% over-provisioning if it ran alone. Blob storage used only 0.11 to 0.14 of its 0.49, so consolidation covered the spikes.
- Fewer clusters: moving the warehouse from HDFS cut its cluster count by 10x.
- Space: blob storage's effective replication fell to about 2.8x.
Lessons from the paper.
- Block groups were too rigid. An early design grouped blocks to save metadata, but with 5% of nodes unavailable, 80% of groups could not accept writes.
- Name and File layers had to be split. An early metadata design combined them and caused hot spots.
- Memory corruption is routine at scale. Checksums are checked within and across process boundaries, including verifying transformations by inverting them.
- Reconstruction storms. Overloaded nodes fail direct reads, which trigger reconstruction reads at 10 times the I/O, which overload more nodes. Tectonic caps reconstructed reads at 10%.
- Higher metadata latency for warehouse engines, which had to parallelise renames.
- No recursive list or du. Hash sharding makes them expensive, so tenants build them client-side and directory usage statistics are aggregated periodically and can be stale.
- Not everything uses it. Bootstrap services need no dependencies, and graph storage needs SSD latency.
Overlooked constraints.
- Disk time, not IOPS or bandwidth, is the true shared resource, because small blob reads are seek-bound while warehouse reads are bandwidth-bound.
- A client library in every application means library bugs ship inside tenant binaries, so client rollout discipline matters as much as server rollout.
- Geo-replication is left to tenants. Tectonic protects against host, rack and power failures only, not data centre loss.
What Meta sacrificed. Lower metadata latency (HDFS kept everything in one node's RAM), recursive directory operations and atomic cross-directory moves, in exchange for exabyte clusters, shared spare capacity and one system to operate.
Deep Dive: Copysets, reconstruction storms and the cost of erasure codingShow
Copysets. A copyset is the set of disks holding one block's chunks. RS(10,4) uses 14 disks. If every block chose 14 random disks, almost every 5-disk combination would hold some block, so any 5 simultaneous failures would lose data. If very few copysets are used, data loss becomes rare but each failed disk's neighbours share many blocks, so rebuilding overloads them. Tectonic keeps about 100 consistent shuffles of all disks and forms copysets from contiguous disks in a shuffle chosen by block ID. This fixes the number of copysets to balance loss probability against reconstruction load. The idea comes from Cidon et al., "Copysets: Reducing the Frequency of Data Loss in Cloud Storage", USENIX ATC 2013.
Reconstruction storm arithmetic (handbook's illustration). A cluster serves 1 million reads per second, each normally 1 disk I/O. If 2% of nodes are overloaded and their reads fall back to RS(10,4) reconstruction, those 20,000 reads cost 10 I/Os each, adding 180,000 I/Os per second (about 18% more load) spread over the other nodes. If that pushes another 2% into overload, the next round adds more, a positive feedback loop. Capping reconstructions at 10% of reads bounds the extra load at 0.1 times 9, or 90% extra I/O in the worst case. In practice it is far less, because the cap is rarely reached.
Contiguous versus striped coding. With contiguous RS, each chunk holds a contiguous piece of the block, so a small read touches one disk. With striped RS, data is spread in small stripes over all data chunks, so every read touches 10 disks, but failures do not change read cost. Tectonic chose contiguous for cheap normal reads and added the reconstruction cap to control the failure case.
Hedged reservation versus plain hedging. Plain hedging sends the full data to extra nodes and cancels the slow ones, wasting bandwidth: for a 72 MB block at RS(9,6), each chunk is 8 MB, so 4 extra nodes waste 32 MB per block. Reservations are tiny messages, so the hedge costs only round trips, and the data goes only to nodes known to have capacity.
Lesson 9: RocksDB and MyRocks, write-optimized storage on flash (2013 to 2016)#
Assumptions. Traffic: a mixed read and write load, often write-heavy (feeds, counters, logs, the social graph's MySQL tier). Latency: reads in the low hundreds of microseconds from flash. Consistency: single-node atomic writes; replication is someone else's job. Maintenance: storage is the main cost of the database tier, so bytes per row and bytes written per row matter more than a few per cent of CPU.
In 2013 Dhruba Borthakur's team started from a simple observation. Fast flash cards could serve a read in roughly 50 microseconds, which is about the same time as one network round trip inside a data centre. So a remote storage server, which adds a network hop, could be twice as slow as a library that reads local flash directly. That argued for an embedded key-value store: a library linked into the server process, not a separate network service.
They started from Google's LevelDB, an open-source log-structured merge tree (LSM tree). An LSM tree buffers writes in memory, flushes them as sorted immutable files, and merges those files in the background. LevelDB was simple and correct, but it was built for a laptop-sized workload. On a server with many cores and flash cards that each deliver around 100,000 I/O operations per second (ten striped cards give about a million), LevelDB hit walls. Its compaction (the background merge) ran on a single thread, so heavy writes caused stalls where the foreground had to wait for compaction to catch up. Its use of memory-mapped files became a bottleneck under heavy reads.
RocksDB kept the LSM design and rebuilt the engine around four goals:
- Scale with cores. Multithreaded compaction, and a separate fast path for read-only data that avoids locking.
- Use fast storage efficiently. Keep the device busy with parallel I/O, and cut write amplification (how many bytes hit the disk per byte the user wrote).
- Be flexible. Make the main parts pluggable: compression per level, the memtable format (for example a prefix-hash memtable), the file format, and compaction filters that can drop keys during merge, which gives cheap expiry.
- Serve many workload shapes. IO-bound data much larger than RAM, fully in-memory data, and write-once bulk loads.
It added two compaction styles. Level compaction keeps each level about ten times larger than the one above and merges a file into the overlapping files of the next level. This gives low space overhead and good reads at the cost of more rewriting. Universal compaction merges whole sorted runs of similar size. It writes less but can temporarily double the space used. It also added prefix bloom filters, so a scan over one key prefix can skip files that hold no key with that prefix, and a merge operator, which lets a write say "add 1 to this counter" without first reading the old value.
The first published results were about ten times faster than LevelDB for random writes and bulk loads and about 30% faster for random reads. Inside Facebook, it quickly ran under viewing history, spam detection, graph search, real-time queries over Hadoop data and queue services. The post reported it managing close to a petabyte of data. The post was clear that RocksDB was a single-node engine, not a distributed database. Replication, sharding and failover were left to the systems built on top. ZippyDB, the next lesson but one, is the main one of those.
MyRocks (2016). Facebook's main user database tier, called UDB, stored the social graph behind TAO in sharded MySQL with the InnoDB engine. Moving to compressed InnoDB had already cut UDB's size by about 40%. Yoshinori Matsunobu's team asked whether RocksDB could do better as a MySQL storage engine. The answer, MyRocks, cut UDB storage by about another 50% relative to compressed InnoDB, which roughly halved the number of servers.
The reasons are worth knowing, because they explain why B-trees and LSM trees behave so differently:
- Random-update write amplification. InnoDB updates a row in place inside a 16 KB page. Changing 100 bytes still writes the whole page, and with the doublewrite buffer (InnoDB's protection against torn page writes) it writes it twice.
- Fragmentation. After random inserts and deletes, B-tree pages tend to sit around half to two-thirds full. That empty space is paid for on disk.
- Fixed compressed page size. Compressed InnoDB must choose a fixed on-disk page size. If a 16 KB page compresses to 5 KB but the chosen size is 8 KB, 3 KB is wasted.
- Per-row metadata. Each InnoDB row carries a 6-byte transaction ID and a 7-byte rollback pointer, uncompressed: 13 bytes per row. RocksDB stores a 7-byte sequence number and a 1-byte type, compresses them, and sets the sequence number to zero at the bottom level when no snapshot needs it, which then compresses to almost nothing. It also uses prefix key encoding, so neighbouring keys that share a prefix store it once.
MyRocks added two features that matter for replicas. Read-free replication: in an LSM tree, inserting into a non-unique secondary index needs no read, because you just write the new index entry. With row-based binary logs, a replica also does not need to read the primary key row or check uniqueness, because the primary already did. So a replica can apply changes with almost no random reads. Bulk loading writes sorted data straight into the bottom level, skipping compaction.
On LinkBench, Facebook's open social-graph benchmark, MyRocks was about 3.5 times smaller than uncompressed InnoDB and about 2 times smaller than compressed InnoDB. It wrote orders of magnitude fewer bytes to flash, with competitive QPS, and was more than six times faster on spinning disks. Lower write amplification had a hidden second benefit: it let Meta buy cheaper flash with lower endurance ratings and reserve less spare capacity on each drive.
The migration. Because MySQL replication is logical (it ships row changes, not disk pages), one replica set could mix InnoDB and MyRocks members. The team dumped a stopped InnoDB secondary and piped it into a new MyRocks instance, then let it catch up through replication. They verified with three checks: consistent snapshots of both engines at the same global transaction ID (GTID), full checksums of every index, and shadow query testing, which replays captured production SELECT queries against both and compares results. One subtle issue: MyRocks has no gap locks (the InnoDB locks on ranges between keys that block phantom inserts). Statement-based replication relies on gap locks to replay statements in the same order, so the primary had to use row-based binlogs, and the team first logged or rejected the queries that depended on gap-lock behaviour.
They did not replace InnoDB everywhere. At the time MyRocks lacked foreign keys, online DDL, full deadlock detection (it relied on short lock-wait timeouts instead), partitioning, and FULLTEXT and SPATIAL indexes. It was based on MySQL 5.6. For a tier like UDB, which used none of these features and was dominated by storage cost, the gaps did not matter.
Overlooked constraints.
- Write amplification is a hardware cost, not just a performance number. Flash wears out per byte written, so a 10x reduction lets you buy cheaper drives.
- An LSM tree moves cost to compaction. If compaction falls behind, write stalls follow, so compaction threads and I/O budget must be sized for the peak write rate, not the average.
- A storage engine swap is a correctness project. Checksums at the same GTID and shadow reads are what make it safe, not the benchmark.
What Meta sacrificed. Read latency on point lookups (an LSM read may check several levels, though bloom filters hide most of it), feature completeness (foreign keys, online DDL), the deep operational knowledge built up around InnoDB, and range-scan predictability during heavy compaction. In return it got half the servers for its largest database.
Deep Dive: Write and space amplification, B-tree versus leveled LSMShow
Three amplifications. Every storage engine trades three costs, sometimes called the RUM trade-off (read, update, memory) from Athanassoulis et al., "Designing Access Methods: The RUM Conjecture", EDBT 2016. Write amplification is bytes written to the device per byte of user data. Read amplification is the I/Os per lookup. Space amplification is bytes on disk per byte of live data. You can improve any two only by hurting the third.
B-tree write amplification (handbook's illustration). A row of 200 bytes is updated. InnoDB writes the 16 KB page, plus the doublewrite copy: about 32 KB for 200 bytes, an amplification of about 160. With batching, several updates may land on the same page before a flush, so in practice it might be 20 to 50, but it stays high for random updates over a large table.
Leveled LSM write amplification. With a size ratio of 10 between levels, each byte is rewritten about 10 times per level as it moves down (because merging one file into the next level rewrites about 10 files' worth of overlap). With 5 levels that suggests up to 50, but the real figure is often 10 to 30, because the top levels are small and much data is overwritten or deleted before it reaches the bottom. The key difference is that LSM writes are large sequential writes of compressed data, and the per-row overhead is tiny.
Space amplification. In leveled compaction, about 90% of data sits in the bottom level. Stale versions in upper levels are at most about 11% extra, so space amplification is about 1.1. A B-tree with pages two-thirds full has space amplification of about 1.5 before compression waste. Add the fixed compressed page size loss and the 13-byte uncompressed row headers, and the 2x gap MyRocks saw becomes easy to believe.
Worked example (handbook's illustration). A 100 TB InnoDB-compressed tier on flash with 3 replicas is 300 TB. At about half the size with MyRocks, it becomes 150 TB, so 150 TB fewer drives. If writes to flash drop from 500 MB per second per server to 50 MB per second, a drive rated for 1 drive-write per day instead of 3 is enough, which is a cheaper class of drive.
Lesson 10: MySQL Raft, consensus inside the database (2023)#
Assumptions. Traffic: millions of MySQL shards holding petabytes on thousands of machines, every shard with its own primary. Latency: commits in about a millisecond inside a region; regions are 10 to 100 ms apart. Consistency: no acknowledged write may be lost on failover, and only one primary may accept writes at a time. Maintenance: machines fail or are drained every day, so failover and replacement must be routine and automatic.
Before Raft, each shard used MySQL semisynchronous replication. The primary would not acknowledge a commit until at least one of two logtailers had the transaction in its binary log. A logtailer is a lightweight process that stores the binlog but does not run a full database. Both logtailers sat in the same region as the primary but in a different failure domain (another rack or power zone), which kept commit latency under a millisecond. Full MySQL replicas in other regions received changes asynchronously.
That data path was fast. The problem was the control plane: who decides the new primary, and how do you stop the old one? That logic lived outside MySQL in Python automation, a "MySQL pool scanner" that watched the fleet, and a service-discovery store that told clients where the primary was. To promote a replica, the automation had to fence the old primary, cutting it off by stopping the logtailers from accepting its binlog, then pick the replica with the most data, then update discovery. Each step needed locks and careful ordering, and every new corner case added another patch. When the automation itself was partitioned or slow, failover could take 20 to 40 seconds or need a human.
The 2023 post by Anirban Rahut, Abhinav Sharma, Yichen Shen and Ahsanul Haque describes replacing all of that with Raft, the consensus algorithm from Diego Ongaro and John Ousterhout, "In Search of an Understandable Consensus Algorithm", USENIX ATC 2014. The key change is that the control plane (membership and leader election) and the data plane (the transactions) go through the same replicated log, inside the mysqld process. A promotion is now a log entry, decided by the same quorum rules as any write. There is no separate system that can disagree with the data.
They forked kuduraft, the Raft library from Apache Kudu, and added several features:
- FlexiRaft: separate quorums for data commits and for leader elections (explained below).
- Proxying: send a log entry across a region boundary once and let a member there forward it, instead of the leader sending to every remote member.
- Compress once: compress each entry before sending to all members, instead of per member.
- A log abstraction, so the MySQL binlog could be the Raft log.
- Primary ban: mark members that may not become leader, for maintenance.
The MySQL side became a plugin, MyRaft, which talks to kuduraft through callbacks.
Topology. A typical shard ring had 12 members. Three regions could host the primary. Each of those held one MySQL server and two logtailers. Three more regions held learners: full MySQL replicas that receive the log but never vote. Roles map onto Raft cleanly: the Raft leader is the MySQL primary, Raft followers are read-only replicas or logtailers, and Raft learners are non-voting replicas.
The binlog is the Raft log. In normal MySQL, a replica copies the primary's binlog into a relay log, applies it, and writes its own binlog. With MySQL Raft, replicas write the received entries straight into their binlog, with no relay log. A separate apply log tracks what has been applied, for crash recovery.
The write path. The engine prepares the transaction. Group commit batches it with others and assigns global transaction IDs. Raft gives each entry an operation ID made of the term and the index, compresses it, puts it in an in-memory log cache, writes it to the binlog and ships it. The user thread waits until 2 of the 3 members in the leader's region have it. Acks from other regions do not count toward the commit. Then the engine commits, and a commit marker follows asynchronously. Commit latency therefore stays the same as semisync: one round trip inside a region.
Crash recovery. When a former leader restarts, each prepared transaction falls into one of three cases. If it never reached the binlog, it rolls back. If it reached the local binlog but not a quorum, the engine rolls it back, and the new leader writes a no-op entry in a higher term that overwrites (truncates) the orphaned tail. If it did reach the next leader, the local engine still rolls it back first, then reapplies it when the commit marker arrives through the log. On promotion, MyRaft callbacks abort in-flight transactions, roll back any GTIDs that were not committed, switch from applying the apply log to writing the binlog as leader, and turn off read-only mode.
FlexiRaft. Plain Raft needs a majority of all 6 voters for both commits and elections, which would put a cross-region round trip on every commit. FlexiRaft builds on Heidi Howard, Dahlia Malkhi and Alexander Spiegelman, "Flexible Paxos: Quorum Intersection Revisited", 2016, which shows that the commit quorum and the election quorum need not each be a majority. They only need to intersect. Meta's "single-region dynamic" mode commits with a majority of the leader's region. An election must then win a majority in the last known leader's region (so it is guaranteed to see every committed entry) and in the candidate's own region (so the new leader can commit). If the candidate is unsure who the last leader was, because terms were skipped, it must win majorities in more regions, up to all of them in the worst case. Pre-elections (checking whether you would win before raising the term) and mock elections (dry runs) keep term gaps rare.
Membership changes happen one member at a time rather than with Raft's joint consensus, which is simpler and safe for single-member changes. The change itself is carried in hijacked MySQL Rotate and Metadata binlog events, so it travels in the same log. Automation still decides when to add, remove or move members, and sets primary bans during maintenance, but it no longer decides correctness.
Production lessons.
- Raft gives correctness, not availability. With 3 in-region voters, two bad ones break the data quorum and writes stop. In a fleet with daily hardware churn, that means replacements must be quick and automatic.
- Stuck leaders after graceful transfer. Kuduraft had no automatic step-down, so a transferred-away leader could linger. Mock elections fixed this.
- Zombie members. A member that had been removed from a ring, or that belonged to an overlapping ring, could keep sending RPCs to members it should no longer talk to, a near-Byzantine case. They blocked removed members from sending at all.
- Tooling was the bigger investment. Dashboards, quorum inspection tools, voting history CLIs and Scuba (Meta's real-time analytics store) logging may have taken more effort than the server changes.
- Quorum Fixer. When a quorum is truly lost, a deliberately manual Python tool stops writes, finds the member with the longest log by checking outside Raft, forces quorum expectations so that member can win, then restores the normal settings. It was kept manual on purpose, so that every quorum loss gets a root-cause investigation instead of a silent auto-repair.
- Rollout. An enable-raft tool converted a semisync ring with a small window of write downtime per ring. Before each new server release, shadow environments ran thousands of injected failovers. Nightly checks compared primaries and replicas for consistency.
Results. Write latency matched semisync with no extra CPU. A graceful promotion took about 300 ms. An unplanned failover took about 2 seconds (500 ms heartbeats, election after 3 missed), compared with 20 to 40 seconds before, roughly a 10x improvement. The project started on MySQL 5.6 and moved to 8.0 along the way. Next steps listed: configurable consistency (quorums spanning regions or a geography, choosing per shard along the PACELC trade-off), proxying a US-to-Europe stream only once, leaderless designs like EPaxos, and a disaggregated log.
Overlooked constraints.
- External failover systems fail in correlated ways with the database they manage, because both are hit by the same network partitions.
- A commit quorum confined to one region means losing that region loses recent writes unless another region was caught up. That is a conscious durability choice, not an accident.
- Operating consensus at fleet scale is mostly about tooling and human procedures for the rare cases where the algorithm halts.
What Meta sacrificed. Cross-region durability on every commit (it kept commit latency in-region instead), the simplicity of a well-understood replication mode, and a large engineering investment in a forked consensus library and its tooling. In return it got one source of truth for both leadership and data, and failover ten times faster.
Deep Dive: Why FlexiRaft's quorums are safe, with numbersShow
The intersection rule. Safety in Raft rests on one fact: any election quorum overlaps any commit quorum, so a new leader always talks to at least one member that holds every committed entry. Flexible Paxos showed that if commit quorums are of size Q1 and election quorums are of size Q2 among N voters, it is enough that Q1 plus Q2 is greater than N. Majorities are one choice, not the only one.
Plain Raft on 6 voters across 3 regions (handbook's illustration). A majority is 4 of 6. With 2 voters per region, a commit must reach at least 2 regions, so every commit pays a 10 to 100 ms cross-region round trip. At 1 ms local latency that is a 10x to 100x slowdown.
FlexiRaft single-region mode. Commit quorum: 2 of the 3 voters in the leader's region (MySQL plus logtailers). Election quorum: a majority in the previous leader's region plus a majority in the candidate's region. Because the commit quorum lies entirely in the previous leader's region, and the election needs a majority there, they must share at least one member. That member has all committed entries, and Raft's log comparison rule makes sure the winner is at least as up to date.
Why term gaps widen the election. If terms 5 and 6 had leaders the candidate never heard of, the candidate does not know which region held the last commit quorum. To be safe it must win a majority in every region that might have led. In the worst case that is all 3 primary-capable regions, which is the same as a global majority. Pre-elections reduce failed elections, so gaps stay rare.
Failover timing. Heartbeat 500 ms, election triggered after 3 missed heartbeats: about 1.5 s to detect. One election round inside a region plus client discovery update: a few hundred ms. Total about 2 s. Compare the old path: detection by an external scanner, locking, fencing by stopping logtailers, choosing a replica, updating discovery: 20 to 40 s.
Availability math (handbook's illustration). If each in-region voter is down 0.5% of the time independently, the chance that 2 of 3 are down at once is about 3 times 0.005 squared, about 0.0075%, or about 40 minutes per year per shard. Across a million shards, that means some shard is in that state almost all the time, which is why prompt replacement and tooling are essential.
Lesson 11: ZippyDB, one managed key-value store instead of a hundred (2013 to 2021)#
Assumptions. Traffic: many tenants, each storing small keys and values, from filesystem metadata to event counters to product data. Total QPS reaches millions per second for single tenants such as feed. Latency: single-digit milliseconds in region, cross-region only when the tenant asks for it. Consistency: varies per tenant and per request. Maintenance: one team operates the service for the whole company.
After RocksDB shipped, many teams embedded it directly. Each team then had to solve the same problems on its own: replication, consistency, failover, recovery and capacity planning. Sarang Masti's 2021 post explains that ZippyDB, first deployed in 2013, was built to remove that duplicated work. It became Meta's largest strongly consistent, geographically distributed key-value store.
The founding design rule was reuse existing infrastructure. ZippyDB is mostly glue around parts that already existed:
- RocksDB for storage on each replica.
- Data Shuttle, a new replication library, and the main thing they built. It replicates with Multi-Paxos or asynchronously.
- Shard Manager (Lesson 20) for placing shards, balancing load, detecting failures and choosing leaders.
- A ZooKeeper-based configuration service for service discovery and configuration.
Tiers and tenants. ZippyDB is deployed as a few tiers, each spanning several regions. Most use cases live on the shared "wildcard" tier, because pooling tenants uses hardware better and costs less to run. A dedicated tier is created only when a tenant needs strict isolation, such as distributed-filesystem metadata.
Shards, replicas and roles. Each tenant's data is split into shards, replicated across regions. Within a shard, some replicas form the global scope: a Paxos group that replicates synchronously. The rest are followers, which receive updates asynchronously, like Paxos learners. Followers let a tenant have many cheap in-region read replicas while keeping the voting group small, so writes stay fast. Tenants can also give stickiness hints: which regions should hold replicas, so that reads and writes stay close to where the traffic comes from. A cache layer and a pub-sub feed of changes are available as options.
Data model. The API mirrors RocksDB: get, put, delete and their batch forms, iteration over a key prefix, and deleting a key range. On top of that come test-and-set, transactions and conditional writes. Writes can carry a TTL (time to live). Expired keys are hidden on read and physically removed during RocksDB's periodic compaction, so expiry costs almost nothing extra. Many apps use ZippyDB through an ORM layer that hides these details.
Micro-shards. Applications never see physical shards. They split their key space into micro-shards (written μshards), small units of related data, for example one per user. A physical shard is 50 to 100 GB and holds tens of thousands of micro-shards. This indirection lets ZippyDB move or split data without any client change. There are two mapping modes. Compact mapping is mostly static and changes only when a shard grows too big or too hot. Akkio mapping lets the Akkio service move micro-shards to the regions that use them (the next lesson).
Replication with epochs. Time on each shard is divided into epochs. Shard Manager picks one leader per epoch and grants it a lease for that epoch, kept alive by heartbeats. When the leader fails, or for load balancing, Shard Manager starts a new epoch with a new leader. Inside an epoch, the leader gives every write a rising sequence number, and Multi-Paxos makes the replicas agree on that order in a durable log. Committed writes are then applied in order on every replica. Meta chose external failure detection to keep the first version simple, and noted plans to move detection into Data Shuttle itself so that failover would not wait on Shard Manager. That is the same move MySQL Raft made in Lesson 10.
Per-request consistency. ZippyDB lets each request choose its trade-off:
- Default write: persisted in a majority of Paxos logs and written to RocksDB on the primary before the ack. A read from the primary then always sees it.
- Fast-acknowledge write: acked as soon as it is queued on the primary. Lower latency, but a primary crash can lose it.
- Eventual read: served by any replica, but ZippyDB refuses to serve from a replica that heartbeats show is too far behind. Because writes in a shard are totally ordered, this is really bounded staleness, which is much stronger than plain eventual consistency.
- Read-your-writes: the client process remembers the sequence number of its latest write and asks for a read "at or after" that version.
- Strong (linearizable) read: sent to the primary, which serves it only while it holds the lease, so no other primary can exist. If the primary is unsure about its lease, the read falls back to a quorum check.
Transactions. Transactions are serializable within one shard, and lower isolation levels are not offered, which keeps both server and client reasoning simple. They use optimistic concurrency control:
- The client reads from a snapshot, often on a secondary, and builds a write set.
- It sends the read set, the write set and the snapshot version to the primary.
- The primary checks whether any already-admitted transaction wrote a key in the read set after that snapshot.
- If there is no conflict, the transaction is admitted and is guaranteed to commit unless a server fails.
The primary tracks recent writes only within the current epoch. Transactions that span an epoch change are rejected, so the write history never needs to be replicated. Old history is purged, so the primary keeps a minimum tracked version and rejects any transaction whose snapshot is older. Conditional writes (preconditions such as key present, key not present, or value matches) are turned into server-side transactions using the same machinery. They can be cheaper, because the client does not need a read first.
Overlooked constraints.
- Multitenancy is the efficiency win, but it needs per-tenant quotas and noisy-neighbour protection, or one tenant's hot shard harms everyone on the tier.
- Lease-based strong reads depend on bounded clock drift between the primary and Shard Manager. That is why the fallback to a quorum read exists.
- Per-request consistency choices push responsibility to app developers, who must understand what "fast-ack" really risks.
What Meta sacrificed. Cross-shard transactions (listed as future work), the lower latency an embedded RocksDB had, and in-band failure detection in the early versions. In return it got one operated service with a menu of guarantees, replacing many hand-built replication layers.
Deep Dive: Choosing quorum size and follower count, with numbersShow
Write latency is set by the quorum. With a global scope of 3 replicas in regions A, B and C and the primary in A, a default write must reach one of B or C. If A to B is 15 ms and A to C is 60 ms, writes take about 15 ms plus local disk. With 5 global-scope replicas, the write needs 2 remote acks, so it waits for the second-closest region, perhaps 40 ms. Bigger quorums give more failure tolerance but higher latency (handbook's illustration).
Followers add reads without slowing writes. A tenant with heavy reads in region D adds 2 followers there. Writes still need only the 3-member quorum. Reads in D become local, perhaps 1 ms instead of 70 ms. The cost is that reads in D are bounded-stale: if the lag threshold is 1 second, a read may miss up to a second of writes.
OCC abort rate. If a hot key gets 1,000 transactions per second and each holds its snapshot for 5 ms before committing, about 5 transactions overlap at any moment. The chance that a transaction conflicts with at least one other on that key is very high, so most would abort and retry. OCC shines when conflicts are rare, for example per-user keys. For hot counters, a merge-style increment or conditional write is better than a read-modify-write transaction.
Why reject transactions across epochs. Conflict detection needs the list of writes since the snapshot. A new primary would need the old primary's in-memory history, which would have to be replicated on every write. Rejecting the rare transaction that spans a failover is far cheaper than replicating that history all the time.
Later: ZGateway, the proxy in front of ZippyDB (2026). Once more than a million client hosts used ZippyDB, the main cost was the traffic around the queries, not the queries. Each client held its own connections, and the same keys were read again and again. Meta's answer was a reverse proxy called ZGateway between the applications and the shards. It uses five techniques, each aimed at a different bottleneck:
- Shared connection pools. These cut idle-connection memory and restart storms.
- Batching. Different keys going to the same use case and shard share the per-request overhead, and the batch flushes on a timer or a size cap, whichever comes first.
- Request coalescing. Several callers asking for the same key share one in-flight lookup.
- Read-through caching. A per-key fill lock prevents stampedes, and a CDC stream keeps entries fresh within an agreed lag.
- Admission control. Bounded queues per use case and priority stop one team's spike from starving the others.
This is the noisy-neighbour constraint from above, solved at the gateway rather than inside storage. The full breakdown, with its trade-offs, is Lesson 6 of Real-World Architecture Lessons. One quick figure shows why coalescing and caching matter more than batching for hot keys: if 1,000 callers read the same profile within one 2 ms lookup window, batching still costs the database 1,000 lookups, while coalescing costs it 1 (handbook's illustration).
Lesson 12: Akkio, move the data to the user, not every copy to every region (2018)#
Assumptions. Traffic: billions of users, each mostly active from the same 2 or 3 regions. Latency: reads should be served in the user's region. Consistency: many datasets need strong consistency, so a local cache is not enough. Maintenance: adding a new data-centre region should not require yet another full copy of every dataset.
Muthukaruppan Annamalai and Victoria Dudin described the problem in 2018. Facebook had opened 15 data centres in eight years and served more than 2.2 billion monthly users. Early on, it kept a full replica of every dataset in every region, which made every read local. As regions multiplied, that became too costly. Each new region needed another full copy, plus the cross-region traffic to keep it updated.
Why not just cache? The obvious answer is a cache in each region in front of fewer replicas. The authors gave three reasons it fails for many important workloads:
- Low read-to-write ratios. If data is written often, cached copies are invalidated all the time, so the cache generates as much cross-region traffic as replication would.
- Strong consistency. Many datasets need it. Building strongly consistent caches is possible but adds much complexity and even more cross-region messages. Popular scalable caches like Memcached and Redis do not offer it, for good reason.
- Misses are expensive. Unless the hit rate is very high, the average latency is dominated by misses that cross regions.
Akkio's idea. Split data into micro-shards with strong access locality, for example one micro-shard per user's feed data, and place each micro-shard's replicas in the regions that use it. A user who reads News Feed every day from Eugene, Oregon might have a copy in Oregon and two more in nearby Utah and New Mexico. That is three copies for fault tolerance, all close enough that a traffic shift between them keeps latency similar. Akkio can track trillions of micro-shards.
The reported results, in limited production: about 40% smaller footprint, about 50% less related WAN traffic and about 50% lower perceived latency. The full design appears in Annamalai et al., "Sharding the Shards: Managing Datastore Locality at Scale with Akkio", OSDI 2018.
Architecture.
- Metadata DB. Maps each micro-shard to a placement. To Akkio a placement is opaque bytes, which may be a shard prefix, a specific shard or a region. The backend decides what it means. Akkio only needs to know which data centres each placement uses. Every access looks up the placement.
- Access DB. Records how often each micro-shard is accessed from each region. It uses ZippyDB's built-in time-windowed counters: one counter per micro-shard per data centre per client service, kept 10 days and usually queried over the last 3. Updating a counter on each access sounds heavy. But batching reduces millions of feed reads per second to a manageable write rate, and one dataset of user locality can be shared by many services. An offline pipeline through Scribe would also work, but would react more slowly.
- Data placement service (DPS). The Akkio client knows the placement's regions and the caller's region, so it can tell when an access crosses regions. Then it sends an asynchronous hint to the DPS. The DPS checks policy (is this micro-shard eligible, have too many migrations run in this window?). Then it reads the last 3 days of access counts, scores each region by accesses and free capacity (disk space, network use, disk IOPS), sums region scores into a score per placement, and picks the best. If that differs from the current placement, it starts a migration.
- New micro-shards are also created through the DPS, never by the client, to avoid a race where a client reads a micro-shard that does not exist yet. With no history, the DPS uses the caller's region and capacity.
- Serialised migrations. A lock in the metadata DB ensures only one DPS instance migrates a micro-shard at a time. If the lock is taken, the DPS drops the work until the next hint.
Consistency during migration. For eventually consistent backends, moving data is easy, because a briefly stale read is allowed. For strongly consistent backends, Akkio uses backend-specific strategies to make sure no stale read is served while the data moves.
Overlooked constraints.
- Every access now pays a metadata lookup. The metadata tier must be faster and more available than the data it describes, so it needs heavy caching.
- Placement must respect fault tolerance. Three copies in one metro would be fast and fragile, so the scoring has to keep copies in separate failure domains.
- Migration storms. A traffic shift such as a regional drain could make millions of micro-shards look misplaced at once. The per-window migration limit stops Akkio from reacting to a temporary shift with a flood of moves.
What Meta sacrificed. Uniform local latency for everyone (a user who travels, or whose traffic is shifted, sees cross-region reads until migration catches up), simple routing (each access needs a lookup), and a new critical service. The authors also noted that the gains depend on Facebook's size, and that smaller organisations are unlikely to see the same return.
Deep Dive: The storage and WAN arithmetic of placementShow
Full replication (handbook's illustration). A dataset of 1 PB with 15 regions, all holding a full copy, is 15 PB. A write of 1 KB is sent to 14 other regions: 14 KB of WAN traffic.
Akkio placement. Each micro-shard has 3 copies: 3 PB total, which is 80% less than 15 PB. A 1 KB write goes to 2 other copies, often in nearby regions: 2 KB of WAN, and much of it on shorter links. The real reported saving was smaller (40% footprint) because Akkio was only partly rolled out and the previous design was not a full copy everywhere for every dataset.
When does a micro-shard deserve a move? Suppose a user makes 200 accesses per day, and the counters show 80% from region West and 20% from East, while the data lives in East. Each West access costs a 60 ms round trip. Moving the data saves 160 times 60 ms, about 9.6 s of user waiting per day, and adds 40 cross-region accesses from East instead. A user's data might be 1 MB, so the migration moves about 3 MB once. That pays for itself in under a day.
Capacity in the score. If West is at 90% disk use, the score should penalise it, or every migration would pile into the most popular region and fill it. Summing region scores into a placement score lets Akkio pick, for example, West plus two nearby regions with spare space.
New regions. With full copies, a new region needs a full copy of everything on day one. With Akkio, the new region starts empty and micro-shards arrive as users are routed there. Capacity can simply move from old regions to the new one.
Lesson 13: Delos, a storage system whose consensus protocol can be swapped live (2019)#
Assumptions. Traffic: modest QPS but critical control-plane state, such as the ledger of which machine belongs to which job. Latency: tens of milliseconds acceptable at first, then much lower. Consistency: strong, durable and highly available. Maintenance: the system sits at the very bottom of the stack, so it must have almost no dependencies and must evolve without downtime.
Mahesh Balakrishnan and Jason Flinn presented Delos at Systems @Scale in 2019. Control-plane services, such as the cluster scheduler and its resource broker, sit at the bottom of the stack. If they depend on other services, a failure can cascade, and you can hit a bootstrap loop where A needs B to start and B needs A. Each of them also wants a different storage interface: SQL-like tables, key-value pairs, a hierarchical namespace or a queue. And each needs different performance and reliability. Building and operating a separate low-dependency storage system for every combination was not realistic.
The diagnosis. The authors argued that replicated systems are hard to build and evolve because they are monolithic. One codebase mixes three jobs:
- Ordering commands consistently and durably.
- Materialising state by applying those commands.
- Reconfiguring which servers do what.
Change any one, for example a new API or a new consensus protocol, and you often have to rewrite all three.
The layered design. Delos separates the three jobs:
- Materialisation above a shared log. Each server keeps a local copy of the state, in any form: a table store, a key-value map, a namespace. To change state, a server appends a command to the log. To read with strong consistency, it first catches up with the log, then reads locally. New APIs are thin layers, because they never deal with distributed coordination.
- VirtualLog. The shared log seen by the materialisation layer is a VirtualLog that chains together a sequence of underlying SimpleLogs. Reconfiguration of any kind, whether a new leader, new members, new parameters or a whole new protocol, means: seal the current SimpleLog, then continue the VirtualLog on a new one.
- SimpleLog. A SimpleLog is deliberately weak. It has fixed membership and fixed roles. It does not have to keep accepting appends through failures, so it does not need fault-tolerant consensus. It only needs a highly available seal operation, which stops further appends. Seal is theoretically weaker than consensus and much simpler to implement. When a SimpleLog fails for appends, the VirtualLog seals it and moves on.
The shared-log approach builds on earlier research such as CORFU by Balakrishnan et al. (NSDI 2012), which Balakrishnan co-authored. The Delos design is described in full in Balakrishnan et al., "Virtual Consensus in Delos", OSDI 2020.
Production story. The first deployment, DelosTable, reached production in eight months. Its first user was the Tupperware Resource Broker, which keeps the ledger of every machine in Meta's data centres and its allocation. DelosTable provided transactions, secondary indexes and range queries, exactly what Resource Broker needed. To ship quickly, the first SimpleLog was a pass-through over the existing ZooKeeper service. In effect Delos used ZooKeeper for ordering. Four months later the team swapped in a native SimpleLog with no downtime, cutting latency about tenfold for that workload. The native log is converged: the log and the materialised state live on the same servers, which removed ZooKeeper from the critical path.
Other experiments followed. One was a ZooKeeper-like hierarchical namespace with more capacity, and another a distributed queue. A third was a disaggregated SimpleLog on LogDevice (Lesson 15), running on separate servers. Delos could switch between the converged log and the LogDevice log based on latency SLAs. It used the converged log, which needs fewer resources and has no extra dependency, while it met the SLA, and the disaggregated one when it did not.
Overlooked constraints.
- The lowest layer of a company's infrastructure cannot depend on the layers above it. Delos's first use of ZooKeeper was a deliberate short-term dependency with an exit plan.
- Strong reads require syncing with the log tail first, so read latency includes a log round trip. That is a classic trade-off of shared-log designs.
- The VirtualLog's own metadata (which SimpleLog covers which range) must itself be stored with consensus. That is the one place where a real consensus protocol is still needed, but it changes rarely.
What Meta sacrificed. Some peak performance a hand-tuned monolith might reach, an extra layer of indirection on every operation, and the comfort of a widely known system like ZooKeeper. In return it got the ability to change APIs and consensus protocols without rewriting or stopping the service, and an eight-month path to production.
Deep Dive: Why seal is easier than consensus, and what a live protocol swap costsShow
Seal versus append. Consensus must keep choosing new values despite failures, which is the hard problem in the FLP impossibility result (Fischer, Lynch and Paterson, "Impossibility of Distributed Consensus with One Faulty Process", JACM 1985). Seal is a one-time, idempotent operation: mark the log so no new append will succeed, and report the tail. With a SimpleLog of 3 storage servers, sealing succeeds once a majority have marked themselves sealed. Any later append must reach a majority, so it overlaps a sealed server and fails. No leader and no repeated rounds are needed.
Why that is enough. The VirtualLog handles leader changes by sealing the old SimpleLog and starting a new one with a new leader. So a SimpleLog can have a fixed, preassigned leader. If that leader dies, appends stop, the VirtualLog seals, and a new SimpleLog with a different leader takes over. Leader election becomes part of reconfiguration, done in one reusable layer.
Cost of a swap (handbook's illustration). Seal takes one round trip to the SimpleLog's servers, perhaps 2 ms. Updating the VirtualLog metadata takes one consensus write, perhaps 5 ms. Servers then learn the new tail on their next append or sync, perhaps one more round trip. Total disruption is around 10 ms, compared with a planned migration that would otherwise copy all state to a new cluster and cut over.
Tenfold latency win. With ZooKeeper as the log, every append went from the Delos server to ZooKeeper and back, plus ZooKeeper's own leader-follower round, and then the server had to read the entry back. With the converged native log, the append is replicated directly among the Delos servers. If the ZooKeeper path cost about 20 ms and the native path about 2 ms, that matches the reported order of improvement.
Family 3: Moving data, logs, queues and metrics
Families 1 and 2 were about storing and serving data. Family 3 is about moving it: change streams, logs, work queues and metrics. These systems glue the stores together. A common thread is that each one picks a different point between strict ordering and loss-free delivery on one side, and availability and cost on the other.
Lesson 14: Wormhole, the database binlog as a pub-sub bus (2013)#
Assumptions. Traffic: more than 1 trillion messages a day from the user databases alone, well over 10 million per second. Latency: a few milliseconds above network latency. Consistency: ordered within a shard, at-least-once. Maintenance: dozens of consuming services, many with thousands of machines, all depending on the stream.
Laurent Demailly's 2013 post described a problem every large system meets. When a row changes in the user database (UDB), many other systems must react. Caches in every region need an invalidation or refill (Lesson 1). Search indexes such as Graph Search must update. The data warehouse (Hadoop, HBase, Hive and others) wants the change too, ideally in real time rather than through a nightly dump. Making the web tier call each of these systems directly would be slow, fragile and not atomic: the database write might succeed while the notification fails.
Wormhole's design has three parts:
- Producer library. Services embed Wormhole messages inside the database transaction, so they land in the MySQL binary log. That gives atomicity: the message exists if and only if the database write committed. This is the same idea as the transactional outbox pattern (change data capture), but using the binlog itself as the outbox.
- Publisher. Runs next to each database, tails its binlog, extracts the messages and serves them as streams.
- Consumers. Subscribe to the updates they care about.
Its properties map directly onto consumer needs:
- One stream per shard. Updates are ordered within a shard, not across shards. A failed shard affects only its own stream. The post calls these parallel wormholes in space.
- Rewind in time. Consumers keep checkpoints and can restart from an earlier position after a failure.
- At-least-once, in-order delivery. The newest update is applied last. When a stream builds a backlog, for example after a long data-centre outage, some consumers want to resume the real-time stream at once and replay the backlog in parallel. That breaks order, so those consumers must resolve conflicts with versions.
- Efficiency. Many subscribers are grouped into a small number of readers called caravans, so the database's binlog is read a few times, not once per subscriber. Sampling and server-side filtering cut the data sent. Publishers can be chained, to send one copy over an expensive long-distance link and fan out at the far end.
Compared with the previous system, Wormhole cut UDB CPU use by 40% and I/O by 60%, and reduced the delay for warehouse loading from about a day to a few seconds. Its two biggest wins were better cross-region cache consistency and real-time warehouse loading. The full design appears in Sharma et al., "Wormhole: Reliable Pub-Sub to Support Geo-replicated Internet Services", NSDI 2015.
Overlooked constraints.
- Using the binlog as the bus makes the database host part of the messaging system. Readers compete with replication for disk and CPU, which is why caravans matter.
- Per-shard ordering is all that is offered. Any consumer that needs order across shards, such as "friend request before acceptance" for two users on different shards, must handle it itself.
- At-least-once means duplicates after every rewind. Every consumer must be idempotent (idempotency).
What Meta sacrificed. Global ordering, exactly-once delivery and a general-purpose pub-sub API (producers must write through the database). In return it got atomic change notification with no extra write path, and far less load on the databases than polling or dumps.
Lesson 15: LogDevice, a log store that separates sequencing from storage (2017)#
Assumptions. Traffic: thousands to hundreds of thousands of logs per cluster, and some logs spiking 10x or more above steady state. Latency: from about 10 ms end to end (TAO secondary indexes) to seconds (Scribe). Consistency: a repeatable total order inside each log. Maintenance: drives, power supplies and switches fail all the time, and rebuilding must outrun the next failure.
Mark Marchukov's 2017 post begins with why logs matter. A log lets you join two pipeline stages without flow-control worries, keep an index in step with a database, delay work by having the consumer lag, order writes for transactions, and make a write-ahead log durable. A log makes two promises that are hard to keep at scale: durable, available storage and a repeatable total order.
LogDevice relaxes the file model to make those promises cheaper:
- Record-oriented. The unit is an indivisible record, not a byte. Readers start at a record. Record numbers, called log sequence numbers (LSNs), may have gaps, and the writer does not know its LSN in advance. Allowing gaps helps availability, as the epoch scheme below shows.
- Append-only. No record is ever modified.
- Trimmable. Logs live days to years. Space is reclaimed by trimming the oldest records under a time or size retention policy.
Workload. Almost every user needs high write availability, because loggers have nowhere else to put their data, even for a few minutes. Durability is universal: once acknowledged, a record must survive hardware failure. Most records are read a few times shortly after being written. But clients sometimes run backfills: a downstream system has failed and must rebuild state, so it reads every log from hours or days ago up to now.
Separate sequencing from storage. Each log has a sequencer, an object whose only job is to hand out increasing sequence numbers. It can run on a storage node or on a dedicated node. Once a record is stamped, its copies (usually 2 or 3) can be stored on any nodes in the log's node set. The node set is a subset of the cluster recorded in the log's metadata, and it can change over time. This gives the flexibility of HDFS's central name node without a name node. It also gives more choice than Ceph's hash-based placement, where a hash function picks only a few candidate locations. With many possible placements, a write succeeds even if many nodes are slow or down, and a spike on one log spreads over many nodes.
Reading. A reader connects to every node in the log's node set. Each node pushes its records as fast as it can over TCP. The client library reorders by LSN and removes duplicates. Each record copy carries its copy set (the list of nodes that hold it) in its header. With a simple server-side filter, only one node in each copy set sends a given record to a given reader, so data is read from disk once. This design is great for sequential log reads and would be poor for random point reads, which is acceptable for a log.
Epochs in LSNs. An LSN is a pair: epoch and offset within the epoch, compared as a tuple. When a sequencer dies, a replacement must issue LSNs larger than any already used, without scanning storage to find the highest. So the new sequencer gets a new, higher epoch from the epoch store, a set of durable counters (one per log) that never go backwards. At the time, the epoch store was ZooKeeper. Some offsets in the old epoch may never have been written, which is why gaps are allowed.
Many-to-many rebuilding. When a drive or node fails, some records drop below their target copy count R. Every surviving node acts as both donor and recipient, so the whole cluster rebuilds in parallel, at 5 to 10 GB per second. Coordination happens through an internal metadata log called the event log, with no central coordinator.
LogsDB, the local store. Storing hours of records at more than 100 MB per second per node rules out RAM. When retention is measured in days, hard drives beat flash on cost. Commodity disks do 100 to 200 MB per second sequentially but only 100 to 140 random I/Os per second, so the local store must keep I/O sequential. LogsDB sits on RocksDB (Lesson 9). It is a time-ordered series of RocksDB column families, called partitions, sharing one write-ahead log. All new writes for all logs go into the newest partition, sorted by log ID and LSN, and flushed as large sorted files. A read may merge up to about 10 files in a partition. Here is the trick: instead of compacting files into bigger runs, LogsDB leaves a full partition alone and starts a new one. Because records are immutable and LSNs rise with time, a reader moves through partitions in order, so it never merges more than one partition's files at once, even with tens of thousands of files in total. Space is reclaimed by deleting the oldest partition whole, which costs almost nothing.
Users. Scribe (next lesson) ingests over a terabyte per second at peak through LogDevice, tuned for per-box efficiency with seconds of latency. TAO secondary indexes use it with strict per-log order and about 10 ms end-to-end latency, which needs very different tuning. Machine-learning pipelines use it to give several training services identical event streams. LogDevice is written in C++ with few dependencies, and was open-sourced.
Overlooked constraints.
- The sequencer is a per-log bottleneck. One log's write rate is bounded by one sequencer's throughput, which is why high-volume streams use many logs (Scribe's partitions).
- Non-deterministic placement means a reader must contact the whole node set, so a large node set costs connections. The node set is a tunable trade-off between write flexibility and read fan-out.
- Backfills are the worst case: every reader goes to disk at once. Sizing for steady-state tailing alone underestimates disk bandwidth.
What Meta sacrificed. Contiguous numbering, random reads, ordering across logs and a POSIX file interface. In return it got very high write availability, tolerance for skewed load, and cheap disk-based retention.
Deep Dive: Why partitions instead of compaction, and how fast rebuilding must beShow
Compaction cost for logs (handbook's illustration). A node ingests 100 MB per second, about 8.6 TB per day. With leveled compaction and a write amplification of 10, the disks would write 86 TB per day, about 1 GB per second, far beyond what the drives can sustain alongside reads. Because log records are immutable and read in LSN order, merging them buys almost nothing. LogsDB's partitions keep write amplification close to 1: write the memtable flush once, delete the partition once.
Read cost. A reader tailing near the head reads from memory. A backfill reads one partition at a time. With at most about 10 files per partition, each read pass merges 10 sorted streams, which is fine for sequential disk reads of large blocks.
Rebuilding race (handbook's illustration). A node with 40 TB of records fails. With R equal to 3, every affected record now has 2 copies. At a cluster rebuild rate of 5 GB per second, re-creating 40 TB takes about 8,000 seconds, a little over 2 hours. If a second failure among the remaining copy holders within those 2 hours is unlikely enough, data stays safe. If only one donor node did the work at 200 MB per second, it would take over 2 days, and the risk of a second and third failure would be far higher. Many-to-many rebuilding is what makes R equal to 3 safe.
Why epochs avoid a scan. Without epochs, a new sequencer would have to ask every node in the node set for its highest LSN. If one node is down, it cannot be sure. With epochs, it simply asks the epoch store for epoch plus one. All its LSNs are larger than any old LSN by tuple order. A later recovery step seals the old epoch and finds which of its records were fully written.
Lesson 16: Scribe, petabytes per hour with a small, accepted loss (2019)#
Assumptions. Traffic: millions of machines writing to hundreds of thousands of categories, input above 2.5 TB per second and output above 7 TB per second. Latency: seconds. Consistency: no ordering promise, and a small amount of loss accepted for most users. Maintenance: one team, more than 40 components, no downtime in its history.
Manolis Karpathiotakis, Dino Wernli and Milos Stojanovic described Scribe in 2019. Logs from Meta's fleet total several petabytes an hour. They are usually processed somewhere else than where they were produced: in the data warehouse for history, or in real-time systems such as Puma, Stylus and Scuba. Scribe hides all the work of getting each log from A to B.
The model. A producer writes a payload to a named stream called a category. Scribe keeps each category for a configurable retention, usually a few days. Consumers tail it, reading sequentially. Writes can take two paths:
- Through Scribed, a daemon on almost every machine. It buffers in memory and on local disk, so the producer can hand off quickly and logs survive a network outage. The downsides: disk buffering adds latency, a stuck Scribed on one host blocks or loses that host's logs, and a heavy writer can starve others on the same machine.
- Directly to the Write Service, a remote tier. This lowers latency and improves availability, because the producer can try many back-end hosts. But if the producer cannot offload fast enough, its in-memory queue fills and excess writes are rejected, so resilience is lower.
Write Service. A load-balancing service picks a back-end host by locality and availability, so the tier has no single point of failure. Logs from one host may land on different servers and different storage clusters, and those clusters share no global clock. Scribe therefore makes no ordering promise. The Write Service batches logs by category and places each batch in one of a subset of storage clusters. That subset is large enough for write availability and small enough that a reader does not need to visit every cluster. Placement also considers where the logs will be read. Until a log is stored durably, it lives in some process's memory and can be lost. That was an explicit choice for throughput. Users who need fewer losses can choose a slower configuration.
Storage on LogDevice. Each log becomes a LogDevice record. A category is backed by many LogDevice partitions across clusters. Scribe used HDFS before, but outgrew it at about the time Meta was retiring HDFS.
Reading. The Read Service (streaming Thrift, following the reactive streams specification) finds the clusters holding a category, reads their partitions and merges them. It gives only rough ordering: output logs are within N minutes of each other by storage time, with N typically 30. Consumers that need exact creation order run a stream processor such as Stylus to reorder.
Design requirements. Scribe has four:
- Simple. The producer API has one write method. Command-line tools let you write with
scribe_catand read a time range withptail. - Write-available. Producers buffer in memory through Scribed restarts. Scribed buffers on disk through network outages. LogDevice replicates. Readers can choose to wait for a slow cluster or skip it and move on.
- Scalable. Each LogDevice partition has a maximum write rate, so Scribe adds partitions to a category automatically as its volume grows. On the read side, buckets shard a category into N streams, so N consumer processes can share the load. A producer can choose a bucket or let Scribe spread logs randomly.
- Multitenant. Each category has a write quota. Going over it can lead to the category being block-listed (new traffic dropped), sampled, or pushed back on. Scribe also spots categories read many times over, because repeated reads waste cross-region bandwidth. Quotas grow automatically with organic growth, and storage is provisioned automatically as traffic rises.
The authors noted that Scribe's API now looks much like other large messaging systems. They kept evolving it, rather than migrating to an open-source system, because it self-manages, self-scales and self-heals at a level that systems relying on external tools for autoscaling and disaster recovery do not reach.
Overlooked constraints.
- Accepting small loss is a product decision. Analytics on billions of events tolerate it, while billing or audit logs do not. Those need the stricter configuration or a different system.
- No ordering means downstream jobs must work on event time with windows and watermarks (stream processing), not on arrival order.
- Cross-region bandwidth is the scarce resource in a write-anywhere design. Re-reading a category from far away is the expensive mistake to detect.
What Meta sacrificed. Ordering, guaranteed delivery for default users, and an open-source release (the archived open version could not keep up with 40-plus internal components). In return it got near-perfect write availability and elastic scale at terabytes per second.
Deep Dive: Sizing partitions, buckets and buffersShow
Partitions per category (handbook's illustration). If one LogDevice partition sustains 20 MB per second and a category peaks at 2 GB per second, Scribe needs at least 100 partitions, plus headroom, say 130. When the category's traffic doubles over a quarter, auto-provisioning must add partitions ahead of the peak, not after write errors begin.
Buckets for consumers. A consumer host with a 25 Gbps NIC can take in about 3 GB per second in theory, but if its processing handles only 200 MB per second of logs, a 2 GB per second category needs at least 10 buckets and 10 consumer processes. Buckets decouple the number of readers from the number of storage partitions.
Local disk buffer. A host writes 2 MB per second of logs. To ride out a 2-hour network partition, Scribed needs about 14 GB of disk buffer. That is cheap on a server with a large disk, but it shows why some container hosts with tiny disks prefer the direct path.
Loss budget. Logs sit in memory between the producer and durable storage for perhaps 1 second. If 0.01% of hosts crash in any given hour and each loses 1 second of logs, the fraction lost is tiny. The design accepts that small, bounded loss instead of paying for a synchronous replicated write on every log line.
Lesson 17: FOQS, a distributed priority queue on sharded MySQL (2021 to 2022)#
Assumptions. Traffic: close to a trillion items a day, backlogs up to hundreds of billions of items. Latency: from milliseconds to days of deliberate delay, chosen per item. Consistency: at-least-once or at-most-once per item, ordered by priority then by ready time. Maintenance: must survive the loss of a whole region without client action.
Akshay Nanavati and Girish Joshi's 2021 post introduced the Facebook Ordered Queueing Service (FOQS): a fully managed, horizontally scalable, multitenant, persistent priority queue built on sharded MySQL. Its big customers are Async (Meta's asynchronous compute platform, the next lesson), video encoding (each upload is split into parts stored as items), and language translation (expensive jobs split up and run in parallel).
Data model.
- Namespace. One use case, the unit of multitenancy, with guaranteed capacity in enqueues per minute. Each namespace maps to one tier (a set of FOQS hosts and MySQL shards).
- Topic. A logical priority queue inside a namespace, named by any string. A topic exists only while it has items, and there can be thousands per namespace.
- Item. One MySQL row with these fields:
- a 32-bit priority (lower number means more urgent)
- an immutable payload up to 10 KB
- small mutable metadata
- a deliver-after time for delay
- a lease duration
- a retry policy
- a TTL
- an ID made of the shard ID plus a 64-bit primary key
API. Enqueue, Dequeue, Ack, Nack and GetActiveTopics, over Thrift. Shard Manager gives each MySQL shard to exactly one FOQS host.
- Enqueue. The request is buffered on the host and returns a promise. A worker per MySQL shard drains the buffer and inserts rows, then fulfils the promise. A circuit breaker marks a shard unhealthy when average query time or error rate over a rolling window passes a threshold, and stops sending it work until it recovers (circuit breaker).
- Dequeue. The client asks for counts per topic. Items come out ordered by priority, then deliver-after. Each shard keeps an in-memory index of ready items sorted by priority. A background prefetch buffer does a k-way merge across the host's shards to find the best items, marks them delivered in MySQL to prevent double delivery, and holds them ready. It refills each topic in proportion to that topic's recent dequeue rate. Dequeue simply reads from the buffer.
- Lease. A dequeued item must be acked or nacked within its lease. If neither happens, the retry policy decides. At-least-once items are redelivered. At-most-once items are deleted.
- Ack and nack. The item ID contains the shard ID, so the client routes to the owning host through Shard Manager. An ack deletes the row. A nack updates the deliver-after time, which allows exponential backoff, and can store partial results in metadata. If an ack is lost, the lease expires and the item is redelivered, which is why consumers must be idempotent.
Pull, not push. Workloads vary in four ways:
- Delay tolerance: milliseconds to days.
- Processing rate: tens to more than 10 million items per minute, often limited by downstream capacity.
- Priority: per topic or per item.
- Location: some items must be processed near their data.
Pull lets each consumer decide how fast and where to take work, and keeps the queue simple. The cost is that consumers must discover where ready items are, which FOQS solved with a routing layer.
Checkpointing MySQL scans. Background jobs (make delayed items ready, expire leases, purge expired items) query on timestamp columns. A query like "every row with timestamp up to now, FOR UPDATE" makes InnoDB lock and keep old row versions for a huge range, which grows the undo history list and slows every read. FOQS keeps a checkpoint of the last processed timestamp, so the query is bounded on both sides:
-- Bounded scan: rows between the last checkpoint and now
SELECT id FROM items
WHERE ready_at >= :checkpoint
AND ready_at <= UNIX_TIMESTAMP()
FOR UPDATE;Disaster readiness, version 1. Each MySQL shard had a primary and asynchronous replicas in two other regions, with the binlog written synchronously to another building in the same region. To drain a data centre, the primary was set read-only for a few milliseconds until a replica caught up, the replica was promoted, and the shard moved to a FOQS host in the new region. Within the tier, an overloaded host forwarded enqueues to another host, and each namespace had a global rate limit across regions.
Disaster readiness, version 2 (2022 post by Dillon George and Jasmit Kaur Saluja). FOQS began in 2018 as regional installations: three-region semisynchronous MySQL, with queue nodes in each region fully isolated, and clients picking a region. That was simple and scaled per region, with low latency when producer, consumer and queue were together. But when a primary failed over to another region, the queue nodes in the original region had to send queries across regions, at up to hundreds of milliseconds. When a region lost network connectivity entirely, clients had to move their own traffic, spare capacity sat unused, and items on shards whose primary was cut off were stuck until connectivity returned. During Hurricane Florence in late 2018, a multi-day event, the team had to rebalance traffic and add capacity by hand.
The fix was global installations, built on two ideas:
- Follow the primary. Shard Manager's global placement moves management of a shard to a queue node in whichever region now holds its MySQL primary, within seconds of a failover. There are no stuck items and no cross-region query latency, and clients see one global service ID.
- A routing service between clients and queue nodes.
- The enqueue distributor maps a client's logical region preference to MySQL shards in or near that region. If the region is down, it sends the item to wherever those shards failed over.
- The dequeue distributor keeps, per topic, an in-memory heap of queue hosts that have ready items, and sends dequeues to them.
Migrating Async, the largest customer, exposed problems. The dequeue cache went stale at Async's scale. Parallelising the cache refresh nearly halved its latency. Then a thundering herd appeared: every router sent dequeues to the same top-k hosts, which were overloaded, while hosts lower in the heap, often in other regions, starved. Adding randomness among the top candidates spread the load and cut queueing delay (thundering herd). The migration finished in mid-2021 with zero downtime. It relied on a shadow environment for load tests, a config-based rollout that could step forward or back, retrospectives on each issue, and clear health dashboards. Afterwards, human involvement in regional events was essentially zero, and FOQS could recover from losing a region in seconds without clients noticing.
Overlooked constraints.
- A queue on a relational database hits relational limits: lock ranges, undo history and index maintenance on every enqueue and delete. Checkpointed scans and in-memory ready indexes are the workarounds.
- Priority ordering across many shards is a distributed top-k problem. The prefetch buffer and routing heap are approximate, so a strictly global priority order is not guaranteed.
- Global rate limits cannot be enforced per region, so a region can briefly get more than its share during a shift.
What Meta sacrificed. Strict global priority order, push delivery and simple per-region deployments. It also accepted the extra routing tier, with its stale caches and herd effects. In return it got a queue that keeps working, and stays reachable from anywhere, when a whole region is lost.
Deep Dive: Leases, delivery semantics and the herd effect, with numbersShow
Choosing a lease (handbook's illustration). Jobs take 2 s at p50 and 40 s at p99. A 30 s lease would redeliver about 1.5% of items while the first worker is still running, doubling their work and possibly their side effects. A 60 s lease avoids that, but a crashed worker's items wait 60 s before retry. Lease length trades duplicate work against recovery delay. Lease extension (heartbeating) avoids the choice but adds traffic.
At-least-once versus at-most-once. At-least-once redelivers on lease expiry, so a consumer that did the work but lost its ack runs it again. It needs an idempotency key, for example the FOQS item ID stored with the result. At-most-once deletes on lease expiry, so a crash loses the item. That fits work like a best-effort notification, where a duplicate is worse than a miss.
Exponential backoff via nack. Failure 1 waits 30 s, failure 2 waits 60 s, failure 3 waits 120 s, up to a maximum retry count, after which the item goes to a dead-letter topic. Because the delay lives in the row's deliver-after column, a downstream outage costs only stored rows, which is how FOQS held backlogs of hundreds of billions of items (retries and backoff).
Herd arithmetic. 200 routing nodes each send dequeues to their top-3 hosts. If they all see the same ranking, 3 hosts take all 200 nodes' requests while 97 sit idle. Choosing randomly among the top 20 spreads the load to about 10 requests per host. The cost is that a few dequeues hit a host with slightly lower-priority items, which is acceptable because priority across hosts was already approximate. This is the same lesson as "power of two choices" load balancing, from Mitzenmacher, "The Power of Two Choices in Randomized Load Balancing", IEEE TPDS 2001.
Lesson 18: Async, a serverless platform for trillions of deferred jobs (2020 to 2023)#
Assumptions. Traffic: multiple trillions of workloads executed each day, after five-fold growth in two years. Latency: not on the user's critical path. Seconds are typical, and some work is deliberately pushed to off-peak hours. Consistency: at-least-once execution. Maintenance: many teams submit functions, and the platform team must keep adding features in parallel.
Sayak Kundu and Artem Denisov's 2023 post describes Async, Meta's serverless platform for asynchronous work. Teams register functions and submit workloads through an SDK. The platform runs them on a large worker fleet and adds load balancing, rate limiting, quotas and protection for downstream services. Any such platform has three layers:
- Ingestion and storage. Accept the work fast and keep it safe until it has run.
- Transport and routing. Move the right amount of work to compute. Too little wastes workers. Too much overloads them. The post calls this flow control. This layer also handles cross-region balancing, quotas, rate limits, backoff and retries.
- Computation. The worker runtime that runs the function.
The 2020 design. A thin Submitter service validated and enqueued work into FOQS. A Dispatcher pulled from FOQS and sent work to workers. Over time the Dispatcher took on everything: managing item lifecycles, protecting FOQS by adapting dequeue rates, rate limits, quotas, priorities, downstream protection, several worker runtimes, and local and cross-region balancing. It became one large component that many engineers had to change at once.
Customers also wanted to trigger work from data already stored elsewhere: streams, warehouse tables, blob storage and pub-sub queues. Each team wrote its own reader that copied that data into FOQS through Submitter. That was duplicated effort, and copying a high-volume stream into a queue just to buffer it cost much more than leaving the data where it was.
The re-architecture.
- Scheduler. The transport layer was split off as a generic, source-agnostic service. It handles execution and compute features (rate limits, quotas, load balancing) and knows nothing about where work came from.
- Tailers. Per-source adapters, like the UNIX
tailcommand, that read new work from a source: FOQS, Scribe streams or others. Onboarding a new source launches tailer instances for it. - Push instead of pull. Tailers push work to the scheduler as RPCs. This removed the wait for ack, nack or lease timeout, and made cross-region balancing more accurate, because one tailer decides instead of each region pulling on its own. The cost: an RPC holds resources on both sides for the whole run, so it suits short jobs. Long jobs also risk transient errors that force a full restart. Most Async workloads finish within seconds, so this was acceptable.
Queues versus streams. With two popular storage choices, FOQS and Scribe, the team could compare them directly:
- Queues give per-item access, any retry policy (nack with any delay), priority order and support for long-running work through leases. Leases need per-item lifecycle tracking, and priorities need a secondary index. That is flexible at a moderate cost.
- Streams hand out immutable batches in order. They cannot retry one item or give random access, but they are much cheaper for high-volume sequential work.
The clogged stream. A stream tailer reads a batch, sends it, and moves its checkpoint forward once the whole batch succeeds. If one item keeps failing, the checkpoint cannot advance and lag builds behind it. Dropping the item would break at-least-once. The fix is a delay service that holds failed items and retries them after a delay (for example exponential backoff) without blocking the stream. Two designs were explored:
- A priority queue as the side store. This assumes failures are a small fraction. If 100% of jobs start failing, the system must clog the stream on purpose rather than copy the whole stream into the delay service.
- Fixed delay streams (30 s, 1 min, 5 min, 30 min). Each one is held back by its delay before being read, and they are combined to build the needed delay. This uses only sequential streams, so it scales further and costs less.
The lesson: there is no one right answer. Streams with RPC push fit high-volume, short jobs. Queues fit long jobs and per-item retries, at the cost of leases and ordering. And a stream with strict delivery guarantees at high volume needs a separate retry path.
Overlooked constraints.
- Flow control is the core of an async platform. Workers have finite capacity and downstream services have their own limits, so the scheduler must know both.
- A deferred-work platform shapes daily load. Moving tolerant work to off-peak hours flattens the peak the fleet is sized for, but only if quotas stop the backlog from becoming a new peak.
- At-least-once over streams needs a side path for failures, and that side path needs a circuit breaker for the case where everything fails.
What Meta sacrificed. Long-running workloads in push mode, the simplicity of one queue for all work, and the per-item flexibility of FOQS for stream-sourced jobs. In return it got no copying of stream data, independent components that teams can change in parallel, and better latency and cross-region balance.
Lesson 19: Beringei and Gorilla, monitoring data in memory (2013 to 2017)#
Assumptions. Traffic: about 12 million data points written per second (700 million per minute) across 2 billion time series in 2015, and later up to 10 billion series and 18 million queries per minute. Latency: reads in under a millisecond on the server, and tens of milliseconds end to end. Consistency: none promised, and losing a few points is acceptable. Maintenance: must keep working through host, network and region failures, and grow about 2x per year.
In early 2013, Facebook's monitoring store, the Operational Data Store (ODS), kept its time series in HBase. Average reads were fine, but p90 query time had grown to several seconds. That was too slow for automation that issues hundreds of queries, and medium queries over a few thousand series took tens of seconds. Engineers had started avoiding queries. The team found that at least 85% of queries asked for data from the last 26 hours. So they built an in-memory write-through cache of the last 26 hours in front of HBase: Gorilla, described in Pelkonen et al., "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015. Its storage engine was open-sourced in 2017 as Beringei, which could be used as an embedded library (like RocksDB) or as a sharded service with Grafana integration.
Why existing options did not fit. Replacing HBase was off the table, since it held about 2 PB. Hive was orders of magnitude slower. ODS's read-through cache missed on the most common query, the latest point. A Memcache write-through cache would need a read-modify-write on every append to a series, which was far too much traffic. OpenTSDB (on HBase), Graphite's Whisper format (one file per series, fixed intervals) and InfluxDB (rich per-event metadata, on disk) were all disk-bound.
The key insight. Monitoring users care about aggregates and recent trends, not individual points. And recent data is worth much more than old data. So Gorilla favours availability of recent writes and reads over completeness and consistency. It is fine to drop a few points if the system stays up.
Compression is what makes RAM affordable. In 2015 the system took in over 1 trillion points per day. At 16 bytes per point (64-bit timestamp plus 64-bit float), 26 hours would need about 16 TB of RAM. Gorilla compresses each series in a streaming way, inside two-hour blocks, to an average of 1.37 bytes per point, a 12x reduction. The two techniques are:
-
Delta-of-delta timestamps. Most series report at a fixed interval, so the gap between gaps is usually zero. Each block header stores an aligned start time. The first point is stored as a 14-bit delta from it. After that, for each point compute D, the change in the gap:
- D equal to 0: store one bit, "0".
- D from -63 to 64: store "10" plus 7 bits.
- D from -255 to 256: store "110" plus 9 bits.
- D from -2047 to 2048: store "1110" plus 12 bits.
- Otherwise: store "1111" plus 32 bits.
About 96% of timestamps compress to a single bit.
-
XOR of floating-point values. Neighbouring values are usually close or identical, so their sign, exponent and leading mantissa bits match. Gorilla XORs each value with the previous one:
- XOR is zero (same value): store "0". This happens for about 51% of values.
- Otherwise store "1" plus a control bit. If the meaningful bits fit inside the previous value's window of leading and trailing zeros, store control "0" and just those bits. About 30% of values, averaging 26.6 bits.
- If not, store control "1", 5 bits for the count of leading zeros, 6 bits for the length, then the meaningful bits. About 19% of values, averaging 36.9 bits.
The scheme was adapted from scientific floating-point compression work by Ratanaworabhan, Ke and Burtscher (DCC 2006), simplified to compare only with the previous value.
Blocks longer than two hours gave little extra compression, but would make short queries decode more. So two hours was chosen.
In-memory structures. Each host keeps a ShardMap that maps a shard to a TSmap. A TSmap holds a vector of shared pointers to series, which allows fast paged scans, plus a hash map from name to series, which allows constant-time lookup. Scans copy the vector of pointers in microseconds, so they never hold a long lock against incoming writes. Each series has a 1-byte spinlock. A series holds closed two-hour blocks, which never change, plus one open append-only block. Reads copy whole compressed blocks into the reply, and the client decompresses.
Persistence. Each shard has a directory on GlusterFS, a distributed file system with 3x replication, holding:
- a key list mapping names to IDs;
- an append-only log, buffered up to 64 KB, about 1 to 2 seconds of data, so a crash can lose that much;
- a complete block file written every two hours;
- a checkpoint file that marks the block file as complete, after which the matching logs are deleted.
The log is deliberately not a write-ahead log, because that would cut write throughput.
Failure handling.
- Two regions. Two fully independent instances run in different regions, and every point is streamed to both with no consistency promise. Reads go to the nearest healthy one. If a region is down for more than about a minute, its data is dropped, and reads are pointed at the other region until the first has been healthy for 26 hours.
- Within a region. Shard Manager reassigns a dead host's shards, usually in under 30 seconds. Clients buffer one minute of writes while shards move, dropping the oldest points first. A new owner loads about 16 GB per shard from GlusterFS in a few minutes. Until then it serves partial results, newest blocks first, marked as partial. The client retries partial results in the other region.
Over six months that covered 3 network cuts, a disaster drill, 6 configuration changes, 6 code releases, a bad release on one coast and 5 host failures, there were zero monitoring disruptions.
Results. Query latency improved 73x to 350x compared with HBase, depending on query size, with p90 at about 10 ms. Query volume grew from 450 per second on ODS to 5,000 steady and 40,000 at peak. The cluster grew from 20 hosts with 1.3 TB of RAM to 80 hosts per region. Beringei later reported about 300 µs from write to readable and about 65 µs p95 server read time. Fast queries made new tools possible:
- a correlation search that compares a "needle" series against up to a million others by Pearson correlation, to answer "what else changed when my service broke?";
- dense horizon-chart dashboards;
- roll-up aggregation moved from MapReduce over HBase to scans of Gorilla.
The authors noted that making it fault-tolerant took months longer than the fast prototype.
Overlooked constraints.
- Time series do not need ACID, but they do need "latest point is present". Design the guarantees around how the data is used, not around database tradition.
- Compression works per series because each series is self-similar. That is why Gorilla does not compress across series.
- Two in-memory copies cost twice the RAM. The paper says plainly that high availability trumped resource efficiency.
What Meta sacrificed. Durability of the last second or two of points, consistency between regions, long retention in memory (26 hours, then HBase roll-ups) and rich tag-based data models (one string key per series). In return it got queries 70x faster, which changed how engineers debugged.
Deep Dive: Encoding a few Gorilla points by handShow
Timestamps (handbook's illustration, following the paper's example). A block starts at 02:00:00. Points arrive at 02:01:02, 02:02:02 and 02:03:02.
- The first delta is 62 s from the block start, stored in 14 bits.
- The next delta is 60, so D is 60 minus 62, which is -2. That falls in the range -63 to 64: store "10" plus 7 bits, 9 bits in total.
- The third delta is 60 again, so D is 0: store "0", 1 bit.
A regular series costs about 1 bit per timestamp instead of 64.
Values. The values are 12.0, 12.0 and 24.0.
- The first is stored raw: 64 bits.
- The second XORs to zero: store "0", 1 bit.
- For the third, 12.0 is 0x4028000000000000 and 24.0 is 0x4038000000000000. Their XOR is 0x0010000000000000, which has 11 leading zeros and a single meaningful bit. If there is no usable previous window, store "11", then 5 bits for 11 leading zeros, 6 bits for length 1, then the bit "1": 2 plus 5 plus 6 plus 1, which is 14 bits.
Per the paper's figure, the whole example compresses 48 bytes to just under 21 bytes, about 167 bits.
Memory math. 2 billion series at one point every 60 s is about 33 million points per minute. Real series often report every 15 to 60 s, and the paper's real rate was 700 million per minute. Over 26 hours that is about 1.1 trillion points. At 16 bytes that is about 17.5 TB. At 1.37 bytes it is about 1.5 TB, close to the 1.3 TB the paper reported at launch, spread over 20 hosts. Two regions double it. That is the gap between "impossible in RAM" and "a few racks".
Why the 26-hour window and 2-hour blocks. 85% of queries hit the last 26 hours, so that window gets in-memory speed while HBase serves the rest. Two-hour blocks are the point where larger blocks stop improving compression. A query for the last 10 minutes decodes at most one open block plus part of one closed block per series.
Family 4: Running the fleet: placement, containers, load balancing, distribution and configuration
The systems above all sit on a shared platform. Something must decide which server runs which container and which shard, how packets reach those servers, how a 10 GB binary or AI model gets to a million processes, and how every server is configured. These are the layers Meta generalised so that product teams do not rebuild them.
Lesson 20: Shard Manager and Twine, generic sharding on a shared fleet (2011 to 2020)#
Assumptions. Traffic: hundreds of sharded applications with tens of millions of shard replicas on hundreds of thousands of servers. Twine runs containers on millions of servers in 15 or more data-centre locations. Latency: the control plane is off the request path, and shard moves take seconds to minutes. Consistency: at most one primary per shard. Maintenance: kernel upgrades, binary pushes and hardware repairs every day, and diurnal traffic swings.
Why a sharding platform? Gerald Guo and Thawan Kooburat's 2020 post starts with the scaling problem. A stateless web tier scales by adding servers and routing at random. Stateful services do not. Simple hash(key) mod N moves almost all data when N changes. Consistent hashing (consistent hashing) moves little, but it needs many fine-grained keys to balance well. It also cannot express placement rules such as "EU users' data stays in EU data centres". So consistent hashing is used mostly for caches. The alternative is explicit sharding: split data into shards and compute an assignment of shards to servers, which can include any constraint.
Every team doing explicit sharding needs the same things:
- Failover when a server dies.
- Draining servers before maintenance.
- Load balancing as shards get hotter or colder.
- Shard scaling: more replicas for hot shards.
Teams were each building partial versions, typically with failover but weak balancing. Shard Manager, nine years old at the time of the post, made this a platform. The design is described in Lee et al., "Shard Manager: A Generic Shard Management Framework for Geo-distributed Applications", SOSP 2021.
Three application types.
- Primary only. One replica per shard, typically a worker that processes its shard's data held elsewhere, as in stream processing. Shard Manager guarantees at most one primary, like a ZooKeeper lock. These are 67% of applications but only 17% of servers.
- Secondaries only. Several equal replicas, mostly read-only, such as ML inference servers that load a model and serve it. Hot shards get more replicas.
- Primary-secondaries. Storage with a primary that takes writes and drives replication, such as ZippyDB (Lesson 11).
Integration is small. An application implements two calls, add_shard(shard_id) and drop_shard(shard_id). What "add" means is up to the application: copy data from a peer, or download a model. A basic move is drop on server A, wait, then add on server B, which keeps the at-most-one-primary guarantee but leaves a short gap when no one serves the shard. For user-facing apps there is a smoother handoff protocol. Primary-secondary apps also implement change_role (promote or demote) and update_membership (tell the primary the new replica set, which Paxos-based stores need). Clients use one routing library: create_rpc_client(app_name, shard_id) hides where the shard lives.
Intent-based specification. Owners declare what they want, not how:
- Fault tolerance. Replicas per shard, spread across fault domains (buildings for regional apps, regions for global ones). Failure detection delay and failover delay are tunable, trading rebuild cost against unavailability. Under a network partition, the app chooses availability or consistency. Failover throttling limits how many shards fail over at once, so a big outage does not crush the healthy servers.
- Load balancing.
- Per-server capacity and per-replica load are collected live, so mixed hardware generations and uneven shards are handled.
- Several resources (CPU, memory, storage) are balanced at once, each with a priority.
- Moves are throttled in total and per server.
- Shard scaling. When a shard's load per replica leaves a set band, replicas are added or removed. This follows the diurnal curve.
- Operational safety. Every shard keeps at least one healthy replica, or a healthy majority for Paxos apps, during maintenance.
Design choices.
- Central control plane. A global view allows globally good placements and coordinated maintenance. If the control plane is down, applications keep running on the last assignment, so it is off the request path.
- Opaque shards. A shard can be a database, a group of logs or a bucket of data.
- Shard granularity sweet spot: hundreds of shards per server. Too coarse balances poorly. Too fine overloads the infrastructure.
- A generic constrained-optimisation solver. New requirements are added as constraints, not as new code paths.
Architecture. Owners give a spec to the Shard Manager Scheduler, which is itself sharded. Application servers link a library that registers liveness through ZooKeeper and implements the transition calls. The scheduler collects load, decides moves and calls the servers. It publishes the shard map to the service discovery system, from which clients route directly.
Twine (2019 post by Kenny Yu and Chunqiang Tang). Twine, formerly Tupperware, is Meta's cluster manager, deployed in 2011. It packages code into images and runs them as containers. It moves containers off failed servers, enforces capacity budgets per team, and stops or moves containers for maintenance. Its parts:
- a front end (API, UI, CLI);
- a scheduler that manages job and container lifecycle, deployed regionally or globally and sharded by job;
- a scheduler proxy that makes the shards look like one control plane;
- an allocator that assigns containers to servers, one per region;
- Resource Broker, one per data centre, the source of truth for servers and maintenance events;
- a health-check service;
- an agent on each server that sets up containers using images, btrfs, cgroup v2 and systemd.
In Kubernetes terms, Twine's scheduler is the control plane and its allocator is the scheduler. Resource Broker is DelosTable's first customer from Lesson 13. The full design is in Tang et al., "Twine: A Unified Cluster Management System for Shared Infrastructure", OSDI 2020.
What sets Twine apart:
- Stateful services through TaskControl. Should Twine upgrade the kernel on 50 of 10,000 servers while one database replica is already down? It depends on whether one of those 50 holds another replica of the same database. Twine tells each stateful service's controller about upcoming restarts, updates, moves and maintenance. The controller can approve, reorder or delay them, for example "do 49 now, hold server X". There is a deadline after which Twine proceeds anyway. Most stateful services use TaskControl through Shard Manager, which knows where every replica is. Even the stateless web tier uses it to pace releases, several per day.
- One control plane across data centres. In 2011 each cluster (racks under one switch) had its own scheduler, so a job could not span clusters. Decommissioning a cluster took months of manual coordination while servers sat idle. Resource Broker now binds servers to schedulers dynamically, so a job states an intent, such as "two fault domains in region PRN", and Twine finds servers even during decommissions.
- Sharded control plane. A single scheduler per region could not scale to hundreds of thousands of servers. It would also put a whole region at risk from one bug or one failure. Scheduler shards each manage a subset of jobs, not a fixed slice of servers, behind one entry point.
- Elastic compute. Power, not floor space, limits Meta's data centres, so Meta prefers small power-efficient servers. Stacking large services on small servers works poorly, so overcommitment is less useful. Instead, big diurnal services such as News Feed, messaging and the web tier shrink at off-peak hours. Resource Broker lends the whole freed servers to batch and ML work, and takes them back quickly if online load spikes. At the time, about 20% of servers were in the shared pool.
Overlooked constraints.
- A shard move is not free. Copying a 100 GB replica at 200 MB per second takes over 8 minutes, so move throttles and the "hundreds of shards per server" rule keep each move small.
- Maintenance is a bigger source of unavailability than failures at fleet scale. Treating it as a first-class, negotiated event is what keeps quorums intact.
- Lending whole servers works only if online services can win them back within the time it takes a load spike to hurt, so the reclaim path must be fast and preemptive.
What Meta sacrificed. Per-team freedom over placement logic, simplicity in the control plane (a solver, TaskControl, scheduler shards), and per-server packing efficiency (whole-server lending instead of fine-grained stacking). In return it got one sharding and container platform that hundreds of services share.
Deep Dive: Shard granularity, move cost and safe maintenance, with numbersShow
Granularity (handbook's illustration). A server holds 2 TB across its shards. With 10 shards of 200 GB, the most loaded server may carry one extra shard, which is 10% imbalance, and moving one shard copies 200 GB, about 17 minutes at 200 MB per second. With 200 shards of 10 GB, imbalance is about 0.5% per shard and a move takes under a minute. With 20,000 shards of 100 MB, balance is excellent, but the scheduler must track millions of replicas fleet-wide and each server keeps 20,000 entries of metadata. "Hundreds per server" sits at the knee of that curve.
Shard scaling. A shard's peak load is 9,000 QPS and its off-peak load is 1,500 QPS. The target band is 1,000 to 2,000 QPS per replica. At peak it needs at least 5 replicas (1,800 each). At night it needs 1 (1,500), but the fault-tolerance minimum may be 2. Across millions of shards that frees a large share of servers at night for elastic compute.
Safe maintenance for a Paxos app. With 5 replicas and a rule that a majority must stay healthy, at most 2 may be down at once. If 1 is already failed, maintenance may take 1 more at a time. Shard Manager must check this for every shard on every server in the batch. That is why a 50-server kernel batch can be held up by one server.
Failover throttling. A rack switch fails, taking 40 servers with 300 shards each, 12,000 shards in total. Failing all of them over at once would start 12,000 rebuilds onto the remaining servers, saturating their disks and network. A throttle of, say, 500 concurrent failovers spreads the work, accepting slower recovery for some shards in exchange for not cascading the failure.
Lesson 21: Katran, a layer 4 load balancer in the kernel's fast path (2018)#
Assumptions. Traffic: every packet entering a point of presence (PoP) or data centre for a virtual IP. Latency: microseconds per packet. Consistency: every packet of one TCP connection must reach the same backend, even if it arrives at a different load balancer. Maintenance: load balancers and backends are upgraded all the time.
Nikita Shirokov and Ranjeeth Dasineni's 2018 post explains Meta's network load balancer. Each site announces virtual IPs (VIPs) to the internet, and a layer 4 load balancer (L4LB) spreads packets for each VIP over backend servers. The backends terminate TCP and run the layer 7 proxy (load balancing). Because the L4LB touches every packet, its packets per second set the ceiling. Hardware appliances are fast but inflexible. Meta's requirements were:
- run on commodity Linux;
- coexist with other services on the same host;
- allow low-disruption maintenance;
- work with standard tools such as tcpdump.
Generation 1 (more than four years in production). It was built from open-source parts:
- VIP announcement. ExaBGP announced VIPs to the top-of-rack switch, which used ECMP (equal-cost multipath routing) to spread packets over the L4LBs.
- Backend selection. A consistent hash of the 5-tuple (source and destination IP and port, plus protocol) means any L4LB picks the same backend for a connection without sharing state, and backend changes move few connections.
- Forwarding. IP-in-IP encapsulation with the IPVS kernel module, so L4LBs and backends could live in different racks. Backends had the VIP on their loopback and replied directly to the client (direct server return, DSR), so the L4LB handled only inbound packets.
- Control plane. An in-house control plane did health checks and VIP configuration.
- Connection table. A table of 5-tuple to backend avoided rehashing. It was an optimisation, not needed for correctness.
The problem was CPU. Packets went through the full Linux network stack before IPVS saw them. So L4LBs ran on separate, fewer machines, which made them vulnerable to load spikes.
Katran, generation 2. It uses XDP (eXpress Data Path) and eBPF. XDP runs a small verified program in the NIC driver as soon as a packet arrives, before the kernel allocates its normal packet structures. eBPF is the in-kernel virtual machine that runs such programs safely.
- Early, parallel processing. The BPF program runs per NIC receive queue in parallel, without locks, using per-CPU maps, so throughput scales linearly with RX queues. A slower "generic XDP" mode also exists.
- Extended Maglev hashing. Katran uses an extended version of Google's Maglev hash (Eisenbud et al., "Maglev: A Fast and Reliable Software Network Load Balancer", NSDI 2016). It distributes load evenly, is resilient to backend failure, and supports unequal weights, which lets a PoP absorb a newer, stronger hardware generation by giving it more weight. The code fits in L1 cache.
- Connection table as an LRU cache. Computing the hash was often cheaper than looking up a large connection table that missed into the last-level cache. So the table is a fixed-size LRU, tuned for packets per second, with a "compute only" switch for severe memory pressure.
- RSS-friendly encapsulation. NICs use Receive Side Scaling to spread flows over CPUs by hashing packet headers. With IP-in-IP, every packet would have the same outer header and land on one CPU. Katran picks the outer source IP per flow, constant within a flow and different across flows, so backends' NICs spread the load.
- No busy polling. Unlike kernel-bypass frameworks such as DPDK, XDP does not spin a CPU waiting for packets, so it uses almost no CPU when idle and can share a host with the backend application.
The outcome: Katran runs on the same hosts as the backends in PoPs, with many more L4LB instances than before, which improves resilience to spikes, failures and maintenance.
Constraints the authors listed.
- DSR mode only.
- An L3-routed network, because packets must reach Katran by IP.
- No fragmented packets, and no fragmenting. Fix this with a larger internal MTU or a lower advertised TCP MSS on the backends (recommended either way).
- No IP options, and packets at most 3.5 KB.
- A "load balancer on a stick" setup, with one interface for both ingress and egress.
Overlooked constraints.
- Load balancers on the same hosts as backends share fate with those hosts. That is acceptable only because there are now many of them and no state needs syncing between them.
- Consistent hashing alone breaks connections when the backend set changes and ECMP sends a flow to a different L4LB with no entry for it. The LRU table only helps on the L4LB that saw the flow. Keeping changes small and gradual is the mitigation.
- MTU and fragmentation are real operational traps. Encapsulation adds 20 bytes, so full-size packets must be prevented at the TCP level.
What Meta sacrificed. Generality (DSR only, no fragments, no IP options, L3 only), the familiar IPVS tooling, and some isolation between the load balancer and the application. In return it got line-rate software load balancing spread across the whole backend fleet.
Deep Dive: Maglev hashing and why the hash can beat the tableShow
How Maglev builds its table. Choose a prime table size M, for example 65,537. For each backend, compute two hashes of its name, giving an offset and a skip, and from them a permutation of the M slots. Backends take turns claiming their next preferred free slot until all slots are full. Each backend ends up with almost exactly M divided by N slots. A packet's 5-tuple hashes to one slot, which names its backend. Lookup is one hash plus one array read.
Disruption on change. When one of 100 backends is removed, its slots must be refilled by others. The permutation scheme means most other slots keep their backend, so only slightly more than 1% of flows move. Plain modulo hashing would move about 99%. Weights are applied by letting a heavier backend claim slots more often.
Why compute beats lookup (handbook's illustration). A table of 65,537 four-byte entries is 256 KB, which fits in L2 cache. A connection table for 10 million flows at about 64 bytes each is 640 MB, so nearly every lookup is a DRAM access at about 80 to 100 ns. Hashing a 5-tuple takes perhaps 10 to 20 ns, plus one L2-hit table read. At 10 million packets per second per core budget of about 100 ns per packet, a DRAM miss uses the whole budget. So a small LRU table that stays in cache, backed by recomputation, is faster than a huge table.
XDP versus the normal stack. The normal path allocates a socket buffer, runs netfilter, routes and then hands to IPVS, often costing 1 to 2 µs per packet of CPU. XDP runs before allocation and can rewrite and transmit the packet in place, often a few hundred nanoseconds. That 5x or so gap is what let the load balancer share hosts with the application.
Lesson 22: Owl, distributing hot content with a central brain and a peer-to-peer body (2022)#
Assumptions. Traffic: 700 to 800 PB a day to more than 10 million client processes. Objects range from about 1 MB to several TB. Latency: download as fast as the client's network or disk allows. Consistency: content-addressed immutable chunks. Maintenance: one team, more than 100 client types, policies changed in seconds.
Jason Flinn and Arushi Aggarwal's 2022 post covers distributing hot content: executables, code artifacts, AI models and search indexes that many hosts need at about the same time. Distribution varies along three axes:
- Fanout: a few readers to millions.
- Size: MB to TB.
- Hotness: reads within seconds of each other, or spread over hours.
Requirements were speed (bounded only by the client's NIC or disk), efficiency, and reliability. Efficiency meant clients served per server, bytes sent, locality (in-rack beats cross-region) and client CPU, memory and disk, with some clients unable to spare memory or disk. Reliability meant the share of downloads within SLA, plus easy operation.
Why prior systems failed. Meta had three systems:
- Hierarchical caches. Clients read from remote caches, which read from deeper caches, then from storage. These needed many dedicated hosts that grew with demand. Hot-content spikes forced strict quotas, which then throttled exactly the bursty readers they served.
- A location-aware BitTorrent.
- A static peer-to-peer tree built on consistent hashing.
The two decentralised systems scaled well but each peer decided alone. Caching was wasteful or insufficient, tail latency was poor, and nobody could see overall health without aggregating millions of peers. Centralised scaled poorly. Decentralised was inefficient and opaque.
Owl's split. Owl pairs a decentralised data plane with a centralised control plane, a mechanism-policy split:
- Peers are a library linked into each client binary. They do only simple things: download a chunk from a given source, cache or evict a chunk, and serve cached chunks to other peers. They can cache in memory, on disk, or share the client's own copy if it is not modified.
- Trackers, 3 to 4 per region, hold the full state. They know, for each chunk, which peers cache it and which are downloading it and from where. For each peer, they know its location (host, rack, region) and its cache contents. They decide where each peer fetches each chunk, how to retry and what to cache. Each peer registers with a random tracker and switches if it fails. Binary distribution has its own trackers for isolation.
- Distribution trees are ephemeral and per chunk. An edge exists only while that chunk moves from source to peer.
Flexibility as a first-class goal. Trackers have modular interfaces for caching and fetch policies, each configurable. Each client type is a bucket with its own policy and its own metrics. The team uses trace-driven emulation to search for the best policy per workload. Policies change on trackers in seconds without updating any peer. After two years in production, with traffic up nearly 200x in 2021, Owl had more than 10 million unique clients, up to 800 PB a day, and 106 client types, 55 of them with custom policies. Speeds and cache hit rates were 2 to 3 times better than BitTorrent and the earlier systems. The design is described in "Owl: Scale and Flexibility in Distribution of Hot Content", OSDI 2022.
Overlooked constraints.
- A central tracker is a scalability and availability risk. It works because trackers hold only metadata, are multiple per region, and peers fail over to any of them.
- Clients differ in what they can spare. A design that assumes every peer can cache gigabytes fails for memory-tight services, so per-bucket policies are not a luxury.
- Observability is a design requirement. The main operational win was that one component made every decision and could explain it.
What Meta sacrificed. The pure decentralisation (and theoretical unlimited scale) of BitTorrent, extra round trips to the tracker for each chunk decision, and a new critical service per region. In return it got 2 to 3 times better speed and hit rate, and a system engineers can reason about.
Lesson 23: Configuration management with Chef, the whole file as data (2014)#
Assumptions. Traffic: hundreds of thousands of servers, each converging its configuration on a schedule. Latency: minutes to apply. Consistency: each server's configuration should match what source control says. Maintenance: a small team, but any engineer should be able to change any system they own.
Phil Dibowitz's 2014 post explains how Meta used Chef, a configuration-management tool, in an unusual way. The goal was a system that lets any engineer make any change to systems they own through simple, data-driven APIs, that scales to Facebook's fleet, and that a small team can run.
The problem with typical cookbooks. A Chef "cookbook" usually defines one attribute for each config option and a template that places each one. That gives either too little control (only the options the author exposed) or too much complexity (hundreds of attributes, more confusing than the config file itself). Every new option in the software needs a cookbook change.
Meta's pattern: model the config file as a data structure. The template simply loops over a hash and writes every key and value. Anything that can go in the file can go in the hash. A new software version with six new options needs no cookbook change. The same idea extends to INI files (sections of key-value pairs, with true meaning "key only" and false meaning "omit"), to JSON (just serialise the hash), and to nested formats such as Apache virtual hosts (nested hashes become nested blocks).
# Template: write every key the user set, nothing hard-coded
<% node['foo']['config_file'].to_hash.each do |key, val| %>
<%= key %> <%= val %>
<% end %>
# Any team, in its own role or recipe, sets only what it needs:
node.default['foo']['config_file']['Port'] = 1234
node.default['foo']['config_file']['SSL'] = 'On'
# Validation lives in a recipe block, not the template
whyrun_safe_ruby_block 'validate vhosts' do
block do
node['apache']['virtual_hosts'].to_hash.each do |name, cfg|
fail "#{name} missing ServerName" unless cfg['ServerName']
end
end
endValidation belongs in a recipe block, not in the template, because templates give poor error messages. Its job is to catch obvious mistakes and fill defaults that cannot be known in advance (for example a default ServerAdmin built from each virtual host's ServerName). It does not re-implement the software's own config test.
Benefits. Users can change anything through a simple, documented API. Cookbooks need little upkeep. Because the cookbook owns the whole file, it removes stale settings automatically, keeping the system idempotent instead of editing lines one by one.
Tools released. Grocery Delivery keeps Chef servers in sync with a source repository (git or svn), so Chef servers are disposable and can be lost or replaced at any time. Taste Tester, built on Chef Zero, lets an engineer test changes on real servers before committing them.
This post covers server configuration (packages, files, services). Meta's application configuration, the feature flags and runtime settings pushed to running services, uses a separate system described in Tang et al., "Holistic Configuration Management at Facebook", SOSP 2015. The shared idea is the same: configuration is code, reviewed and tested, and delivered by automation.
Overlooked constraints.
- Hash-merged attributes from many teams can conflict. Precedence rules (default, override) must be clear, or two teams' settings silently fight.
- Managing the whole file is powerful and dangerous. One bad attribute reaches every server that converges, so canarying (Taste Tester, staged rollout) is essential (deployment strategies).
- Disposable Chef servers only work if the source repository is the single source of truth. Hand edits on a server are lost by design.
What Meta sacrificed. Strong typing and per-option validation (any key is accepted), the safety of a cookbook author curating options, and compatibility with typical community cookbooks. In return it got a small team supporting the whole fleet, and engineers who can change anything they own.
Deep Dive: Distribution and configuration rollout arithmeticShow
Owl versus central caches (handbook's illustration). A 2 GB binary goes to 100,000 hosts in 10 minutes, 200 TB in total. A central cache tier serving 200 TB in 600 s needs about 333 GB per second, which is roughly 270 servers at 10 Gbps each running flat out, sized for a spike that lasts minutes. With peer-to-peer distribution in which each rack fetches once from storage and shares inside the rack, 100,000 hosts in 2,500 racks of 40 means storage serves 2,500 copies, 5 TB, and the rest moves over in-rack links, which are cheap and plentiful.
Chunking. A 2 GB object in 4 MB chunks is 500 chunks. Different peers can fetch different chunks from different sources in parallel, then swap, so the time to spread is about the time to move one copy over one rack link plus a few hops. Without chunking, the first peer must finish the whole 2 GB before anyone can copy from it.
Config rollout risk. A Chef run every 15 minutes on 200,000 hosts means about 220 hosts converge per second. A bad change merged to the main branch reaches every host within one interval. If Taste Tester first applies it to 20 hosts for an hour, a fault caught there affects 0.01% of the fleet instead of 100%. This is the same staged-rollout logic as the October 2021 outage lesson later in this page, where a bad command bypassed a faulty audit and reached the whole backbone.
Family 5: Products built on the platform: ranking, recommendations, live video, encrypted sync and a launch
The next five lessons are product stories. Each is a familiar interview prompt (news feed, recommendations, live streaming, chat on many devices, a viral launch), and each shows which platform layers from the earlier families the product leaned on.
Lesson 24: News Feed ranking, a multi-pass funnel with a value model (2021)#
Assumptions. Traffic: more than 2 billion people, with more than 1,000 candidate posts per person per day on average. Latency: ranking runs on every feed open, in real time, within a few hundred milliseconds. Consistency: features must be fresh. A post liked by thousands in the last minute, or a viewer who just liked three videos, must affect the next ranking. Maintenance: models change constantly, and the system must allow new prediction tasks.
Akos Lada, Meihong Wang and Tak Yan's 2021 post explains the ranking problem with a hypothetical user. Since their last visit, a close friend posted a dog photo, another friend posted a running video, a followed Page shared an article, and a Group posted four recipes. All are eligible. Which goes first?
From one objective to many. Start with one signal: will this viewer like this post? For post i, viewer j and time t, a model f predicts Y from features x: post type, recency, viewer-author relationship (for example, whether they marked each other as family), and the viewer's past behaviour. Liking is only one way to express value, though. People also comment, share and watch. So there are many predictions Y for each event type k, and they must be combined into one value V. To choose the weights, Meta surveys people about which interactions felt meaningful and which posts were worth their time. That aligns the combination with what people say they value, not just with what they click.
The serving path. A client (iOS, Android, web) calls the Web/PHP front end, which calls the feed aggregator. The aggregator fetches actions, objects and object summaries from feed leaf databases, then ranks and returns a list of FeedStories. The aggregator's steps are:
- Query inventory. Collect every non-deleted post shared with the viewer by friends, Groups and Pages since the last login. Two bumping rules widen this. Unread bumping brings back posts ranked in an earlier session but not seen. Action bumping brings back a seen post if it later sparked an active conversation among the viewer's friends.
- Integrity checks. Decide which integrity measures apply to each candidate.
- Pass 0. A lightweight model picks about 500 of the most relevant posts, with high recall, so heavier models run on fewer items.
- Pass 1, main scoring. Multitask neural networks predict each event for each post, using many features including embeddings. The predictions run in parallel on many machines called predictors. The combined score is a weighted sum, V = w1·Y1 + w2·Y2 + ... + wk·Yk, with weights personalised per viewer.
- Pass 2, contextual. Rules that depend on the ranked list, such as content-type diversity (no run of videos back to back), reorder the final feed.
Why a linear combination? It is simple and tractable, and it has a useful property. If a viewer almost never does event k, its predicted probability is near zero, so it contributes almost nothing whatever its weight. Personalisation can then go further. If a viewer's behaviour shows that event k correlates more with their long-term value, its weight can rise, as long as the change is made incrementally and corrected for confounding variables.
This is the ranking half of a news feed. The fan-out and storage half (push versus pull, celebrity handling) is covered in the news feed case study, and the graph reads come from TAO (Lesson 5).
Overlooked constraints.
- 2 billion people times 1,000 candidates is 2 trillion candidate scorings a day before pass 0. The funnel exists because the heavy model cannot see everything.
- Fresh features need a streaming path. A like counted an hour late is a wrong feature, so counters and viewer actions must flow in seconds.
- Optimising raw engagement drifts toward clickbait. The survey-derived weights are an explicit guard against metric gaming.
What Meta sacrificed. Exact global optimality (pass 0 can drop a post the heavy model would have loved), model simplicity (several passes and many tasks), and a single clean objective (survey weights are a human judgement). In return it gets real-time personalised ranking at planet scale within a latency budget.
Deep Dive: Funnel compute arithmetic and value-model behaviourShow
Compute budget (handbook's illustration). Suppose 1.5 billion feed opens per day (a person opening several times), each with 1,500 inventory posts, so 2.25 trillion candidates a day, about 26 million per second on average and maybe 50 million per second at peak. If the heavy multitask model costs 50 µs of accelerator time per candidate, scoring everything needs 2,500 accelerator-seconds per second, so 2,500 fully busy devices at peak, before replication. Pass 0 cuts 1,500 to 500, which cuts pass 1 cost by two thirds. A second cut to 100 for an even heavier model would cut it by 15 times. Each funnel stage trades recall for compute.
The linear value model in action. For one viewer the weights are like 1, comment 4 and share 6. Post A has P(like) 0.30, P(comment) 0.02 and P(share) 0.01, so V = 0.30 + 0.08 + 0.06 = 0.44. Post B has P(like) 0.10, P(comment) 0.06 and P(share) 0.03, so V = 0.10 + 0.24 + 0.18 = 0.52. B wins although A gets three times more likes, because the viewer's comments and shares are worth more. For a viewer who never comments, P(comment) is about 0 for every post, so the comment weight changes nothing, which is the property the post highlights.
Multitask networks. One shared trunk with a head per event shares features and compute across tasks, and helps rare tasks (shares) learn from common ones (likes). A known variant, Multi-gate Mixture-of-Experts (Ma et al., "Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts", KDD 2018), lets tasks that conflict use different experts.
Lesson 25: Instagram Explore, a four-stage recommender built on caching (2023)#
Assumptions. Traffic: hundreds of millions of daily visitors choosing from billions of media items. Latency: real time, a few hundred milliseconds for the whole funnel. Consistency: user features fresh to the session; item embeddings refreshed daily. Maintenance: hundreds of tunable parameters, models retrained hourly.
Vladislav Vorotilov and Ilnur Shugaepov's 2023 post describes Explore, one of Instagram's largest recommendation surfaces. Unlike News Feed, Explore recommends content from accounts the user does not follow, so the candidate pool is all of Instagram. Its theme, in the authors' words, is clever caching and pre-computation at every stage, so heavier models can run everywhere. The stages are:
- Retrieval: billions down to thousands.
- First-stage ranking: thousands down to about a hundred.
- Second-stage ranking: score the hundred precisely.
- Final reranking: integrity and diversity.
The full design is in the recommendation system case study.
Retrieval sources. Several sources each pick hundreds of items. Sources may be heuristic (trending posts) or ML-based. They may be real-time (recent interactions) or pre-generated offline in off-peak hours (for example, locally popular media). Sources are mixed with tunable weights per user group.
Two Tower networks. Explore's earlier ML retrieval used Word2Vec (Mikolov et al., "Efficient Estimation of Word Representations in Vector Space", 2013) to learn embeddings for users and media from their IDs. The Two Tower model generalises it:
- A user tower and an item tower each take only their own entity's features and output an embedding.
- Training makes the similarity (dot product) of the two embeddings predict engagement, possibly for several tasks.
- After training, the towers are independent. The item tower embeds every item offline, daily, and the embeddings go into an approximate nearest neighbour (ANN) index such as FAISS (Johnson, Douze and Jégou, "Billion-scale similarity search with GPUs", 2017) or HNSW (Malkov and Yashunin, IEEE TPAMI 2018).
- Online, the user tower runs once on the freshest user features, and the ANN index returns the nearest items.
The price is that the model cannot use user-item interaction features, such as "how often has this user engaged with this author", which are usually the most predictive. Using them would break the independence that makes both embeddings cacheable.
Interaction-history retrieval. Take items the user liked, saved or shared, find neighbours of each by embedding, and merge the lists. This gives finer control over which engagement types drive recall. The seed items need filtering by rules (remove objectionable images, heavily reported posts), or one accidental click floods recommendations with junk.
Ranking. Both rankers are neural networks, because they handle categorical features through embeddings and can be fine-tuned every hour on fresh data (continual online training) to follow trends.
- First stage: a Two Tower model again, for cacheability, with both sides cached. Its label is "was this item in the second stage's top K?", so the light model learns to imitate the heavy one, a form of knowledge distillation (Hinton, Vinyals and Dean, "Distilling the Knowledge in a Neural Network", 2015).
- Second stage: a multi-task multi-label (MTML) network that predicts P(click), P(like), P(see less) and so on, and that can use user-item interaction features. Because it is heavy, recommendations for some users are precomputed off-peak so Explore stays available at peak.
The value model combines the predictions: expected value = W_click·P(click) + W_like·P(like) − W_see_less·P(see less) + ... Tuning the weights trades one engagement metric against another.
Final reranking. Down-rank or remove items with integrity concerns, and apply diversity rules such as "no two items from the same author in a row".
Tuning hundreds of parameters. Explore has many knobs: value-model weights, how many items each source returns, how many items to rank, and so on.
- Online Bayesian optimisation needs only the parameters, a goal metric and guardrail limits on other metrics. It can take more than a month to converge with many parameters and insensitive metrics.
- Offline tuning learns, from historical experiments, a mapping from offline-metric changes to online-metric changes, then searches offline (often with Bayesian optimisation). It sets up in hours instead of weeks, but it only works if offline and online metrics correlate strongly.
Overlooked constraints.
- Recommendation from unfollowed accounts makes integrity a first-class stage. A bad item is amplified to strangers.
- Precomputing off-peak means some users see recommendations that are hours old at peak. That is acceptable for discovery, not for a chat inbox.
- Feedback loops: a model trained on what it recommended learns its own biases. The authors list maintainability and feedback loops as the growing challenges.
What Meta sacrificed. The predictive power of user-item features in early stages (for cacheability), freshness for some users at peak (for availability), and simplicity (many sources and hundreds of parameters). In return it gets heavy models at every stage within the latency budget.
Deep Dive: Why two towers are cheap and what ANN buysShow
Brute force versus ANN (handbook's illustration). One billion items with 128-dimension float embeddings is 512 GB. Brute-force scoring one user is one billion dot products of 128 multiply-adds, about 256 GFLOP, roughly 1 second on a fast GPU, far too slow per request. An HNSW graph index visits a few thousand nodes per query and returns the top 1,000 in a few milliseconds at about 90 to 95% recall. Product quantisation, as in FAISS, compresses each vector to perhaps 32 bytes, so the index is 32 GB and fits in one large machine's memory.
Why interaction features break caching. A two tower score is u·v, where u depends only on the user and v only on the item. So v can be computed once a day for every item, and u once per request. A feature like "user's clicks on this author in the last week" depends on the pair. It would have to be computed for every candidate on every request, and it cannot be precomputed into either vector. That is exactly the second-stage model's job, which is why that stage scores 100 items, not 10,000.
First-stage cost. With both sides cached, first-stage scoring of 5,000 candidates is 5,000 dot products of 128 values, 1.28 million multiply-adds, under a millisecond on a CPU. A heavy MTML model at maybe 1 ms of accelerator time per item for 100 items is 100 ms of accelerator time per request, so the 50-times cut in the first stage saves about 5 seconds of accelerator time per request.
Distillation label. Training the first stage on "in stage two's top K" instead of raw clicks aligns the stages. Without it, the first stage might drop items the second stage would rank highly, because each was trained for a different target.
Lesson 26: Live video, request coalescing and a push protocol (2015)#
Assumptions. Traffic: one broadcast may have more than a million simultaneous viewers, with no warning. Latency: the first product (public figures) accepted HLS delay. The second (everyone) needed 2 to 3 seconds. Consistency: all viewers need the same segments, in order. Maintenance: built on the existing edge and origin cache tiers.
Federico Larumbe and Abhishek Mathur's 2015 post covers two launches: Live for public figures through the Mentions app, and Live for everyone on iPhone.
Problem 1: thundering herd. When a celebrity starts a stream, a million players ask for the same new segment at the same moment. The video is cut into 3-second HLS segments, which players request in sequence over HTTP. Requests go to an HTTP proxy in an edge PoP. If the segment is cached there, it is returned. Otherwise the proxy asks the origin cache, a second tier with the same design. If origin misses too, it asks the live stream server for that broadcast. Each tier caches the response. More than 98% of segments were served from the edge.
That still let about 1.8% of requests through, which at a million viewers is around 18,000 requests per segment aimed at one stream server. Live viewing is unlike regular video, where viewing spreads over time and a viral spike builds gradually. Live viewers arrive together and ask for a segment that may not exist in cache yet. The fix is request coalescing: on a miss, the edge forwards only the first request and holds the rest in a queue. When the response arrives, it caches the segment and answers the queued requests as hits. The origin does the same for requests from many edges, for example Chicago and Miami asking for the same segment at once (cache failure modes).
Problem 2: latency. Ordinary people often broadcast to a small, interactive group, so a 10- to 30-second HLS delay ruins the conversation. The team switched viewer playback to RTMP, which keeps a persistent TCP connection and pushes data. Audio and video are separate streams, cut into 4 KB chunks and interleaved on the connection. At 500 Kbps a 4 KB chunk is only 64 ms of video, versus a 3-second HLS segment. The broadcaster sends each chunk as soon as it is encoded, the transcoder produces several bit rates, and proxies forward chunks to players. Push plus small chunks cut broadcaster-to-viewer delay about 5 times, to 2 to 3 seconds. Most live products used HLS because it works with any HTTP CDN. Meta modified the nginx-rtmp module and built an RTMP proxy, reusing the lessons from the HLS path so it scaled to millions of broadcasters.
Overlooked constraints.
- Coalescing makes the queued requests wait for the first one. If the origin is slow or the first fetch fails, thousands of viewers stall together, so timeouts and a retry by the next queued request matter.
- Push protocols hold a TCP connection per viewer, so proxies carry long-lived connection state that HTTP caches do not. That costs memory, and draining a proxy means moving live connections.
- Latency and scale pull against each other. Bigger segments cache better and survive bad networks, smaller chunks feel live. Meta ran both paths.
What Meta sacrificed. The simplicity of a pure HTTP CDN path (it built and runs an RTMP stack), some tail latency for queued viewers under coalescing, and HLS's easy compatibility. In return it handles million-viewer spikes and near-real-time interaction. For a full design see the video streaming case study, and for the comment side see live comments.
Deep Dive: What coalescing saves, in numbersShow
Without coalescing (handbook's illustration). One million viewers, a new 3-second segment every 3 seconds, and 1.8% leakage past the edge gives 18,000 requests per segment to the origin tier, about 6,000 per second, all for the same object. If origin also leaks, a single stream server could see thousands of requests per second for one segment, all arriving within a few hundred milliseconds of each other.
With coalescing. Say there are 100 edge PoPs, each with many viewers. Each PoP sends at most one request per segment (per cache host, if a PoP has several), so the origin sees about 100 requests per segment. The origin coalesces those too and sends 1 request to the stream server. Load on the stream server is now independent of audience size: one request per segment per origin host.
RTMP chunk timing. 4 KB is 32,768 bits. At 500,000 bits per second that is 0.0655 s, the 64 ms in the post. An HLS player typically buffers about three segments before starting, so its delay is at least 9 seconds plus encode and network time. RTMP's floor is one chunk plus transcoding and hops, which is how 2 to 3 seconds becomes reachable.
Coalescing as a general pattern. The same idea is called "single flight" in Go, and request collapsing in Varnish and other CDNs. It appears wherever many clients want the same not-yet-cached object at the same time: cache stampedes after expiry, hot keys after a cold start, and DNS resolvers.
Lesson 27: WhatsApp multi-device, end-to-end encryption without a primary phone (2021)#
Assumptions. Traffic: billions of users, each now with a phone plus up to four companion devices (web, desktop, Portal). Latency: messages delivered in near real time to every device. Consistency: chat history and application state (contact names, archived and starred flags) should match across devices. Maintenance: the server must never see plaintext, and must store as little as possible.
The 2021 WhatsApp post describes a rebuild of the device model. Before it, the phone was the source of truth. Companion devices kept a secure connection to the phone and mirrored it. Only the phone could encrypt messages or start calls. That was simple and secure, but companions were slow and often disconnected when the phone had poor signal, low battery or a killed app process. And only one companion could be active at a time.
Identity per device. Previously each user had one identity key from which all session keys came. Now each device has its own identity key. The server keeps a map from account to device identities, and a sender fetches the device list before sending.
Defending against a malicious server. If the server can add devices to an account, a compromised server could quietly add an eavesdropping device. WhatsApp uses three layers of defence:
- Security codes now cover the combination of all a user's device identities, so contacts can verify every device they send to.
- Automatic Device Verification lets a user's devices vouch for each other, so a contact only needs to re-verify if the user re-registers the whole account, not on every new device.
- Linking controls. New companions are linked by scanning a QR code from the phone, with a biometric check where enabled. Users can see every linked device and when it was last used, and log any of them out remotely.
Client fanout. In a one-to-one chat, a pairwise encrypted session exists between each of the sender's devices and each of the recipient's devices. The sending client encrypts the message separately for every device in both device lists, the recipient's and the sender's own other devices, and sends N ciphertexts. The server does not keep messages after delivery. Groups keep using the Sender Keys scheme from the Signal Protocol, which scales better: each sender distributes one sender key to group members through pairwise sessions, then encrypts each message once. The Signal Protocol's key ratchet is specified in Perrin and Marlinspike, "The Double Ratchet Algorithm", 2016.
Calls. The caller creates a random 32-byte SRTP master secret for each of the callee's devices and sends each one inside an incoming-call message, fanned out per device. Whichever device answers uses its own secret to key the encrypted call. The secret lives only in memory for the call, and servers never see it. In group calls, the server picks a random participating device to generate the secret, which it sends to the other active devices over pairwise sessions. The key is regenerated whenever someone joins or leaves.
History and state sync.
- Message history. On linking, the phone encrypts a bundle of recent chats and uploads it as a blob. It sends the blob's key to the new device in an end-to-end encrypted message. The device downloads, decrypts and stores the history locally, and the keys are deleted. From then on the device has its own local database.
- Application state (new contacts, mutes, stars) changes constantly. The server stores an encrypted copy of each application state that all of a user's devices can reach. The data and even the metadata about what kind of data it is are encrypted with frequently rotated keys known only to the user's devices.
Overlooked constraints.
- Client fanout multiplies upload. A message to someone with five devices, from a sender with five devices, is about nine encryptions and uploads instead of one. That is why groups use Sender Keys.
- The device list is a trust anchor held by the server. All the verification machinery exists because the server could lie about it.
- Encrypted state sync means the server cannot merge conflicts. Devices must reconcile among themselves using patches and versions, which pushes CRDT-like logic into clients (collaborative editing discusses such merges).
What Meta sacrificed. Bandwidth and battery for per-device fanout, server-side features that need plaintext (no server search or server merge), and some simplicity in key management. In return phones are no longer a single point of failure, while end-to-end encryption is kept. For a general chat design see the chat system case study and security fundamentals.
Deep Dive: Client fanout cost versus Sender KeysShow
One-to-one (handbook's illustration). Alice has 3 devices and Bob has 5. A 1 KB text from Alice's phone is encrypted for Bob's 5 devices and Alice's other 2, which is 7 ciphertexts, about 7 KB uploaded. Each encryption is a fast symmetric operation after the session exists, so the CPU cost is negligible. The real cost is setting up pairwise sessions, one per device pair, created on first contact using prekeys fetched from the server.
Groups. A 256-member group with an average of 2 devices each has 512 devices. Pairwise fanout would mean 511 encryptions and 511 uploads per message, about 511 KB for a 1 KB text. With Sender Keys, each sender device distributes its sender key once (511 pairwise messages, only on joins and key rotation), then encrypts each message once and uploads one ciphertext, which the server fans out. Per-message upload drops from 511 KB to 1 KB. The trade-off is weaker forward secrecy within a group epoch, so keys are rotated when members change.
Why a fresh key per history bundle. The history blob may sit in storage for a while. Encrypting it with a one-time key that is sent over the end-to-end channel and then deleted means a later compromise of the storage cannot decrypt it, and the server never holds a key that opens it.
Lesson 28: Threads, a launch on two days' notice (2023)#
Assumptions. Traffic: more than 100 million sign-ups in five days. Latency: onboarding must feel instant. Consistency: follow relationships and counters must end up correct, but can lag by seconds or minutes. Maintenance: built by a small team in five months of technical work. The infrastructure teams got two days' notice of the launch date.
Laine Campbell and Chunqiang Tang's 2023 post makes one point: Threads scaled because of more than a decade of shared infrastructure, not because of anything built for it. Posts and replies live in TAO over MySQL. The post highlights two other systems.
ZippyDB (Lesson 11) for counters, feed state and search.
- Capacity absorption. ZippyDB runs on a common hardware pool tied to Meta's capacity management. Once capacity is granted, machines join the pool and the load balancer moves data onto them. Thousands of machines can be absorbed within a few hours. But approving and draining capacity from other services can take a couple of days, which is too slow for a surprise.
- Absorbing a surge immediately. ZippyDB relies on multi-tenancy with strong isolation. Keyspaces with complementary load share hosts, and the pool has slack from unused allocations and disaster-recovery buffers. Config changes can shift unused allocation between keyspaces and let hosts run hotter for a couple of days.
- Resharding with zero downtime. Clients hash keys to logical shards, which map to physical shards. To scale out, ZippyDB provisions new physical shards and pushes a new logical-to-physical mapping to clients through live config. Workers then move logical shards one at a time, atomically, using hidden access keys on the server. When every logical shard has moved, the old mapping is removed. The resharding stack uses a coordinator-worker model, so it scales horizontally, and emergency operator tools exist for sudden growth. Use cases start small and reshard as they grow, to avoid over-provisioning. For Threads the team resharded ahead of time for 100x growth, finishing just as traffic opened at midnight UK time.
Async (Lesson 18) for follow-graph import and notifications. Async, also called XFaaS (Sahraei et al., "XFaaS: Hyperscale and Low Cost Serverless Functions at Meta", SOSP 2023), runs trillions of function calls a day on more than 100,000 servers, in Hack, Python, Haskell and Erlang. It handles deployment, queueing, scheduling, scaling and disaster readiness, with configurable retries, delivery deadlines, rate limits and capacity accounting. Its jobs do not block a user and can run seconds to hours later.
At Threads sign-up, users could follow everyone they followed on Instagram. Copying that graph is expensive, so it ran in Async, not in the sign-up request. Celebrity joins queued millions of follow operations and notifications. Job volume was several orders of magnitude above the initial forecast. Async queued the jobs and ran them under rate limits, adjusting execution to its own capacity and to downstream capacity such as the social graph database, with no manual intervention.
Culture as infrastructure. Except for finding capacity at short notice, redistribution, load balancing and scaling were automatic. The SEV incident-management culture (Meta's severity-rated incident process) gave fast cross-team visibility and focus.
Overlooked constraints.
- A launch's real bottleneck is often capacity approval, not provisioning. Slack and multi-tenancy are what buy the first days.
- Graph-import fan-out is a write amplification bomb. 100 million users times hundreds of follows is tens of billions of edge writes. It must be asynchronous, and it must be rate-limited to protect the graph store.
- Resharding ahead of demand only works if the system can reshard online. Systems that need downtime to reshard must over-provision at launch.
What Meta sacrificed. Immediate consistency for follow graphs and notifications (they arrive over minutes), some host headroom and disaster buffer during the surge, and the efficiency of right-sized shards (it pre-sharded for 100x). In return the launch was reliable on two days' notice. The lesson for design reviews is to move expensive fan-out off the request path and plan capacity with headroom.
Deep Dive: Threads launch arithmetic and logical shardsShow
Follow import (handbook's illustration). 100 million users in 5 days is about 230 sign-ups per second on average, and probably 2,000 or more per second in the first hours. If each copies 300 follows, that is 30 billion edge writes. Spread over 5 days, that is about 70,000 writes per second, on top of normal traffic, and much more at peak. Running it synchronously would add seconds to every sign-up and could overwhelm the graph store's write path. A queue lets the backlog grow during the peak and drain overnight.
Logical shards. 65,536 logical shards over 256 physical shards is 256 logical per physical. Scaling to 2,560 physical shards moves 90% of logical shards. Because each logical shard is small (total data divided by 65,536) and moves on its own, each step is fast and only one logical shard at a time is in transition. Clients look up the logical-to-physical map, so no key ever rehashes. This is the same idea as Redis Cluster's 16,384 hash slots, and it avoids both modulo rehashing and fine-grained consistent hashing.
Why reshard first. Resharding copies data, using disk and network on hosts that are also serving traffic. Doing it before the surge means the copy runs on idle hosts. Doing it during the surge competes with the load you are trying to absorb.
Family 6: When it all goes wrong: two outages, eleven years apart
Meta's two most-cited public postmortems are short. They teach more per word than most design documents, because each shows a safety mechanism that turned into the failure.
Lesson 29: The 2010 outage, a self-healing loop that could not stop (2010)#
Assumptions. Traffic: every web server reads configuration values through the cache. Latency: config reads are on the request path. Consistency: the cache should mirror a persistent store, the source of truth. Maintenance: an automated checker repairs bad cached values.
Robert Johnson's 2010 post explains Facebook's worst outage in more than four years: the site was down or unreachable for about 2.5 hours. The cause was one error-handling decision.
An automated system checked configuration values in the cache. If a value looked invalid, it replaced it with the value from the persistent store. That fixes a transient cache problem. It cannot fix a bad source of truth.
The failure unfolded in four steps:
- An engineer changed the persistent copy of a configuration value to something the checker considered invalid.
- Every client saw the invalid value and tried to "fix" it by querying the database cluster. Hundreds of thousands of queries per second swamped it.
- Worse, when a client's database query failed, it treated the failure as an invalid value and deleted the cache key. So the next read missed again and queried the database again.
- Even after the bad value was corrected, the loop continued. As long as some database requests failed, they generated more requests to the database. The system had entered a positive feedback loop with no stable recovery point.
The only fix was to stop all traffic to that database cluster, which meant taking the site down. Once the databases recovered and the root cause was fixed, users were let back in gradually. The checker was turned off, and the team planned a redesign along the lines of other Facebook systems that handle feedback loops and transient spikes gracefully.
The general lessons map directly onto patterns covered elsewhere in this handbook:
- Never treat "I could not check" as "the value is bad". An error is not evidence. Cache-repair logic should leave the old value in place, or serve stale, when the source cannot be reached (cache failure modes).
- Validate at the source, not at every consumer. If the persistent value is invalid, reject the write. Hundreds of thousands of clients should not each discover the problem.
- Bound the repair rate. A global limit on repair queries, with jitter and backoff, turns a storm into a trickle (resilience patterns).
- Have a "stop the world" lever that is not "turn off the site". Load shedding, or a kill switch for the repair system, would have broken the loop without a full outage.
- Recover gradually. Letting users back in slowly is the same idea as cold-cache warm-up in Lesson 1.
Lesson 3 (Polaris) and the memcache lease mechanism in Lesson 1 show how later designs addressed exactly this class of problem: bound the number of clients that can go to the database for one key, and measure cache-source divergence directly instead of guessing.
Overlooked constraints.
- Automated remediation is code that runs during abnormal conditions, which are the least-tested conditions there are.
- Retry and repair loops have gain. If each failure causes more than one new request, the system is unstable once failures start.
- The cache is part of the database's capacity plan. Deleting keys removes database protection at the worst moment.
What Meta sacrificed. 2.5 hours of availability and the convenience of self-healing config. It chose a hard stop because no softer lever existed. The lasting change was cultural: treat automated repair systems as dangerous and rate-limited by default.
Deep Dive: Loop gain, metastable failure and why the loop would not stopShow
A loop with gain (handbook's illustration). Let a database cluster handle 50,000 QPS. Normal cached reads send it 5,000 QPS. Now 200,000 clients each read the value once a second, and each sees "invalid", so 200,000 QPS arrives. The cluster can serve 50,000, and the other 150,000 time out. Each timeout deletes the cache key, so those 150,000 clients miss again on their next read and query again. Even after the source is fixed, the arrival rate stays near 200,000 QPS because 75% of queries fail, so 75% of clients keep their caches empty. The system is stable in a bad state.
The recovery condition. Successful queries refill the cache and stop that client's misses. If the database succeeds on a fraction s of requests, the repaired fraction grows by s each round, while failures keep the others querying. With s = 0.25 and nothing else changing, recovery would happen eventually, but in practice overload also slows the successful requests, retries pile up and s falls toward zero. Cutting arrival to zero (shutting the site) resets s to 1.
Metastable failures. This is a textbook metastable failure: a trigger (the bad value) pushes the system into a state that sustains itself after the trigger is removed. Bronson et al., "Metastable Failures in Distributed Systems", HotOS 2021, describes the pattern and names retries, cache dependence and failover storms as common sustaining effects. The standard defences are to break the amplifier (do not delete on error), add a rate limit, and shed load early.
Lesson 30: The October 2021 outage, a backbone command, DNS that withdrew itself, and a careful restart (2021)#
Assumptions. Traffic: every Facebook, Instagram, WhatsApp and Messenger request worldwide crosses Meta's backbone. Latency: users reach a nearby edge site, which talks over the backbone to a large data centre. Consistency: not the issue, since this was a total reachability failure. Maintenance: engineers routinely take parts of the backbone offline for fibre repairs, capacity additions and router software updates.
Santosh Janardhan posted two updates: a short one on 4 October and a detailed one on 5 October 2021. Public reporting put the outage at roughly six hours. The posts themselves do not give a number, and they confirm no malicious activity and no evidence of user data being compromised.
The network.
- The backbone is tens of thousands of miles of fibre linking all of Meta's facilities.
- Large data centres house millions of machines.
- Smaller edge facilities connect the backbone to the internet.
- A user's request goes to the nearest facility, which uses the backbone to reach a data centre.
Trigger. During routine maintenance, an engineer issued a command meant to assess the availability of global backbone capacity. Instead it took down all backbone connections, disconnecting every data centre. An audit tool existed to block exactly this kind of mistake, but a bug in it let the command through.
Amplifier: DNS withdrew itself. Meta's authoritative DNS servers sit at the edge facilities, on well-known IP addresses that are announced to the internet with BGP (Border Gateway Protocol, how networks tell each other which IP ranges they can reach). As a safety feature, a DNS site stops announcing its BGP routes if it cannot reach the data centres, because that suggests the site's network is unhealthy and users should go elsewhere. With the whole backbone down, every site judged itself unhealthy at once and withdrew. The DNS servers were running, but no one on the internet could reach them, so facebook.com and every other name stopped resolving (DNS).
Why recovery was slow.
- Engineers could not reach data centres through normal means, because those networks were down. Out-of-band access was down too.
- Losing DNS broke many internal tools used to diagnose outages.
- Engineers were sent on site. The facilities are built to be hard to get into, and the routers hard to change even with physical access. Activating the secure-access procedures took time.
Janardhan noted the irony: security hardening slowed recovery from a self-inflicted error. He judged the trade worth it, stronger everyday security against a slower recovery from a rare event.
Why the restart was careful. Restoring the backbone brought services back. But turning everything on at once risked a new round of crashes from the surge. Individual data centres had seen power use drop by tens of megawatts, and reversing that instantly could stress electrical systems as well as caches (the cold-cache problem from Lesson 1). Meta had run "storm" drills for years, taking a service, a data centre or a whole region offline to stress the infrastructure. That experience let it raise load in steps without further system-wide failures. Meta had never run a storm simulating the loss of the whole backbone, and said it would look for ways to do so.
Overlooked constraints.
- Health checks that fail closed everywhere at once are a single point of failure. The DNS withdrawal rule is right for one sick site and catastrophic when every site is sick for the same reason. A guard such as "do not withdraw if more than half of sites would withdraw" turns a global outage into a degraded one (high availability).
- Your recovery tools must not depend on the thing that failed. Out-of-band access, chat, runbooks, badge systems and DNS for internal tools all need paths that survive a total backbone and DNS loss (disaster recovery).
- Safety tools are code. The audit tool was the last line of defence and had a bug. Test guards like production code, and add a second independent check, such as staged rollout of network changes, for commands with global blast radius.
- Restart is a load event. Power, caches and databases each need a ramp. Plan the restart like a launch (incident management).
What Meta sacrificed. Hours of global availability and recovery speed, the latter knowingly, in exchange for strong physical and logical security. It kept the security trade-off and invested in testing, drills and resilience instead.
Deep Dive: Anycast DNS, health-based withdrawal and the correlated-failure trapShow
Anycast. Meta announces the same DNS server IP addresses from many sites. BGP routes each resolver to the nearest announcing site. If one site has a problem, withdrawing its announcement sends its users to the next nearest. This works because failures are expected to be independent.
Correlated failure (handbook's illustration). Suppose each of 30 sites is independently unhealthy 0.1% of the time. The chance all 30 withdraw together is 0.001 to the power 30, effectively zero. The rule fails only when withdrawals are correlated, which happens when every site uses the same signal ("can I reach the data centres?") and that signal depends on one shared component (the backbone). The probability of global withdrawal then equals the probability the backbone fails, not the product of site failures.
Design fixes this suggests.
- Use a quorum-aware rule: a site withdraws only if it is unhealthy and peers report being healthy.
- Keep a static "last resort" announcement or an external secondary DNS provider that answers with cached records when the primary is gone.
- Use long enough TTLs on key records that resolvers can ride out short outages, at the cost of slower intentional changes.
Megawatt ramp. A data centre that dropped 20 MW in minutes, as the post's "tens of megawatts" suggests, cannot jump back in one step without stressing the utility feed, transformers and backup systems. Ramping region by region over tens of minutes spreads the electrical, cache-warm and database load. That is the same staged-restart logic as memcache cold-cluster warm-up in Lesson 1.
Family 7: The AI turn: from failure-masking fleets to synchronous supercomputers
The last three lessons show the biggest assumption change in Meta's history. For twenty years the fleet was cheap, unreliable machines whose failures software hid, by retrying elsewhere. An AI training cluster is the opposite: thousands of expensive accelerators running one synchronous job, where any single failure stops everyone.
Lesson 31: Twenty-one years of infrastructure, and why AI broke the assumptions (2004 to 2026)#
Assumptions. Traffic: from a few thousand students to more than 3.4 billion people across several apps. Latency: web requests in hundreds of milliseconds. Training jobs measured in weeks. Consistency: from one database per university to globally replicated caches. Maintenance: from a few co-location facilities to multi-building regions and gigawatt clusters.
Yee Jiun Song and Kaushik Veeraraghavan's 2025 post is a history in four eras, and it ties together most earlier lessons on this page.
Era 1, scaling the software stack (2004 to 2010).
- Facebook started on LAMP (Linux, Apache, MySQL, PHP). Each university had its own database, and shared web servers connected each student to theirs. Students wanted friends at other schools, so the social graph was born, linking everyone.
- As the user base opened to high schools and then everyone, memcache (Lesson 1), then TAO (Lesson 5), plus News Feed ranking (Lesson 24) and a photo service (Lesson 7) carried the load.
- Expansion to Europe forced scaling below software: a co-location site in Ashburn, Virginia, then Meta's first own data centres in Prineville, Oregon and Forest City, North Carolina.
- Two new problems followed. Users needed to reach data centres, which meant an edge with compute next to local ISPs and peering. Every data centre needed the whole stack replicated, which meant a high-bandwidth multipath backbone. Meta now runs hundreds of PoPs.
Era 2, the hard corner cases (2010 to 2020).
- Cache consistency. Users got a "you were tagged" notification but could not see the photo, or chat messages arrived out of order. This happened because the photo or message had not yet replicated to the region the user was served from. The fixes were invalidation delivery systems (Lesson 14) and eventually a consistency API (Lessons 3 and 6).
- Fleet management. Twine, Tectonic, ZippyDB, Shard Manager and Delos (Lessons 8, 11, 13 and 20), plus ServiceRouter for the global service mesh (Saokar et al., "ServiceRouter: Hyperscale and Minimal Cost Service Mesh at Meta", OSDI 2023).
- Masking hardware failure.
- Kraken uses live traffic load tests to find bottlenecks (Veeraraghavan et al., "Kraken: Leveraging Live Traffic Tests to Identify and Resolve Resource Utilization Bottlenecks in Large Scale Web Services", OSDI 2016).
- Taiji balances user traffic from the edge to data centres (Chou et al., "Taiji: Managing Global User Traffic for Large-Scale Internet Services at the Edge", SOSP 2019).
- Maelstrom drains whole data centres safely during disasters (Veeraraghavan et al., "Maelstrom: Mitigating Datacenter-level Disasters by Draining Interdependent Traffic Safely and Efficiently", OSDI 2018).
Era 3, AI workloads arrive (late 2010s to 2020). Short-form video changed ranking. Facebook had ranked what a person's community (a few hundred friends) interacted with. Video recommendation must rank everything uploaded, orders of magnitude more, for each person. That needs embeddings, vectors in which similar videos sit close together, and sequence models over a user's clicks. It also needs GPUs, which are matrix machines rather than CPUs' load-store design, with orders of magnitude more arithmetic. The first AI clusters had 4,000 GPUs, and the team quickly learned that space, cooling, mechanical systems, hardware, network, storage and software must be planned together.
Era 4, large language models (2022 onward).
- In 2022 clusters had 4,000 GPUs, but a typical job used 128. Within weeks of starting LLM work, jobs grew to 2,000 and then 4,000 synchronous GPUs.
- Any straggler holds up everyone, and any failure stops the job. Unlike web serving, you cannot retry on another machine, because every machine is part of the one job. Checkpoint and restart time eats progress if failures are frequent. With industry partners Meta cut the interruption rate about 50 times on normalised metrics.
- LLM ideas also fed back into recommendation. HSTU (Hierarchical Sequential Transduction Units) sped up training and inference of generative recommenders by 10 to 1,000 times (Zhai et al., "Actions Speak Louder than Words: Trillion-Parameter Sequential Transducers for Generative Recommendations", ICML 2024).
- 2023: two 24,000-GPU H100 clusters, each sized to use all the power of one data-centre building (low tens of MW). One used InfiniBand and one RoCE (Lesson 32).
- Next, a 129,000-H100 cluster built by emptying out five production data-centre buildings in one region, in a matter of months.
- Heterogeneity. Ranking models, LLM pre-training, reinforcement learning, fine-tuning and test-time reasoning each want different hardware. Meta uses NVIDIA, AMD (MI300) and its own MTIA (Meta Training and Inference Accelerator), which is optimised for ranking and recommendation inference, deployed at scale mainly for ads, with a training chip ramping.
- A GB200 "Catalina" pod of six racks has two racks holding 72 Blackwell GPUs at about 140 kW, plus four air-assisted liquid cooling racks, because the older buildings lack facility liquid cooling. The pod gives about 360 PFLOPS of FP16.
- PyTorch and Triton hide hardware differences from developers.
- Physics limits.
- The reticle limit of about 830 mm² per die forces multi-die designs with 2.5D and 3D packaging.
- HBM next to compute competes for limited chip edge ("beachfront"), so memory may move off-chip or off-machine (memory disaggregation).
- Silicon photonics may be the only path past about 3.2 Tbps of "shoreline" I/O, with its own power and reliability challenges.
- Open standards. Handling 5 to 6 new hardware SKUs a year makes workloads hard to move, so hardware sits underused. Meta pushes open standards through the Open Compute Project, which it co-founded, with 187 contributions, about 25% of the total. Examples include the Catalina rack and the Grand Teton platform.
- Next: gigawatt clusters. Prometheus, about 1 GW, spans five or more buildings in a region plus weatherproof tents and nearby co-location sites. Twine and MAST (Meta's global ML training scheduler) are being extended for training across distant data centres. Hyperion is planned to scale to 5 GW from 2028.
Overlooked constraints.
- Power is the unit of capacity. Clusters are sized by the megawatts a building can deliver, not by floor space or budget.
- Lead times differ by layer. Software changes in days, hardware in a year or more, and buildings and power grids in years. That is why tents and repurposed buildings appear.
- Heterogeneity has a utilisation cost. Each extra SKU fragments the fleet, so portability layers (PyTorch, Triton) and open standards are capacity tools as well as developer conveniences.
What Meta sacrificed. Regular production capacity (five buildings emptied), the uniform, cheap, failure-tolerant fleet model, and the simplicity of a single vendor. In return it gets the compute to train frontier models.
Lesson 32: Training LLMs on 24,576-GPU clusters, network, storage and reliability (2024)#
Assumptions. Traffic: one job across thousands of hosts, exchanging gradients and activations every step. Meta's fleet runs hundreds of trillions of AI model executions a day for inference. Latency: the slowest GPU sets each step's time. Consistency: all ranks must be in lockstep, and a checkpoint must be a consistent snapshot of all of them. Maintenance: hardware fails often, and failures grow with cluster size.
Two 2024 posts are combined here. Kevin Lee, Adi Gangidi and Mathew Oldham described the clusters. Adi Gangidi, KR Kishore and Jenya Lee described how training works on them. Earlier, Meta's AI Research SuperCluster (RSC, 2022) had 16,000 A100 GPUs and trained Llama and Llama 2. The new clusters each have 24,576 H100 GPUs and were used for Llama 3. The 2024 target was 350,000 H100s, part of a portfolio equal to nearly 600,000 H100s of compute.
The shift in workload. Recommendation training meant many jobs with modest GPU counts. Generative AI means few, very large jobs. Four factors matter:
- Hardware reliability: test, screen and remediate quickly, so failures do not interrupt jobs.
- Fast recovery: reduce rescheduling overhead and re-initialisation time.
- Efficient checkpoints: save and restore training state often and quickly.
- Optimal GPU connectivity: a slow exchange between a few GPUs slows the whole job.
Network: build both. Meta had run RoCE (RDMA over Converged Ethernet) clusters for four years, but the largest had only 4,000 GPUs. It had built InfiniBand research clusters of up to 16,000 GPUs, but they were not integrated with production or built for the newest GPUs. So it built one cluster of each, with 400 Gbps endpoints:
- RoCE cluster: Arista 7800 with Wedge400 and Minipack2 OCP rack switches. Optimised for quick build time.
- InfiniBand cluster: NVIDIA Quantum-2. Optimised for full bisection bandwidth.
Both were tuned to equivalent performance for large generative AI jobs, and the largest Llama 3 model trained on the RoCE cluster. Three optimisations made this work:
- Map parallelism to topology. Each kind of parallelism (model, data and pipeline) produces its own traffic pattern. Each pattern is placed on the network layer that suits it. Tensor parallelism, which talks most, stays within a host or rack, and data parallelism crosses higher layers.
- Topology-aware collectives. Replace default ring algorithms with recursive doubling or halving, which are less sensitive to latency at scale.
- Load balancing for fat flows. Training creates a few huge, long-lived flows, which ECMP hashing spreads badly. Meta invested in routing and load balancing to spread them across all paths.
Out of the box, large clusters were bad. AllGather bandwidth on small clusters reached more than 90% of the theoretical limit, but on large unoptimised clusters it ranged from 10% to 90%. Topology-aware job scheduling (placing a job's ranks close together, which cut traffic to upper network tiers), routing changes and NCCL changes brought large clusters back above 90%.
Compute and data centre.
- Both clusters use Grand Teton, Meta's open GPU platform that integrates power, control, compute and fabric interfaces in one chassis. It descends from Big Sur, Meta's open GPU platform of 2015. The racks use Open Rack power.
- For H100s, Grand Teton was modified to raise GPU TDP to 700 W and move to HBM3. There was no time to change the cooling infrastructure, so it stayed air-cooled. That forced mechanical and thermal redesign and a new validation cycle.
- Halls were laid out to maximise GPU racks within fixed power and cooling. Supporting services, such as data readers, were moved out of the data hall.
Storage.
- Training data and checkpoints use a FUSE (filesystem in userspace) API over a flash-optimised version of Tectonic (Lesson 8). It lets thousands of GPUs save and load checkpoints in sync and provides exabyte-scale throughput for data loading.
- A parallel NFS deployment co-developed with Hammerspace supports interactive debugging, because code changes are visible on all nodes at once.
- Both run on YV3 Sierra Point servers with high-capacity E1.S SSDs. Servers per rack were tuned to balance throughput, rack count and power.
- New storage paths let checkpointing across thousands of ranks run in hundreds of milliseconds.
Software.
- H100s allow FP8 training.
- Desync debug, a distributed collective flight recorder, finds the one GPU stalling a job.
- PyTorch process-group initialisation, which sometimes took hours, was cut to minutes.
Reliability. Failures scale with cluster size, and a cluster-wide job needs spare capacity to restart quickly. The most frequent failure modes were:
- GPUs "falling off" the PCIe bus, mostly early in a server's life.
- Uncorrectable DRAM and SRAM errors. Repeat offenders are tracked against thresholds and returned to the vendor (RMA) when error rates exceed the vendor's limits.
- Network cables, which make servers unreachable, also mostly early in life.
Early-life failures argue for burn-in before a host joins a big job.
Overlooked constraints.
- Lost work per failure = time since last checkpoint + restart time. Both terms must shrink as clusters grow, or useful time collapses.
- The network is the computer. A cluster with fast GPUs but badly placed ranks reaches 10% of its bandwidth. Scheduling is a networking decision.
- Cooling locked hardware choices. Staying air-cooled was a schedule decision, and it constrained TDP and mechanical design.
What Meta sacrificed. Uniformity (two fabrics to learn from), some peak density (air cooling), and spare capacity held idle for fast restarts. In return it trained Llama 3 at scale and learned which fabric scales.
Deep Dive: Failure rates, checkpoint intervals and collective algorithmsShow
Cluster failure rate (handbook's illustration). If one GPU-host fails on average once every 5 years (about 43,800 hours), a job on 2,000 hosts (16,000 GPUs) sees a failure every 43,800 / 2,000 ≈ 22 hours. On 16,000 hosts it sees one every 2.7 hours. Reliability that is fine for a web server is crippling for a synchronous job, which is why interruption-rate work (the ~50x in Lesson 31) matters so much.
Optimal checkpoint interval. Young's approximation (J. W. Young, "A first order approximation to the optimum checkpoint interval", Communications of the ACM, 1974), refined by Daly (Future Generation Computer Systems, 2006), says the best interval is about √(2 × C × M), where C is checkpoint cost and M is mean time between failures. With C = 60 s and M = 22 h (79,200 s), the interval is √(9,504,000) ≈ 3,083 s, about 51 minutes. Expected waste is about C/T + T/(2M), roughly 2% + 2% = 4%. If checkpoints take 0.5 s (the "hundreds of milliseconds" from fast storage), the interval drops to about 4.7 minutes and waste to about 0.35%. Faster checkpoints are a direct throughput gain.
Ring versus recursive halving and doubling. For an allreduce of n bytes over p ranks, with α per-message latency and β per-byte time:
- Ring takes about 2(p−1)α + 2((p−1)/p)nβ. Bandwidth-optimal, but the latency term grows linearly with p. At p = 16,000 and α = 5 µs, the latency alone is 160 ms per allreduce.
- Recursive halving and doubling (Thakur, Rabenseifner and Gropp, "Optimization of Collective Communication Operations in MPICH", IJHPCA 2005) takes about 2·log₂(p)·α plus a bandwidth term close to the ring's. log₂(16,000) ≈ 14, so the latency term is about 140 µs. That is why the post calls custom collectives "less latency-sensitive" at scale.
Why fat flows defeat ECMP. ECMP hashes each flow to one path. With thousands of flows of similar size, hashing averages out. With a few hundred elephant flows, two may land on one link while another link idles, and the collective waits for the slower path. Fixes include more queue pairs per connection (more, smaller flows), path-aware routing, and placing ranks so traffic stays low in the tree.
Lesson 33: Maintaining AI capacity, maintenance trains and OpsPlanner (2024)#
Assumptions. Traffic: thousands of training jobs a day from hundreds of teams, from one GPU for minutes to trillion-parameter jobs across thousands of hosts. The plan was 600,000 GPUs within a year. Latency: online and recurring training jobs need capacity guaranteed all the time. Consistency: hosts in a job must run compatible stacks. Maintenance: more than 30 kinds of maintenance operations, more than 50 updated components, 3 host-verification tasks, and thousands of disruptive host tasks every day.
Saranyan A. Vigraham and Benjamin Leonhardi's 2024 post explains how Meta keeps updating firmware, drivers and networks on training clusters without breaking guarantees. GPU training is demanding in five ways:
- Capacity guarantees. Many jobs are time-critical, recurring or online, so maintenance cannot take large chunks of capacity.
- Bad hosts are very bad. A slightly slow host, one with a non-fatal hardware fault, or one with a network problem drags down a synchronous job.
- Low interruption tolerance, because many hosts share one problem.
- Rollout safety. The AI stack is deep and faults are hard to pinpoint.
- Host consistency. Except for CUDA version, hard incompatibilities are rare, but consistent clusters are much easier to debug and avoid incidents (SEVs).
No big-bang upgrades. Small environments upgrade a whole cluster in one window. At Meta's size that is too risky and impossible to schedule, so components are made compatible with each other and upgraded in a sliding fashion, with many changes in flight at once.
Maintenance trains. A small slice of servers, one maintenance domain, is taken out, receives all pending upgrades, and returns. The train moves cyclically through all capacity, compute and storage. Trains guarantee that all capacity minus one maintenance domain is up 24/7, which is mandatory for online and recurring training. A train picks up any new upgrade and guarantees a full visit within a fixed time. Long upgrades can span several cycles, and upgrades can be aligned with each other. AI capacity has tuned domains, strict SLOs, and a contract that lets services avoid train interruptions where possible.
Gradual rollout with a split stack. Lower-level components (firmware, kernel, drivers) take hours to install or need reboots, so they roll out gradually, and different hosts may run different versions for a while. The job's own stack, including the CUDA library inside the job container, is always consistent, and it can be restarted quickly. Making this safe needed lower-level testing, special monitoring, vendor collaboration, and tooling for rare compatibility-breaking upgrades.
Choosing the maintenance domain size. A bigger domain means fewer interruptions to jobs, because each job is hit less often. A smaller domain means less buffer capacity reserved. Meta worked with AI teams to size domains on both costs, which significantly cut maintenance overhead.
OpsPlanner. Some changes need consistency. A new CUDA version may need every host on a new driver first. OpsPlanner is the orchestrator for all disruptive work. It:
- serialises overlapping scopes of operations correctly;
- takes hosts out of production and returns them safely;
- has a handover flow that ensures correct escalation and avoids overlaps and deadlocks;
- makes sure required upgrades are applied before a host re-enters production;
- owns and protects the planned-maintenance and failure buffers.
It handles about a million operations a day. Its safety features include:
- Autostop of trains when maintenance or failure buffers run out.
- Automatic offboarding of failing upgrades.
- Rollout phases, so only well-tested changes reach global systems.
- Emergency trains and large-scale maintenance for breaking fixes.
Overlooked constraints.
- Maintenance is load. Thousands of disruptive tasks a day are a permanent drain, so it must be planned as a capacity line item, not a surprise.
- Consistency for debugging is worth paying for. When a job misbehaves, "which hosts differ?" must have a small answer.
- Orchestrators can deadlock. Overlapping operations that each hold some hosts and wait for others are a classic resource-ordering problem, which is why OpsPlanner has explicit handover and serialisation.
What Meta sacrificed. Perfect uniformity (low-level versions vary for a time), a permanent buffer of idle capacity, and the simplicity of whole-cluster windows. In return it gets continuous upgrades with guaranteed capacity.
Deep Dive: Sizing a maintenance domainShow
Setup (handbook's illustration). A 10,000-host cluster runs jobs that each span 1,000 hosts. Every host must be visited once every 30 days, and a visit takes 4 hours of downtime.
Option A: 1% domains (100 hosts). There are 100 domains. Each visit takes 4 hours, so a full cycle takes 400 hours (about 17 days), which meets the 30-day target. Buffer reserved is 100 hosts, 1% of the cluster. But a 1,000-host job spread across the cluster may be hit in many of those 100 windows. If a job touches 10 domains, it is interrupted 10 times per cycle.
Option B: 10% domains (1,000 hosts). There are 10 domains, and a full cycle takes 40 hours. Buffer is 1,000 hosts, 10%. If jobs are aligned to domains (scheduled within one domain), each job is interrupted once per cycle. Its owners can plan around it and checkpoint just before.
Cost comparison. If each interruption costs a 1,000-host job 30 minutes (restart plus lost work since checkpoint), Option A costs 10 × 0.5 h × 1,000 hosts = 5,000 host-hours per job per cycle, and Option B costs 500. The buffer in Option B costs 1,000 hosts × 720 hours = 720,000 host-hours per month, compared with 72,000 for Option A. The best size depends on how many large jobs there are and how well placement aligns jobs to domains. That is exactly the joint optimisation of interruption cost and buffer cost that the post describes.
Family 8: Synthesis
Lesson 34: Recurring patterns across Meta's posts#
Read together, the 33 lessons repeat a small number of moves.
1. Look-aside caching with a protocol, not just a cache. memcache leases (Lesson 1), mcrouter's routing and replication (Lesson 2), Polaris measuring divergence (Lesson 3), TAO's write-through graph cache (Lesson 5) and CDN coalescing for live video (Lesson 26) all treat the cache as a component with rules. Those rules are who may fill a key, who invalidates it, and how to prove it matches the source. The 2010 outage (Lesson 29) is what happens when the rules go wrong.
2. Separate ordering from storage, and the log from the materialised state. Wormhole tails the MySQL binlog (Lesson 14). LogDevice splits sequencing from storage (Lesson 15). Delos virtualises the log so its consensus can be swapped live (Lesson 13). MySQL Raft puts consensus inside the database's own log (Lesson 10). The log is the source of truth, and everything else is a view.
3. Shard explicitly, then make sharding a platform. ZippyDB (Lesson 11), Akkio (Lesson 12), FOQS (Lesson 17) and Threads' logical shards (Lesson 28) all use many small shards mapped to servers, and Shard Manager (Lesson 20) generalises the mapping. Explicit maps enable placement constraints, gradual moves and online resharding, which hashing alone cannot.
4. Match storage cost to data temperature. Haystack for hot photos, f4 for warm ones and cold storage for the rest (Lesson 7). Tectonic's tenants with different durability encodings (Lesson 8). MyRocks halving flash use (Lesson 9). Gorilla's 12x compression to keep 26 hours in RAM (Lesson 19). Every byte is placed by how often it is read.
5. Push heavy work off the request path, and rate-limit it. Async and FOQS defer work to off-peak hours and protect downstream services (Lessons 17, 18, 28). Scribe accepts small loss for throughput (Lesson 16). Explore precomputes some recommendations off-peak (Lesson 25).
6. Centralise decisions, decentralise data movement. Shard Manager's scheduler, Owl's trackers, OpsPlanner and Twine's allocator all decide centrally, while the data plane (app servers, peers, hosts) acts locally and keeps working if the brain is down (Lessons 20, 22, 33).
7. Treat maintenance and failure as normal traffic. TaskControl (Lesson 20), maintenance trains (Lesson 33), storm drills (Lesson 30), FOQS disaster readiness (Lesson 17) and Maelstrom (Lesson 31) all plan for the planned and unplanned loss of capacity every day.
8. Funnels for ranking. News Feed's pass 0, 1 and 2 (Lesson 24) and Explore's four stages (Lesson 25) both spend cheap compute on many candidates and expensive compute on few, and cache whatever does not depend on the user-item pair.
9. Safety mechanisms are the most dangerous code. The 2010 config checker, the 2021 audit tool and DNS self-withdrawal were all built to prevent outages and instead caused or amplified them (Lessons 29 and 30). Test guards like production code, and look for correlated triggers.
The deeper theme: one shared platform, many products. Threads launched on two days' notice (Lesson 28) because ZippyDB, Async, TAO, Shard Manager and Twine already existed and were multi-tenant. Meta's strategy is to make every hard problem (caching, sharding, queues, config, distribution, AI capacity) a platform used by hundreds of teams. Platform teams accept huge scope and complexity so product teams do not have to.
What Meta sacrificed overall. Meta paid in build-and-own cost and in coupling. It wrote its own caches, graph store, storage engines, logs, queues, schedulers, load balancers, file systems and chips. Most are open-sourced or published, but they are run by Meta alone. Shared platforms also mean shared fate: one bad config, one audit-tool bug, or one backbone command can reach everything at once, which the October 2021 outage showed. A smaller company should use the published ideas, such as leases, explicit shard maps, funnels and maintenance trains, on rented infrastructure.
Deep Dive: Shared platform economics and blast radiusShow
Why platforms pay at Meta scale (handbook's illustration). Say 200 teams each need a sharded key-value store. If each team builds its own with 2 engineers, that is 400 engineers, and each solution is mediocre. One platform team of 40 serving all 200 saves 360 engineers and produces a better system, because failover, balancing and resharding are built once. At 5 teams the platform team would cost more than the teams' own efforts. The crossover is roughly where the number of teams times their per-team cost exceeds the platform team plus the cost of onboarding.
Shared fate. If 200 services share one platform with 99.99% availability, each inherits its outages. Two levers keep blast radius down. Cellular deployment splits the platform into independent cells, so one bad push hits one cell. Staged rollout goes 1% to 10% to 100% with automated health gates. With 20 cells and per-cell rollout, a bad change caught in the first cell affects 5% of tenants instead of 100%. The October 2021 backbone command bypassed exactly this kind of staging because it acted on the global network at once.
Tail at scale. A News Feed request fans out to hundreds of leaf and predictor calls. If each has a 1% chance of exceeding 100 ms, a request touching 100 of them is slow 1 − 0.99 to the power 100, about 63% of the time. That is why Meta's systems hedge, time out early and degrade (Dean and Barroso, "The Tail at Scale", Communications of the ACM, 2013).
Cross-cutting: caching, low-latency feeds, edges, live comments and large media, seen through Meta#
Six classic interview problems overlap directly with Meta's lessons. Here is how each common answer maps onto what Meta built.
1. Caching read-heavy data with Redis or Memcached (a ticketing site). When tickets go on sale, thousands of users refresh the same event page. The good answer for search caches the results of repeated queries in Redis or Memcached. The key is built from every parameter that can change the result (keyword, start date, end date), and a TTL keeps entries fresh, for example 24 hours for a search over static events. The difficulties are stale results, especially for fuzzy queries, and miss storms at peak. A mix of TTLs and invalidation triggers tied to cache tags controls staleness. A stronger option uses the search engine's own caches: Elasticsearch caches filter results per shard and full responses in a shard request cache. A CDN can also cache non-personalised search results near users.
The great answer for the view path combines three things:
- Caching. Cache data with high read rates and low change rates (event names, dates, venues, performer bios, venue capacity) under keys such as eventId to event object, read-through, so misses load from the database and fill the cache. Invalidate through database triggers or change events when details change. Use long TTLs for static venue data and short ones for availability.
- Load balancing. Round-robin or least-connections across instances.
- Horizontal scaling. Stateless event services that scale by adding instances.
The challenges are cache-database consistency and the operational load of many instances (deploys, rollbacks).
Meta's version is memcache plus mcrouter (Lessons 1 and 2). Invalidations are driven by the MySQL commit log, like a trigger but asynchronous and reliable (Lesson 14). Leases stop the thundering herd when a hot key expires. Polaris (Lesson 3) measures how often the cache disagrees with the database. The same rule applies here: never cache seat availability for long. Cache what is static, and read what is contended from the source of truth (dealing with contention, scaling reads).
2. Delivering a feed in under 500 ms (a photo-sharing app). A follower-based feed must load quickly for hundreds of millions of daily users. The standard choices are:
- Fan-out on write. Precompute each user's feed into a cache or table when someone they follow posts, so a read is one lookup.
- Fan-out on read for accounts with huge follower counts, merged at read time, because writing a celebrity's post into 100 million feeds is too slow.
- Cache the hydrated posts and serve media from a CDN.
Meta's lessons show what sits behind this. TAO (Lesson 5) answers "who do I follow" and "what did they post" from cache in about a millisecond. News Feed's aggregator (Lesson 24) ranks a candidate inventory in passes on a predictor fleet. Akkio (Lesson 12) places a user's data in the region they use most, so the feed read stays local. With a 500 ms budget, a plausible split is 50 ms for network, 50 to 100 ms for inventory from caches, 150 to 200 ms for ranking, and the rest for hydration and rendering. See the Instagram case study and the news feed case study.
3. Serving redirects from the edge (a URL shortener). The great answer serves the short domain through a CDN with PoPs worldwide. Edges cache short-code to long-URL mappings and can run redirect logic as edge functions (Cloudflare Workers, AWS Lambda@Edge), so popular codes never reach the origin. The challenges are:
- Cache invalidation across every PoP, for edited or deleted links.
- Configuration. Edge functions need extra setup and knowledge of serverless runtimes.
- Cost at high traffic.
- Runtime limits on execution time, memory and libraries.
- Debugging and monitoring, which are harder when logic is spread across many edges.
You are trading cost and complexity for latency. Meta's edge story is Katran and the PoP fleet (Lesson 21), with request coalescing at edge and origin caches (Lesson 26). Coalescing is what stops a newly viral short code from stampeding the origin the moment its cache entry is cold (CDN, edge computing).
4. Posting comments on a live video. A viewer sends POST /comments/:liveVideoId with the text. A comment management service validates it and writes it to the comments database. A key-value store such as DynamoDB fits, because comments are simple records with no complex relationships or transactions, though Postgres or MySQL also work. The same service later serves comments to viewers. Meta's own live-video work (Lesson 26) concerns the video stream. Comments follow the same principles at Meta scale: TAO stores the comment objects and their association to the video, and fan-out to viewers uses the push and subscription infrastructure (live comments case study, realtime updates).
5. Showing comments posted before a viewer joined. A joining viewer needs live comments plus history, loaded as they scroll up ("infinite scroll"). The query is "give me the N most recent comments before this point", which needs pagination.
- Bad: offset pagination (?offset=0&pagesize=10). The database must step over every earlier row, so it slows as comments grow. Worse, it is unstable: if comments arrive or are deleted while the user scrolls, offsets shift and the user sees duplicates or gaps. On a fast live feed this happens constantly.
- Great: cursor pagination (?cursor=last_comment_id&pageSize=10). The cursor names the last item seen, and the query reads items strictly older than it, newest first, using an index on (video, comment ID). It is efficient at any depth, stable under inserts and deletes, and maps directly onto DynamoDB key-condition queries: partition key liveVideoId, sort key commentId less than the cursor, reverse order, limit page size. Each page still costs one query, which adds up at very high traffic, so recent pages are good candidates for caching.
Comment IDs that sort by time, such as Snowflake-style IDs, make the cursor and the order the same thing (unique ID generation, API design).
-- Cursor page in SQL (comment_id is time-ordered)
SELECT comment_id, author_id, body, created_at
FROM comments
WHERE live_video_id = $1
AND comment_id < $2 -- cursor: last comment the client has
ORDER BY comment_id DESC
LIMIT 20;
-- Index: (live_video_id, comment_id DESC)6. Uploading and serving large files (file sync and video).
-
Bad: store files on the application server. Disks fill, scaling means more servers, and one dead server loses files.
-
Good: store files in blob storage (Amazon S3, Google Cloud Storage), with metadata in a database. Blob storage scales almost without limit, survives server loss, and offers lifecycle rules and versioning. Two problems remain. The file and its metadata can get out of sync (file uploaded but metadata missing, or the reverse), so save metadata only on a confirmed upload. And the file is uploaded twice, client to backend, then backend to blob store.
-
Great: upload directly to blob storage with presigned URLs. In three steps:
- The client asks the backend for a presigned URL, a time-limited URL granting permission to write one specific object. The backend creates it with the storage SDK and records the metadata with status "uploading".
- The client uploads straight to the blob store.
- The blob store sends an event notification to the backend, which marks the file as uploaded.
This is faster and cheaper, because the bytes never touch the application servers (handling large blobs, object storage).
-
For playback, the bad answer is "download the whole video". The client fetches the full file from a URL before playing. A 10 GB file on a 100 Mbps link takes more than 13 minutes, and one network drop in a single HTTP request loses all progress. It is not streaming. The better answers download segments incrementally, and then use adaptive bit rate formats such as HLS or DASH, which is exactly the 3-second segment design in Lesson 26.
Meta's storage lessons sit under all of this. Haystack (Lesson 7) exists because storing billions of photos as files on ordinary filesystems wasted disk reads on metadata. Tectonic (Lesson 8) is Meta's blob layer. Owl (Lesson 22) handles the case where one huge file goes to many readers at once (video streaming case study, file sync case study).
Deep Dive: Sizing the six answersShow
Ticketing cache (handbook's illustration). A big on-sale has 2 million users refreshing an event page every 5 seconds, which is 400,000 reads per second. With a 99% cache hit rate, the database sees 4,000 per second, which one well-indexed Postgres primary with replicas can handle. A memcache-style lease means a cold key causes 1 database read, not 4,000. Search caching with a key per parameter set and a 24-hour TTL suits a catalogue that changes daily. Seat availability must bypass that cache.
Feed under 500 ms. 500 million daily users opening the feed 8 times a day is 4 billion reads a day, about 46,000 per second on average and perhaps 150,000 at peak. A precomputed feed of 500 post IDs at 8 bytes each is 4 KB per user, so 2 TB for 500 million users. That fits in a sharded Redis or memcache tier of about 40 nodes with 64 GB each, plus replicas.
Edge redirects. 100 million daily users clicking 5 links a day is 500 million redirects a day, about 6,000 per second, with peaks of 50,000. If the top 1% of codes take 80% of clicks and are cached at 300 PoPs, the origin sees about 20% of traffic, around 10,000 per second at peak. An edge function costs fractions of a cent per thousand calls, so at 15 billion a month the edge bill is in the thousands of dollars. Whether that is worth it depends on whether 50 to 100 ms of saved latency matters to the product.
Live comments. A popular stream with 1 million viewers, of whom 0.5% comment once a minute, gets about 83 comments per second. Writes are trivial. The hard part is delivering 83 comments per second to 1 million viewers, 83 million deliveries per second, which is why fan-out goes through a pub-sub layer with per-stream channels and sampling for very large streams.
Cursor versus offset. At comment 1,000,000 an offset query reads and discards a million index entries, perhaps 50 to 200 ms. A cursor query seeks directly to the position in the index, under 1 ms, regardless of depth.
Direct upload. 1 million uploads a day averaging 20 MB is 20 TB a day through the application tier if it proxies, about 230 MB per second on average and much more at peak, needing a fleet of servers just to copy bytes. With presigned URLs the application handles 1 million tiny API calls a day, about 12 per second, and the blob store carries the bytes.
When to Use It#
Study the Meta posts when:
- You are designing anything read-heavy and social. Lessons 1 to 6 cover look-aside caching with leases, routing, consistency measurement, a graph cache and atomic reads over it.
- You need storage that matches cost to access pattern. Lessons 7 to 9 show hot and warm blob tiers, a multi-tenant exabyte file system and LSM storage for flash.
- You need replication, consensus or placement beyond a single database. Lessons 10 to 13 cover Raft in MySQL, a managed key-value store, data placement by access locality, and a log whose consensus can be replaced live.
- You are building logs, queues or monitoring. Lessons 14 to 19 cover CDC pub-sub, a sequenced log store, high-throughput ingestion, a priority queue, a deferred-work platform and compressed time series.
- You run a fleet. Lessons 20 to 23 cover sharding as a platform, cluster management, an XDP load balancer, peer-to-peer content distribution and configuration as data.
- You are designing feeds, recommendations, live video, multi-device messaging or a launch. Lessons 24 to 28.
- You want to learn from failure, or you run AI infrastructure. Lessons 29 to 33.
When NOT to Use It#
- Do not build what Meta built. Each system answered a problem at billions of users. Redis, managed Kafka, S3, Kubernetes, a cloud load balancer and a managed vector index cover almost every need below that scale.
- Do not adopt eventual consistency where users notice. TAO's design is right for likes and wrong for payments or inventory. Use transactions where an anomaly costs money or trust.
- Do not copy a two-day launch culture without the platform. Threads worked because a decade of multi-tenant infrastructure already existed. Without it, a two-day notice is a recipe for an outage.
- Do not take post numbers as current. Many posts are years old (memcache in 2013, Katran in 2018, Chef in 2014). Treat numbers as of their dates.
- Do not copy AI cluster designs before you have one big job. Maintenance trains, topology-aware scheduling and custom collectives matter at thousands of GPUs. A few nodes need a managed training service.
How to Implement It#
Apply the lessons in this order for a social product growing from one region.
- Put a look-aside cache with leases in front of the database (Lesson 1). Use delete-on-write invalidation driven by the commit log (Lesson 14), and measure staleness (Lesson 3).
- Model social data as objects and associations and cache them by graph shape (Lesson 5). Keep transactions for the few places that need them.
- Store media in a blob store with presigned uploads, a CDN in front, and tiering by age (Lessons 7 and 8).
- Use an LSM engine for write-heavy tables (Lesson 9), and consensus-based replication for the primary (Lesson 10).
- Defer non-urgent work to a queue with rate limits (Lessons 17 and 18). Make every job idempotent.
- Collect metrics in a compressed time-series store, with recent data in memory (Lesson 19).
- Shard with an explicit map of many small logical shards (Lessons 11 and 28), so you can reshard online.
- Negotiate maintenance with stateful services before restarting hosts (Lessons 20 and 33).
- Rank with a funnel: cheap retrieval, a light ranker and a heavy ranker, then rules (Lessons 24 and 25).
- Coalesce requests at every cache tier for live or viral content (Lesson 26).
- Test your safety mechanisms: drills, staged network and config changes, guards against correlated health checks, and out-of-band access (Lessons 29 and 30).
A configuration sketch combining Lessons 1, 17 and 20 (handbook's illustration):
cache:
engine: memcached
routing: mcrouter
pools:
- name: feed_objects
replicas_per_region: 1
leases:
token_ttl_ms: 10000
min_retry_interval_ms: 10
invalidation:
source: mysql_binlog # commit-log driven deletes
delivery: at_least_once
consistency_monitor:
sample_rate: 0.001 # Polaris-style probe
deferred_jobs:
queue: priority_queue_on_sharded_mysql
lease_seconds: 60
rate_limit_per_downstream:
social_graph_writes: 50000
retries: { max: 5, backoff: exponential_jitter }
shards:
logical_shards: 65536
per_server_target: 200
replicas: 3
fault_domain: building
maintenance_min_healthy: majorityTechnology choices.
| Need | Meta choice | Alternatives | When each fits |
|---|---|---|---|
| Look-aside cache | memcache with mcrouter | Redis, ElastiCache, Twemproxy, Envoy Redis proxy | Redis for data structures; memcached for pure key-value at high throughput |
| Cache engine library | CacheLib | Caffeine, Ehcache, embedded RocksDB | Caffeine for JVM in-process caches |
| Graph store | TAO over MySQL | Neo4j, a relational adjacency table with a cache, Amazon Neptune | Adjacency tables plus cache for most social apps |
| Hot and warm blobs | Haystack, f4 | S3 with Intelligent-Tiering, GCS storage classes | Cloud tiers unless you hold exabytes |
| File system | Tectonic | HDFS, Ceph, cloud object storage | Object storage first; Ceph on premises |
| Storage engine | RocksDB, MyRocks | InnoDB, WiredTiger, Pebble | InnoDB for read-heavy; RocksDB for write-heavy and flash |
| Consensus replication | MySQL Raft | MySQL Group Replication, Vitess with semi-sync, CockroachDB | Managed databases with automatic failover |
| Key-value store | ZippyDB | DynamoDB, TiKV, FoundationDB | DynamoDB to avoid operations |
| Change data capture | Wormhole | Debezium with Kafka | Debezium for most teams |
| Log store | LogDevice | Kafka, Pulsar, BookKeeper | Kafka for most; Pulsar for tiered storage and many topics |
| Priority queue | FOQS | SQS with priority queues, Redis sorted sets, a database table with leases | SQS when priorities are few |
| Deferred functions | Async (XFaaS) | AWS Lambda with SQS, Temporal, Celery | Lambda plus SQS on AWS; Temporal for workflows |
| Time series | Gorilla, Beringei | Prometheus, VictoriaMetrics, InfluxDB, M3 | Prometheus-compatible stores |
| Sharding platform | Shard Manager | Apache Helix, Vitess, Kubernetes operators | Helix for custom stateful services |
| Cluster manager | Twine | Kubernetes, Nomad | Kubernetes |
| L4 load balancer | Katran | Cloud NLB, IPVS, Cilium, Google Maglev design | Cloud load balancers; Cilium on Kubernetes |
| Content distribution | Owl | BitTorrent-based tools, Dragonfly, Kraken (Uber's P2P registry) | A container registry with P2P for large fleets |
| Server configuration | Chef with data-driven cookbooks | Ansible, Puppet, Salt, Nix | Ansible for small fleets; immutable images where possible |
| ANN retrieval | FAISS-based services | HNSW libraries, Milvus, pgvector, managed vector databases | pgvector for millions of items; dedicated engines for billions |
| AI training fabric | RoCE and InfiniBand | Cloud GPU clusters with EFA or InfiniBand | Managed clusters below thousands of GPUs |
Trade-offs#
| Choice Meta made | What it bought | What it cost |
|---|---|---|
| Look-aside cache with delete invalidation | Simple, fast, huge read scale | Staleness windows, herd risk, needed leases and Polaris |
| TAO's eventual consistency | Millisecond graph reads globally | Read anomalies, later fixed only partly by RAMP-TAO |
| Tiered blob storage | Large savings on warm and cold data | Several systems to run, migration between tiers |
| LSM storage on flash | About half the space, less write wear | Read and compaction complexity, tuning |
| Raft inside MySQL | Faster, safer failover | Years of engineering on a core system |
| Explicit shard maps | Constraints, online resharding, gradual moves | A central scheduler and solver to run |
| Log-centric pipelines | Replay, decoupling, many consumers | Ordering and retention to manage, extra latency |
| Scribe's accepted loss | Throughput and simplicity | Rare data gaps for analytics |
| XDP load balancing on backends | Line rate in software, many instances | DSR only, MTU limits, shared fate with hosts |
| Central trackers for Owl | Better speed, hit rate and visibility | A critical metadata service per region |
| Ranking funnels | Heavy models within latency | Recall loss at early stages, many parameters |
| Client fanout for E2E encryption | No phone dependency, server never sees plaintext | More uploads, harder state sync |
| Shared multi-tenant platforms | Fast launches like Threads | Shared fate and global blast radius |
| Strong physical and logical security | Protection from attackers | Slower recovery in the 2021 outage |
| Maintenance trains for AI capacity | Guaranteed capacity with continuous upgrades | Permanent buffer, temporary version mix |
Common Pitfalls#
- Deleting cache keys on errors. A failed read is not an invalid value. The 2010 outage came from this exact rule.
- Caching without herd protection. A hot key expiring under 100,000 readers needs leases or coalescing, or the database falls over.
- Using offset pagination on live, growing lists. It slows with depth and shows duplicates and gaps. Use cursors.
- Proxying uploads through application servers. Use presigned URLs to the blob store.
- Health checks that all fail together. A rule that is safe for one site can withdraw every site at once when they share a dependency.
- Recovery tools that depend on production. Keep out-of-band access, chat and runbooks off the systems they help repair.
- Restarting everything at once. Ramp by region and watch caches, databases and power.
- Moving big shards. Keep shards small (hundreds per server) so moves are quick and balance is fine-grained.
- Ignoring user-item features until it is too late, or using them too early. Put them in the heavy stage only, so earlier stages stay cacheable.
- Treating maintenance as rare. At scale it is constant. Size buffers and domains for it.
- Upgrading AI clusters in one big window. Roll lower-level components gradually and keep the job's own stack consistent.
Real-World Examples#
- Twitter, Pinterest and Snap all run large memcached or Redis fleets with proxies similar to mcrouter, such as Twemproxy, created at Twitter.
- LinkedIn built Kafka and Espresso, which play roles similar to LogDevice and ZippyDB.
- Google's Maglev (NSDI 2016) is the hashing design behind Katran, and Google's Borg (Verma et al., "Large-scale cluster management at Google with Borg", EuroSys 2015) is the closest relative of Twine.
- Apache Helix, from LinkedIn, is the open-source sharding framework the Shard Manager post compares itself to.
- Uber's Kraken (an open-source P2P Docker registry, not Meta's Kraken load-testing system) and Alibaba's Dragonfly solve the same hot-content problem as Owl.
- Signal uses the protocol whose Sender Keys and pairwise sessions WhatsApp multi-device builds on.
- Netflix, Discord, Uber and Cloudflare appear in this handbook's other blog pages, with their own caching, storage and outage lessons. See Netflix engineering, Discord engineering, Uber engineering and Cloudflare engineering.
In the Interview#
Deep Dive: designing a small social app with Meta's lessonsShow
Requirements (handbook's illustration). 2 million daily users in one region, each opening the app 10 times a day and posting a photo every few days. 300,000 photos a day at 2 MB each. Likes and comments at 50 per second average, 500 at peak.
Reads. 20 million feed opens a day is about 230 per second, perhaps 1,000 at peak. Each open reads about 30 objects. With a Redis or memcached cache at 95% hit rate, the database sees about 1,500 reads per second at peak, which one Postgres primary with two read replicas handles. Use a lease or a per-key lock on fill to avoid stampedes when a popular post's key expires.
Graph. Store follows and likes as rows in Postgres: (user_id, type, target_id, created_at) with indexes on both directions. A few hundred million rows fit on one server. Cache adjacency lists for active users. No TAO is needed.
Media. 300,000 photos a day at 2 MB is 600 GB a day, about 220 TB a year. Upload with presigned URLs to S3 or GCS, make thumbnails asynchronously in a queue, and serve through a CDN. Move originals older than 90 days to an infrequent-access class, the cloud version of the Haystack and f4 split.
Feed. Fan-out on write into a per-user Redis list of 500 post IDs, with fan-out on read for the few accounts with more than 100,000 followers. Rank the top 200 with a light model or simple scoring by recency and affinity. No funnel of neural networks is needed yet.
Deferred work. Notifications, thumbnailing and counts go through a managed queue (SQS, Cloud Tasks) with retries and per-downstream rate limits.
Reliability. Never delete cache keys on database errors. Rate-limit repair jobs. Keep a status page and an admin path that do not depend on the main DNS name. Practise restoring from backups, and ramp traffic slowly after an outage.
What to say about trade-offs. This design uses rented infrastructure and Meta's ideas (leases, commit-log invalidation, presigned uploads, tiered storage, fan-out hybrids, rate-limited deferred work), not Meta's systems. Move to sharding, a graph cache or explicit shard maps only when a single primary or region stops being enough.
Key Takeaways#
- A cache needs a protocol. Leases, commit-log invalidation and consistency measurement made memcache safe at billions of requests per second.
- Model the product's data shape. TAO's objects and associations turned social reads into cacheable graph queries.
- Put each byte where its access pattern says. Haystack, f4, Tectonic, MyRocks and Gorilla each cut cost by matching storage to temperature.
- The log is the truth. Wormhole, LogDevice, Delos and MySQL Raft all treat an ordered log as the source and everything else as views.
- Shard explicitly and make it a platform. Many small shards and a central map enable constraints, online resharding and safe maintenance.
- Move heavy work off the request path, and throttle it. Async and FOQS absorbed Threads' surge without hurting the graph store.
- Rank with funnels and cache what you can. Two-tower retrieval and distilled first stages let heavy models run where they matter.
- Safety mechanisms are risky code. The 2010 and 2021 outages both came from protections that misfired. Test them and guard against correlated triggers.
- AI inverts the web fleet's assumptions. One synchronous job means every failure counts, so checkpoints, topology, spares and maintenance trains decide throughput.
- Shared platforms make launches easy and failures wide. That is the core trade-off of Meta's infrastructure.