Summary#
Uber matches millions of riders, eaters and couriers with drivers in real time, in thousands of cities. Every trip is a location problem (where is everyone, and how long will it take to get there), a consistency problem (one driver must not be given two trips, one rider must not be charged twice) and a data problem (every GPS ping, price and payment must be stored, analyzed and fed back into models). Uber's engineering blog covers all three, from the early days of a Node.js dispatch service to platforms that serve tens of millions of reads per second.
This page studies 31 posts in six families: geography and the marketplace (H3, Ringpop, the routing engine, DeepETA, the fulfillment re-architecture on Spanner), service architecture (domain-oriented microservices), storage (Schemaless in four parts, Postgres to MySQL, CacheFront at 40 million reads per second, Cassandra operations, Herb replication), the data platform (the big data platform, Hudi, Pinot, uReplicator, reprocessing with dead-letter queues, M3 metrics), reliability and real-time (distributed tracing, the push platform and its gRPC successor, QALM, Cinnamon and its auto-tuner), and machine learning and product (Michelangelo, Ludwig, the experimentation platform, Eats query understanding, the payments platform).
Why It Exists#
A ride-hailing design in an interview usually has a location service, a matching service and a trips table. Uber's posts show what that hides:
- Location data is enormous and always moving. Drivers send GPS updates every few seconds. Pricing, dispatch and analytics all need to group those points into areas, so the choice of grid affects every downstream system.
- The marketplace is local but the company is global. Supply and demand are balanced per neighborhood, while trips, payments and accounts must be consistent across regions and data centres.
- Writes are append-heavy and must never be lost. Trip records, payments and audit trails are immutable facts. Uber built its own datastore, Schemaless, around that idea.
- Thousands of services, thousands of engineers. By the late 2010s Uber ran a few thousand microservices. Ownership, dependency and failure isolation became problems in their own right.
- Overload is normal. New Year's Eve, concerts and storms create sudden peaks. Load shedding and prioritization had to be built into every service.
- Data drives every decision. Surge pricing, ETAs, fraud checks, Eats search and experiments all depend on data pipelines with minutes or seconds of freshness.
The textbook pages (geospatial indexing, ride-hailing case study, failure detection and gossip, Kafka) explain each idea alone. Uber's posts show the same ideas at the scale of a global marketplace, with the costs that came with them.
For each post the page asks:
- Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
- Production architecture. What did Uber actually build?
- Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
- Sacrifice. What did Uber give up to get the benefit?
How It Works#
The diagram shows where each family sits on the path of a trip. A rider's app talks to Uber through edge gateways and a push channel. Location updates are bucketed into H3 cells and feed supply and demand for pricing and matching. The fulfillment platform assigns a driver and stores the trip transactionally. Trips, payments and events land in storage (Schemaless, Docstore, MySQL, Cassandra) and stream through Kafka into the data platform (Hudi, Pinot, Hive, Presto), where ML models are trained and served. Reliability systems such as tracing, M3 and load shedders wrap everything.
The lessons follow the six families in order. Each covers one post, or a few closely linked posts, and ends with what the design gave up.
Family 1: Geography and the marketplace
Lesson 1: H3, a hexagonal hierarchical spatial index (2018)#
Assumptions. Millions of marketplace events happen every day, each at a point on Earth: a ride request, a driver accepting, a food order. Pricing, dispatch and analysis need to reason about areas, not exact points, because analysis at single-point precision is expensive and noisy. The authors assumed:
- Areas must be comparable across cities. A cell in São Paulo and a cell in Seattle should have similar size and shape so models trained in one place mean something in another.
- People move. Riders and drivers cross area boundaries constantly, so the bucketing should introduce as little error as possible when someone moves.
- Hierarchy is needed. Some decisions are made at city level, others at block level, and moving between them should be cheap.
Why not postal codes or hand-drawn zones. Postal code areas have irregular sizes and shapes and change for reasons unrelated to ride demand. Zones drawn by operations teams need constant updating and have arbitrary edges. A grid has comparable cells everywhere and does not change on its own. Grids do not follow streets, but neighborhoods can be represented as clusters of cells chosen by an objective function, and checking whether a point is in a cluster is just a set lookup on its cell ID.
The design. A global grid needs a map projection (from the 3D Earth to 2D planes) and a grid laid over it.
- Why not Mercator and squares. Mercator distorts size badly toward the poles, so cell areas would vary hugely. Squares have two kinds of neighbours: four sharing an edge and four sharing only a corner, at different distances. Analysis such as smoothing then needs separate coefficients for each kind.
- Icosahedron projection. H3 projects the sphere onto an icosahedron, a 20-faced solid, using a gnomonic projection centred on each face (one where great circles become straight lines). It lays the grid directly on the 20 faces rather than unfolding them, making a geodesic discrete global grid.
- Hexagons. A hexagon has one distance from its centre to all six neighbours' centres, versus two distances for squares and three for triangles. That makes gradients, smoothing and "nearby" calculations uniform. Hexagons also minimize quantization error for moving objects.
- 122 base cells and 12 pentagons. H3 starts with 122 base cells, about ten per face, some spanning faces. A sphere cannot be tiled with hexagons alone, so there are exactly 12 pentagons, one at each icosahedron vertex. The icosahedron is oriented like R. Buckminster Fuller's Dymaxion map, which places all twelve vertices in the ocean, so pentagons rarely appear where people are.
- 16 resolutions. Resolutions run from 0 (coarsest) to 15 (finest). Each finer resolution has cells about one seventh the area of the parent. Seven hexagons do not exactly tile a larger hexagon, so children are only approximately inside their parent; this mismatch is called aperture-7 subdivision with a slight rotation between levels.
- 64-bit IDs that truncate. A cell ID is a 64-bit integer encoding the base cell and one digit per resolution level. Truncating the ID gives the ancestor at a coarser resolution, a cheap bit operation. Truncation introduces a fixed shape distortion because children are approximately contained, but indexing a point at a chosen resolution is exact.
The API. geoToH3 turns latitude, longitude and resolution into a 64-bit cell; h3ToGeo and h3ToGeoBoundary return a cell's centre and outline. kRing returns all cells within grid distance k, which approximates a circle: k = 1 gives 7 cells, k = 2 gives 19. compact replaces complete groups of children with their parent: an area of 10,633 resolution-6 cells compacted to 901 cells of mixed resolution. Directed edges encode movement from one cell to a neighbour, also as 64-bit integers. The library is written in C with bindings in many languages, and Uber open-sourced it in 2018. Uber uses H3 for surge pricing (supply and demand per hexagon), dispatch and analysis, and the post notes that hexagon sets also approximate radius search in systems such as Elasticsearch.
Overlooked constraints.
- Pentagons exist. Code that assumes six neighbours breaks at the 12 pentagons. Placing them in the ocean reduces the problem but does not remove it.
- Parent-child containment is approximate. Rolling up counts from children to parents by truncation is fast but not exact at the edges, so area-precise statistics need care.
- Resolution choice is a modelling decision. Too coarse and you average away real differences between blocks; too fine and most cells have zero events, making estimates noisy.
What Uber sacrificed. Alignment with the real world: hexagons ignore streets, rivers and neighborhoods, so analysts must cluster cells to recover meaningful zones. Exact hierarchy, in exchange for equal-distance neighbours. And a simple flat map, in exchange for an icosahedron projection that is harder to reason about than latitude and longitude.
Deep Dive: H3 resolutions, ring sizes and the cost of surge cellsShow
Cell sizes. Resolution 0 cells average about 4.4 million km². Each step divides area by about 7, so resolution r has about 4.4 million ÷ 7^r km². That gives roughly 5 km² at resolution 7, 0.74 km² at resolution 8, about 0.1 km² at resolution 9, and about 0.9 m² at resolution 15. The number of cells at resolution r is 2 + 120 × 7^r: 122 at resolution 0 and about 569 trillion at resolution 15.
Ring sizes. A k-ring contains 1 + 3k(k + 1) cells: 1, 7, 19, 37, 61 for k = 0 to 4. A resolution-9 hexagon has an edge of about 0.17 km, so a k = 4 ring covers a radius of roughly 4 × 0.3 km ≈ 1.2 km. Finding drivers within about a kilometre therefore becomes "look up drivers in these 61 cell IDs", a set of key lookups instead of a geometric query.
Surge math (handbook's illustration). A city of 1,500 km² at resolution 8 has about 2,000 cells. If pricing recomputes supply and demand every minute, that is 2,000 small aggregations per minute per city, trivial work. At resolution 9, 14,000 cells, each with far fewer events. If a cell averages 2 requests per minute, the Poisson noise is about √2 ≈ 1.4 requests, a 70% relative error, so raw cells are too noisy. Smoothing over a k = 1 ring (7 cells, about 14 requests) cuts relative noise to about 27%. Hexagons make that smoothing uniform because all six neighbours are equally far.
Compaction. The post's example reduces 10,633 cells to 901, about 12 times fewer IDs. A geofence for a large airport or city zone stored compacted takes a few KB instead of tens of KB, and checking membership means truncating a point's cell ID to each stored resolution and doing a hash lookup, at most 16 lookups.
Lesson 2: Ringpop, gossip and consistent hashing inside the application (2016)#
Assumptions. Uber was running many millions of trips a day on six continents and growing fast. The first user of Ringpop was Geospatial, the first layer of matching, which tracks the live location of every online driver and searches those locations when a rider opens the app. The authors assumed:
- The state is ephemeral. Driver locations change every few seconds and are worthless a minute later, so writing them to a database would be wasted work. The state should live in the memory of the workers.
- Capacity changes all the time. Nodes are added for growth and lost to failures. Work must move automatically, without code changes or manual reassignment.
- Clients should not know the sharding. Callers should be able to hit any instance and still reach the owner of their data.
The previous system held all active vehicles in memory and scanned every car for every request, even cars on the other side of the city. It worked until growth made the scan too slow.
The three parts of Ringpop. Ringpop is a Node.js library embedded in the application. It turns a set of independent workers into a cooperating cluster.
- Membership with SWIM. SWIM ("Scalable Weakly-consistent Infection-style Process Group Membership Protocol", Das, Gupta and Motivala, 2002) is a gossip protocol. Each node periodically pings a random peer. If there is no reply, it asks a few other peers to ping that node indirectly, which avoids declaring a node dead because of one bad network link. Suspected nodes are marked "suspect" before "faulty", giving them time to refute. Membership changes piggyback on the ping messages and spread like an infection, so every node learns about every other within a few rounds. Ringpop's variant gossips over TCP, computes checksums of the membership list and the ring so nodes can detect disagreement quickly, and keeps down members in its list rather than forgetting them.
- Consistent hashing. Keys hash onto a ring with FarmHash. Each node owns the intervals before its points on the ring, and each node gets the same number of replica points (virtual nodes) to spread load evenly. The ring is stored in a red-black tree so finding the owner of a key is a logarithmic lookup. When a node leaves, only the keys in its intervals move, to the next node on the ring. The post's analogy: when a manager quits, you move their team to the nearest manager instead of reshuffling the whole office.
- Handle or forward. Any node can receive any request. It hashes the shard key; if it owns the key it handles the request, otherwise it forwards it to the owner over TChannel, Uber's RPC transport, packing forwarded HTTP requests inside TChannel frames. Forwarding is invisible to the business logic and to clients.
Bootstrap is a list of hosts: the first node forms a cluster of one, the next finds it through the same list, they exchange membership and place themselves on the ring, and so on. There was no multicast discovery.
Where it was used. Beyond Geospatial, Uber teams used Ringpop for sharding, leader election, ordering or batching writes into a distributed database, request coalescing, work delegation, aggregation and caching. Its idea comes from Amazon's Dynamo ("Dynamo: Amazon's Highly Available Key-value Store", DeCandia et al., 2007), which partitions with consistent hashing and spreads membership by gossip, but Ringpop applies it at the application layer instead of in a database.
Overlooked constraints.
- Gossip converges eventually, not instantly. During convergence two nodes can disagree about who owns a key, so two owners may briefly serve it. That is acceptable for ephemeral location data, not for money.
- State moves with ownership. When a node dies, its in-memory state is gone. For Geospatial that is fine because drivers resend locations within seconds; for other uses the new owner must rebuild or reload state.
- Forwarding adds a hop. Random routing means most requests take an extra network hop to the owner. Client-side ring awareness would remove it but would bring back the coupling Ringpop was trying to avoid.
What Uber sacrificed. Strong consistency of ownership: a gossip ring gives "eventually one owner", not "exactly one owner at all times". Every embedding service also carries a full membership protocol in its process, and debugging a split-brain or flapping ring is harder than debugging a central coordinator such as ZooKeeper. Uber later moved many sharded services to other systems, but Ringpop's model of self-organizing, self-healing workers shaped later designs.
Deep Dive: how fast SWIM converges and how even the ring isShow
Detection time. In SWIM each node pings one random peer per protocol period T. The chance that a failed node is not picked by any of the other n − 1 nodes in one period is about (1 − 1 ÷ n)^(n − 1) ≈ 1 ÷ e ≈ 0.37 for large n. So the expected time until some node first pings the failed one is about T × e ÷ (e − 1) ≈ 1.58 T, independent of cluster size. With T = 200 ms, first detection takes about 300 ms on average, plus the suspicion timeout.
Dissemination. Gossip spreads like an epidemic: the number of informed nodes roughly doubles each round, so all n nodes know in about log₂ n rounds plus a small tail. For 1,000 nodes, about 10 to 15 rounds. At 200 ms per round, the whole cluster agrees in 2 to 3 seconds. Ringpop's checksums let nodes notice they disagree and resync full lists sooner.
Message load. Each node sends one ping per period plus occasional indirect pings, so load per node is constant, about 5 messages per second at T = 200 ms, unlike heartbeat-to-everyone schemes where each node sends n − 1 messages per period. At 1,000 nodes, all-to-all would be 5,000 messages per second per node.
Ring balance. With v virtual points per node, the load on a node is roughly the sum of v random interval lengths. The relative standard deviation of load is about 1 ÷ √v. With v = 100, about 10%; with v = 1,000, about 3%. A red-black tree with 100 nodes × 100 points = 10,000 entries finds an owner in about 14 comparisons.
Moved keys. Adding the 11th node to a 10-node ring moves about 1 ÷ 11 ≈ 9% of keys. With modulo hashing, about 10 ÷ 11 ≈ 91% of keys would move.
Lesson 3: The routing engine and ETAs (2015)#
Assumptions. The ETA is the first thing a rider sees when opening the app, and it is computed before every dispatch. So the routing engine must answer in single-digit milliseconds, with a p99 under 100 ms, at hundreds of thousands of requests per second, and it must reflect current traffic. Most queries are short (driver to rider), but full-trip ETAs matter for pricing and products such as uberPOOL and UberRUSH.
2011 to 2014: Goldeta. Early Uber combined open-source routing engines including OSRM (Open Source Routing Machine) and used them only for ETAs and for map matching, which snaps GPS points to roads to draw cars on the map; there was no in-app navigation yet. Goldeta was a model on top that adjusted the routing engines' estimates using historical Uber trips over similar routes and times. It beat any single engine, but had a cold-start problem: new cities had no history, so their ETAs were worse. Adding features to OSRM, which was not built for dispatch, was also slow.
Routing basics. A road network is a graph. In the node-based model, intersections are nodes and road segments are edges, with weights for distance or travel time; one-way streets, turn restrictions, turn costs and speed limits are encoded too. The edge-based model makes road segments the nodes and turns the edges, which represents turn costs naturally at the price of a larger graph. Dijkstra's algorithm finds shortest paths but is far too slow on a continental graph at Uber's query rate, so production engines preprocess the graph.
What Uber tried in 2014 for its own engine, Gurafu.
- Contraction hierarchies, made dynamic. OSRM uses contraction hierarchies (CH; Geisberger, Sanders, Schultes and Delling, 2008). CH ranks nodes by importance and adds "shortcut" edges that skip less important nodes, so a query only climbs up the hierarchy from both ends and meets in the middle, taking a few milliseconds. But building the contracted world graph took about 12 hours, so traffic could never be current. Keeping the node order fixed and only recomputing affected shortcuts cut a world update to about 10 minutes even with 10% of segments changing speed, still too stale. Dead end.
- Sharding by region. Smaller graphs contract faster, but each region would need its own server cluster, and a busy region could not borrow capacity from a quiet one. With limited servers, Uber rejected it.
- A* search. A* is Dijkstra guided by a heuristic such as straight-line distance to the goal, so it explores fewer nodes. It needs no preprocessing, so edge weights can change in real time, and it is fine for short pickup routes. But work grows quickly with route length: Presidio to the Mission in San Francisco took about 120 ms, several times slower than CH. ALT (A* with landmarks and the triangle inequality) did not speed it up enough. Long routes fell back to a contracted graph without live traffic.
2015: the answer. Uber needed preprocessing for speed and fast weight updates for traffic. The final design divides the graph into layers of small, relatively independent cells, so a traffic change only re-runs preprocessing for the cells it touches, in parallel. This is the idea behind customizable route planning (CRP; Delling, Goldberg, Pajor and Werneck, 2011), which separates a slow, metric-independent partitioning step from a fast, per-cell "customization" step. In April 2015 Uber launched the new engine globally, based on Gurafu plus Flux, its first historical traffic system built from GPS data sent by driver phones. Accuracy was checked with a tool reading Kafka logs in real time to compare each ETA with the actual time of arrival (ATA), with in-app bug reports and web tools to compare routes visually. Over a sample of more than 100,000 trips, the error distribution was taller and tighter than Goldeta's. The system handles hundreds of thousands of ETA requests per second at single-digit millisecond latency, and new products such as uberPOOL and UberEATS start from it.
Overlooked constraints.
- Freshness and speed fight each other. Every preprocessing scheme trades query speed for update cost. The right partition size is set by how often traffic changes, not by the graph alone.
- Load balancing beats locality. Regional sharding was rejected because of uneven load across regions, an infrastructure reason rather than an algorithmic one.
- Measure against reality. ETA accuracy must be checked against actual arrival, which requires streaming trip completion data back into an evaluation loop.
What Uber sacrificed. The simplicity and community of an open-source engine for an in-house one that it must maintain. Exactness of travel times, since cell-level customization uses aggregated speeds. And engineering time spent on two dead-end approaches before the cell-based design.
Deep Dive: why preprocessing turns seconds into millisecondsShow
Dijkstra cost (handbook's illustration). A road graph of a large metro area may have 5 million nodes and 12 million edges. Dijkstra with a binary heap costs about (V + E) log V operations in the worst case. For a 20 km route it may settle a million nodes, around 100 ms or more. A continent-scale graph of hundreds of millions of nodes makes long queries take seconds.
Contraction hierarchies. After preprocessing, a CH query settles only a few hundred to a few thousand nodes, because both searches only move "upward" in importance. That is 1,000 times less work, which is why queries take about a millisecond. The cost is moved to preprocessing: contracting every node and adding shortcuts, the 12 hours in the post for the world graph.
Cell-based customization. Split the graph into cells of about 1,000 to 10,000 nodes, in several levels. For each cell, precompute the shortest travel times between its boundary nodes. When traffic changes on 1% of edges, only cells containing those edges need recomputing, each a small Dijkstra on a few thousand nodes, run in parallel across cores. If a city has 5,000 cells and 300 are touched, at 10 ms each on 32 cores, an update takes about 0.1 seconds per level. Queries then run on the overlay of boundary nodes, a much smaller graph.
Why A* is fine for pickups. A pickup route of 2 km in a grid city has a search frontier of a few thousand nodes, so A* runs in a few ms. The search area grows roughly with the square of route length, so a 20 km route explores about 100 times more, which matches the 120 ms seen for longer cross-city routes.
Lesson 4: DeepETA, predicting arrival times with deep learning (2022)#
Assumptions. ETAs are used for fares, pickup estimates, matching and delivery planning. A routing engine sums segment travel times along the best path, but "the map is not the terrain": the graph is only a model, and the route the driver actually takes is unknown. So Uber predicts the residual, the difference between the routing engine's ETA and reality, with ML. For years this was a gradient-boosted tree ensemble, and Uber's Spark team contributed upstream changes to XGBoost so it could grow deeper, making it one of the largest XGBoost ensembles of its time. Eventually larger data and deeper trees became untenable. Deep learning scales to big data more easily with data-parallel SGD. Three requirements:
- Latency: an answer within a few milliseconds at most. This is Uber's highest-QPS model.
- Accuracy: mean absolute error (MAE) must improve significantly over XGBoost.
- Generality: one model for all business lines (rides and delivery) worldwide.
The hybrid design. The routing engine is the "physical model"; DeepETA is a post-processing model that adds a learned correction. Inputs include origin, destination, request time, real-time traffic and request type (delivery drop-off or ride pickup). Updating a post-processing model to absorb new data or business needs is easier than changing the routing engine.
Making it accurate. The team tried seven architectures: MLP, NODE, TabNet, sparsely gated mixture-of-experts, HyperNetworks, Transformer and linear Transformer. An encoder-decoder with self-attention won.
- Self-attention for tabular data. Each feature (origin, time of day, traffic) becomes one vector, like a word in a sentence. Self-attention computes a K × K matrix of pairwise interactions among the K features, so each feature's representation is a weighted mix of all others. There is no positional encoding, because feature order means nothing.
- Discretize and embed everything. Categorical features are embedded. Continuous features are bucketized and then embedded, which, counterintuitively, beat feeding raw values. A network given buckets does not spend parameters learning to partition the input. Quantile buckets beat equal-width ones, plausibly because they maximize entropy: each bucket holds the same share of data, so the bucket index carries the most information.
- Geospatial embeddings. Origin and destination are quantized into grids at several resolutions. Three ways to map cells to embeddings: exact indexing (one embedding per cell, most memory), feature hashing (hash cells into fewer bins; saves space but collisions lose accuracy), and multiple feature hashing (hash each cell with several independent hash functions into several tables). The last gave the best accuracy and latency with less memory than exact indexing, because the network can combine several buckets to undo a collision in any one of them.
Making it fast.
- Linear transformer. Standard attention is O(K²d) for K features of dimension d. A linear transformer uses a kernel trick to avoid the attention matrix and costs O(Kd²). With K = 40 and d = 8, that is 12,800 versus 2,560 operations, five times less. It wins whenever K is greater than d.
- More embeddings, fewer layers. The model has hundreds of millions of parameters, but they sit mostly in embedding tables. Each prediction touches only about 0.25% of them. The network itself is shallow. Looking up a location embedding is quantize plus hash, O(1), versus O(log N) for a tree or far more for learning the mapping with dense layers. It is a space-for-time trade: precompute partial answers in big tables during training.
Making it general.
- Bias adjustment decoder. A fully connected decoder plus a segment bias layer that adjusts predictions for delivery versus rides, long versus short, pickup versus drop-off, and mega-region. This beat adding segment features, and was chosen over a multi-task decoder for latency. ReLU on the output keeps ETAs positive, and clamping limits extreme values.
- Asymmetric Huber loss. One loss with two knobs. Delta moves smoothly between squared error and absolute error, so outliers can be down-weighted. Omega sets the relative cost of predicting too low versus too high, for cases where being late is worse than being early. Different consumers can get a mean, a robust mean or a quantile from the same model family.
Training and serving. The model is trained and deployed with Canvas on Michelangelo, Uber's ML platform (covered later on this page). Requests reach uRoute, the front end for all routing lookups, which asks the routing engine for a route line and ETA, then calls the Michelangelo online prediction service for the DeepETA correction. Periodic retraining workflows retrain and validate the model. DeepETA went to production for global four-wheel ETAs, improving metrics immediately. Continuous, incremental training on fresher data was listed as future work.
Overlooked constraints.
- The highest-QPS model sets its own architecture. Accuracy research was bounded by a millisecond budget, which ruled out the most accurate standard transformer and a multi-task decoder.
- Sparse parameters need memory, not compute. Hundreds of millions of embedding parameters must sit in RAM on every serving host, even though each request touches 0.25% of them.
- One model for every segment risks average behaviour. Bias layers and a tunable loss are what let one global model serve both deliveries and rides.
What Uber sacrificed. The interpretability of trees for a neural network whose interactions are harder to explain. Memory per serving host for speed. And a single universal loss: different consumers now ask for different point estimates, which must be managed as configuration.
Deep Dive: attention cost, hashing collisions and what the residual buysShow
Attention arithmetic. For K = 40 features and d = 8, standard attention computes 40 × 40 = 1,600 dot products of length 8 (12,800 multiply-adds) per head. The linear form computes a d × d summary (64 entries) from K vectors and applies it to each, about K × d² = 2,560. With several heads and layers, the saving per request is tens of thousands of operations, small for a GPU but meaningful on CPUs at hundreds of thousands of requests per second.
Multiple hashing (handbook's illustration). Suppose a fine grid has 100 million cells but the table has 1 million bins. With one hash, two busy cells collide with probability about 1 in 1 million per pair, but with millions of active cells, many collide somewhere. With two independent hashes into two tables, a cell's pair of bins is shared with another specific cell only if both hashes collide, about 1 in 10^12. The network sees the sum or concatenation of both embeddings, so a collision in one table is corrected by the other.
Why predict the residual. If the routing engine's ETA has an MAE of 3 minutes and much of that error is systematic (rush hour, airport pickups, slow apartment entrances), a model learning only the residual starts from a strong baseline. It needs to learn corrections of a minute or two, a smaller and smoother target than learning travel time from scratch. It also degrades gracefully: if the model service fails, the routing ETA alone is still usable.
Cost of 0.25%. With 400 million parameters, 0.25% is 1 million parameters per prediction, about 4 MB of float32 reads from memory. At 100,000 predictions per second per cluster, that is 400 GB per second of memory traffic across the fleet, spread over many hosts. Shallow layers keep compute small; memory bandwidth is the real limit.
Lesson 5: Re-architecting the fulfillment platform on Spanner (2021)#
Assumptions. "Fulfillment" means capturing a consumer's intent (a ride, a meal, a package) and matching it with providers (drivers, couriers), then running the order until it finishes. In 2021 the platform handled more than a million concurrent users, billions of trips a year in over ten thousand cities, and billions of database transactions a day. Hundreds of microservices treat it as the source of truth for trips and driver sessions; its events feed hundreds of offline datasets; and 500+ developers have built 120+ distinct fulfillment flows on it. The 2014 design came from a smaller Uber with simpler flows. Since then there are reservations with a driver confirmed upfront, batched offers with several trips at once, airport virtual queues, the three-sided Eats marketplace and package delivery. The team spent two years rebuilding it, with 100+ engineers across 30+ teams.
The old design (2014 to 2020). Two entities. A Trip, owned by the rt-demand service, was a unit of work with at least two waypoints (a location plus tasks to do there: pickup, drop-off, optional "via" stops). A Supply, owned by rt-supply, was a driver's ongoing session with an ordered plan of waypoints across one or more trips. Three write patterns had to work:
- Concurrent read-modify-write on one entity, such as a driver going offline while matching links a new offer to them.
- Writes across entities: accepting an offer changes the trip, the supply and the supply's plan.
- All-or-nothing writes across many entities: accepting a batch offer with several trips.
How the old stack handled them, choosing availability over consistency:
- Pods for failure isolation: inside each of two regions, several pods held the core fulfillment services, and each city was assigned to one pod.
- Marketplace Storage Gateway (MSG): a key-value API over Cassandra. Each write went to two separate Cassandra clusters in the region, each with three replicas, with asynchronous cross-region replication.
- Ringpop for locking: each key had one owning worker (Lesson 2). A single-threaded Node.js process with a serial queue and an in-memory lock serialized read-modify-writes, but forwarding was best-effort.
- Caches: an in-process cache served most reads, with Redis as a fallback when MSG failed.
- Timers and post-commit work: the sevnup framework handed ownership of timers (offer expiry) and pending side effects to a new node when the ring changed.
- Sagas for multi-entity writes: a coordinator sent "propose" to every entity, then "commit" if all agreed, or "cancel" to run compensations.
- Secondary indexes as separate Cassandra tables. A new trip was written first to the rider-to-trips table, then to the trip table, then a best-effort cache invalidation went to the rider's owning worker.
Why it had to change.
- Consistency was best-effort. Without atomic multi-step writes, failures needed reconciliation. During deploys and region failovers, split-brain could let two owners write the same key, and Cassandra's last-write-wins silently dropped one.
- Sagas were hard to debug. Between steps the system was visibly inconsistent, and failures spanning entities and services were hard to trace.
- Ringpop had a ceiling. A pod's size was bounded by the largest workable peer-to-peer ring, so a city with too many concurrent trips could not grow past one pod.
- Old tools. By 2018 Node.js and the HTTP/JSON framework were deprecated internally, so new engineers had to learn a legacy language and protocol.
- Cache incoherence across in-process buffers, Redis and two Cassandra clusters.
- No extension model, after 400+ engineers had changed the core.
Requirements and the database choice. After six months of auditing every product and collecting 200+ pages of requirements: 99.99% availability despite a region, zone or intermittent failure; strong consistency for single-row, multi-row and multi-table transactions across regions; no data loss; secondary indexes, CDC and ACID; latency the same or better; horizontal elasticity; and low operational effort (no-downtime schema changes, automatic sharding). Three options were weighed:
- Improve the NoSQL stack: Apache Helix plus ZooKeeper for central shard management instead of Ringpop, a serial queue or central lock per entity, and Sagas kept for cross-shard work.
- Sharded in-house MySQL, which needed new tooling for sharding, schema upgrades, cross-region replication, promoting replicas and consistency during failover.
- NewSQL: transactions plus horizontal scale, on-prem (CockroachDB, FoundationDB) or managed (Google Cloud Spanner).
Uber chose NewSQL, with no prior use in the company, and after benchmarking picked Google Cloud Spanner in the North America multi-region configuration nam3. The fulfillment services stay in Uber's own regions and make network calls to Spanner in Google Cloud for every transaction. Features relied on:
- External consistency, the strictest guarantee: if transaction T1 commits before T2 starts, every reader sees T1 before T2, as if there were one global clock (Spanner's TrueTime; Corbett et al., "Spanner: Google's Globally-Distributed Database", 2012).
- Server-side buffering of DML, so one module's update is visible to later modules inside the same transaction.
- Range sharding by primary key, which scales if keys avoid hotspots.
- Cross-row, cross-table, cross-shard transactions, with lock tracking, contention aborts and deadlock avoidance.
- Stale reads, at an exact timestamp or with bounded staleness, for reads that can be a little behind.
Post-commit work without CDC: LATE. Public Spanner did not then offer change data capture. So Uber built Latent Asynchronous Task Execution (LATE): every side effect and timer is written in the same transaction to a LATE action table, and LATE workers scan the table and execute each row at least once. This is the transactional outbox (see change data capture and the outbox), with timers as delayed rows.
The programming model.
- Statecharts. Each entity's lifecycle is a hierarchical state machine: states can have substates. A statechart has states (behaviour plus entry and exit actions), transitions and triggers (a user intent or a system event). When a trigger arrives, the active state runs the matching transition. Entities are defined in configuration, data is modelled in Protobuf, and a generic Java framework runs the machines. Each trigger is also an RPC, so apps, timers and pipelines invoke it the same way.
- Business transaction coordinator. A food order creates an order entity, a job for preparation and a job for delivery. The coordinator takes a directed acyclic graph of entity triggers and runs them all inside one read-write Spanner transaction, so consumers see a consistent view. Side effects (Kafka events, notifications) then run at least once through LATE.
- Query planner for reads at chosen consistency levels across related entities.
- ORM layer so product engineers do not hand-write transaction code.
How they shipped it. Hundreds of decisions needed a decision framework (who decides, along which dimensions, how risk is mitigated). Daily lead syncs and weekly all-team demos. Teams paused their own roadmaps to form one virtual team. Migration was designed upfront for hundreds of API callers, thousands of offline consumers and a million live sessions. They wrote end-to-end tests for 200+ product flows and back-tested them on the old stack, built a session-based shadow framework to compare old and new responses, and used test cities configured like real ones.
Overlooked constraints.
- A cross-cloud dependency for every transaction. Each write is several round trips from Uber's data centers to Google Cloud, so latency and the network link become part of the availability budget.
- Hotspots in range-sharded keys. Spanner scales only if keys spread out; sequential IDs or a hot city entity would concentrate load on one split.
- Side effects still need at-least-once handling. A strongly consistent database does not make Kafka or push notifications transactional, so every consumer of LATE output must be idempotent.
What Uber sacrificed. The old stack's local, sub-millisecond in-memory reads and its "always accept the write" availability, in exchange for correctness. Control over the storage engine, by depending on a managed product in another company's cloud. And roughly two years of a large team's product roadmap.
Deep Dive: Saga versus one transaction, in failures and latencyShow
What the Saga cost. Accepting a batch offer with 2 trips touched 3 entities. With a Saga, that is 3 propose calls, 3 commit calls and, on failure, up to 3 cancels, each an RPC to a different owner with its own storage write. If each RPC fails independently with probability 0.1% (handbook's illustration), the chance that some step of 6 fails is about 0.6%, and each such case leaves a partly applied state that a compensating path or a reconciler must fix. At millions of offers a day, that is thousands of repair cases daily.
What one transaction costs. Spanner commits with a Paxos round across replicas and, for multi-split transactions, two-phase commit between split leaders. In a multi-region configuration, the commit waits for a quorum of replicas across regions, often 10 to 30 ms, plus TrueTime's commit wait of a few milliseconds. A coordinated DAG of 3 triggers might take 5 to 10 round trips to Spanner. At 2 to 5 ms per round trip from Uber's regions, a trigger can take 30 to 80 ms (handbook's illustration). That is slower than an in-memory Ringpop update but removes the repair cases entirely.
Why statecharts help with transactions. A trigger is valid only from certain states. Because the coordinator reads the current state inside the transaction, two conflicting triggers (driver going offline versus being offered a trip) serialize: one commits, and the other aborts or re-runs and finds the new state, where its transition may no longer be legal. The old serial queue gave this only while Ringpop ownership was stable; Spanner's locks give it always.
LATE in numbers. If each transaction writes one LATE row and there are billions of transactions a day, about 20,000 to 50,000 rows per second must be scanned and executed. Workers can split the table by key range and use the row's due time as an index, so timers (offer expiry in 15 seconds) and immediate side effects share one mechanism.
Family 2: Service architecture
Lesson 6: Domain-oriented microservice architecture (DOMA) (2020)#
Assumptions. By 2020 Uber had about 2,200 critical microservices and thousands of engineers. Around 2012 to 2013 it had mostly two monoliths, and moved to microservices because one regression could take down all of Uber, deploys were risky and often rolled back, code boundaries had blurred during hypergrowth, and teams could not ship independently. Microservices fixed that: one service fails and is rolled back alone, each service must justify why it exists, ownership is clear, and teams deploy at their own pace. The post is clear that Uber could not have reached its scale without them.
The problem microservices created. The post's framing: a microservice is a library with a performance cost (network I/O plus serialization on every call), adopted for independent deployment and scaling. That trade is worth it with hundreds of engineers and a strong argument against adopting it early. At thousands of engineers, a monolith's code becomes many black boxes whose behaviour can change at any time:
- One incident investigation needed about 50 services across 12 teams.
- A latency spike deep in a call chain cascades upward, and without tracing nobody can see why.
- A simple feature needed changes in many services owned by different teams, so ownership blurred as teams edited each other's services, data models and even deploys. A simple integration in 2018 had 10 touch points.
- Networked monoliths formed: services that look independent but must be deployed together.
DOMA in four ideas. It treats the whole service fleet as one large distributed program and applies old code-organization ideas to it: domain-driven design (Eric Evans, "Domain-Driven Design", 2003), Clean Architecture (Robert C. Martin), service-oriented architecture and interface-oriented design.
- Domains: a collection of related services for one logical function, such as map search, fares or matching. Size is not fixed: one service or tens. They do not have to match the org chart; Uber Maps is three domains with 80 services behind three gateways.
- Layers: domains are grouped into layers, and a service may only depend on layers below it. Lower layers are more general and have a bigger blast radius (more dependents); higher layers are more product-specific and smaller in blast radius. Functionality is expected to move down over time as a feature becomes a platform; many core business platforms began as rider- or driver-only features before Eats and Freight needed them. Uber's five layers:
- Infrastructure: anything any company could use, such as storage and networking.
- Business: useful to all of Uber but not to one line of business (Rides, Eats, Freight).
- Product: specific to a line of business but not to one app, such as "request a ride" logic shared by the Rider app, the lite app and m.uber.com.
- Presentation: features of a particular consumer-facing app.
- Edge: safely exposes services to the outside world; this layer knows about mobile apps.
- Gateways: one entry point per domain that hides its services, tables and ETL pipelines and exposes only RPC APIs, events and queries. In object-oriented terms, the gateway is the interface and the services are the implementation.
- Extensions: a way for other teams to add logic or data to a domain without changing its code or hurting its reliability.
- Logic extensions are a provider or plugin pattern. For "driver goes online", the platform defines an interface (request type, response type). The safety, compliance and other teams each register an extension that returns whether the driver may go online; the endpoint runs them and rejects if any says no. Extensions are isolated from the core and from each other, and observability and feature flags can wrap them.
- Data extensions use Protobuf's Any type to attach arbitrary data to a request, so the core platform stores or forwards it to a logic extension without ever deserializing it. Any costs some infrastructure for strong typing; a JSON string is a simpler alternative.
- Custom extensions: some domains have their own, such as presentation integrations built on DAG-based task execution.
Results. 2,200 services were classified into 70 domains, about half implemented. Platform support costs often fell by an order of magnitude. One team cut the time to prioritize and integrate a new feature from three days to three hours using extensions. Onboarding a new feature onto a platform took 25 to 50% less time, because consumers call one gateway instead of many services. Uber measured the half-life of a microservice at 1.5 years: half of services are replaced every 18 months. Without gateways, every rewrite forces all callers to migrate. Two of Uber's largest platform rewrites in a year happened behind gateways, each with hundreds of dependent services that would otherwise have needed migrating.
Advice by company size.
- Startups: microservices may not be worth it yet, and they need dedicated platform engineers. If you adopt them, think of them as one distributed application and choose boundaries carefully, because the first services describe the core of the business and last longest.
- Midsize: start thinking about hierarchy and dependency management as some services become critical. Invest early in product-agnostic platforms, and consider extensions to keep product logic out of them. A domain can be a single service.
- Large: DOMA pays off fully. Clusters of services become domains behind gateways, ready for the rewrites to come. Keep product logic out of platforms.
Evolving the architecture is like "trimming a hedge": steady nudges at the right time, not a single top-down rewrite. See microservices patterns, domain-driven design and API gateways.
// Logic extension for "driver goes online"; each team registers one
interface GoOnlineExtension {
name: string;
check(ctx: DriverContext): Promise<{ allowed: boolean; reason?: string }>;
}
async function goOnline(ctx: DriverContext, exts: GoOnlineExtension[]) {
const results = await Promise.all(exts.map(e => e.check(ctx)));
const denied = results.find(r => !r.allowed);
if (denied) return { online: false, reason: denied.reason };
return { online: true };
}Overlooked constraints.
- Layer rules need enforcement. "Only depend downward" decays unless a dependency checker or service registry rejects violations.
- Gateways can become bottlenecks of their own, in latency (one more hop) and in team process, if one team must approve every API change.
- Extensions run inside the platform's request path. A slow or failing extension can slow the core endpoint, so timeouts and isolation per extension matter.
What Uber sacrificed. Some freedom for teams to call any service directly. An extra network hop at each gateway. And the effort of a cross-company classification and design project, involving nearly 60 engineers over two years.
Deep Dive: why a 1.5-year half-life makes gateways pay offShow
Migration math (handbook's illustration). A platform of 20 services has 300 callers. Without a gateway, each caller depends on an average of 4 of those services. If half the platform's services are replaced every 1.5 years, each caller sees about 2 breaking replacements per 1.5 years. That is 600 caller migrations, and at 2 engineer-days each, 1,200 engineer-days every 18 months. With a gateway, the platform team absorbs the rewrite behind a stable API, perhaps 100 engineer-days of adapter work, and callers change nothing.
Blast radius by layer. If an infrastructure service has 1,000 transitive dependents and a presentation service has 5, the same 0.1% failure rate costs very different amounts of user impact. Layering puts the strictest reviews, the slowest rollouts and the highest availability targets where the dependents are, and lets product layers move fast.
Why "library with a performance cost" is the right lens. An in-process call costs nanoseconds; an RPC in the same data center costs about 0.5 to 2 ms with serialization. A request that fans out through 6 sequential service hops pays about 6 to 12 ms of pure overhead, plus each hop's tail latency. Grouping related services into a domain with one gateway does not remove internal hops, but it limits how many hops a caller must understand.
Family 3: Storage
Lesson 7: Schemaless, an append-only datastore on MySQL (2016)#
Assumptions. In early 2014 trip data was growing so fast that one Postgres instance would run out of space by the end of the year. Five requirements for its replacement:
- Linear scaling: add servers to add both disk and lower response times.
- Write availability: an earlier workaround buffered failed Postgres writes in Redis, but buffered trips could not be read, so billing could not see them, and the Redis buffer itself stopped scaling. The new store had to prefer accepting writes over read-your-writes.
- Change notification: billing, analytics and other steps ran together, so one failure meant retrying all of them. Uber wanted each step triggered by a data change, without the losses of its Kafka 0.7-based event system.
- Secondary indexes, to keep querying trips the way Postgres indexes allowed.
- Operational trust: at 3 am, does the team know how to fix it?
Uber compared Cassandra, Riak, MongoDB and others. All scaled linearly; only some accepted writes during failover; none had built-in change notification; their indexes used scatter-gather across nodes, slow with many indexes; and Uber lacked operational experience running them for user-facing traffic. The decisive factor was operational trust, so Uber built Schemaless, inspired by FriendFeed's schemaless MySQL design and by Pinterest's operational focus. (Uber later used Cassandra and Riak successfully elsewhere.) The trips migration off Postgres was called Project Mezzanine, and Schemaless has been in production since October 2014.
Data model: an append-only, sparse, three-dimensional hash map, similar to Google's Bigtable (Chang et al., "Bigtable: A Distributed Storage System for Structured Data", 2006). The smallest unit is a cell: an immutable JSON blob addressed by row key (a UUID), column name (a string) and ref key (an integer). To "update", you write a new cell with a higher ref key; the latest version is the highest ref key. Columns are not declared; each application decides its own. A trip in the Mezzanine instance has:
- BASE: driver, rider, times; written once when the trip ends.
- STATUS: one cell per billing attempt, since a card can be declined or expired.
- NOTES: notes from the rider, driver or operations staff, possibly days later.
- FARE ADJUSTMENT: written only if the fare changes, for example for an inefficient route.
Splitting by who writes and when avoids races (billing and notes never write the same cell) and keeps each write small.
Architecture.
- Worker nodes take HTTP requests, route them to storage nodes, merge results and run background jobs. Clients retry other workers on failure. Every write is idempotent, because a cell with the same row key, column and ref key is rejected, so retries are always safe.
- Storage nodes: data is split into a fixed 4,096 shards by row key, mapped to storage clusters of one master and two minions (replicas), with minions in other data centers. Reads default to the master (so you see your writes) but can choose a minion. Writes go to the master, which replicates to minions asynchronously, typically in under a second.
- Failure handling. Reads work while any node in the cluster is up, with circuit breakers to move off a struggling node. If a master is down, writes still succeed by persisting to another, randomly chosen master, similar to hinted handoff in Dynamo and Cassandra. Those writes are not readable until the master returns or a minion is promoted, and Schemaless tells the client so.
- Buffered writes. Asynchronous replication can lose a write if the master dies before replicating. So every write goes to a secondary master's buffer table first, then to the primary, and succeeds only if both do. A background job deletes the buffered copy once it appears on the primary's minions. Idempotency makes replay safe.
- Single master per shard gives a total order of writes per shard, identical on all replicas, which is what triggers depend on.
MySQL as the storage engine. Schemaless is a thin routing layer; each shard is a separate MySQL database with an entity table plus one table per secondary index:
CREATE TABLE entity (
added_id BIGINT AUTO_INCREMENT PRIMARY KEY, -- insertion order, log offset
row_key BINARY(16) NOT NULL, -- UUID
column_name VARCHAR(64) NOT NULL,
ref_key BIGINT NOT NULL, -- version
body MEDIUMBLOB NOT NULL, -- MessagePack, then zlib
created_at DATETIME NOT NULL,
UNIQUE KEY cell (row_key, column_name, ref_key)
);An auto-increment primary key makes InnoDB append rows in insertion order on disk and gives each cell an offset for triggers. The unique compound index finds cells by key and rejects duplicates. Bodies are MessagePack plus zlib, chosen for speed and size. (The DDL above is the handbook's sketch of the post's column list.)
Secondary indexes. An index is defined in YAML over fields of a column, for example a driver_partner_index on BASE with driver UUID, city and trip creation time, so you can find a driver's trips in a city within a time range. One field is the shard field (here the driver UUID), so an index query goes to one shard. A good shard field is well spread: UUIDs are best, city IDs are poor, and enums are harmful. Fields can be denormalized into the index so the query never needs a second lookup, trading storage for speed. The shard field must be immutable. Indexes are eventually consistent: the cell and its index entries usually live on different shards, and making them atomic would need two-phase commit, so the index is updated separately, typically within 20 ms.
Triggers: the datastore as a log. Because cells are never overwritten, each shard is an ordered log of changes keyed by added_id. The API has random access (put_cell, get_cell, get_cell_latest) and log access (get_cells_for_shard with a shard number, a location given as an added_id or a timestamp, and a limit, which returns the next location). A program declares a trigger on a column, such as bill_rider on BASE: when a trip's BASE cell is written, the function receives the row key, reads the latest STATUS, skips if is_completed is already set, otherwise charges the card and writes a new STATUS cell. The framework:
- Calls each function at least once per cell, so functions must be idempotent.
- Splits shards across worker processes, with one shard owned by exactly one process; a leader assigns shards and reassigns them if a process dies. Up to 4,096 workers per client.
- Stores each shard's last processed added_id in ZooKeeper or in Schemaless itself, also used for leader election and membership.
- Processes cells in order within a shard. A cell that keeps failing would stall its shard, so it can be marked and moved to a separate retry queue; if too many are marked, triggering stops for a human to fix a likely systematic bug.
- Keeps running during leader election or ZooKeeper loss (only rebalancing pauses), and reads from any replica, so a database node failure does not stop it.
Triggers drive the whole trip flow, from "End Trip" to billing, to warehouse ingestion and cross-data-center replication. It is the same idea as LinkedIn's Databus or today's CDC (see change data capture).
Overlooked constraints.
- Immutable cells mean storage only grows. Every billing retry and note adds a row; deletes happen only in special cases.
- Write availability costs read-your-writes. A write buffered on another master succeeds but is invisible until recovery, so callers must handle "accepted but not readable".
- Fixed shard count. 4,096 shards caps trigger parallelism and means a hot row key cannot be split.
What Uber sacrificed. A general-purpose query and update API (no in-place updates, no schema, no joins), consistency between cells and indexes, and immediate readability during master failures. It bought simple, trusted operations on MySQL and a built-in change log.
Deep Dive: buffered writes, shard counts and index lagShow
Durability with buffered writes. Suppose a master fails before replicating about once per year per cluster, and replication lag is 0.5 s. With 2,000 writes per second on that cluster, about 1,000 writes are unreplicated at the moment of failure. Without the secondary buffer, those are lost. With it, each also sits on a second host, so a loss requires both hosts to fail within the same half-second, roughly the probability of a single failure times a fraction of a second over a year, which is negligible (handbook's illustration).
Why 4,096 shards. A fixed, large shard count lets you start with a few clusters (each holding hundreds of shards) and split clusters by moving whole shards, never re-hashing keys. With 16 clusters, each holds 256 shards; with 256 clusters, 16 each. It also caps trigger parallelism at 4,096 workers, plenty for trips.
Index lag. Index writes happen right after the cell write, on another shard, typically within 20 ms. A reader who writes a trip and then immediately queries "my trips" may miss it for a few tens of milliseconds. Read the cell by row key for read-your-writes, and use the index for lists where a short delay is fine.
Log tailing cost. A trigger worker polling each of 256 shards with limit 100 every 100 ms issues 2,560 small range scans per second on added_id, cheap because the primary key is the scan order. Ten trigger clients multiply that by ten, which is why they read from minions.
Lesson 8: Docstore, evolving Schemaless into a distributed SQL database (2021)#
Assumptions. Schemaless was reliable, but its append-only cells and narrow API made it hard to use as a general database. Teams moved to Cassandra for flexibility, but at Uber's scale Cassandra lacked operational maturity and efficiency, and its eventual consistency forced developers to design around missing guarantees. So Uber evolved Schemaless into Docstore, a general-purpose transactional database. Docstore's operational platform serves tens of millions of queries per second at 99.99% or more availability and stores tens of petabytes.
Design: schema enforcement plus flexibility. Uber did not want "just another NoSQL". Tables enforce a schema on write by default (schema-on-write), but schemas evolve without table rebuilds, old and new record shapes coexist, and sparse and nested types are first-class. Features: transactions, materialized views, associations (one-to-many and many-to-many), change data capture, and one-click provisioning.
Architecture. An instance has three layers:
- A stateless query engine that routes requests.
- A storage engine of partitions. Each partition is a group of 3 to 5 nodes in different zones, and partitions are replicated to other geographic locations.
- A control plane that assigns shards (a few hundred gigabytes of rows each) to partitions and moves them after failures.
Tables and keys. Tables have rows, columns, user-defined nested types and a primary key of one or more columns. Keys are stored as byte arrays with an order-preserving encoding, and rows are sorted by primary key, so range scans work. Applications choose a partition key to control locality (otherwise the primary key is used), for example partition by rider so all of one rider's rows are together, then range-scan by the rest of the key. Materialized views re-partition a table by another column for different access patterns. This "flexible document model" covers both relational and hierarchical data.
Consistency via Raft. Each partition runs Raft (Ongaro and Ousterhout, "In Search of an Understandable Consensus Algorithm", 2014): one leader, followers, and a replicated log. A write commits only after consensus, so every node applies the same writes in the same order, and any later read of a key sees that write or a newer one. Docstore is strictly serializable per partition: transactions behave as if run one at a time in real-time order. In CAP terms it is a CP system (see CAP and PACELC).
Transactions on MySQL. MySQL is still the storage engine. The unit of replication is a MySQL transaction: the leader executes the operations in a MySQL transaction, MySQL's row locks serialize concurrent writers to the same rows, and the transaction is replicated through Raft before commit. Failover between replicas therefore keeps ACID. Docstore inherits MySQL's transaction behaviour, both its strengths and its limits.
Overlooked constraints.
- Strictness stops at the partition. Transactions are strictly serializable within one partition; data that must change together should share a partition key.
- A CP system loses writes for a partition during leader election. It is short, but callers must retry.
- Inherited MySQL limits. Lock waits, deadlocks and long transactions behave as in MySQL.
What Uber sacrificed. Schemaless's always-accept-writes behaviour, in exchange for consistency. Cross-partition transactions by default. And a large engineering investment in a home-grown database instead of adopting an external one.
Deep Dive: Raft quorums and the cost of a commitShow
Quorum sizes. With 3 nodes, a write needs 2 acknowledgements and survives 1 failure. With 5 nodes, it needs 3 and survives 2. The leader counts itself, so with 3 nodes it waits for the faster of 2 followers.
Latency (handbook's illustration). If zones in one region are 0.5 to 1 ms apart, a commit costs the MySQL execution (about 1 ms) plus one round trip to the faster follower (about 1 ms) plus an fsync (0.2 to 2 ms on SSD). Total about 2 to 4 ms. If the followers were in other regions 30 ms away, the commit would cost 30 ms or more, which is why the post keeps partition nodes in independent zones and treats geographic copies separately.
Throughput. One partition's writes all pass through one leader, so per-partition throughput is bounded by one MySQL primary, perhaps a few thousand transactions per second. Scaling comes from many partitions. A table with 50,000 writes per second at peak needs at least 20 to 30 partitions, more if keys are skewed.
Choosing the partition key. For a rider's orders, partition by rider ID: one rider's order and items commit in one partition, and "list my orders" is a range scan. "All orders for a restaurant" is then a materialized view partitioned by restaurant ID, refreshed asynchronously.
Lesson 9: Why Uber moved from Postgres to MySQL (2016)#
Assumptions. Early Uber was a monolithic Python backend on Postgres (version 9.2 in this analysis). By 2016 most data sat on Schemaless over MySQL, or Cassandra for special cases. The post lists five limits: inefficient writes, inefficient replication, table corruption, poor MVCC on replicas, and hard upgrades. All come from one root, how Postgres lays out rows and indexes on disk, compared with MySQL's InnoDB engine.
Postgres layout. Rows ("tuples") are immutable. Each tuple has a ctid, its physical location on disk. An update writes a new tuple with a new ctid and a link to the old one; old versions stay for MVCC (multiversion concurrency control, which lets each transaction see a consistent snapshot) until autovacuum removes them. Every index, primary and secondary, stores ctids. Consider a users table with a primary key on id and secondary indexes on (first, last) and birth_year. Changing al-Khwarizmi's birth year from 780 to 770 creates a new tuple, so all three indexes get a new entry for the new ctid, even though id and name did not change.
Consequences.
- Write amplification. One small logical update means 4 physical writes here (tuple plus 3 indexes), each also in the WAL. A table with 12 indexes updates all 12 when one indexed field changes.
- Replication amplification. Postgres streaming replication ships the WAL (write-ahead log), the crash-recovery log, which describes physical changes ("at this offset write these bytes"). A replica is in permanent crash recovery while serving reads. The replica is byte-for-byte identical to the master, so rsync can repair it, but every index change crosses the network. Uber replicated from a West Coast colocation site to an East Coast DR site; cascading replication limited cross-country traffic to one stream, but that stream was huge. WAL archiving to a storage web service also could not keep up at peak.
- Corruption that spreads. During a routine master promotion, a Postgres 9.2 bug made replicas follow timeline switches incorrectly and misapply WAL records, so some old row versions were not marked dead. A query by id returned two rows (780 and 770). Different replicas had different bad rows; it was unclear whether the master was affected. Because replication is physical, a bug like this could in principle corrupt B-tree pages during rebalancing. The fix was to re-sync every replica from a new master snapshot, a few at a time due to capacity.
- No true MVCC on replicas. Since replicas apply physical changes, a long read transaction on a replica that needs old row versions blocks WAL apply. Postgres pauses replication, then kills the query after a timeout. Replicas lag seconds, and code that holds a transaction open while sending an email (often hidden by an ORM) gets killed.
- Upgrades. Physical replication cannot span major versions. Upgrading meant: stop the master, run pg_upgrade for hours, restart, snapshot (hours), wipe and restore each replica, let them catch up. Uber did 9.1 to 9.2 once and could not afford 9.3, so legacy instances stayed on 9.2 while 9.5 was current. The pglogical extension (9.4+) offered logical replication but was not in mainline then.
InnoDB layout. Secondary indexes store the primary key, not a disk location. A lookup by name finds the id, then looks up the id in the clustered primary index. That is one extra lookup per secondary read, but:
- Updates happen in place when they fit, with old versions copied to the rollback segment (undo log) for MVCC.
- Only indexes on changed columns are touched: the birth-year update changes the row and the birth_year index, not the primary or name indexes.
- Purging old versions reads the rollback segment instead of scanning tables.
- Replication (the binlog) is logical: statement-based (compact, but a replica may re-run an expensive statement), row-based (more verbose but predictable), or mixed. Replicas derive index changes themselves.
- Replicas have real MVCC, so reads do not block replication.
- Corruption is contained: a bad statement may be skipped or applied twice, giving wrong data but not a destroyed B-tree.
- Version upgrades go replica by replica, then promote one, with almost no downtime.
Two more advantages.
- Buffer pool. Postgres relies on the OS page cache: Uber's largest replicas had 768 GB of RAM, but only about 25 GB was Postgres process memory, so most reads went through lseek and read system calls (not even pread) with context switches. InnoDB keeps its own LRU buffer pool in user space, with scan-resistant policies and no syscall per page; huge pages reduce TLB misses.
- Connections. MySQL uses a thread per connection and some Uber instances ran close to 10,000 connections. Postgres 9.2 uses a process per connection with System V IPC (slower than futexes), and struggled past a few hundred active connections. pgbouncer pooling helped, but application bugs that left connections "idle in transaction" caused long outages.
What has changed since. These points describe Postgres 9.2. Postgres has long had heap-only tuple (HOT) updates (since 8.3), which skip index updates when no indexed column changes and the page has room, although in the post's example an indexed column did change. Built-in logical replication arrived in Postgres 10. The core design difference, indexes pointing at physical tuples, remains. See PostgreSQL and replication.
Overlooked constraints.
- Index count drives write cost. The pain scales with the number of secondary indexes on frequently updated tables; a table with one index sees little difference.
- Cross-data-center bandwidth is finite. A design fine within one data center can fail once replication crosses a continent.
- Upgrade cost compounds with data size. Skipping one upgrade makes the next one longer, so a team can get stuck on an old version.
What Uber sacrificed. Postgres's richer SQL features and extensions, faster secondary-index reads (one lookup instead of two) and byte-identical replicas. It gained cheaper writes, compact replication, safer upgrades and better behaviour with many connections.
Deep Dive: counting writes for one updateShow
Postgres (handbook's illustration). A trips table has a primary key plus 8 secondary indexes, and a status field (indexed) is updated 5 times per trip. Each update writes 1 new tuple and 9 index entries, each with WAL records: about 20 page modifications. If each WAL record averages 100 bytes and full-page images after checkpoints add more, a 4-byte status change can produce several kilobytes of WAL. At 10,000 updates per second that is tens of megabytes per second of WAL, all shipped cross-country and archived.
InnoDB. The same update changes the row in place, writes one undo record, and updates only the status index (delete old entry, insert new). The row-based binlog event carries the before and after row images, a few hundred bytes. Replication traffic falls by roughly 10 times in this example.
The read side. A query by a secondary index in InnoDB does two B-tree descents. If each is 3 to 4 levels and the upper levels are cached in the buffer pool, the extra cost is one or two page reads from memory, a few microseconds. That is why the trade usually favours InnoDB for write-heavy, index-heavy tables.
Why HOT does not always help. HOT applies only if no indexed column changes and the new version fits on the same 8 KB page. Updating an indexed status column, or a page already full, falls back to the full index update. Lowering the table's fillfactor leaves room on pages for HOT, at the cost of more disk.
Lesson 10: CacheFront, an integrated cache serving 40 million reads per second (2024)#
Assumptions. By 2024 Docstore (Lesson 8) stored tens of petabytes and served tens of millions of requests per second. Its query layer does planning, routing, sharding, schema management, health checks, validation and auth. Its storage layer does Raft, replication, transactions, concurrency control and load management, with partitions of one leader and two followers on MySQL with NVMe SSDs. One new use case needed far higher read throughput than anyone before. Serving it from disk was technically possible but would cost too much:
- Disk speed has a floor, and query tuning only goes so far.
- Vertical scaling stops when the database engine becomes the bottleneck.
- Horizontal scaling by splitting shards is slow, operationally risky, and does not fix hot keys.
- Reads often outnumber writes by orders of magnitude.
- Cost multiplies by 6: every capacity unit is paid for on 3 stateful nodes in each of 2 regions.
Teams already put Redis in front of Docstore, but each provisioned and ran its own, wrote its own invalidation, and either replicated caches across regions or suffered a cold cache after failover.
Goals for CacheFront. Cut storage scaling for read-heavy loads using cheaper cache hosts; improve p50 and p99 and smooth microbursts; replace custom caches; be transparent through the existing Docstore client; let the Docstore team swap cache technology later; decouple cache sharding from database sharding to avoid hot shards; scale the cache independently; and move Redis on-call from feature teams to the Docstore team.
Design. Docstore queries are ReadRows (point reads by primary key), ReadPartition (all rows of a partition) and QueryRows (partition plus a filter). Over 50% of queries are ReadRows, the simplest case, so CacheFront started there. The cache lives in the query engine layer, which already sees every read and write. Caching is opt-in per database, table and request: an eater's cart can bypass the cache for strong consistency, while a restaurant menu (rarely written) uses it.
Cached reads (cache-aside). The query engine looks up the requested rows in Redis and streams hits back immediately. It reads the misses from the storage engine, streams them back, and asynchronously writes them to Redis. See distributed caching.
Invalidation, in layers.
- TTL of 5 minutes by default. Shorter TTLs reduce hit rate without giving real guarantees.
- CDC through Flux. Conditional updates ("change holiday hours for all chains in a region") do not tell the query engine which rows changed, so it cannot invalidate them on the write path. Flux, Docstore's CDC service, tails each cluster's MySQL binlog and feeds replication, materialized views, data lake ingestion and consistency checks. A new Flux consumer invalidates or upserts changed rows in Redis, bringing staleness from minutes to seconds. Because binlogs contain only committed changes, uncommitted transactions never pollute the cache.
- Version-checked writes. Reads and Flux both write the cache, so a slow read could overwrite a newer value with an older one. Each cached value encodes the row's MySQL timestamp as a version, and writes go through a Lua script via EVAL that, like MSET, writes many keys but only if each is newer, atomically in one round trip.
- Explicit invalidation for read-your-writes. A dedicated API lets a caller invalidate rows right after its own point write. Conditional updates still rely on Flux.
-- KEYS: cache keys; ARGV: pairs of (version, encoded_row) per key
for i, key in ipairs(KEYS) do
local newVersion = tonumber(ARGV[2*i - 1])
local current = redis.call('GET', key)
local curVersion = current and tonumber(string.match(current, '^(%d+)|')) or -1
if newVersion > curVersion then
redis.call('SET', key, ARGV[2*i - 1] .. '|' .. ARGV[2*i], 'EX', 300)
end
end
return 1(The script is the handbook's sketch of the idea; the post does not publish its code or codec format.)
Keys and codec. A primary key (row key) identifies a row; the partition key is a prefix of it that picks the shard (for orders: partition by cust_id, primary key cust_id plus order_id). Since Redis stores strings, a codec encodes each row key with database and table identifiers so different databases share Redis clusters but stay isolated.
Resilience features.
- Compare cache. A shadow mode reads both cache and database and logs mismatches (stale rows, or rows in cache but not in the database). With Flux invalidation the cache measured 99.99% consistent.
- Cache warming across regions. Docstore is active-active across two regions. If one region's cache is cold, failover sends a flood of misses to the database, so the database could never be scaled down. Replicating Redis values directly would create a second replication path that could disagree with Docstore's own. Instead, CacheFront tails the Redis write stream, ships only keys to the remote region, and there issues normal reads through the query engine, which fill the cache from that region's database on a miss. Results are discarded. The same working set stays warm in both regions, consistent with each region's data, with little cross-region bandwidth.
- Negative caching. Rows that were requested but do not exist are cached with a flag, so repeated lookups for missing rows skip the database.
- Sharding. One Docstore instance can map to several Redis clusters, and Redis is sharded by partition key on a different scheme from Docstore's. If one Redis cluster fails, its misses spread across all database shards instead of hammering one.
- Sliding-window circuit breakers per Redis node: errors are counted per time bucket over a window; a fraction of requests proportional to the errors is short-circuited, and at the limit the breaker trips until the window passes.
- Adaptive timeouts. A fixed Redis timeout is either too short (needless misses, more database load) or too long (bad p99.9 and p99.99). CacheFront adjusts the timeout to about the p99.99 of cache latency, so 99.99% of requests use the cache and the slowest 0.01% are cut off early and served from the database. Only a maximum is configured.
Results. p75 latency down 75% and p99.9 down over 67%, with fewer spikes. One of the largest early use cases serves over 6 million requests per second at about a 99% hit rate and survived a full failover to the remote region. Serving it from storage would have taken about 60,000 CPU cores; with CacheFront at about 99.9% hits it needs about 3,000 Redis cores. Across Docstore, CacheFront serves over 40 million requests per second.
Overlooked constraints.
- A cache that saves the database also hides its true load. If the cache fails, the database must survive the misses. Spreading Redis shards differently from database shards is how CacheFront keeps a cache failure from becoming a hot database shard.
- Two writers, one key. Reads and CDC both fill the cache, so without versions the cache can go backwards in time.
- Warmth is a capacity question. The database can only be shrunk if the cache stays warm in every region that might take traffic.
What Uber sacrificed. Strict consistency for cached reads (eventual, within seconds, about 99.99% consistent), extra infrastructure (Flux consumers, warming streams, many Redis clusters) owned by the Docstore team, and complexity in the query engine.
Deep Dive: the cost math of 6 million requests per secondShow
Cores. The post's numbers: about 60,000 cores to serve 6 million requests per second from storage, about 100 requests per second per core, versus about 3,000 Redis cores, about 2,000 requests per second per core. Redis is about 20 times more efficient per core for point reads, before counting that storage cores sit on 3 replicas in 2 regions.
Hit rate sensitivity. At 6 million requests per second, a 99% hit rate sends 60,000 per second to storage; 99.9% sends 6,000. Every tenth of a percent of hit rate is thousands of database reads per second, which is why negative caching and warm failover matter so much.
Failover without warming (handbook's illustration). If region B has a cold cache and takes region A's 3 million requests per second, its miss rate for that traffic starts near 100%, demanding 3 million reads per second from storage sized for 30,000. The database would collapse. Key-only warming keeps region B's hit rate near region A's.
Adaptive timeout payoff. Suppose Redis p99 is 1 ms, p99.99 is 5 ms, and occasionally a request stalls for 100 ms. A fixed 100 ms timeout lets stalls hit p99.99 user latency. A 5 ms adaptive timeout sends those requests to the database after 5 ms, which answers in perhaps 5 to 10 ms, cutting the tail by around 10 times while sending only 0.01% of traffic to the database.
Lesson 11: Herb, replicating Schemaless across data centers (2018)#
Assumptions. By 2018 Schemaless served 600+ cities and 15 million rides a day, with 50+ instances and thousands of storage nodes. Uber ran an active-active architecture: applications read and write in any data center and keep working if one fails. That needs a replication engine between data centers with five properties:
- Consistency: data should be fresh and match across data centers.
- At-least-once delivery: fine because Schemaless is append-only and writes are idempotent, so reapplying is harmless.
- In-order delivery per origin: updates that start in DC1 appear in the same order in DC2 and DC3, so a reader in any data center sees one origin's updates in one order.
- Independent speeds: a slow data center must not hold back a fast one.
- Fault tolerance: one data center's failure must not stop replication among the others.
Architecture. Herb, written in Go, connects every Schemaless instance to its peers in a full mesh, with one stream in each direction for each pair of data centers. Herb workers find each other through the Uber Naming Scheme (UNS) and use Ringpop (Lesson 2) to form a ring and split tasks, each an independent goroutine. The transport is pluggable: TCP first, then HTTP, then YARPC, Uber's open-source RPC framework for Go.
Reading changes: logs, not queries. A prototype polled the database, which wasted resources on idle datastores and did not scale. Herb instead streams the commit log: every change is a record with a unique, monotonically increasing number, stored in a data file with an index file mapping record numbers to disk offsets, so Herb reads changes without querying or slowing the database.
Ordering and offsets. Herb keeps a separate acknowledged offset per destination. Example: DC1 has updates a, b, c, d, e. DC2 has acknowledged up to d; DC3 only a. If Herb in DC1 restarts, it resumes DC2 at e and DC3 at b, each in origin order. If DC2 had received b and c but DC1 only recorded a's acknowledgement, DC2 gets b and c again, which idempotent appends ignore. A write counts as replicated when the remote data center acknowledges it, so the system is eventually consistent.
Deployment. Instances are grouped into replication cohorts, each a deployment unit sharing Herb workers. A busy instance can share with a quiet one, critical instances get their own cohort, every instance has guaranteed minimum resources, and test and staging have separate cohorts.
Performance. On a production Mezzanine datastore with 550 to 900 cells per second, median replication lag was 82 to 90 ms, of which about 40 ms is network time between data centers.
Validation. Echoing Leslie Lamport's 1987 line that a distributed system is one where a computer you did not know existed can make yours unusable, Uber validated Herb before and after launch: shadowing production writes into a test instance and comparing, then a near-real-time continuous checker that reads replicated data across data centers and verifies each origin's order. Next step: generalize Herb's change streams to feed the warehouse and other consumers. That is the CDC role Flux later played (Lesson 10).
Overlooked constraints.
- Only per-origin ordering. Updates from DC1 and DC2 to related data are not ordered relative to each other, so the application must avoid conflicting writes from two data centers, which immutable cells help with.
- A full mesh grows as n squared. With n data centers there are n times (n minus 1) streams; fine for a few data centers, costly for many.
- Replicated means acknowledged remotely, not instantly readable everywhere: a failover in the 90 ms window can lose visibility of the last updates until replay.
What Uber sacrificed. Synchronous cross-data-center consistency for low write latency, and a global order across origins. It kept per-origin order and idempotent replay.
Deep Dive: lag, offsets and why logs beat pollingShow
Lag budget. At 82 to 90 ms median with 40 ms of network, Herb's own processing is about 40 to 50 ms: reading the log, batching, sending and the remote write. If a failover happens, writes from roughly the last 0.1 seconds may not yet be in the other data center; at 900 cells per second that is about 90 cells, which replay recovers once the origin returns.
Polling cost (handbook's illustration). Polling 50 instances times 4,096 shards every 100 ms is about 2 million queries per second, mostly returning nothing for quiet datastores. Tailing an append-only log with an index costs almost nothing when idle and is sequential I/O when busy.
Offsets per destination. If one data center is slow (say it is catching up after maintenance at 5,000 cells per second while live traffic is 900), keeping a separate offset lets the fast destinations stay current. A single shared offset would hold every data center back to the slowest one.
Mesh size. 3 data centers give 6 directed streams; 5 give 20; 10 give 90. A hub-and-spoke design gives 2 times (n minus 1) streams but adds a hop and a single point of failure, which is why few-region systems often choose a mesh.
Lesson 12: Running Cassandra as a service at scale (2023)#
Assumptions. Uber has run Apache Cassandra as a managed service since 2016: tens of millions of queries per second, petabytes, tens of thousands of nodes, thousands of keyspaces and hundreds of clusters of 6 to 450 nodes, spanning regions. Workloads range from read-heavy to write-heavy; most use TTLs. The Cassandra team owns features and upstream fixes, integration with Uber's control plane and observability, data-model guidance, and a 99.99% availability target with 24/7 support. See Cassandra.
Platform pieces.
- Odin, Uber's stateful control plane, plus a Cassandra framework on it that makes seed selection, rolling restarts, capacity changes, node replacement, decommission and nodetool runs one-click operations.
- Forked Go and Java clients that find contact points through service discovery (no hard-coded hosts) and record query fingerprints and feature usage.
- Service discovery updated by the framework as nodes go up, down or away.
Challenge 1: unreliable node replacement. Nodes are replaced daily for hardware failures and fleet optimization (and in bulk for topology changes or DR). Decommission sometimes hung forever, bootstrap failed intermittently, and data became inconsistent. The math: 95% success with 500 replacements a day is 25 manual fixes a day, about two engineers full-time, and automation would have to pause. Causes and fixes:
- Orphan hints. Cassandra stores hints (writes saved for a replica that was down) and never deleted hints for nodes that had left the ring; decommissioning nodes even passed them to successors. Terabytes of garbage built up, and hint transfer during decommission is rate-limited inversely to cluster size, so it could take days. Uber purged orphan hints and tuned the hint throttle (hinted_handoff_throttle_in_kb) dynamically, so backlogs finished in hours.
- Invisible state. Decommission also failed when other work (rolling restarts for upgrades) ran in parallel, and the control plane could not see decommission or bootstrap progress. Uber exposed that state through JMX so the control plane could check it and react.
- Result: 99.99% reliable, fully automated replacement, with tens of thousands of nodes replaced in a few weeks.
Challenge 2: lightweight transaction errors. Lightweight transactions (LWT) are Cassandra's Paxos-based compare-and-set. Some critical use cases saw error bursts every couple of weeks, and the team assumed LWT was just unreliable. The error appeared when there was more than one pending token range movement. After ruling out the control plane starting parallel replacements, they found one node believed two range movements were pending while the majority saw one. A new metric and alert caught the cause: a replacement node, started with replace_address_first_boot pointing at the old host, kept resolving the old host's DNS name in gossip after joining. When that DNS entry disappeared, an exception left its caches out of sync, fixable only by restart. Better gossip error handling ended the issue; none were seen in about 12 months.
Challenge 3: repair built in like compaction. Anti-entropy repair compares replicas and fixes differences caused by downed nodes and deletes. Slow repair meant deleted data could resurrect once tombstones expired. Instead of an external orchestrator, Uber put a repair scheduler inside Cassandra: a dedicated thread pool, a replicated repair-history table in the system_distributed keyspace, picking nodes repaired longest ago, repairing every table and token range, in parallel across nodes, split into sub-ranges with retries. It starts with the cluster and needs no human. p99 repair duration fell from tens of days to under ten days.
The lesson: many small, incremental fixes compound into large reliability gains at fleet scale.
Overlooked constraints.
- Rare failures become daily toil at scale. A 5% failure rate is invisible on 10 nodes and is two full-time jobs on tens of thousands.
- Gossip state can diverge on one node. A single node's wrong view of pending ranges broke Paxos-based LWT for the cluster's callers.
- Repair speed is a correctness bound. If repair is slower than gc_grace_seconds, deletes can come back.
What Uber sacrificed. Running pure upstream Cassandra: it maintains forks of clients and server patches, and a team for the service. It gained 99.99% availability and automated operations at a scale few run Cassandra.
Deep Dive: tombstones, repair windows and hint backlogsShow
Resurrection. In Cassandra a delete writes a tombstone. After gc_grace_seconds (10 days by default) compaction may drop it. If one replica missed the delete and repair has not run within that window, the tombstone disappears on the others while the old value survives on the missed replica, and the next read repair spreads the deleted value back. That is why repair duration must stay below gc_grace_seconds; cutting p99 from tens of days to under ten days brings repair inside the default window.
Hint backlog (handbook's illustration). If a node holds 2 TB of orphan hints and the throttle allows 1,024 KB per second divided across, say, 200 nodes, the effective rate can be a few megabytes per second at best, and 2 TB at 5 MB per second takes about 4.6 days. Purging orphans removes most of the backlog; raising the throttle finishes the rest in hours.
LWT cost. A lightweight transaction runs Paxos rounds among replicas: prepare and promise, read, propose and accept, then commit, about 4 round trips versus 1 for a normal quorum write. At 1 ms per round trip within a region, an LWT costs about 4 to 5 ms and is very sensitive to any replica disagreeing about token ownership.
Family 4: Data platform
Lesson 13: The big data platform, from Vertica to a 100-petabyte lake (2018)#
Assumptions. Three kinds of users: city operations (thousands, simple SQL), data scientists and analysts (hundreds), and engineers building data products such as fraud detection and driver onboarding (hundreds). Data changes after the fact: a fare adjusted hours later, a rating left with the next trip weeks later, backfills months later. Tables are very wide (about 1,000 columns, five or more levels of nesting) but queries touch a few columns.
Generation 1 (before 2014 to about 2015): a warehouse. Data lived in a few MySQL and Postgres databases, a few terabytes in total, with no global view. Uber chose Vertica, a columnar warehouse, loaded by ad hoc ETL from S3, OLTP databases and logs, with SQL as the standard interface through an online query service. Within months there were tens of terabytes and hundreds of users, and products like uberPOOL and upfront pricing were built on it. Limits:
- Source data was mostly JSON without schema contracts, so producer changes broke ingestion.
- The warehouse was used as a data lake too, so cost rose, old data was deleted, and parts were not horizontally scalable.
- Different users ingested the same data with different transforms, loading upstream databases and storing near-duplicates. Backfills were laborious because transforms happened during ingestion.
Generation 2: a Hadoop data lake. Raw data was ingested once, untransformed, into HDFS. Users got Presto for interactive queries, Spark for programmatic access, and Hive for very large queries. All modelling moved into Hadoop, with only critical modelled tables copied to the warehouse. Data was stored in Parquet (columnar, compressed, schema included), with a central schema service and client libraries. Scale: tens of petabytes, tens of terabytes per day, 10,000+ vcores and 100,000+ batch jobs a day. Limits:
- Small files overloaded the HDFS NameNode.
- 24-hour data latency. Each ingestion took a full snapshot of the source and converted the whole table to Parquet: for one table, over 100 TB rewritten to add about 100 GB of new data, taking over 20 hours with 1,000+ Spark executors. Snapshots were needed because HDFS and Parquet cannot update records, and updates to old data were common.
Generation 3 (2017): incremental with Hudi. At 100+ PB, 100,000 vcores, 100,000 Presto queries, 10,000 Spark jobs and 20,000 Hive queries a day, four pain points:
- HDFS scale: NameNode limits typically bite above 10 PB and become serious at 50 to 100 PB. Fixes: ViewFS, NameNode federation, fewer small files, and separate clusters for HBase and YARN logs.
- Fresher data through incremental ingestion of only new and changed rows.
- Updates and deletes on HDFS and Parquet, keeping columnar formats for wide tables.
- Incremental ETL: derived tables updated from changes, not rebuilt.
The answer was Hudi (Hadoop Upserts anD Incrementals; Lesson 14). With it:
- Kafka as the handoff. Storage changelogs and service logs flow into Kafka in a unified Avro encoding with standard headers: timestamp, row key, version, data center and origin host.
- Marmaray, Uber's open-source ingestion framework, runs Spark mini-batches every 10 to 15 minutes, applying changelogs to Hadoop tables with Hudi upserts. Raw data latency is about 30 minutes, with headroom for one or two failed runs. Ingestion is EL, not ETL: no transforms during ingestion, so each source is ingested once and transforms can be re-run with more parallelism if they fail.
- Incremental modelling. Over 3,000 raw tables (2017). Modelling jobs pass a checkpoint timestamp to a Hudi reader to get only changed records, from any date partition, and use a Hudi writer to update old partitions of derived tables. ETL finishes in under 30 minutes, so derived tables are less than one hour old end to end.
- Two read views: latest (the merged current state of every record) and incremental (all changes since a timestamp, including intermediate versions).
- Standard raw tables: a changelog history table (every change; may be sparse when changelogs carry only changed columns) and a merged snapshot table (latest full row). The history table also stores the snapshot table's date partition for each key, so joining them avoids a full scan.
Generation 4 plans. Data quality: schema checks enforced upstream, and semantic types in the schema service (for example an integer that must be between 0 and 150). Latency: 5 minutes for raw and 10 minutes for modelled data, letting more use cases move from streaming to cheaper mini-batches; and a Hudi real-time view based on merge-on-read. Efficiency: containerized services and one resource scheduler across YARN, Mesos and Myriad. Reliability: a unified changelog format from all storage systems, with source technology only as metadata. And Parquet files over 1 GB instead of 128 MB, avoiding copy-on-write rewrites (Lesson 14). See data pipelines and analytics and batch and stream processing.
Overlooked constraints.
- Late updates dominate design. A ride's data keeps changing for weeks, so date-partitioned files can never be treated as final.
- Ingestion must not load the source. Generation 1's repeated ingests hurt the online databases; ingest-once EL from changelogs protects them.
- File count is a capacity limit, separate from bytes. NameNode memory sets how many files the lake can hold.
What Uber sacrificed. Transform-at-ingest convenience (users must model after landing), simplicity (Kafka, Marmaray, Hudi, schema service and several query engines to run), and pure streaming latency: minutes, not seconds, for most analytics.
Deep Dive: snapshot versus incremental ingestion in numbersShow
Snapshot cost. The post's example: 100 TB per table rewritten to add 100 GB a day. That is 1,000 times more I/O than the new data. At, say, 1 GB per minute per executor of read, convert and write (handbook's illustration), 1,000 executors process 1 TB a minute, and 100 TB takes about 100 minutes of pure throughput; in practice with source extraction and shuffle it took over 20 hours.
Incremental cost. Upserting 100 GB a day as mini-batches every 15 minutes is about 1 GB per batch. Each batch must find which files hold the updated keys (Hudi's index) and rewrite or append to those files only. If updates touch 2% of files, the job rewrites about 2 TB a day in copy-on-write mode, or appends 100 GB of logs in merge-on-read mode, versus 100 TB.
Latency budget. 10 to 15 minute batches plus room for 1 to 2 retries gives about 30 minutes for raw tables; incremental modelling jobs under 30 minutes on top give under an hour end to end, versus more than 24 hours before.
NameNode math. A NameNode keeps about 150 bytes of heap per file, directory or block object. 500 million files with one block each need about 150 GB of heap, near the practical limit of one NameNode. Larger files (1 GB instead of 128 MB) cut object count by about 8 times for the same data.
Lesson 14: Hudi, upserts and incremental processing on Hadoop (2017)#
Assumptions. With columnar formats (Parquet, ORC) and fast query engines (Presto, Impala), Hadoop could become one unified serving layer for workloads that tolerate a few minutes of latency, if ingestion and preparation were fast. The alternatives each have two serving layers:
- Lambda architecture (named by Nathan Marz) runs a batch layer every few hours for accurate state and a streaming layer for a fresh approximation, so computation and serving are doubled, or a complex system like Druid handles both record updates and bulk loads.
- Kappa architecture (Jay Kreps, "Questioning the Lambda Architecture", 2014) uses only streaming, replaying the log with more parallelism to reprocess. Computation is unified, but serving is still split: record-level "speed" stores (in-memory like MemSQL, or heavily indexed like Elasticsearch) handle fresh data with 30 to 90 days or a few TB of retention, and HDFS handles history.
For workloads fine with about 10 minutes of latency, Uber argued you do not need a separate speed layer if HDFS can (1) apply mutations quickly to large datasets, (2) stay optimized for analytical scans, and (3) chain updates efficiently into modelled datasets. Mutations are unavoidable because of late-arriving data, event time versus processing time, and deletions for compliance. In terms of the Dataflow model's latency and completeness trade-offs (Akidau et al., "The Dataflow Model", 2015), Uber uses record-level streaming for the few use cases needing about 1 minute latency and simple metrics, batch for heavy jobs like ML training and experiment analysis, and Hudi incremental processing for complex joins and heavy computation at near real time.
Storage layout. A Hudi dataset is a Hive-like partitioned directory tree under a basepath. Within a partition, records are in files identified by a fileId and the commit that wrote them; updates create new versions with the same fileId. Each record key maps permanently to one fileId after its first write. Three parts:
- Timeline metadata: commits (atomic batch writes, identified by a monotonically increasing start timestamp), cleans (removing file versions no running query needs), and compactions (merging row-based logs into columnar files).
- Index, pluggable: a Bloom filter in each Parquet file footer (default; no external system, always consistent with the data) or HBase (fast lookups for small batches).
- Data in two formats: scan-optimized columnar (Parquet) and write-optimized row-based (Avro).
Write path (merge-on-read). Ingestion is a Spark job running mini-batches of about 1 to 2 minutes (or scheduled by Oozie or Airflow):
- Tag: load Bloom filters for the partitions in the batch and mark each record as an update (with its fileId) or an insert. The join is range-partitioned and sub-partitioned to avoid skew and Spark's 2 GB shuffle-block limit.
- Inserts: grouped per partition, appended to a new fileId's log until it reaches the HDFS block size, then a new fileId.
- Updates: appended to the fileId's Avro log file.
- Commit: on success, atomically rename an inflight file to a commit file in the timeline.
- Compaction: every few minutes a scheduler builds a prioritized list, largest logs first, because rewriting a Parquet file is only worth it when many updates amortize the cost. Compaction runs asynchronously, locking specific log versions through ZooKeeper while new updates go to a new log version.
Files are kept HDFS block-sized to balance compaction parallelism, scan parallelism and file count. Small files left by compaction are fixed later, as new inserts are packed into them.
Failure recovery. Spark retries transient failures; a failed job is retried next iteration. Partial Avro blocks are skipped using block start offsets in commit metadata. Partial Parquet files from a failed compaction are ignored because queries only pick files from the last completed compaction, and the next run rolls back and retries.
Query path. A custom InputFormat, registered in the Hive metastore, gives two views over the same data:
- Read-optimized (HoodieReadOptimizedInputFormat): only the latest compacted Parquet files. Fastest, slightly stale.
- Real-time (HoodieRealtimeInputFormat): latest Parquet merged with its logs during the scan. Fresher, slower.
Both extend the standard Parquet readers, so Presto and Spark SQL work unchanged.
Incremental pull. Because the timeline records which file versions each commit produced, a query can ask for changes between two commit times: pick file versions in that range and push down a commit-time predicate. How far back you can go depends on how many old versions the cleaner keeps. This enables stream-to-dataset and stream-to-stream joins that upsert modelled tables inside HDFS.
Copy-on-write versus merge-on-read. The earlier generation, copy-on-write, has no logs: every update rewrites the whole Parquet file. It is simpler but increases latency and write amplification. Merge-on-read appends updates to logs and compacts later.
Overlooked constraints.
- Index lookup is the hidden cost. Every batch must check incoming keys against Bloom filters of every file in affected partitions; updates spread over many old partitions make tagging slow.
- Retention of versions limits incremental history. Cleaning old versions saves space but shortens how far back an incremental query can read.
- Real-time view costs readers. Merging logs at query time moves work from writers to every reader.
What Uber sacrificed. Second-level freshness (minutes instead), simple files (a timeline, logs and versions to manage), and some reader speed in the real-time view, for one serving layer instead of two.
Deep Dive: Bloom filters, compaction priority and write amplificationShow
Bloom filter sizing. A Bloom filter with m bits, n keys and k hash functions has a false-positive rate of about (1 minus e to the power minus kn over m) to the power k. With 10 bits per key and k = 7, the rate is about 0.8%. A 128 MB Parquet file with 1 million records needs a 10 million bit (1.25 MB) filter. A false positive only means Hudi checks that file for the key unnecessarily; it never loses data.
Why largest logs first. Rewriting a 128 MB Parquet file costs the same whether its log has 10 updates or 100,000. Compacting a file with 100,000 updates amortizes the cost over 100,000 records (about 1.3 KB of rewrite per update); one with 10 updates costs 13 MB per update. Prioritizing by log size maximizes updates merged per byte rewritten within a time-limited compaction window.
Write amplification. In copy-on-write, a batch of 1 GB of updates spread over 2,000 files rewrites about 256 GB, 256 times amplification (handbook's illustration). Merge-on-read appends 1 GB of logs and compacts perhaps 200 of those files per cycle, rewriting about 25 GB. The price is that readers of the real-time view merge logs at query time.
Lesson 15: Operating Apache Pinot at Uber scale (2020)#
Assumptions. Traffic: thousands of analytical queries per second per region, growing about 30 times in a few years. Latency: milliseconds to sub-second for dashboards and backend services. Freshness: seconds, with a p99 freshness target under 5 minutes for important tables. Consistency: analytics can tolerate slightly wrong recent numbers if they are corrected later. Maintenance: a small platform team must serve hundreds of use cases, so onboarding and node replacement must be self-service.
Uber needed answers like "which Uber Eats orders are delayed in the last five minutes" or "how many riders are opening the app in this city right now". A data warehouse such as Hive answers these in minutes. A key-value store cannot answer them at all, because they are aggregations over many rows sliced by many dimensions. The answer is an OLAP store (OnLine Analytical Processing: a database built for fast aggregations over large data). Uber chose Apache Pinot, which LinkedIn built. It grew from a 10-node cluster holding tens of GB to hundreds of nodes per region holding tens of TB.
Three kinds of use cases.
- Dashboards. The Uber Eats Restaurant Manager lets a restaurant owner slice their own orders by item, rating and time. City operations teams watch live supply, demand and delayed orders.
- Analytical applications. Backend services run analytical queries inside product flows, for example finding geographic hotspots for grouping riders, or spotting abandoned carts to send an incentive.
- Near-real-time exploration. Engineers triage incidents by joining recent events from many services with SQL, through Presto on top of Pinot.
Ingestion: real-time and offline into one table. Pinot reads Kafka topics directly. When a topic needs a join or a pre-aggregation first, a FlinkSQL job (Uber's AthenaX, later contributed to Apache Flink) turns a SQL query into a Flink job whose output is another Kafka topic that Pinot reads. Offline data in HDFS is loaded by Piper, Uber's workflow scheduler: it runs a Hive query as a Spark job, builds Pinot segments (Pinot's unit of storage: an immutable, columnar, indexed chunk of rows) and pushes them hourly or daily.
A Pinot hybrid table combines the two halves behind one logical name. The broker reads real-time segments for recent time and offline segments for older time, split at a time boundary. The offline side serves four purposes:
- Data correction. Kafka data may be missing or wrong. Owners fix it later in the offline dataset, and the offline segments then replace the real-time ones for that period.
- Bulk bootstrap. Loading three months of history by replaying Kafka would take far too long; loading segments built in Spark is fast.
- Fast serving of batch outputs. Hive and Presto on HDFS cannot answer in under a second, so teams load ETL outputs into Pinot.
- Complex computation. ML features that FlinkSQL cannot express are computed in Spark and served from Pinot.
Storage: tenants and regions. A Pinot cluster has a controller (the cluster brain, which uses Apache Helix on ZooKeeper to track which server holds which segment), brokers (which scatter a query to servers and gather the results) and servers (which hold segments and run query fragments). A tenant is a named group of brokers and servers owned by one use case, for example Eats or Maps. A bad query from one tenant hurts only its own hosts. This is the main tool for avoiding noisy neighbours.
Each region runs the same stack: Pinot, Kafka and HDFS. A table is either:
- Region-local: it ingests only local Kafka and HDFS. This gives the freshest data and suits region-specific facts such as live delayed orders.
- Global: it ingests aggregate Kafka topics that hold data from every region (built by uReplicator, Lesson 16). Each region then holds the full global dataset, so the table is automatically active-active: one region can fail and every query still works.
Two supporting services complete the picture. A schema service is the source of truth for Kafka schemas; a custom decoder fetches the schema during ingestion. A segment store archives sealed segments so that a replacement server can download them.
Querying. Clients originally had to know which brokers belonged to which tenant. Uber added a Pinot REST proxy behind HAProxy. Each proxy caches the routing table from Helix, picks the right tenant's brokers and forwards the query asynchronously. Spark jobs ask the proxy, not the controller, for table metadata, which keeps request spikes away from the controller. Later Uber connected Presto to Pinot. Filters and aggregations are pushed down into Pinot, so full SQL with joins runs in under a second. The long-term plan was to replace the proxy with Presto.
Uber's contributions.
- Self-service onboarding. Onboarding once took 3 days to a week with an engineer. Schema inference now turns an Avro schema from Kafka or Parquet into a Pinot schema, choosing a timestamp column and flattening nested records. It works for over 80% of datasets. A FlinkSQL job or Piper job can "push to Pinot", which creates a staging table automatically. Users then iterate on schema and indexes (star-tree, sorted, inverted). Staging memory and disk use predict production needs, and every table must run in staging for at least 24 hours before promotion.
- HDFS as deep store. Pinot's real-time ingestion protocol, LLC (low-level consumer, where each server consumes specific Kafka partitions directly), expected an NFS mount on the controller. Uber does not run NFS. With LinkedIn, Uber changed the segment-completion step so that it can upload to HDFS or S3.
- Schema evolution. Adding a column to a real-time table left the new column missing from the segment still being written, so queries failed. Uber fixed this upstream.
- Full SQL via Presto, described above.
Operational lessons.
- Large scans cause GC pauses. A Presto
select *with no time filter loads huge amounts of data into memory (Uber used in-memory indexes rather than memory-mapped files). The resulting full garbage-collection pauses slow down every table on that server. The options are off-heap indexes (slower queries) or a lower query-parallelism limit (lower throughput). In practice, Uber moved ad hoc querying into its own tenant. - A metrics library filled the controller heap. Helix kept a histogram metric with a 1-hour sliding window, so a busy controller held millions of samples and outgrew its 4 GB heap. When the leader controller stalls in GC, no new segments are created and ingestion stops cluster-wide. Uber made the window configurable upstream.
- Other memory traps. HyperLogLog queries degrade sharply when data volume grows 2 to 5 times. IN clauses with thousands of values multiply memory across segments. Traffic surges of 2 to 3 times during a region failover cause severe GC.
- Too many segments. When a server comes online, Helix sends one state-transition message per segment through ZooKeeper. A server with too many segments floods ZooKeeper beyond its buffer limit and crashes servers and controllers. Uber added message throttling in the controller.
- Hotspots after expansion. New segments go to the least-loaded host, so after adding servers all of the newest, hottest segments land on the new machines. Uber runs a table rebalance after every expansion.
- The deep store became a single point of failure. HDFS was sometimes down for about an hour for maintenance, which stopped real-time ingestion and broke the 5-minute freshness target. All uploads and downloads also went through the controller. Uber proposed letting servers download completed segments from peer replicas while the deep store is down.
Overlooked constraints.
- Control-plane metadata grows with segment count, not data volume. Thousands of small segments hurt ZooKeeper long before disks fill up.
- SQL flexibility invites unbounded queries. Adding Presto opened the door to
select *scans that a fixed dashboard would never issue. - The archive sits on the ingestion path. A store used "only for recovery" turned out to block every real-time commit.
What Uber sacrificed. Exact, immediately correct numbers (real-time data is corrected later by offline loads), heap headroom (in-memory indexes are fast but punish large scans), and operational simplicity (tenants, proxies and two ingestion paths) in exchange for millisecond analytics on fresh data for hundreds of teams.
Deep Dive: Why OLAP stores scan so fast, and sizing a tenantShow
Columnar layout plus indexes. Pinot stores each column separately, dictionary-encoded: a city column with 600 distinct values becomes 10-bit codes instead of strings. A query count orders where city = X and status = delayed in the last 5 minutes reads only 3 columns. A sorted index on time turns the time filter into a range of row numbers. An inverted index on city maps each value to a bitmap of matching rows. ANDing two bitmaps of 10 million bits takes microseconds. A star-tree index pre-aggregates chosen dimension combinations, so a group-by over city and product reads a few thousand pre-computed nodes instead of millions of rows.
Worked sizing (handbook's illustration). A tenant ingests 20,000 events per second at 200 bytes raw, which is 4 MB/s or about 345 GB per day. Columnar compression of 5 to 10 times brings that to roughly 50 GB per day. Keeping 30 days with 2 replicas needs about 3 TB. Servers with 500 GB of usable SSD need 6 servers, plus headroom for rebalancing, so plan for 8. At 1,000 QPS with each query touching 20 segments of 2 ms each, servers do about 40 core-seconds of work per second. Eight servers with 16 cores each have 128 cores, so they run at about 30% utilisation before the 2 to 3 times failover surge. That surge is the number to plan for, because Uber saw it cause severe GC.
Why hybrid tables need a time boundary. If real-time and offline segments both cover yesterday, a naive broker counts rows twice. The broker sets a boundary at the newest offline time: offline answers for time before it and real-time answers for time after it. When the next daily offline push lands, the boundary moves forward and corrected data replaces the real-time version for that day.
Lesson 16: uReplicator, a Kafka replicator without rebalance storms (2016)#
Assumptions. Traffic: thousands of topic-partitions from several data centers merged into an aggregate cluster for global analytics. Latency: end-to-end delivery within minutes; a 5 to 10 minute stall breaks the guarantee. Consistency: zero data loss, duplicates allowed (at-least-once delivery). Maintenance: topics are added often, so adding one must not require a restart.
Uber runs Kafka clusters in several data centers. Global metrics, such as all trips worldwide, need every region's data in one place, so an aggregate cluster receives copies of regional topics. Kafka's built-in MirrorMaker (version 0.8.2) did this simply: a high-level consumer reads from the source and a producer writes to the destination.
Why MirrorMaker broke at Uber's scale.
- Rebalance storms. The high-level consumers coordinate through ZooKeeper to divide partitions among themselves. Any membership or topic change triggers a rebalance in which all of them stop. Uber saw 5 to 10 minutes of zero traffic, and after 32 failed attempts the consumers gave up and stayed stuck. When they resumed, the backlog hit the destination as a traffic spike that caused outages downstream.
- Static whitelist. The list of topics to mirror (which controls WAN bandwidth) was read at startup. Adding a topic meant a restart, and a restart meant a rebalance.
- Data loss. The consumer auto-committed offsets for fetched messages before the producer had confirmed writing them to the destination. A crash in between lost those messages.
- Config drift. If one node failed to pick up the new topic list, the workers disagreed and the whole cluster went down.
Three options considered.
| Option | Pros | Cons |
|---|---|---|
| A. Many small MirrorMaker clusters | Easy to add topics, fast restarts | Many clusters to deploy and run |
| B. Apache Samza job with static assignment | Stable, one job for many topics | Restart to add topics or workers; topic expansion handled manually |
| C. Apache Helix controller plus simple consumers | Add or remove topics and nodes live; no restarts except upgrades | New dependency on Helix (shared across clusters) |
Uber chose C. Apache Helix is a cluster-management framework (also from LinkedIn) that stores an assignment of resources to nodes in ZooKeeper and notifies nodes when it changes.
The design.
- A controller cluster decides which worker owns which topic-partition. It handles topic and worker changes, detects worker failures and reassigns only the failed worker's partitions. A REST API adds, removes or changes mirrored topics.
- Each worker copies its assigned partitions from source to destination.
- A Helix agent on each worker receives a callback when its assignment changes.
- A DynamicKafkaConsumer (the high-level consumer with the rebalance logic removed) adds or drops partitions on the fly without stopping the others.
Zero data loss comes from committing source offsets only after the destination cluster has acknowledged the data. A crash replays a few messages as duplicates instead of losing them.
Results. Before uReplicator there was an outage of some kind almost every week. In its first eight months of production there were none. Adding topics produced no gaps or spikes in destination traffic. Rebalancing happens only at startup and when nodes change, and it moves only a subset of partitions.
Overlooked constraints.
- Coordination protocols are themselves a failure mode. A rebalance that pauses everyone turns a small change into a global outage. Central assignment trades that for a dependency on the controller.
- Recovery creates its own load spike. After a stall, the catch-up burst hurt downstream consumers more than the stall itself.
- Offset commit order defines your guarantee. Committing before the destination acknowledges gives at-most-once delivery by accident.
What Uber sacrificed. Using the stock tool and its upgrades for free (they now owned a fork), a new dependency on Helix, and exactly-once delivery (duplicates on crash), in exchange for no rebalance stalls and live topic changes. Kafka later shipped MirrorMaker 2 on Kafka Connect, which fixes several of the same problems; Uber built uReplicator years before it existed.
Deep Dive: Cooperative versus stop-the-world assignment, with numbersShow
Stop-the-world cost. Suppose 3,000 partitions carry 600 MB/s in total across 30 workers, so 20 MB/s per worker (handbook's illustration). A 7-minute rebalance builds a backlog of 600 MB/s times 420 s, about 250 GB. If workers can push 2 times normal speed while catching up, they drain an extra 600 MB/s, so the backlog takes another 7 minutes to clear. During those 7 minutes the destination receives 1,200 MB/s, double its normal load, and every downstream consumer sees the same double load. One topic addition costs about 14 minutes of degraded freshness plus a load spike.
Incremental assignment cost. Adding a topic with 8 partitions in uReplicator touches 8 of 3,030 partitions. No other partition pauses. When a worker dies, the controller moves only its 100 partitions. They resume from their last committed offsets after the failure detection time (seconds) plus fetcher start-up. The backlog is roughly 20 MB/s times 30 s, about 600 MB, spread over the surviving workers.
Duplicates under at-least-once. If a worker commits offsets every 10 seconds per partition at 200 KB/s, a crash replays up to 2 MB per partition. Downstream consumers deduplicate with a unique event ID (Lesson 17 shows the same assumption in reprocessing). Modern Kafka's cooperative sticky assignor (KIP-429) applies the same idea inside Kafka's own consumer groups: only the partitions that move are paused.
Lesson 17: Reliable reprocessing and dead letter queues with Kafka (2018)#
Assumptions. Traffic: one event per trip for enrolled drivers in more than 200 cities, so thousands of events per minute at peak. Latency: real-time charging, so a failed event must not delay healthy ones. Consistency: no event may be lost (at-least-once delivery), so every downstream call must be idempotent. Maintenance: errors must be visible, countable and replayable by the owning team.
Uber's Insurance team ran Driver Injury Protection, which deducts a per-mile premium for each trip of an enrolled driver. Each trip event triggers two independent jobs: charge the premium and write a reporting record. The post explains the design using an online shop. A PreOrder topic feeds two consumer groups, one calling the Payment service and one calling the Reporting service.
Why simple retries fail. The obvious fix is to retry inside the consumer with backoff. Two problems appear:
- Head-of-line blocking. A Kafka consumer moves forward by committing an offset. If one message keeps failing, for example because Payment started rejecting a whole class of orders after a breaking change, the consumer never commits it. It re-reads the same batch again and again while new messages pile up behind it. The worst messages use the most time and resources.
- No metadata. It is hard to see when a message first failed or how many times it has been retried.
The design: a ladder of retry topics. Each consumer group gets its own chain of topics:
- The main consumer tries the handler. If it still fails after a few quick attempts, it publishes the message to the first retry topic and commits the original offset. Success is redefined: a message is done when it has a conclusive outcome, either processed or parked somewhere else.
- A separate group of retry consumers reads each retry topic. On failure it publishes the message to the next topic down.
- The last topic is the dead letter queue (DLQ), where messages wait for a human.
- Each level waits longer before processing: a level-1 consumer only handles a message once it is, say, 1 minute old, and a level-2 consumer once it is 10 minutes old. Uber calls these delayed processing queues. The delay acts like a leaky bucket and stops retries from spamming a struggling dependency. The delay is a minimum, not an exact schedule.
- A tool built on its own consumer can list the DLQ, purge it, or merge it, which republishes messages into the first retry topic so that they never compete with live traffic.
Classify errors. A network timeout is worth retrying. A null-pointer exception or validation bug will fail every time, so it goes straight to the DLQ.
What the design buys.
- Unblocked batches. Healthy messages in the same batch keep flowing.
- Decoupling. Each consumer group has its own ladder. If reporting fails but payment succeeds, only reporting retries.
- Configurability. One generic consumer class, configured with which topic to read, which to publish to on failure, and how long to delay. New topics cost almost nothing and share one schema.
- Observability. Comparing the production rate of the main topic against each retry topic and the DLQ gives an alerting signal and a measure of real service uptime.
- Flexibility and durability. Clients in many languages (many Uber services use Go), Avro for schema evolution, and Kafka's at-least-once delivery.
Overlooked constraints.
- Ordering is lost. A retried message is processed after newer messages for the same key. The application must tolerate events arriving out of order. For a payment, a refund could be processed before the charge it refunds.
- Every handler must be idempotent. At-least-once delivery plus republishing means the Payment call may run twice; it needs an idempotency key (see /apis/idempotency).
- Topic explosion. One ladder per consumer group per event type multiplies topics. The alternative is one retry topic with retry count and timestamp fields inside the message, which moves scheduling from topology into code.
What Uber sacrificed. Strict per-key ordering, a smaller topic count, and immediate retries, in exchange for real-time throughput that one bad dependency cannot stall, plus a visible, replayable failure queue.
Deep Dive: How long-delay retry consumers wait, and the arithmetic of the ladderShow
Implementing the delay. Kafka has no per-message delay. A retry consumer reads the message's timestamp and, if it is too young, sleeps or pauses the partition until it is old enough. Because a partition is ordered by time, if the head message is too young, so are all messages behind it, and pausing the whole partition is correct and cheap. In Java clients, consumer.pause plus a timer avoids exceeding max.poll.interval.ms, which would otherwise make the group think the consumer died.
async function handleRetry(msg: Msg, level: Level): Promise<void> {
const readyAt = msg.firstFailedAt + level.delayMs;
if (Date.now() < readyAt) {
await pausePartitionUntil(msg.partition, readyAt);
}
try {
await level.handler(msg); // must be idempotent
} catch (err) {
if (isPermanent(err) || level.next === undefined) {
await publish(dlqTopic, withMeta(msg, err));
} else {
await publish(level.next.topic, withMeta(msg, err));
}
}
await commit(msg); // conclusive outcome reached
}Worked numbers (handbook's illustration). Payment fails 2% of 10,000 events per minute during a partial outage: 200 per minute enter retry 1. If the dependency recovers within 5 minutes, the 1-minute level re-fails about 80% of what it sees during the outage, the 10-minute level succeeds for nearly all, and only messages with permanent errors reach the DLQ. Without the ladder, a consumer retrying 3 times with 1-second backoff on each of 200 bad messages per minute spends 600 seconds per minute stuck, so the main flow falls 10 times behind real time.
Retry budget. If level delays are 1, 10 and 60 minutes, the worst case before the DLQ is 71 minutes. Choose the last delay to exceed your typical incident recovery time, otherwise outages dump the whole backlog into the DLQ and a human has to merge it back.
Lesson 18: M3, a metrics platform for billions of time series (2018)#
Assumptions. Traffic: 500 million metric samples per second aggregated, 20 million per second written to storage, 6.6 billion unique time series. Latency: interactive dashboards and alerting, with queries of up to 100,000 series spanning years. Consistency: quorum writes to 3 replicas in a region; a lost sample is tolerable but a missing alert is not. Maintenance: the platform must run itself, without the constant tuning Cassandra needed.
By late 2014 Uber sent every metric to Graphite: Whisper files on a sharded Carbon cluster, Grafana dashboards and Nagios alerts. Growing the cluster meant manual resharding, and with no replication a single failed disk lost its metrics permanently. Uber wanted reliability and scale, cross-data-center queries, low query latency, first-class tagged metrics (a metric name plus key-value labels such as endpoint=signup, as Prometheus popularised), and backwards compatibility with hundreds of services that still emitted StatsD and Graphite metrics.
From open source parts to a native design. The first M3 (2015) was assembled from statsite for aggregation, Cassandra with Date Tiered Compaction for storage and Elasticsearch for indexing. Operational load, cost and new features pushed Uber to replace each one. The result is M3DB, a distributed time series database with a built-in reverse index and configurable out-of-order writes, and M3 Coordinator, a sidecar that lets Prometheus use M3 as remote storage.
Design principles.
- Compress hard. M3 extends the compression from Facebook's Gorilla paper (Pelkonen et al., "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015) to compress float64 values further. Uber calls it M3TSZ.
- Keep memory lean. Much metric data is "write once, read never". M3DB keeps only a Bloom filter and an index summary per shard per time block, in memory-mapped files.
- Avoid compaction. Metrics are immutable, so rewriting them is wasted work. M3DB only merges time blocks when it must, for example for backfills.
- Downsample at ingest, not later. Classic downsampling re-reads stored data to compute 1-minute or 1-hour averages, which costs network, CPU and disk. M3 aggregates when samples arrive.
Storage policies. Engineers do not think much about metric lifecycles, so defaults matter. Every metric gets a few sensible defaults, for example 2 days at full resolution and 30 days at 1 minute. Longer retention is opt-in through tag matchers. Policies range from 1 second to 10 minutes or more in resolution, and from 2 days to 5 years in retention.
- name: Retain all disk_used metrics
filter: "name:disk_used* device:sd*"
policies:
- resolution: 10s
retention: 2d
- resolution: 1m
retention: 30d
- resolution: 1h
retention: 5yRollup rules aggregate across dimensions at ingest, for example summing request counts over all hosts of a service, and give the result its own policy. They are the equivalent of Prometheus recording rules.
Global view without global replication. Each region writes only to its local M3DB cluster, replicated 3 ways across availability zones or racks. etcd, which holds placement and rules, runs inside the seed nodes' binary. A query fans out to the local cluster and to the coordinators in remote regions, which read their own storage and return still-compressed M3TSZ blocks. One Grafana data source shows every region. A service that fails over between regions can be summed in one query.
The later plan was a regional aggregator cluster that can roll up across many Prometheus instances, with leader election on etcd. This avoids the usual Prometheus high-availability setup, where two identical instances both write every sample and double long-term storage.
Overlooked constraints.
- Cardinality, not sample rate, is the real limit. Each unique tag combination is a new series with its own index entry. One tag holding a user ID can add millions of series.
- Downsampling at ingest needs the rules up front. An ad hoc question about high-resolution data from three months ago cannot be answered if only 1-hour data was kept.
- Cross-region queries depend on every region. A remote region that is slow or unreachable makes the global answer partial or slow.
What Uber sacrificed. Off-the-shelf components (they built a database), full-resolution history (opt-in only), and cross-region replicas of metrics (each region's data lives only there), in exchange for 20 million writes per second on modest hardware and a single global view.
Deep Dive: Gorilla compression and the cost of a time seriesShow
Timestamps: delta of delta. Samples arrive every 10 seconds, so timestamps are t, t+10, t+20, and so on. The first delta is 10 and the next delta-of-delta is 0. Gorilla stores a 0 delta-of-delta as a single bit. Most timestamps therefore take 1 bit instead of 64.
Values: XOR with the previous value. Consecutive float64 values of a gauge are often equal or close. XOR of two equal values is 0, stored as 1 bit. When they differ, the XOR usually has long runs of leading and trailing zeros, so Gorilla stores only the meaningful middle bits plus their position. The paper reports about 1.37 bytes per sample on average, versus 16 bytes uncompressed. M3TSZ adds tricks such as detecting values that are really integers, which compress further.
Worked sizing (handbook's illustration). 20 million samples per second at 1.4 bytes is 28 MB/s, about 2.4 TB per day before replication, or 7.3 TB per day with 3 replicas. Keeping only the default 2 days at full resolution needs about 15 TB. Thirty days of 1-minute data is 6 times fewer samples per series, so about 1.2 TB per day replicated, or 37 TB for 30 days. Without the opt-in rule, keeping everything at 10 seconds for 5 years would need about 13 PB. Retention policy is the biggest cost lever, larger than any compression gain.
Index cost. 6.6 billion series with 100 bytes of tags each is 660 GB of raw labels before the inverted index. That is why M3DB builds its reverse index per time block: series that stop reporting fall out of new blocks instead of living in the index forever.
Family 5: Reliability and real-time
Lesson 19: Evolving distributed tracing, from Merckx to Jaeger (2017)#
Assumptions. Traffic: about 500 microservices in fall 2015 and over 2,000 by early 2017, in four main languages (Node.js, Python, Go, Java). Latency: tracing must add negligible overhead to requests. Volume: recording every request would create more tracing traffic than business traffic, so only a sample is kept. Maintenance: a two-person team had to make tracing available to every service, most of which did not share one RPC framework.
Distributed tracing follows one request across every service it touches. Each unit of work is a span (an operation with a start time, a duration, tags and logs). Spans share a trace ID, and each span records its parent span ID, so the spans form a tree that shows where time went. Google's Dapper paper (Sigelman et al., "Dapper, a Large-Scale Distributed Systems Tracing Infrastructure", Google Technical Report, 2010) set the model. Metrics tell you that the p99 latency rose; a trace tells you which of 30 downstream calls caused it.
Generation 1: Merckx. Uber's first tracer instrumented the Python monolith automatically: HTTP, SQL, Redis, even JSON parsing. It recorded which database shards and replicas each request used and how long transactions stayed open, and it supported rich ad hoc queries over a Kafka stream. Two flaws ended it:
- No context propagation. It could not follow a call into another service, so it saw only one level.
- Thread-local state. It stored the request context in thread-local storage. When Uber adopted Tornado, an asynchronous Python framework where many requests share one thread, the context mixed up requests. The lesson: request context must be passed explicitly, not hidden in globals.
Generation 2: tracing inside TChannel. In 2015 Uber built TChannel, its own RPC framing protocol, with Dapper-style tracing in the binary header: a 64-bit span ID, parent ID and trace ID plus 1 byte of flags. Its client libraries forced a context argument on every outbound call (in Go, Call(ctx, method, arg, resp)), so propagation was built in. Google had Stubby and Twitter had Finagle; tracing succeeded there because one RPC framework carried the context everywhere. Uber's problem was that most core services did not use TChannel. The prototype backend, built on Riak and Solr behind the Zipkin UI, also struggled to scale.
Generation 3: Jaeger. The New York Observability team already ran Cassandra, Zipkin's native store, so they:
- rewrote the collectors in Go and stored Zipkin-compatible spans in Cassandra, adding search by custom tags;
- added a traffic multiplier in each collector to replay production spans n times as a stress test;
- wrote client libraries in Go, Java, Python and Node.js against the OpenTracing API, tested together for wire compatibility on every pull request by Uber's crossdock framework;
- moved span reporting to a jaeger-agent sidecar on every host. Clients send spans over UDP to localhost and poll the agent for sampling settings. Routing and discovery live in the agent, so services only need basic networking libraries;
- finally replaced the Zipkin UI and data model with their own. The new model supports key-value span logs, spans that reference several parents (a DAG rather than a strict tree), and process tags sent once per batch instead of in every span. A new React UI added a duration scatter plot, a trace minimap, DAG views and critical-path views.
Jaeger was open sourced in April 2017, joined the CNCF in September 2017 and graduated in October 2019.
Adaptive sampling from the backend. A fixed sampling rate set in each service fails at Uber's scale in two ways. A service with modest QPS can call a downstream service with a huge fan-out, so its "small" rate generates a flood of spans it cannot see. And demand has strong daily cycles, so a rate that is right at 4 a.m. is too high at the evening peak. Jaeger moved the decision to the backend: clients poll for a sampling strategy (probabilistic, or rate-limited with a leaky bucket), and the backend adjusts it as traffic changes.
Overlooked constraints.
- Tracing is only as good as propagation coverage. One uninstrumented service in the middle breaks the trace into disconnected halves.
- Tracing volume follows fan-out, not request rate. The cost of a trace depends on the number of spans per request, which the caller does not control.
- Asynchronous frameworks break implicit context. Thread-local storage stops working once requests share threads; the context must travel with the request.
What Uber sacrificed. Using Zipkin's ecosystem as is (they wrote their own clients, then their own backend and UI), and complete data (sampling discards most traces), in exchange for consistent libraries across four languages and tracing costs that the backend controls.
Deep Dive: Head sampling, tail sampling and the math of a sampling budgetShow
Head-based sampling decides at the root and propagates the decision in the flags. It is cheap: unsampled requests create almost no work. Its weakness is that it decides before knowing whether the request will be slow or fail. At 0.1% sampling, an error that occurs once in 100,000 requests is captured on average once per 100 million requests.
Rate-limited sampling per endpoint. Suppose a service has 5 endpoints at 10,000, 1,000, 100, 10 and 1 QPS. A 0.1% probabilistic rate keeps 10, 1, 0.1, 0.01 and 0.001 traces per second; the rare endpoint is almost never seen. A rate limiter of 1 trace per second per endpoint (a leaky bucket) keeps up to 1 per second for each endpoint, so rare endpoints are fully covered while the busy one costs only 1 trace per second. Jaeger's adaptive sampling later combined the two: a lower-bound rate per endpoint plus a probability computed by the backend to hit a target number of traces per second.
Budget arithmetic (handbook's illustration). 2,000 services, 1 million requests per second at the edge, 40 spans per request and 500 bytes per span. Tracing everything means 40 million spans per second, or 20 GB/s. With a target of 5,000 traces per second, it is 200,000 spans per second, or 100 MB/s, about 8.6 TB per day before compression. That is why sampling decisions belong in a central place that sees total volume.
Tail-based sampling buffers all spans of a trace for a few seconds and decides after the trace finishes, keeping all errors and slow traces. It needs memory proportional to traffic times buffer time: 20 GB/s for 10 seconds is 200 GB of buffer. The post described buffering in agents as the next step toward this "post-trace sampling".
Lesson 20: RAMEN, the real-time push platform (2020)#
Assumptions. Traffic: at the time of the post, over 1.5 million concurrent connections and over 250,000 messages per second, up from 600,000 connections and 70,000 messages per second in the first generation. Latency: a driver offer is valid for about 30 seconds, so delivery must take far less. Consistency: at-least-once delivery, and for most message types only the latest version matters. Maintenance: hundreds of features built by many teams must be able to push data without learning a new system.
The problem with polling. A rider waits for a driver to be assigned; a driver waits for an offer. The simplest design is for each app to poll every few seconds. At one point 80% of requests to Uber's API gateway were polling calls. Polling wastes server capacity, drains batteries, congests 2G and 3G networks, and any bug in polling frequency becomes a backend incident. Teams overloaded existing polling APIs with more features until those APIs were just shards of payload. Cold start was worst: on app open, every feature fetched its state at once, with no priority, and the screen could not render until the critical pieces arrived.
Design principles. Reuse the payload-building logic of existing polling APIs; make pushing feel like writing a polling API; deliver reliably with retries; and minimise bytes on the wire, because drivers in developing markets pay for data and stay connected for hours. The result was RAMEN (Realtime Asynchronous MEssaging Network).
Three separate jobs.
- When to push: Fireball. Fireball listens to events (a driver accepts an offer, the app opens, a timer fires, a geofence is crossed, a business event arrives on Kafka) and, based mostly on configuration, decides which messages to send to which users. One trigger often produces several messages for several people.
- What to push: the API gateway. Fireball calls a push API on the gateway. A push API is the same endpoint code as a pull API plus a "push" middleware that captures the response and forwards it to delivery. The same logic builds a user object whether the app pulls it or Fireball pushes it. The gateway also applies rate limits, routing and schema validation. Fireball adds the device context (locale, OS, app version) from the RAMEN server so the payload is localised correctly.
- Delivery: the RAMEN server, which holds connections to millions of devices.
Message metadata.
- Priority: high for core experience, medium for incremental features, low for large or rare messages. On connect, messages are written in priority order. High-priority messages get server-side retries and cross-region replication.
- Time to live: from a few seconds up to 30 minutes. Until the TTL expires, the server keeps the message and retries.
- Deduplication: for most types, only the newest message of that type is sent, which cuts data transfer.
The delivery protocol on SSE. In 2015 the options were HTTP/1.1 long polling, WebSockets and Server-Sent Events (SSE: a long-lived HTTP response with Content-Type: text/event-stream over which the server writes events). Uber chose SSE for security, mobile SDK support, small binary size and fit with its existing HTTP and JSON stack. SSE is one-way, so Uber built acknowledgements on top:
- The client opens
/ramen/receive?seq=0at the start of a session. The server sends pending messages in priority order, numbering them 1, 2, 3 and so on. - Because TCP delivers bytes in order, if message 3 never arrived the connection must have broken. The client reconnects with the highest sequence number it saw, say
seq=2. The server resends from 3 (or a newer, higher-priority message). Reconnecting with seq N is itself the acknowledgement of everything up to N. - The server sends a 1-byte heartbeat every 4 seconds. A client that hears nothing for 7 seconds reconnects.
- On good networks a connection can last minutes, so the client also calls
/ramen/ack?seq=Nevery 30 seconds to let the server free acknowledged messages.
The server stores each device context, keyed by a hash of the user and device parameters, so a user with two phones or two apps gets separate streams.
Generation 1 and why it was replaced. The first server was written in Node.js on Ringpop (Lesson 2), sharding connections by user UUID with Redis for storage. As the ring grew, gossip took longer to converge, and Node.js event-loop lag delayed membership updates further. Nodes briefly disagreed about who owned a user, causing lost messages, timeouts and errors.
Generation 2 (2017). Uber moved from decentralised to centralised topology management:
- Streamgate implements the protocol on Netty (a high-performance Java networking library whose byte buffers avoid copying). Each node is a Helix participant that heartbeats to ZooKeeper.
- StreamgateFE is a Helix spectator that watches the topology and works as a reverse proxy. Every request, from Fireball, the gateway or a phone, is routed to the Streamgate node that owns that user.
- A five-node Helix controller service reassigns partitions when nodes start or stop, using a custom leader-follower topology and a gradual rebalance.
- Cassandra stores messages durably with cross-region replication, ready for multi-region. Redis sits in front as a capacity cache, so that a deployment or failover does not send a thundering herd straight to Cassandra.
The result was 99.99% server-side reliability across more than ten app types on iOS, Android and web.
Overlooked constraints.
- Push needs a "when" service, not just a pipe. Without Fireball, every team would build its own trigger logic.
- Gossip convergence grows with the cluster. What works at 50 nodes misroutes users at hundreds; ownership of a live connection needs a single source of truth.
- Acknowledgements cost data. Batching acks every 30 seconds saved bandwidth but made it impossible to know quickly whether a 30-second offer had arrived (Lesson 21).
What Uber sacrificed. Bidirectional messaging and binary payloads (SSE is text and one-way), prompt delivery confirmation, and the simplicity of a decentralised ring (they added ZooKeeper, Helix and five controllers), in exchange for removing most polling and reusing every existing pull API.
Deep Dive: Connection math, heartbeats and what polling really costsShow
Polling cost (handbook's illustration). 5 million active apps polling 10 endpoints every 5 seconds is 10 million requests per second at the gateway, most of which return "nothing changed". If state changes on average once a minute per user per feature, push sends 5 million times 10 divided by 60, about 830,000 messages per second, 12 times fewer, and each message carries real news. Deduplication by type, which sends only the newest, lowers this further when changes arrive faster than the device can receive them.
Why 4 and 7 seconds. The heartbeat interval sets how fast a dead connection is noticed; the timeout must cover the interval plus network jitter. With a 4-second heartbeat and a 7-second timeout, one missed heartbeat plus 3 seconds of jitter is tolerated, and a broken connection is detected within 7 seconds. Each heartbeat is 1 byte of payload plus TCP and TLS overhead, perhaps 60 to 100 bytes per packet, so 1.5 million connections send about 1.5 million divided by 4, or 375,000 small packets per second, roughly 30 MB/s in total. That is cheap compared with polling.
Memory per connection. On Netty, an idle TLS connection might use 10 to 30 KB for buffers and state. 1.5 million connections times 20 KB is 30 GB, spread over a cluster, for example 50 nodes holding 30,000 connections each. Messages waiting for acknowledgement add to this: 30 seconds of unacknowledged messages at 250,000 per second and 1 KB each is about 7.5 GB cluster-wide. Faster acknowledgements directly shrink server memory, a point the gRPC post makes.
Sequence numbers versus per-message acks. The cumulative scheme (the highest seq seen acknowledges everything before it) is how TCP itself acknowledges bytes. It needs one number per reconnect instead of one message per item, which suits expensive mobile data. The cost is coarse knowledge: the server knows only that "some prefix arrived".
Lesson 21: Moving the push platform to gRPC bidirectional streaming (2022)#
Assumptions. Same scale as Lesson 20, rolled out to the Rider, Driver and Eats apps on Android and iOS worldwide. Latency: delivery status must be known within seconds, because a driver offer is valid for about 30 seconds. Network: many users are on slow, lossy 2G or 3G links. Maintenance: one protocol implementation across many client languages.
Limits of the SSE protocol.
- Delayed acknowledgement. A message's delivery status was unknown for up to 30 seconds, exactly the lifetime of a driver offer, so the server could not tell whether to resend it. With HTTP/1.1, real-time acks need either a second connection in the opposite direction (double the connections, with races where only one is up, or each lands in a different data center) or one HTTP request per ack (headers waste upload bandwidth).
- Heartbeats stuck behind data. Heartbeats shared the stream with messages. A large message on a slow link delayed the heartbeat, and the client disconnected a healthy connection. HTTP/2 and QUIC carry control frames separately from data.
- Text only. SSE carries newline-separated, escaped JSON, so binary payloads such as images or audio need base64, about 33% larger. A custom binary SSE would be non-standard and hard to maintain.
- QUIC ended at the edge. QUIC (HTTP/3) connections terminated at the front-end layer, which knows nothing about application state, so RAMEN could not use QUIC's streams and flow control.
- Hand-written clients. Every platform parsed the text stream with pattern matching and managed heartbeats and acks itself, so behaviour differed across versions.
Why gRPC. It supports bidirectional streaming natively, so acks travel instantly on the reverse direction of the same stream. Real-time acks let the server measure round-trip time (RTT) per connection and free memory sooner. On mobile, gRPC can run over Cronet (Chromium's network stack) and reuse the app's existing QUIC session, so the first push message arrives sooner. Earlier Uber experiments showed QUIC improving tail latencies of HTTPS traffic by 10 to 30 percent. It also brings standard tooling, and the rest of Uber was moving to gRPC.
Contract (proto3). One bidirectional RPC.
- Client to server: acks carrying the sequence ID, feature acks from the feature plugins that consume messages, and control messages such as "terminate connection" (later, flow control and prioritisation).
- Server to client: RAMEN messages, control messages such as "disconnect", and a heartbeat every 5 seconds.
Server changes. Streamgate itself stayed the same; only its front layer changed. Its in-memory message cache and mailboxes (kept for speed and so that it can fail open) must exist once per user, and a separate gRPC runtime would have doubled them and risked inconsistency. gRPC's Java server is itself built on Netty, so the byte-buffer code carried over. A new StreamgateFE-gRPC runtime uses a gRPC proxy library. It reads the method name and user ID from call metadata, asks the Helix routing layer for the owning Streamgate host and forwards on a cached channel. There is one gRPC channel per Streamgate host, carrying both streaming and unary calls.
Client changes. The public interface of the mobile RAMEN module stayed the same, so feature teams changed nothing. The networking stack's interceptors were rebuilt for gRPC: failover and redirect (switching hostname after failures), OAuth and header injection, and network monitoring (DNS, connect, TLS and end-to-end timing). The client reconnects with exponential backoff after a heartbeat timeout, a server disconnect message or a network error.
Lessons from the rollout.
- Concurrency. gRPC's
StreamObserver.onNextis not thread-safe. Writing to one stream from several threads without synchronisation caused bugs. - Flow control at bootstrap. Wrapping the observer in
ServerCallStreamObserverlet the server refuse client messages (acks) until the connection bootstrap had finished. - Graceful shutdown. On shutdown, every active stream must be cancelled explicitly. A map of shutdown handlers did this.
- Missing callbacks. Sometimes the client-termination callback never arrived, so heartbeat timers ran forever and CPU and memory climbed. The fix: check that the stream is still writable before each write and cancel the task if not.
- Compression. Some messages were larger than 1 MB. On EDGE or 3G they took 20 to 50 seconds to download, and heartbeats waited behind them, causing timeouts. SSE had not shown this, because the client read the payload in chunks, while gRPC delivers a whole message at once. Turning on gzip cut the download to about 5 seconds.
- Fallback. A client-side switch that falls back to SSE when gRPC connectivity fails mitigated several rollout problems.
Results. p95 connect latency improved by at least 45%. Push success rates rose by at least 1 to 2% across apps, with more messages delivered per session. Real-time RTT became visible, and every client now shares one implementation.
Alternatives rejected. Writing a custom HTTP/2 client and server would be "reinventing gRPC" across many platforms. Reactive Streams (RSocket) had less community activity and would mean supporting a second framework.
Still open. Payloads were still JSON on top of gRPC, with Thrift contracts; the plan was binary encoding first and then protobuf. One stream still has head-of-line blocking between messages, so the plan was several streams with application-level priority, because no HTTP/2 implementation, including gRPC-Java, implements stream priorities.
Overlooked constraints.
- Whole-message framing changes failure behaviour. A protocol that delivers complete messages makes large payloads block heartbeats in a way a chunked stream did not.
- Callbacks are not guaranteed. Long-lived streams need defensive checks, not just event handlers.
- Mobile rollouts need a way back. You cannot roll back an installed app quickly, so the old protocol must stay as a runtime fallback.
What Uber sacrificed. Some upstream data (an ack per message), the simplicity of a single protocol during migration (two front-end runtimes and two client stacks), and dependence on gRPC's limits (no stream priorities), in exchange for instant acks, RTT visibility, QUIC benefits and one standard client.
Deep Dive: Head-of-line blocking at three layersShow
TCP layer. HTTP/2 multiplexes streams over one TCP connection, but TCP delivers bytes in order. One lost packet stalls every stream until it is retransmitted. On a link with 2% loss and 300 ms RTT, each loss stalls everything for at least one RTT. QUIC runs over UDP and orders bytes per stream, so a loss stalls only its own stream.
Stream layer. Within one gRPC stream, messages are ordered. A 1 MB message on a 200 kbps link takes 40 seconds; anything queued behind it waits. Gzip on JSON often reaches 5 to 10 times compression, and the post measured about 5 seconds after compression. Splitting critical messages onto their own stream fixes the rest, which is the "leverage gRPC streams" plan.
Application layer. The heartbeat timeout must exceed the worst time to deliver one message. With a 5-second heartbeat, a client timeout of perhaps 10 seconds, and a 200 kbps link, any single message over about 125 KB can cause a false disconnect (handbook's illustration). Options: cap message size, compress, send large payloads as a URL to fetch, or send heartbeats on a separate stream. HTTP/2 PING frames are control frames and are not blocked by data on other streams, but they are still blocked by TCP loss.
The ack trade-off in numbers. A per-message ack is perhaps 20 to 40 bytes of protobuf on an open stream. At 10 messages per minute per user, that is about 400 bytes per minute upstream, small compared with the 30-second ack batches over separate HTTP requests whose headers alone can be 500 to 1,000 bytes each.
Lesson 22: QALM, criticality-aware load shedding (2018)#
Assumptions. Traffic: Uber's customer platform team ran four services on thousands of hosts, with peaks up to 300,000 requests per second and more than 450 internal callers. Latency: callers time out after a few seconds, so a request that waits 20 seconds is wasted work. Consistency: none needed; this is about which requests get served at all. Maintenance: capacity changes often, so a static threshold goes stale.
A review of six months of outages found that 28% could have been avoided or reduced by graceful degradation. The three most common causes were changes in inbound traffic (overload, bad actors), resource exhaustion (CPU, memory, the event loop, network), and failures of dependencies. Load shedding means deliberately rejecting some requests quickly so that the rest finish in time. The question is which requests to drop and when.
Why not a static rate limit. A fixed requests-per-second threshold must be updated whenever capacity changes, and endpoints with different SLAs and costs each need their own number. QALM (QoS Aware Load Management) detects overload dynamically instead.
Overload detection inspired by CoDel. CoDel (Nichols and Jacobson, "Controlling Queue Delay", ACM Queue, 2012) is an algorithm from network routers. It watches how long packets sit in a queue rather than how long the queue is. QALM puts a small buffer (goroutines and channels in Go) in front of each enabled endpoint and measures the delay between a request arriving and its handler starting. If the minimum queueing delay within a sliding window exceeds a threshold, the endpoint is overloaded. The minimum matters: if even the luckiest request in the window waited, a standing queue has formed, which is different from a brief burst.
Endpoint isolation. Each endpoint has its own queue and detector, so overload in one endpoint sheds only that endpoint's traffic.
Four criticality levels.
- Core infrastructure requests: never dropped.
- Core trip flow requests: never dropped.
- User-facing feature requests: may be dropped under overload.
- Internal traffic such as tests: dropped first.
Criticality is set per endpoint and caller pair, in a config file or a UI that uses Jaeger traces to pre-fill the list of callers. Changes take effect within a couple of minutes.
Results in load tests.
- One endpoint at 6,000 RPS without QALM: p99 latency grew to about 20 seconds. With QALM: p99 stayed under 400 ms while about 20% of requests (the non-critical ones) were dropped, a 98% improvement in latency for successful requests.
- Two callers at about 2,300 RPS each, one critical and one staging: QALM shed about half of the staging requests and every critical request succeeded.
- Uber Visa: the critical
applyendpoint at about 10 RPS while a non-critical endpoint spiked above 1,200 RPS. Without QALM, everyapplyrequest timed out. With QALM, the spike reached 1,800 RPS and only twoapplyrequests timed out in 30 minutes, about 50% more spike tolerance.
From library to middleware. Integrating QALM as a library needed code and config changes in each service, which slowed adoption. Uber rewrote it as inbound middleware for YARPC (its Go RPC framework) plus a module for UberFx (its dependency-injection framework). Enabling it became a config change, and setup time fell from a couple of days to under two minutes. CPU overhead measured at about 3% with five endpoints at 100 RPS each.
Overlooked constraints.
- Criticality by caller is too coarse. A critical service that also serves test traffic passes on test requests marked as critical (Lesson 23 fixes this by propagating priority).
- Capacity is still a number someone sets. QALM limits concurrency with a configured maximum, which drifts as hardware and traffic change.
- Reliability features in business code do not spread. Moving shedding into the RPC layer, not better algorithms, is what drove adoption.
What Uber sacrificed. Some user-facing features during overload (deliberately dropped), about 3% CPU, and the work of labelling every caller, in exchange for keeping trip flows alive when an endpoint is overloaded.
Deep Dive: Why latency explodes past capacity, and why shedding fixes itShow
Queueing past saturation. If an endpoint can serve 5,000 RPS and receives 6,000, the queue grows by 1,000 requests every second. After 20 seconds, 20,000 requests are waiting, so a new request waits 20,000 divided by 5,000, which is 4 seconds. Since callers time out after perhaps 1 to 2 seconds, the server spends its whole capacity on requests whose callers have already given up. Goodput, the rate of useful successful responses, collapses towards zero even though the server is busy all the time. This is the 20-second p99 in Uber's test.
Shedding restores goodput. Rejecting 1,000 RPS (about 17%) in microseconds keeps the queue near empty, so accepted requests see only their service time. Uber dropped about 20% and kept p99 under 400 ms. A fast rejection lets the caller retry elsewhere or degrade, which is far better than a slow timeout.
Why the minimum delay in a window. Queueing delay during a short burst rises and falls; the minimum over a 100 ms window stays near zero because the queue empties at some point. Under sustained overload the queue never empties, so even the minimum is high. This separates "good queue" (absorbing bursts) from "bad queue" (a standing backlog), which is CoDel's key insight.
Lesson 23: Cinnamon, a load shedder with a PID controller and priority propagation (2023)#
Assumptions. Traffic: thousands of microservices serving about 130 million monthly customers, with millions of requests per second. Overload comes from traffic spikes (an aggressive batch job) or slowness (a slow database). Latency: high-priority requests must stay fast even at 3 times capacity. Maintenance: zero configuration, because even one setting per service costs many engineering hours across thousands of services and goes stale.
QALM worked, but its configuration slowed adoption. Three problems drove its successor, Cinnamon:
- Priority by caller is wrong one hop away. Service 1 serves both mobile apps and a test system, and both call Service 2. Service 2 marks Service 1 as high priority, so test traffic is treated as high priority too.
- Maximum concurrency is hard to set. The right value changes with request mix, hardware and noisy neighbours.
- Go channels are synchronisation points and cost performance under heavy load.
Priority set at the edge and propagated. The edge endpoint that receives the request from the app stamps it with a priority. The priority travels to every downstream service in the request's Jaeger tracing context (Lesson 19). Every service instance can then decide on its own, yet all of them agree on which requests matter. A priority has two parts:
- A tier from 0 (most important) to 5 (least important).
- A cohort from 0 to 127, derived by hashing the user, inspired by WeChat (Zhou et al., "Overload Control for Scaling WeChat Microservices", SoCC 2018). If a service must shed 5% of tier 1, it sheds the same 5% of users as every other service. Shedding a different 5% at each hop could break almost every user's multi-step flow. Time is mixed into the hash so that the same users are not always shed first.
Six tiers times 128 cohorts gives 768 priorities, few enough for a priority queue with one bucket per priority.
The request path.
- Priority: use the propagated priority, or a default based on the caller.
- Rejector: decide whether to reject now.
- Priority queue: accepted requests wait, highest priority first.
- Scheduler: start requests only while fewer than the inflight limit are running.
- Timeout: a request that waits too long in the queue is rejected with a rate-limit error. The queue timeout is typically 33% of the normal request timeout.
Two background goroutines tune the system. The PID controller sets the rejection ratio to keep the queue small. The auto-tuner sets the inflight limit to maximise throughput without hurting latency (Lesson 24). Both are needed. Limiting concurrency alone still lets a queue form when arrivals exceed what the limit can serve. Rejecting alone does not stop the service from overloading itself with too many concurrent requests.
When is an endpoint overloaded? If the queue has not been empty in the last 10 seconds or so, an idea Cinnamon credits to Facebook (described in Ben Maurer, "Fail at Scale", ACM Queue, 2015).
The PID controller. Once overloaded, the rejector measures the flow into and out of the priority queue. A PID controller (proportional, integral, derivative: a feedback controller from control engineering whose roots go back centuries to mechanical governors) computes the share of requests to reject. It finds the right level in a few iterations and then lowers the ratio slowly once the queue drains, which avoids oscillation. Using flows rather than absolute counts makes it work the same for 10 RPS and 10,000 RPS. The ratio maps to a priority threshold: the lowest tiers and cohorts are rejected first.
Results against QALM. The test endpoint mixed memory allocation, sorting and sleeping, taking about 120 ms unloaded. Two backends handled about 650 RPS each, so the service capacity was about 1,300 RPS. Traffic was 50% tier 1 and 50% tier 5, with a 1-second timeout.
- Goodput (throughput times one minus the error rate). Below capacity, everything succeeds. At 1,500 RPS QALM was about 2% better (1,280 versus 1,258), because Cinnamon's auto-tuner was still searching. From 2,000 RPS up, Cinnamon stayed near capacity (1,000 tier 1 plus 302 tier 5 at 2,000 RPS). QALM began timing out tier 1 too, and at 3,000 RPS its goodput was 552, about 40% of capacity. With no shedder, the service died above 3,000 RPS.
- Latency for tier 1. p99 was about 140 ms unloaded and about 190 ms at 1,000 RPS. Above capacity, QALM's p50 and p99 approached the 1-second timeout, while Cinnamon stayed under 500 ms at p99, with a p50 of about 180 ms.
- Why QALM failed. CoDel's on/off decision swings between rejecting everything and rejecting nothing. Under heavy load every request looks delayed, so it rejects nearly everything, and the single Go channel makes this worse. At 4,000 RPS QALM's successes swung between about 0 and 500, while Cinnamon's rejection rate stayed steady.
- Overhead: about 1 microsecond per request. The headline: p50 latency rises only about 50% at 300% overload.
Overlooked constraints.
- Priority must travel with the request. Local decisions are only consistent if every hop sees the same label.
- Shedding must be consistent across users. Random shedding at each hop compounds; cohort hashing makes the same users lose, so others succeed end to end.
- Rejecting costs capacity too. At very high overload the service spends more resources rejecting, so goodput slowly falls below capacity.
What Uber sacrificed. Simplicity (two feedback loops plus a propagated priority in every request), and a few percent of goodput near capacity while the tuner converges, in exchange for zero configuration and stable latency at several times capacity.
Deep Dive: PID control of a rejection ratio, step by stepShow
The loop. Let the error e be the queue's net growth per interval: inflow minus outflow, normalised by outflow. A positive e means the queue is growing. The controller output is the rejection ratio r = Kp times e, plus Ki times the sum of past e, plus Kd times the change in e since the last interval.
- P reacts to the current error: a growing queue raises r immediately.
- I remembers persistent error: if the queue keeps growing a little, r keeps rising until it stops. This term holds r at a steady 30% when overload is steady, which matches Cinnamon at 2,000 RPS.
- D damps sudden changes and prevents overshoot.
Worked example (handbook's illustration). Capacity is 1,300 RPS and inflow is 2,000 RPS. The correct steady rejection ratio is 1 minus 1,300 over 2,000, which is 35%. Start with r = 0. Interval 1: inflow is 2,000 and outflow 1,300, so e is about 0.54 and P with Kp = 0.5 sets r to 27%. Interval 2: accepted inflow is 1,460, so e is about 0.12; P adds 6% and I adds the accumulated error, so r is about 36%. Interval 3: the queue is slightly shrinking, e is about minus 0.02, and r settles near 35%. Then the queue drains and r is reduced slowly, as Cinnamon does, to avoid swinging back into overload.
From ratio to priority threshold. Requests are sorted into 768 buckets. If the measured mix is 50% tier 1 and 50% tier 5, rejecting 35% means rejecting all of tier 5's lowest cohorts until 35% of traffic is covered: about 70% of tier 5's cohorts, so roughly cohorts 38 to 127 of tier 5. Tier 1 is untouched. This is exactly the "302 tier 5 requests still served at 2,000 RPS" result.
Why not CoDel's on/off rule. A binary rule is a controller with only a huge P term and no I: it overshoots to "reject all", the queue empties, it flips to "reject none", the queue refills. The success rate oscillating between 0 and 500 in QALM's 4,000 RPS run is that limit cycle.
Lesson 24: The Cinnamon auto-tuner, adaptive concurrency with TCP Vegas (2023)#
Assumptions. Response times vary from 10 to 50 ms for most services to 1 to 10 seconds for a few. Workloads shift during the day, after every deploy, and between endpoints and hosts. A batch job can raise traffic 10 times in seconds. Maintenance: no service owner tunes anything.
Every load shedder needs to know the service's capacity, best expressed as the maximum number of concurrent requests. Throughput rises with concurrency up to a point, then falls sharply as requests fight over CPU, memory and locks. Too low a limit wastes the machine; too high a limit lets latency climb until the service falls over. The best value differs between services, endpoints, hosts and times of day, so it must be learned continuously.
TCP Vegas. Brakmo, O'Malley and Peterson ("TCP Vegas: New Techniques for Congestion Detection and Avoidance", SIGCOMM 1994) proposed that a TCP sender compare the current round-trip time with the lowest one it has seen. A rising RTT means queues are building somewhere, so the sender slows down before packets are lost. Applied to a service: compare the observed latency sample with a target latency (the best recent latency). Using the ratio of the two and the current limit, estimate how many requests are queuing. If few are queuing, raise the limit; if many, lower it; otherwise keep it. Vegas uses logarithmic thresholds, so the dead zone in which nothing changes is relatively wider for small limits: small limits need larger latency swings before they move.
// Simplified Vegas-style limit update (handbook's sketch, not Uber's code)
function updateLimit(limit: number, sample: number, target: number): number {
const queued = limit * (1 - target / sample); // estimated requests waiting
const lo = 3 * Math.log10(limit);
const hi = 6 * Math.log10(limit);
if (queued < lo) return limit + Math.log10(limit); // room to grow
if (queued > hi) return Math.max(1, limit - Math.log10(limit)); // back off
return limit; // dead zone
}Why vanilla Vegas fails in production, and Uber's fixes.
- Single samples are noisy. One request delayed by a routing blip or a busy CPU skews the comparison. Uber collects successful requests over an interval of at least 2 seconds and at most 30 seconds, requiring at least 250 requests. It counts only time in business logic, not time in Cinnamon's queue. It takes the p90 and smooths it with a median filter and exponential smoothing. Durations go into a t-digest (Ted Dunning's compact structure for approximate quantiles), trading some accuracy for fixed memory. Services behind a cache with a 90% hit rate see p90 jump between hit and miss latency, so they use p80 or p95 instead.
- The target latency drifts up during long overloads. The usual approach takes the lowest sample as the target and resets it periodically. Under sustained overload the reset picks a high, loaded latency, which permits a higher limit, which raises latency, which raises the next target. Uber added a covariance check. Over the last 50 intervals it converts the actual observed concurrency and the latency sample into throughput using Little's Law (concurrency equals throughput times latency, so throughput equals concurrency divided by latency) and computes the covariance between concurrency and throughput. If it is negative, more concurrency is making throughput worse, and the reset always lowers the limit. The check uses observed concurrency, not the limit, because a limit of 20 may see only 3 requests running.
- The limit grows without bound when all is well. When the service is healthy, the sample is close to the target and Vegas keeps raising the limit, even though real concurrency is flat. When overload finally arrives, it takes ages to come down. Uber caps the limit at 10 times the observed concurrency (observing 10 concurrent requests caps the limit at 100), which still leaves room for bursts. That is why healthy services show about 10% limit utilisation.
- A floor at the number of CPU cores, so a CPU-bound endpoint can keep every core busy. Hitting the floor several times in a row signals a wrong target latency and triggers a reset.
Before choosing Vegas, Uber tried AIMD (additive increase, multiplicative decrease, the classic TCP Reno rule) and gradient descent. Vegas gave more stable limits and handled latency variation better at low limits. The post points to Netflix's open-source concurrency-limits library as a starting point (see /engineering-blogs/blog-netflix).
In production.
- Load test with Ballast. Uber's Ballast load-testing framework loads a single production node, marks its traffic as low priority (tiers 4 and 5) so that Cinnamon sheds it first, and ramps up gradually. When latency rose, the auto-tuner lowered the limit to 16, the floor for that service. After hitting the floor repeatedly it discarded the target latency, overshot slightly and settled at 18.
- A slow dependency. Service foo, on 9 nodes in one data center, was overloaded not by more traffic but because its dependency bar got slower. The auto-tuner cut foo's inflight limit, limit utilisation rose from about 10% to 100%, and foo sent fewer concurrent requests to bar. Bar slowed but did not die. Foo's p50 stayed flat while p90 and p99 rose. CPU never saturated: the service was overloaded by latency, not by CPU, which a CPU-based autoscaler would never have noticed.
Overlooked constraints.
- Overload is not the same as high CPU. A slow dependency overloads a service with idle CPUs; only latency-based limits notice.
- Reference values drift under the condition you are guarding against. Any "baseline" re-learned during an incident will learn the incident.
- Unbounded growth during quiet times is a hidden risk, because recovery speed depends on how far the limit must fall.
What Uber sacrificed. Optimality (Vegas aims for stability, not perfect throughput), some accuracy (t-digest approximations and p90 instead of the full distribution), and quick reaction for slow services (up to 30-second intervals), in exchange for limits that stay correct without anyone tuning them.
Deep Dive: Little's Law and choosing the inflight limit by handShow
Little's Law. In any stable system, the average number of items inside (L) equals the arrival rate (lambda) times the average time each spends inside (W). For a service: concurrency equals throughput times latency.
Worked example (handbook's illustration). An endpoint takes 50 ms when unloaded and runs on 8 cores. If it is CPU bound at 5 ms of CPU per request, the cores can complete 8 divided by 0.005, which is 1,600 requests per second. To keep 1,600 RPS flowing at 50 ms each, Little's Law needs 1,600 times 0.05, which is 80 requests in flight. Allow 120 and the extra 40 can only queue for CPU. Latency becomes 120 divided by 1,600, which is 75 ms, with no extra throughput. Allow 400 and latency reaches 250 ms; with garbage collection and lock contention, throughput often falls too. That is the falling right side of the throughput curve.
What Vegas sees. With target 50 ms and sample 75 ms at a limit of 120, the estimated queue is 120 times (1 minus 50 over 75), which is 40. The thresholds at a limit of 120 are 3 times log10 of 120, about 6.2, and 6 times that log, about 12.5. A queue of 40 exceeds 12.5, so the limit decreases by about 2 per interval until the estimated queue falls into the dead zone, near a limit of roughly 85 to 90.
When the dependency slows. If the 50 ms is mostly waiting on a dependency that slows to 300 ms, the same 80 in flight now deliver only 80 divided by 0.3, about 267 RPS. Raising concurrency to restore 1,600 RPS would need 480 in flight and would pile more load on the struggling dependency. Lowering the limit instead, as Cinnamon did for foo, accepts lower throughput and lets the PID controller shed lower priorities, which is the right call: the bottleneck is downstream.
Family 6: ML and product
Lesson 25: Michelangelo, machine learning as a service (2017)#
Assumptions. Traffic: the busiest models served more than 250,000 predictions per second. Latency: p95 under 5 ms without feature lookups and under 10 ms with Cassandra feature reads. Data: billions of training samples. Consistency: features at prediction time must be computed exactly as at training time. Maintenance: dozens of teams must ship models without building their own serving systems.
Before Michelangelo, data scientists used R, scikit-learn and custom code, and separate engineering teams rebuilt each model for production in a one-off serving container. Training was limited to what fitted on a desktop. There was no standard place to store experiments, no way to compare them, and no standard path to production. Uber saw the anti-patterns described in Sculley et al., "Hidden Technical Debt in Machine Learning Systems" (NeurIPS 2015): glue code, pipeline jungles and training-serving skew. Work started in mid-2015 with training and serving, then feature pipelines, then developer speed.
Running example: Uber Eats delivery time. Predicting the time from order to doorstep covers restaurant acknowledgement, preparation (which depends on the order and on how busy the kitchen is), dispatching a courier, driving, parking, walking in and out, driving to the customer and walking to the door. The estimate is shown before ordering and updated at each stage. The model is a gradient boosted decision tree regression with three kinds of features: request features (time of day, location), historical features (average prep time over 7 days) and near-real-time features (average prep time over the last hour).
Built from: HDFS, Spark, Samza, Cassandra, MLlib, XGBoost and TensorFlow, on top of Uber's data lake, Kafka, managed Cassandra and deployment tools.
The six-step workflow.
- Manage data. Finding good features is the hardest and most expensive part of ML.
- Offline: Spark and Hive jobs over the HDFS lake compute features on a schedule, with data-quality monitoring.
- Online: a model serving a request cannot query HDFS, and it cannot compute "average prep time this hour" by querying the order service. Features are precomputed into Cassandra, either by batch precompute (loading HDFS results every few hours or daily, used for the 7-day average) or by near-real-time compute (Kafka events aggregated by Samza jobs, written to Cassandra and also logged to HDFS for future training, used for the 1-hour average). A backfill tool builds training data from historical logs to avoid a cold start.
- Feature store: about 10,000 shared features, each with an owner, description and SLA. A model refers to a feature by its canonical name, and the system joins the right HDFS data for training and reads the right Cassandra value online.
- Feature DSL: a pure functional subset of Scala for selecting, transforming (timestamp to hour of day, normalisation, filling missing values) and combining features, with user-defined functions. The DSL expressions are part of the model configuration, so training and serving run identical transformations. This is the main defence against training-serving skew.
- Train. Distributed training of decision trees, linear and logistic models, k-means, time series and deep networks, on YARN or Mesos. A model configuration names the type, hyperparameters, data source, DSL expressions and resources (machines, memory, GPUs). Hyperparameter search is supported, as are partitioned models: one model per city, falling back to a country model when a city lacks enough data.
- Evaluate. Every trained model is a versioned record in Cassandra: who trained it and when, the full configuration, references to training and test data, feature importance and distributions, accuracy metrics, standard charts (ROC and PR curves, confusion matrix) and the learned parameters. Tree visualisations show the path a given input takes through each tree. Feature reports show partial dependence plots, including two-way interactions. Hundreds of models that never ship still guide the search, so keeping them matters.
- Deploy. Three modes: offline (a Spark job for batch scoring), online (a prediction cluster of hundreds of machines behind a load balancer, called by RPC) and library (embedded in a service through a Java API, planned). Artifacts (metadata, parameters, compiled DSL) are zipped and shipped with Uber's normal code deployment tooling, and containers load them from disk.
- Predict. Raw features pass through the compiled DSL, which may fetch more from the feature store, and then the model scores the final vector. Several models can share a container, addressed by UUID or by a tag. Deploying a new model to an existing tag switches clients with no code change, as long as the feature signature is unchanged. Gradual switching by UUID and A/B tests through the experimentation platform (Lesson 27) are also possible.
- Monitor. Accuracy at training time is measured on the past. Michelangelo logs a share of predictions, joins them later to the real outcomes, and publishes live R-squared, RMSLE, RMSE and mean absolute error to the time series monitoring system (M3, Lesson 18) for alerting.
Scale. Models are stateless and share nothing, so serving scales by adding hosts or Spark executors.
Overlooked constraints.
- Training-serving skew is a data problem, not a modelling problem. Without shared pipelines and the DSL in the model configuration, the model sees different features in production.
- Online features need their own storage. A model cannot compute aggregates over operational databases on the request path.
- Models decay silently. Without joining predictions to outcomes, a broken upstream pipeline can degrade accuracy for weeks.
What Uber sacrificed. Freedom of tools (a fixed set of model types and a custom DSL), freshness for batch features (hours to a day old) and team autonomy over serving, in exchange for a standard path from idea to production with no skew between training and serving.
Deep Dive: Point-in-time correctness and the feature store's hardest problemShow
The leak. To train the delivery-time model on an order placed at 18:05 on 3 March, the feature "average prep time over the last hour" must be the value as it was at 18:05 that day, not today's value and not a value computed with the order's own outcome. Joining today's feature table to old labels leaks future information. The model looks brilliant offline and fails in production.
How the near-real-time path solves it. Samza writes each computed feature value to Cassandra for serving and logs the same value, with its timestamp, to HDFS. Training joins labels to the logged value that was current at prediction time, which is a point-in-time join (an "as-of" join). The served value and the training value are identical bytes.
Worked sizing (handbook's illustration). 250,000 predictions per second, each reading 20 features from Cassandra in one batched query, is 250,000 queries per second carrying 5 million values per second. At 1 ms per read in parallel with the DSL, this fits the observed under-10 ms p95. 10,000 features for 1 million restaurants and couriers at 16 bytes each is about 160 GB per replica, which is modest for Cassandra. The expensive part is the streaming jobs that keep 1-hour windows current, not the storage.
Partitioned models in numbers. One model per city across 600 cities, with a city model used only if it beats the country model on held-out data. A small city with 2,000 orders a month cannot support a 500-tree GBDT without overfitting, so it uses its country's model. That hierarchy trades some local accuracy for robustness. See /playbooks/ml-system-design-and-feature-stores for the general design.
Lesson 26: Ludwig, deep learning from a configuration file (2019)#
Assumptions. Users: data scientists and engineers who know their data but not TensorFlow. Iteration: comparing many architectures quickly matters more than squeezing the last 0.1% of accuracy. Scale: Horovod for multi-GPU and multi-machine training when needed.
Uber used deep learning for customer support, object detection, maps, chat and fraud. Building each model meant writing tensor code, preprocessing and evaluation from scratch. Uber AI had already released Pyro (probabilistic programming on PyTorch) and Horovod (distributed training; Sergeev and Del Balso, "Horovod: fast and easy distributed deep learning in TensorFlow", 2018). Ludwig, built on TensorFlow and used internally for two years, lets users train and test deep models without writing code. Internal uses included the Customer Obsession Ticket Assistant (COTA), extracting information from driver licences, spotting points of interest in driver-rider conversations, and food delivery time prediction.
Influences. From Weka and MLlib, working directly on raw data with pre-built models. From Caffe, a declarative model definition file. From scikit-learn, a simple programmatic API. The post's analogy: deep learning libraries give you bricks to build a building; Ludwig gives you buildings to build a city.
The key idea: encoders and decoders per data type. Each supported data type (binary, numerical, category, set, bag, sequence, text, image, time series) has its own preprocessing, one or more encoders (raw data to tensor) and decoders (tensor to raw data). A combiner joins the encoder outputs; the default concat combiner concatenates them and passes them through fully connected layers. Tasks emerge from composition: text encoder plus category decoder gives a text classifier; image encoder plus text decoder gives an image captioner. Several outputs give multi-task learning for free.
input_features:
- name: title
type: text
encoder: rnn # default is a CNN encoder
cell_type: lstm
bidirectional: true
- name: author
type: category
- name: description
type: text
- name: cover
type: image
output_features:
- name: genre
type: category
- name: price
type: numerical
training:
epochs: 100
learning_rate: 0.001
batch_size: 64ludwig train splits the data into training, validation and test sets, preprocesses it, builds four encoders, a combiner and two decoders, and trains until validation accuracy stops improving or the epoch limit is reached. ludwig predict scores new data. ludwig visualize draws learning curves and compares models. ludwig experiment trains and then predicts in one step. A Python API (LudwigModel(definition).train(df), .predict(df)) embeds trained models in applications.
Overlooked constraints.
- Defaults carry the expertise. No-code works only because sensible defaults for preprocessing, architectures and training come from experience and the literature; bad defaults would silently produce bad models.
- Declarative tools limit novelty. A new architecture still needs code, which Ludwig handles by letting experts add encoders, decoders and combiners.
- Training is not production. A saved model still needs serving, monitoring and feature pipelines, which is Michelangelo's job.
What Uber sacrificed. Full control over architecture and the last bits of accuracy, in exchange for fast baselines and comparisons that non-experts can run.
Deep Dive: Why type-based composition generalises, and what multi-task learning costsShow
Combinatorics. With 9 input types and 9 output types, and one or more encoders per type, the space of tasks is every combination of input and output sets. Instead of writing one model per task, Ludwig writes one encoder and one decoder per type, so the code grows linearly while the number of tasks grows combinatorially. This is the same "interfaces between modules" idea as plug-in architectures in systems design.
Multi-task loss. With two outputs, the total loss is a weighted sum: cross-entropy for genre plus mean squared error for price. The weights matter because the losses have different scales. A price in dollars with MSE around 25 would dominate a cross-entropy around 1, so the model would learn price and ignore genre unless the price loss is weighted down or the target normalised. Ludwig exposes per-output weights for this.
Strong baselines. A useful habit Ludwig encourages: before building a custom model, train a few config variants (CNN versus RNN text encoder, with and without the image) and compare them. If the cover image adds 0.3% accuracy at 10 times the training cost, drop it. This ablation is cheap when each variant is a YAML change.
Lesson 27: Under the hood of the experimentation platform (XP)#
Assumptions. Traffic: over 1,000 experiments running at any time across the Rider, Driver, Uber Eats and Freight apps, using over 1,000 reusable metrics. Latency: harmful experiments must be detected within days or hours, not after a fixed test ends. Statistics: a 5% false positive rate and 80% power as standard targets. Maintenance: methods must be "one size fits most" so that every team gets valid results without a statistician.
XP launches, measures and monitors product features, marketing campaigns, promotions and ML models. It also supports a universal holdout: a group kept out of all experiments in a domain to measure their combined long-term effect.
Four families of methods.
- Fixed-horizon A/B/N tests: t-test, chi-squared and rank-sum tests.
- Sequential tests: mSPRT, for continuous monitoring.
- Causal inference for observational data: synthetic control and difference-in-differences.
- Continuous experiments: multi-armed bandits with Thompson sampling, upper confidence bounds and contextual Bayesian optimization.
Standard errors use block bootstrap and the delta method, and regression-based methods correct bias.
The statistics engine for A/B tests.
- Choose a decision metric, for example rider gross bookings. XP gathers and validates the data.
- Validate. Sample ratio mismatch: if a 50/50 split produced 52/48, randomisation is broken and the results cannot be trusted. Flickers: users who switched groups, for example someone who moved from an iPhone in an iOS-only treatment to Android, are excluded.
- Classify the metric. Continuous (bookings per user), proportion (share of sign-ups who take a trip) or ratio (completed trips divided by requests, two columns per user).
- Preprocess. Clustering-based outlier removal. CUPED variance reduction (Deng, Xu, Kohavi and Walker, "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data", WSDM 2013) uses each user's pre-experiment behaviour to remove predictable variance. Difference-in-differences corrects pre-existing differences between groups, which matter at Uber because users vary so much.
- Compute the p-value. Welch's t-test is the default for continuous metrics. The Mann-Whitney U rank-sum test handles heavy skew. Chi-squared handles proportions. The delta method and bootstrap give standard errors for ratio metrics and small samples.
- Correct for multiple comparisons. With more than one treatment, Benjamini-Hochberg controls the false discovery rate.
- Power and sample size. Low power means many false negatives and a high false discovery rate. XP computes power, assuming a t-test, and the sample size needed to reach 0.8.
Metric recommendation. With over 1,000 metrics, experimenters miss important ones. XP uses item-based collaborative filtering, because which metrics go together depends on the experiment, not on the person (someone moving from Rider to Eats should not get Rider suggestions). Two scores are added with weights. The popularity score is the Jaccard index of how often two metrics are chosen together in past experiments. The absolute score is the Pearson correlation of the two metrics across a sample of users, which surfaces surprising links. Example: a test of driver supply hours should probably also track trips by new riders, because both sides of the marketplace move together.
Sequential testing for outage detection. Checking a fixed-horizon t-test every day ("peeking") inflates the false positive rate far above 5%. XP monitors metrics such as crash rate and trip frequency for running experiments with the mixture sequential probability ratio test (mSPRT; see Johari, Koomen, Pekelis and Walsh, "Peeking at A/B Tests: Why it matters, and what to do about it", KDD 2017). It mixes the likelihood ratio over a normal prior on the effect size, which gives a closed form. Under the null hypothesis the statistic is a martingale (its expected next value equals its current value), which yields confidence intervals that stay valid however often you look. Daily data from the same users is correlated, so XP estimates variance with delete-a-group jackknife or block bootstrap. Many metrics are monitored at once, so Benjamini-Hochberg is applied (rather than the stricter Bonferroni, because missing a real degradation is costly), with per-metric tuning of minimum detectable effect, power and a practical-significance tolerance. If the interval moves away from zero beyond the tolerance, the experiment is flagged or paused.
Continuous experiments with bandits. A bandit shifts traffic towards better variants while still exploring. The Uber Eats EMEA CRM team tested 10 email subject lines for open rate with a bandit and improved engagement compared with a classic test. The Eats data science team tuned the parameters of MOO, a multiple-objective linear-programming model that ranks restaurants on the home feed using conversion rate, booking fees and retention. A separate A/B test for each parameter combination would take too long, so they used contextual bandits and Bayesian optimization to search the black-box parameter space with personalisation.
Overlooked constraints.
- Marketplace interference. Treating some riders changes what drivers do for everyone. The post's answer for pre-existing bias is diff-in-diff and synthetic control; the general answer is switchback or geographic randomisation (see /case-studies/cs-experimentation-platform).
- Peeking is the default human behaviour. A platform that shows daily results must use sequential methods, or 5% becomes 20% or more.
- Too many metrics make false alarms certain. Monitoring 50 metrics at 5% each almost guarantees one false alert, which is why FDR control is necessary.
What Uber sacrificed. Some statistical power (sequential tests need more data than a single fixed-horizon test), clean learning in bandits (they optimise rather than measure precisely), and simplicity (many methods behind one engine), in exchange for valid results across thousands of experiments and early detection of harmful launches.
Deep Dive: Sample sizes, CUPED and why peeking breaks the 5%Show
Sample size. For a two-sided test at alpha 0.05 and power 0.8, each group needs about n = 16 times sigma squared divided by delta squared, where sigma is the standard deviation and delta the effect to detect. A metric with mean 10 trips per month and standard deviation 15, with an effect of 1% (0.1 trips), needs 16 times 225 divided by 0.01, which is 360,000 users per group. Detecting 0.5% needs 4 times as many.
CUPED. Let Y be the metric during the experiment and X the same metric before it. Use Y minus theta times (X minus the mean of X), with theta = cov(X, Y) divided by var(X). The variance shrinks by a factor of 1 minus rho squared, where rho is the correlation of X and Y. Riders' trip counts month to month might have rho = 0.7, which cuts variance by 49%, so the required sample nearly halves: 360,000 becomes about 184,000 per group. The estimate stays unbiased because X was measured before randomisation and cannot be affected by the treatment.
Peeking. Checking a fixed-horizon test daily for 20 days and stopping at the first p below 0.05 gives a real false positive rate of roughly 25% or more when there is no effect at all, because a random walk crosses a fixed boundary much more often than once in 20 tries. mSPRT's always-valid intervals widen early and narrow as data accumulates, so the chance of ever crossing under the null stays at 5% however often you look.
Benjamini-Hochberg. Sort m p-values from smallest to largest. Find the largest k with p(k) at most k divided by m times q, where q is the target FDR, and reject the first k. With 20 metrics and q = 0.05, the smallest p-value must be under 0.0025 and the tenth under 0.025. Bonferroni would demand 0.0025 for all of them, which misses more real degradations.
Lesson 28: Uber Eats query understanding, a food knowledge graph plus query2vec (2018)#
Assumptions. Data: thousands of restaurants and far more menu items per location, filtered by delivery radius. Latency: a search must be rewritten and answered within an interactive budget (the handbook assumes about 100 ms for the whole search, so 10 to 20 ms for rewriting). Freshness: new cities launch with almost no behaviour data. Correctness: some queries (dietary restrictions) must never be "expanded" loosely.
The problem. Intent is sometimes sharp ("bubble tea") and often vague ("something Asian"). An eater may search "udon" and happily order soba. A restaurant tagged "Chinese" may also sell Japanese dishes. Similar dishes have unrelated names. The delivery radius often means the exact match does not exist nearby, so plain text matching returns zero results. Classic NLP text matching works only when intent is clear.
Tool 1: a food knowledge graph. Restaurants, cuisines, dish types and menu items are heterogeneous entities with natural relationships, so Uber modelled them as a graph, in the tradition of large knowledge bases such as Google's Knowledge Vault (Dong et al., KDD 2014). The hard part is the ontology, the vocabulary of entity types, properties and relationships. It must be flexible enough to add facts easily, yet specific enough that the graph is more than a blob. The offline pipeline works in three stages:
- Ingest data from several sources (internal account data and external sources such as Foursquare) and transform it to fit the ontology.
- Classifiers de-duplicate and link records across sources, for example deciding that a Foursquare restaurant is the same as one in Uber's records. This is entity resolution.
- Store the result so that it can be queried in real time with low latency.
The graph is used in two complementary ways:
- Offline tagging annotates restaurants and items with rich tags, so that a restaurant selling udon dishes is findable even if "udon" is not in its name. This improves recall (the share of relevant results found).
- Online query rewriting expands the query in real time. "Asian" covers its subsets "Chinese" and "Japanese". "Udon" adds "ramen", "soba" and "Japanese".
Rewriting alone fails if restaurants are badly tagged, and tagging alone cannot interpret queries, so Uber combines both for accuracy and low latency. For the zero-result problem, for example "Shanghai Dumpling King" when the address is in San Jose but the restaurant only delivers in San Francisco, the graph links restaurant nodes to cuisines and to areas. So it can suggest nearby restaurants with similar cuisines instead of an empty page.
Tool 2: query2vec, learning from behaviour. Inspired by GloVe (Pennington, Socher and Manning, "GloVe: Global Vectors for Word Representation", EMNLP 2014), Uber treats each whole query as one "word". The "context" is the restaurant: two queries share a context if both led to an order from the same restaurant. "Spicy food" and "tan tan noodle" both leading to orders at a Hunan noodle house makes them neighbours. Uber builds a pointwise mutual information matrix: PMI(q1, q2) = log of p(q1, q2) divided by p(q1) to the power a times p(q2) to the power b. The joint probability comes from co-occurrence counts within the same restaurant, and the exponents a and b are tuning knobs that dampen very popular queries. A GloVe-style factorisation of this matrix gives one vector per query. These vectors serve as features in downstream models, and their distances drive query expansion. The exact model variant was chosen by online A/B tests.
Serving expansion fast. Finding the queries nearest to the input vector in real time is a nearest-neighbour search. Exact search over millions of query vectors is too slow, so Uber used approximate methods such as clustering the vectors to shrink the search space (see /technologies/tech-vector-databases for IVF and HNSW). "Tan tan noodles" with no nearby seller expands to "Szechuan", "Chinese" and "spicy food". Results for each expansion are retrieved, merged and ranked.
Why both tools are needed. Embeddings say how close two queries are, not how they are related. "Halal" sits near "Middle Eastern" and "Mediterranean" because many halal restaurants are also tagged that way, but the reverse does not hold. Expanding "halal" to non-halal restaurants misleads the eater badly, and the graph's typed relationships (dietary attribute versus cuisine) prevent that. Embeddings also need behaviour data, which a new city lacks, and searches for restaurants not on the platform produce no orders to learn from. The graph covers the cold start; embeddings cover associations nobody wrote into the ontology. Learning-to-rank then blends results from original and expanded queries.
Overlooked constraints.
- Geography bounds the answer set. In general web search the best page exists somewhere. In delivery, the best match may be 3 km outside the radius, so expansion is a core feature, not a nice-to-have.
- Similarity is not substitutability for hard constraints. Dietary, allergy and religious filters must be strict filters, never soft expansions.
- Entity resolution errors spread. A wrong merge of two restaurants corrupts tags and suggestions everywhere they are used.
What Uber sacrificed. Precision on some expanded queries (soba results for an udon search) and the cost of maintaining an ontology and an offline pipeline, in exchange for far fewer zero-result pages and better recall in thin markets.
Deep Dive: PMI intuition, popularity damping and expansion budgetsShow
PMI intuition. PMI compares how often two queries co-occur with how often they would co-occur by chance. Suppose "pizza" appears in 10% of restaurant contexts and "burger" in 8%. By chance they would co-occur in 0.8%. If they actually co-occur in 2%, PMI = log(0.02 / 0.008), about 0.92 in natural log, a positive association. "Halal" and "Mediterranean" at 1.5% observed against 0.3% expected gives log 5, about 1.6, a strong link, which is exactly why a typed graph must override the embedding for that query.
Why the exponents. With a = b = 1, a very rare query seen once at one restaurant gets a huge PMI with everything else there, which is noise. Raising p(q) to a power below 1 for the context marginal (word2vec's well-known 0.75 smoothing is the same idea) shrinks PMI for rare items and stops very popular queries from dominating. Tuning a and b is how Uber balanced the two.
Expansion budget (handbook's illustration). Each expanded query costs a retrieval call. With 3 expansions plus the original, retrieval load is 4 times the query rate. At 20,000 searches per second at peak, that is 80,000 retrievals per second. Teams therefore expand only when the original query's recall is low (for example under 10 results nearby), and cap the number of expansions, so that average load stays near 1.5 times rather than 4 times.
ANN by clustering. With 5 million query vectors in 1,000 clusters, a lookup compares against 1,000 centroids and then the 5,000 vectors in the nearest cluster or two. That is about 11,000 distance computations instead of 5 million, at a small recall loss for queries near a cluster boundary.
Lesson 29: The next-generation payments platform (2017 to 2018)#
Sources and limits. Uber's 2018 post summarises talks from a payments meetup rather than describing the design in detail, and the System Design Newsletter's piece on Uber payments (whose headline claims 30 million transactions per day) is mostly behind a paywall; only its tokenization section was readable. The facts below come from those two sources. Mechanisms the handbook spells out to explain them are marked as the handbook's illustration.
Assumptions. Traffic: millions of trips and orders a day, each causing several money movements (charge, driver pay, fees, taxes, tips, refunds). Latency: the rider must not wait for payment at drop-off, so collection can be asynchronous. Consistency: money must move exactly once, and every cent must be traceable. Maintenance: new lines of business (Eats, Freight, health, business travel), new payment methods and new countries keep arriving.
Design goals as stated by Uber, for the platform launched in 2017:
- high reliability through an active-active architecture;
- exactly-once processing through idempotency and strong consistency;
- auditability through double-entry bookkeeping;
- easy extension to new businesses, payment types and regions.
Collections and disbursements. The platform has two halves. Collections take money from riders and eaters through payment service providers. Disbursements pay drivers, couriers and restaurants through banks and payout providers. Money does not flow straight from rider to driver. A fare splits into driver earnings, Uber's fee, taxes and other fees, so the model needs entities (people and businesses), accounts owned by entities, and money movements between accounts.
Double-entry bookkeeping. Every movement is recorded as at least two entries, a debit and a credit, which sum to zero. The system can therefore always prove that money was neither created nor lost. The ledger is append-only: corrections are new reversing entries, never edits.
Asynchronous stream processing of immutable orders. A trip or meal produces an immutable payment order, a record of what is owed. Loosely coupled services consume orders from a stream and produce collections, ledger entries and payouts. Uber credits this design with cutting the time to launch a new business line in a new market from months to days, because a new business only emits orders in the standard shape.
Payment methods. Uber supports more than ten ways to pay through different processors: cards, Venmo, regional methods such as Paytm in India and iDEAL in the Netherlands, and Google Pay through its SDK. Adding one means threading it through many microservices and testing it at several levels.
Tokenization (from the newsletter). Card numbers never touch Uber's servers or stay on the phone. The provider's SDK in the app sends the card details directly to the payment provider, together with metadata (the Uber account and the method type). The provider returns a token that stands for the card and is bound to that metadata. A stolen token is useless elsewhere because only Uber's account can charge it. This keeps most of Uber's systems out of PCI DSS scope.
Patterns from the "To the Nines" talk on the processing system:
- Storing request metadata for idempotent multiplexing and retries, so that a retried call to a bank or provider reuses the same identity and cannot charge twice.
- Generating external IDs efficiently when a partner allows only a small ID namespace (for example a short reference field).
- Deterministic batching with reliable scheduling, so that a batch payout file can be regenerated identically after a crash and processed idempotently.
Overlooked constraints.
- The outside world is not idempotent by default. Banks and processors time out, and some lack idempotency keys or allow only short reference IDs. The platform must create safety with stored metadata and deterministic IDs.
- Batch payouts are the riskiest step. A payout file sent twice pays drivers twice, and recovering that money is slow and painful, hence deterministic batching.
- Active-active plus exactly-once is a real tension. Two regions processing the same order must not both charge it. That requires strong consistency on the idempotency record, which costs cross-region latency on writes (see /scaling-data/multi-region-data).
What Uber sacrificed. Synchronous simplicity (money moves later, through streams, so "paid" is a state the UI must track), write latency (strongly consistent idempotency records), and effort on reconciliation and ledger tooling, in exchange for exactly-once money movement, full auditability and fast launches of new businesses.
Deep Dive: A fare in double entry, and why deterministic batches matterShow
A 20.00 trip in double entry (handbook's illustration). Accounts: rider receivable, PSP clearing, driver payable, Uber revenue, tax payable.
- Trip completes: debit rider receivable 20.00; credit driver payable 14.40, Uber revenue 4.00, tax payable 1.60. The debits equal the credits.
- Card charged: debit PSP clearing 20.00, credit rider receivable 20.00. The rider receivable is now zero.
- PSP settles to the bank: debit bank 19.40 and PSP fees expense 0.60, credit PSP clearing 20.00.
- Weekly payout: debit driver payable 14.40, credit bank 14.40.
At every step, the sum of all balances is zero. Any non-zero total, or any account balance that disagrees with the external statement, is an alarm.
Volume. At 30 million transactions a day (the newsletter's headline figure), with an average of 4 ledger entries each, the ledger grows by 120 million rows a day, or about 1,400 per second on average and perhaps 5,000 per second at peak. At 200 bytes per entry that is 24 GB a day. Because entries are append-only, the store can be partitioned by account and time, with old partitions moved to cheaper storage.
Deterministic batching. Suppose 2 million driver payouts are due on Monday. If the batch job selects "all unpaid payouts now", a crash and rerun at 10:05 may include payouts created after 10:00 and produce a different file with different IDs, and the bank may accept both files. Making the batch deterministic means its contents are a pure function of a cut-off time and a batch ID, for example all payouts with created_at before Monday 00:00 in region EU, batch 2026-W49-EU-01. The file and each line's external ID are derived from that, so a rerun produces byte-identical output, and the bank or Uber's own check rejects the duplicate. When the partner's reference field is short, IDs can be built as a compact encoding of the batch number plus line number. That keeps them unique within the namespace instead of relying on random IDs that might collide.
Idempotent multiplexing. One internal "charge" may fan out to several provider calls (authorise, capture, maybe a 3-D Secure challenge). Storing the metadata of each outbound request keyed by the internal idempotency key means a retry of the internal request replays the same outbound calls with the same keys rather than inventing new ones. See /apis/idempotency and /case-studies/cs-payment-system.
Family 7: Synthesis
Lesson 30: Recurring patterns across Uber's posts#
Read side by side, Uber's posts repeat a handful of moves. Each is a reusable design decision with a known price.
| Pattern | Where it appears | What it buys | What it costs |
|---|---|---|---|
| Discretize the world into stable IDs | Lesson 1 H3 cells, Lesson 3 road segments, Lesson 15 Pinot segments | Aggregation, joins and sharding on a simple key | Error at cell or segment edges; resolution choice is hard to change |
| Shard state in application memory, route to the owner | Lesson 2 Ringpop, Lesson 11 Herb tasks, Lesson 20 Streamgate | No database on the hot path for ephemeral state | Rebalance pain on membership change; state lost on crash |
| Append-only, immutable records | Lesson 7 Schemaless cells, Lesson 14 Hudi commits, Lesson 29 payment orders and ledger | Idempotent replays, simple replication, audit trail | Storage growth, compaction and "latest version" logic |
| Logs as the integration bus | Lessons 7 triggers, 10 Flux CDC, 11 Herb, 16 uReplicator, 17 retry topics | Loose coupling, replay, many consumers | Ordering, lag and duplicate handling in every consumer |
| Build in-house when nothing fits, then open source | H3, Ringpop, Jaeger, M3, Ludwig, Hudi, uReplicator, Cadence | Exact fit and community help | Years of ownership and migration when the industry moves |
| Strong consistency only where money or assignment demands it | Lesson 5 Spanner, Lesson 8 Raft per partition, Lesson 29 idempotency records | One driver per trip, one charge per order | Write latency and cross-region cost |
| Protect the core by priority, not by luck | Lessons 22 to 24 QALM, Cinnamon, auto-tuner | Critical traffic survives overload | Priority metadata everywhere; tuning controllers |
| Measure in production, not offline | Lesson 18 M3, 19 Jaeger, 25 model monitoring, 27 sequential tests | Problems found in hours, not weeks | Pipelines and storage for telemetry itself |
| Organize the fleet like a program | Lesson 6 DOMA layers and gateways, Lesson 25 one ML platform | Fewer touch points and clearer ownership | Platform teams and gateway design effort |
The deeper theme: local marketplaces on a global platform. Supply and demand meet in a few square kilometres, but accounts, payments and data are global. Many posts are about drawing the line between them. Local, fast and approximate state includes H3 cells, Ringpop's in-memory driver locations and region-local Pinot tables. Global, durable and exact state includes trips on Spanner, payments with idempotency and double entry, and Docstore with Raft. Asynchronous logs (Herb, uReplicator, Kafka) connect the two.
What Uber sacrificed overall. Uber repeatedly paid with engineering ownership for exact fit. It built and ran its own datastores, replicators, metrics, tracing, push, ML and experimentation platforms. That bought scale and speed during hypergrowth, but it also brought migrations away from home-grown systems when the industry caught up: Schemaless to Docstore, Merckx to Jaeger and then OpenTelemetry, SSE to gRPC, the original fulfillment stack to Spanner. A smaller company should usually rent what Uber had to build.
Deep Dive: when to build, when to buy, and the cost of strong consistencyShow
Build versus buy (handbook's illustration). A platform team of 8 engineers at a loaded cost of 250,000 dollars each is 2 million dollars a year. If an in-house metrics store saves 30% of a 10 million dollar vendor bill, it pays for itself with 1 million dollars to spare. At a 1 million dollar bill it never does. Uber's choices made sense because its scale multiplied the savings. M3's 6.6 billion series would cost far more at per-series vendor prices.
Strong consistency budget. A Spanner-style write across 3 regions with a 30 ms round trip between the two nearest commits in about 30 to 60 ms, while a single-region quorum write takes 5 to 10 ms. If a trip lifecycle makes 20 consistent writes, the difference is about 0.5 to 1 second spread over a trip lasting many minutes, which is acceptable. A location update every 4 seconds for 5 million drivers is 1.25 million writes per second. Doing that globally and consistently would be wasteful and slow, which is why locations stay in local, ephemeral memory (Lesson 2) and only trips and payments pay for consistency.
Ordering guarantee as a cost line. Per-key ordering (Kafka partition, Herb per-origin order) is cheap. Total ordering across keys requires one sequencer or consensus on every write. Every Uber design here chose per-key ordering and handled cross-key cases with idempotency and reconciliation.
Cross-cutting: hot keys, write bursts, indexed queries, push and caching, seen through Uber#
Several classic interview problems map directly onto Uber's posts.
1. Millions of concurrent reads for the same cached data. A hot key is one key with an outsized share of traffic, such as a popular restaurant menu during a promotion or a city's surge multiplier read by every rider app. A sharded cache still keeps each key on one node, so one node melts while others idle. Answers, from cheapest up:
- An in-process cache in each service instance with a 1 to 5 second TTL. Each of N instances reads the shared cache at most once per TTL, so load on the hot key becomes N divided by the TTL, independent of user traffic. The cost is a few seconds of staleness, which surge multipliers and menus tolerate.
- Request coalescing (single-flight): concurrent misses for the same key wait on one fetch. This also prevents the cache stampede, when a popular entry expires and thousands of requests rebuild it at once. Add jittered TTLs so many keys do not expire together, and refresh ahead of expiry (or "stale while revalidate") for the hottest ones.
- Hot-key replication: store copies under suffixed keys spread across cache nodes and read a random copy. Writes must update or invalidate every copy.
- Decouple cache sharding from database sharding. This was an explicit CacheFront goal (Lesson 10). A hot Docstore shard need not be a hot cache node because Redis keys are spread by their own hash.
- Invalidation that must be visible immediately. CacheFront combines a TTL, CDC from the binlog (seconds), version-checked writes so stale data cannot overwrite fresh data, and an explicit invalidate-after-write API for read-your-writes. Data that truly needs immediate visibility, like an eater's cart, simply bypasses the cache.
See Distributed caching and the Scaling reads pattern.
2. Handling write bursts with queues and load shedding. New Year's Eve at midnight or the end of a concert creates request spikes several times the normal peak. There are two complementary tools:
- Write queues absorb bursts. Put non-urgent writes (trip events for analytics, notifications, ledger postings) on Kafka and let consumers drain at the rate the database can sustain. Queues smooth bursts but do not create capacity. If the arrival rate stays above the drain rate, the backlog and the delay grow without limit, so watch consumer lag and set a maximum acceptable delay. Uber's retry topics and DLQs (Lesson 17) keep failed messages from blocking the queue.
- Load shedding protects what must be synchronous. Requests that need an answer now (request a ride, accept an offer) cannot wait in a long queue, because a reply after the client has timed out is wasted work. QALM and Cinnamon (Lessons 22 to 24) drop low-priority requests first, using queue delay rather than queue length as the overload signal. Shed early and cheaply at the edge, before any expensive work.
- Batching and hierarchical aggregation. Group many small writes into one (M3 aggregates 500 million points per second down to 20 million stored, Lesson 18), and aggregate in tiers (per host, per region, then global) so no single node sees the full write rate.
- Hot write keys. A single counter, like trips in progress in one city, can be split into N sub-counters (key#0 to key#N) and summed on read. This can be done for all keys, or only for keys detected as hot.
See the Scaling writes pattern and Rate limiting.
3. Indexed databases for real-time querying. In a matching feed like Tinder's, or a "drivers near me" query, the request filters by location plus attributes (age range and preferences; vehicle type and status). The good solution indexes the fields the query uses, especially a geospatial index, in a search-optimized store such as Elasticsearch or OpenSearch, so results come back in tens of milliseconds. The challenge is keeping that index consistent with the primary database. The fix is change data capture from the primary into the index, with batched writes, because search engines are tuned for reads and suffer under many small writes (each refresh creates segments to merge). Uber's version: driver locations bucketed into H3 cells (Lesson 1) and held in memory, sharded by Ringpop (Lesson 2), because positions change every few seconds, which is too fast for a search index's refresh cycle. Precomputed results in a cache are another option, but active users exhaust them and they go stale. The strongest design combines an indexed store for freshness with precomputation for the first page. See Geospatial indexing, Elasticsearch and Change data capture.
4. Server-Sent Events for push. SSE is a standard on top of HTTP where the server keeps one response open and streams many small messages, each processed by the client as it arrives, instead of one complete JSON body at the end. Its limits are practical:
- Servers, load balancers and proxies close long-lived connections, so the client must reconnect and send the last event ID it saw, and the server must keep recent messages to resend what was missed.
- Some misbehaving networks buffer the streamed response and deliver it in one lump, which defeats the purpose.
- It is one-way, so acknowledgements need separate requests.
RAMEN Gen 2 (Lesson 20) used exactly this model: sequence numbers for resumption, a 4 second heartbeat with a 7 second timeout to detect dead connections, and acknowledgements on a separate call every 30 seconds. Those limits, plus head-of-line blocking and the cost of separate ack calls, are why Uber moved to gRPC bidirectional streams (Lesson 21) while keeping SSE as a fallback. In an interview, SSE is a strong answer for one-way live updates such as auction prices, driver location on the rider's map or order status. See Real-time communication and the Real-time updates pattern.
5. Cache architectures.
- Cache-aside (lazy loading) is the default: the application checks the cache, and on a miss reads the database, stores the result and returns it. Only requested data is cached, but each miss pays extra latency. CacheFront (Lesson 10) is cache-aside built into the database's query layer, with asynchronous cache fills so misses do not wait on Redis writes.
- Write-through: the application writes to the cache, which writes synchronously to the database before acknowledging. Reads are always fresh, but writes are slower, the cache fills with data that may never be read, and the dual-write problem remains if one write fails (Redis needs application code or a library for this).
- Write-behind (write-back): the cache acknowledges immediately and flushes to the database in batches later. Writes are very fast, but a crash before flushing loses data, so it suits metrics and analytics, not trips or payments.
- Read-through: the cache acts as a proxy that loads misses itself. CDNs work this way; for application caches with Redis, cache-aside is far more common.
6. Distributed system building blocks. The classic list of distributed-systems primitives (heartbeats, service discovery, consensus, distributed locking, gossip, circuit breakers, disaster recovery, distributed tracing) shows up across Uber's posts:
- Heartbeats: RAMEN's 4 second SSE heartbeats and 5 second gRPC heartbeats (Lessons 20, 21).
- Gossip and failure detection: SWIM in Ringpop (Lesson 2) and Cassandra's gossip, including the stale-DNS bug of Lesson 12.
- Service discovery: UNS for Herb (Lesson 11) and discovery-based contact points for Cassandra clients (Lesson 12).
- Consensus: Raft per Docstore partition (Lesson 8), Paxos in Spanner (Lesson 5) and Cassandra LWTs (Lesson 12), and etcd in M3 (Lesson 18).
- Coordination and locking: Helix and ZooKeeper for Pinot and uReplicator (Lessons 15, 16). Kleppmann's point that a lock needs fencing tokens to be safe under pauses ("How to do distributed locking", 2016) is why designs here prefer single ownership plus idempotency over locks.
- Circuit breakers and shedding: QALM and Cinnamon (Lessons 22 to 24).
- Disaster recovery: active-active data centres with Herb (Lesson 11) and region failover for push (Lesson 20).
- Distributed tracing: Jaeger (Lesson 19), whose context also carries Cinnamon's priorities (Lesson 23).
See Failure detection and gossip, Consensus, Leader election and coordination, Resilience patterns and Disaster recovery.
7. Reading other companies' engineering articles the same way. The commonly recommended must-read posts include Discord storing trillions of messages, Netflix in-video search, Canva scaling media uploads to 50 million a day, Airbnb avoiding double payments in a distributed payments system, Stripe's ten years of payments APIs, and Slack's real-time messaging. They reward the same four questions this page asks: assumptions, production architecture, overlooked constraints and sacrifices. The Airbnb and Stripe articles pair with Lesson 29 (idempotent money movement), Slack and Discord with Lessons 20 and 21 (persistent connections), and Canva with Lessons 13 and 14 (pipelines that grow by orders of magnitude). See Discord engineering and Netflix engineering.
Deep Dive: sizing a hot key, a burst queue and an SSE fleetShow
Hot key (handbook's illustration). A surge multiplier for a stadium area is read by 400,000 app opens in 2 minutes after a match, about 3,300 reads per second, by 300 service instances. With a 2 second in-process TTL, the shared cache sees at most 300 divided by 2, or 150 reads per second for that key, a 22-fold cut, and the multiplier is at most 2 seconds stale. Surge is recomputed every minute or so anyway, so this costs nothing in practice.
Burst queue. Trip-completion events normally arrive at 2,000 per second and peak at 12,000 per second for 10 minutes on New Year's Eve. A consumer fleet that drains 5,000 per second builds a backlog of (12,000 minus 5,000) times 600 seconds, which is 4.2 million events. Draining it at the 3,000 per second of spare capacity after the peak takes about 23 minutes. If 30 minutes of delay is acceptable for analytics and receipts, no extra capacity is needed. If receipts must arrive within 1 minute, the consumers must scale to 12,000 per second or receipts must get a separate, higher-priority topic.
SSE fleet. 5 million connected apps with a 4 second heartbeat produce 1.25 million heartbeat frames per second of about 50 bytes each, roughly 62 MB per second, or 500 Mbps, before any real messages. Raising the heartbeat to 15 seconds cuts this to about 130 Mbps but makes dead connections take up to 30 seconds to detect. At about 20 KB of memory per idle connection, 5 million connections need about 100 GB of RAM across the fleet, for example 50 servers with 2 GB each for sockets plus headroom.
When to Use It#
Study the Uber posts when:
- You are designing ride-hailing, delivery or any location marketplace. Lessons 1 to 5 cover grids, in-memory location sharding, routing, ETAs and consistent assignment.
- You need a datastore story beyond "use Postgres". Lessons 7 to 12 show an append-only store on MySQL, its evolution to a Raft-based SQL store, an integrated cache, cross-datacentre replication and Cassandra operations.
- You are building data pipelines with late, changing data. Lessons 13 to 18 cover incremental lakes (Hudi), real-time OLAP (Pinot), Kafka replication, retries and metrics at billions of series.
- You run many services under unpredictable load. Lessons 6 and 19 to 24 cover domain layering, tracing, push at millions of connections and priority-aware load shedding.
- You are designing ML, experimentation, search or payments platforms. Lessons 25 to 29 cover feature stores, declarative deep learning, statistical engines, query expansion and exactly-once money movement.
When NOT to Use It#
- Do not copy the build-everything habit. Uber built many of these systems because nothing on the market fitted at its scale in 2014 to 2018. Today managed Kafka, Spanner or CockroachDB, Prometheus-compatible stores, OpenTelemetry, Pinot, Hudi or Iceberg, and managed ML platforms cover most needs.
- Do not adopt 2,200 microservices. DOMA (Lesson 6) is a cure for a disease that a team of 50 engineers does not have. A modular monolith or a dozen services is the right start.
- Do not take posts as current state. Uber moved from Schemaless to Docstore, from SSE to gRPC, and from Merckx to Jaeger. Treat each post as a snapshot and its numbers as of its date.
- Do not use the marketplace's eventual consistency for money. Location and supply can be approximate; payments and assignment cannot. Use Lessons 5 and 29, not Lesson 2, for those.
- Do not copy machine-learning platforms before you have models. Michelangelo was built after dozens of teams already had models in production. One model needs a notebook, a scheduled job and a monitoring dashboard.
How to Implement It#
Apply the lessons in this order for a ride or delivery marketplace.
- Bucket locations into a hierarchical grid such as H3 (Lesson 1), choosing a resolution near the scale of your decisions (about 0.1 km squared for pickup areas).
- Keep live driver locations in memory, sharded by cell, with consistent hashing and membership by gossip or a coordinator (Lesson 2). Do not write every ping to a database.
- Use a routing engine with contraction hierarchies or a similar preprocessing method, plus a learned correction for ETAs (Lessons 3 and 4).
- Store trips and offers in a strongly consistent store with transactions (Lesson 5), so one driver cannot be given two trips.
- Group services into domains and layers with gateways (Lesson 6) once you have more than a few dozen services.
- Write immutable events and publish them through CDC into Kafka (Lessons 7, 10, 11), with retry topics and DLQs (Lesson 17).
- Build the lake incrementally with Hudi or Iceberg (Lesson 14), and serve real-time dashboards from Pinot or a similar OLAP store (Lesson 15).
- Instrument with metrics, traces and priority propagation from day one (Lessons 18, 19, 23).
- Push updates over a persistent stream with sequence numbers, heartbeats and a fallback (Lessons 20, 21).
- Shed load by priority at every service with a queue-delay signal and adaptive concurrency (Lessons 22 to 24).
- Move money through idempotent, double-entry flows with deterministic batches (Lesson 29), and ship models and experiments through shared platforms once several teams need them (Lessons 25 to 27).
A per-service load-shedding and caching configuration in the style of Lessons 10 and 23 (handbook's illustration):
service: offer-service
shedder:
priority:
source: request_header # set at the edge, carried in trace context
tiers: 6 # 0 is most critical
cohorts_per_tier: 128 # 768 buckets in total
overload_signal:
queue_not_empty_for_ms: 10000
target_queue_delay_ms: 5
controller:
type: pid
interval_ms: 1000
concurrency:
type: vegas
min_limit: cpu_cores
max_limit_multiplier: 10 # relative to observed concurrency
timeout_fraction_of_deadline: 0.33
cache:
mode: cache_aside
scope: table_menus # carts bypass the cache
ttl_seconds: 300
invalidation: [cdc_binlog, explicit_after_write]
version_check: row_timestampTechnology choices.
| Need | Uber choice | Alternatives | When each fits |
|---|---|---|---|
| Spatial index | H3 | S2, geohash, PostGIS R-trees | S2 for exact cell coverings; geohash for simple prefixes; PostGIS for polygons in SQL |
| In-memory sharding | Ringpop | Akka Cluster, Orleans, Kubernetes with a coordinator | A coordinator such as ZooKeeper or etcd for smaller, steadier fleets |
| Transactional store | Spanner, Docstore | CockroachDB, YugabyteDB, Vitess | CockroachDB or YugabyteDB outside Google Cloud; Vitess for MySQL shops |
| Append-only store | Schemaless on MySQL | DynamoDB, Cassandra, Bigtable | DynamoDB to avoid operations; Cassandra for multi-region writes |
| Cache | CacheFront over Redis | Memcached, DAX for DynamoDB, plain Redis cache-aside | Plain Redis cache-aside until invalidation becomes a team-wide problem |
| Lake table format | Hudi | Apache Iceberg, Delta Lake | Iceberg for broad engine support; Delta for Databricks users |
| Real-time OLAP | Pinot | Apache Druid, ClickHouse | ClickHouse for simpler operations; Druid for time-series rollups |
| Kafka replication | uReplicator | MirrorMaker 2, Confluent Replicator, Cluster Linking | MirrorMaker 2 for most teams today |
| Metrics | M3 | Prometheus with Thanos or Mimir, VictoriaMetrics | Prometheus-compatible stores unless you have billions of series |
| Tracing | Jaeger | OpenTelemetry with Tempo, Zipkin, vendor APM | OpenTelemetry SDKs everywhere, with any backend |
| Push | RAMEN on gRPC | WebSockets, SSE, MQTT, Firebase Cloud Messaging | SSE for one-way web updates; MQTT for constrained devices |
| Load shedding | Cinnamon | Netflix concurrency-limits, Envoy adaptive concurrency | Envoy's filter if you run a service mesh |
| Workflows | Cadence | Temporal, AWS Step Functions | Temporal for new projects; Step Functions on AWS |
| ML platform | Michelangelo | SageMaker, Vertex AI, Kubeflow, Feast for features | Managed platforms for small teams |
| Experiments | XP | Optimizely, Statsig, Eppo, GrowthBook | A vendor until you need marketplace-specific methods |
Trade-offs#
| Choice Uber made | What it bought | What it cost |
|---|---|---|
| Hexagonal grid for all spatial logic | Uniform neighbours, comparable cells, cheap joins | Pentagons, approximate edges, a fixed resolution choice |
| Application-level sharding with Ringpop | No database on the location hot path | Rebalance storms, lost state on crash, hard debugging |
| Building Schemaless on MySQL | A trusted engine and append-only simplicity | A narrow API, later migrated to Docstore |
| Spanner for fulfillment | Transactions across trips, offers and drivers | Latency on every write, cost, cloud dependency |
| CacheFront in the query layer | Transparent caching, one team owns it | Staleness windows; caching limited to simple read shapes first |
| Active-active with eventual replication | Survives a data centre loss | Conflicts and cross-region staleness to manage |
| Incremental lake with Hudi | Minutes instead of 24 hours of latency | Merge-on-read complexity and compaction tuning |
| Pinot for real-time OLAP | Sub-second analytics over fresh data | Heavy operations: segments, tenants, ZooKeeper load |
| Priority-based load shedding | Critical flows survive overload | Priority must be set correctly at the edge and carried everywhere |
| gRPC bidirectional push | Acks in-band, lower latency, one protocol | Mobile network quirks, a proxy layer, SSE fallback kept |
| In-house platforms | Exact fit during hypergrowth | Years of ownership and later migrations |
Common Pitfalls#
- Writing every location ping to a database. Live positions are worthless in a minute. Keep them in memory and persist samples for analytics through a log.
- Using one grid resolution for everything. Pricing, dispatch and analytics need different cell sizes. Use the hierarchy, not one level.
- Mixing ephemeral and money data in one consistency model. Approximate is fine for supply; it is a bug for charges.
- Caching without a version check. A slow read that fills the cache after a fresh write can store an old value for a full TTL. Compare versions on every cache write.
- Retrying in place on the main topic. A poison message blocks its partition. Use retry topics with delays and a DLQ.
- Shedding by queue length. A long queue that drains quickly is fine; a short one that never empties is not. Shed by queue delay.
- Letting every caller default to "critical". Priority only works if most traffic is not top priority. Assign priorities centrally at the edge.
- Peeking at experiment results daily with a fixed-horizon test. The real false positive rate rises far above 5%. Use sequential tests for monitoring.
- Computing features differently in training and serving. Put transformations in one shared definition, as Michelangelo's DSL did.
- Non-deterministic payout batches. A rerun that produces a different file can pay people twice. Derive batch contents and IDs from fixed inputs.
Real-World Examples#
- Lyft built the Envoy proxy, now a CNCF project used as the data plane in many service meshes, to handle the same service-to-service problems DOMA and Ringpop's forwarding addressed at Uber.
- Google Spanner (Corbett et al., "Spanner: Google's Globally-Distributed Database", OSDI 2012) is the database behind Lesson 5, and its TrueTime idea inspired CockroachDB and YugabyteDB.
- LinkedIn created both Apache Kafka and Apache Pinot, the two systems behind several of Uber's data lessons.
- Facebook's Gorilla time series database introduced the compression that M3TSZ builds on (Lesson 18).
- Twitter created Zipkin, the tracer Uber prototyped with before building Jaeger (Lesson 19). Both follow Google's Dapper design.
- Airbnb and Stripe have written about idempotent payment processing, the same problem as Lesson 29. See Payment system case study.
- Netflix and Discord appear in this handbook's other blog pages, with their own versions of concurrency limits, push and hot-key handling. See Netflix engineering and Discord engineering.
In the Interview#
Deep Dive: designing a small ride-hailing app with Uber's lessonsShow
Requirements (handbook's illustration). One country, 50,000 online drivers at peak, 500,000 trips a day, peaking at 30 trip requests per second, with bursts to 150 per second on holidays. Drivers send a location every 4 seconds.
Location. 50,000 drivers divided by 4 seconds is 12,500 updates per second, each about 50 bytes, about 625 KB per second. That fits in the memory of 2 or 3 location servers sharded by H3 resolution-7 cell, with a third for failover. Store one sample every 30 seconds to Kafka for analytics instead of every ping. A nearby search for a rider looks at the rider's cell and its first ring (7 cells at resolution 8, about 5 km squared) and returns perhaps 20 candidates.
Matching and trips. 30 requests per second at peak, each doing about 10 transactional writes (trip, offer, driver state), is 300 writes per second. That is easily handled by a single PostgreSQL primary with a synchronous replica, or by CockroachDB if you need multi-region. Use a conditional update on the driver's status ("set busy where status is available") to prevent double assignment. Spanner-class global consistency is not needed at this scale.
Payments. 500,000 trips a day with 4 ledger entries each is 2 million rows a day, about 23 per second. One PostgreSQL ledger table partitioned by month is enough for years. Every charge uses a stored idempotency key; payouts run as deterministic weekly batches.
Push. 50,000 drivers plus up to 100,000 riders with open apps is 150,000 connections. Two or three gRPC or WebSocket gateway servers handle this; use a 10 second heartbeat. Riders on the web can use SSE.
Overload. At 150 requests per second during bursts, shed analytics and "fare estimate" calls before "request ride" and "accept offer". A simple priority header and a concurrency limit per service cover this. A full PID controller is unnecessary.
Data. CDC from PostgreSQL to Kafka to an object-store lake with Iceberg or Hudi; ClickHouse or Pinot for a live demand-per-cell dashboard.
What to say about trade-offs. This design keeps live locations ephemeral and approximate, gives assignment and money strong consistency on one primary, and accepts minutes of delay for analytics. Moving to Uber's architecture is warranted only when a single primary or a single region stops being enough.
Key Takeaways#
- Discretize space once and reuse it everywhere. H3 cells became the shared key for pricing, dispatch, analytics and ML.
- Match consistency to what is at stake. Ephemeral locations live in memory; trips use transactions on Spanner; money uses idempotency and double entry.
- Immutable logs are the backbone. Schemaless cells, Herb, Flux CDC, uReplicator, Hudi commits and payment orders all rely on append-only records that can be replayed safely.
- Caching at scale is an invalidation problem. CacheFront needed TTLs, CDC, version-checked writes and explicit invalidation to reach 40 million reads per second safely.
- Incremental beats full recompute. Hudi turned 24-hour lake latency into minutes by upserting only what changed.
- Shed by priority and by queue delay. QALM, Cinnamon and the Vegas auto-tuner keep critical flows alive under overload with almost no overhead.
- Platforms come after repetition. Michelangelo, XP, DOMA gateways and RAMEN each replaced many one-off team solutions.
- Measure live and correct statistically. Model monitoring, sequential tests and FDR control catch problems in hours without false alarms.
- Build only what you must, and plan the migration. Many of Uber's in-house systems were later replaced or rebuilt. That was the price of exact fit during hypergrowth.