Case Study: Uber — Location, Driver Tracking, Matching, Pricing, Trip Storage
"Geospatial, the first layer of Uber’s matching system, keeps track of the real-time location of every active online driver partner on our platform" — Uber Engineering, How Ringpop from Uber Engineering Helps Distribute Your Application, Uber Blog, 4 February 2016
Summary: Uber is a real-time two-sided marketplace: millions of phones report where they are, a matcher pairs riders with drivers within seconds, prices move per neighbourhood, and every trip becomes a record that billing, payouts, support and analytics read for years. This page rebuilds that system from Uber's own engineering posts, papers and talks, and labels everything else as inference. Focus: location ingestion (4-second pings, ephemeral state, the phone as a state carrier), geospatial indexing (Google S2 in 2015, Uber's H3 hexagons from 2018), supply, demand and DISCO matching, Ringpop (SWIM gossip, consistent hashing, handle or forward), geofences, ETA and the routing engine, surge and dynamic pricing per hexagon, trip storage (Mezzanine, Schemaless, Docstore on MySQL, and the 2016 Postgres to MySQL post with its critiques), real-time push (RAMEN, SSE, gRPC over QUIC), Kafka, uReplicator and Flink, DOMA, M3 and Jaeger, multi-region failover, Cadence, and payments with idempotency, with Go and Laravel 13 re-implementations of the core mechanisms. Learning goal: Walk through the 4-step method for a ride-hailing system, defend each decision with the published Uber evidence (or say clearly that it is an inference), and know which generic chapter of this site holds the reusable mechanism.
This is the first chapter of the Case Studies group. It applies The 4-Step Approach to one company and does not re-teach the mechanisms: cells and k-rings live in Geospatial Indexing, SWIM in Gossip Protocols, ring internals in Consistent Hashing, SSE and WebSockets in Real-Time Communication, the broker in Kafka in Depth, workflows in Durable Workflows & Jobs and money movement in Payment Processing Architecture.
How to read the claims on this page
Every architecture statement about Uber cites an Uber engineering post, an Uber paper, Uber's open-source documentation, or a talk by an Uber engineer, all fetched and listed in References. Dates are the publication dates of those posts; a 2016 post describes 2016, not today. Anything I derived, generalised or guessed is marked inference. Code on this page is a small teaching re-implementation, never Uber's code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole system in three tables | Everything in one minute |
| Why study Uber at all, and the core trade-off | Why it exists |
| Which post says what, and when | Where it comes from, What changed over time |
| Requirements and numbers (steps 1 and 2) | Step 1: scope, Step 2: estimate |
| The high-level picture (step 3) | Step 3: high-level design |
| Driver location pings, update rate, state digest | Location ingestion |
| S2 and H3 | Geospatial indexing at Uber |
| Supply, demand, DISCO | Matching and dispatch |
| Ringpop, SWIM, consistent hashing | Ringpop |
| Geofences, ETA, routing engine | Geofences, ETA and routing |
| Surge pricing | Pricing |
| Trip storage, Schemaless, Docstore, Postgres vs MySQL | Mezzanine and Schemaless, Postgres to MySQL, Docstore |
| Pushing to phones | Push to mobile clients |
| Kafka, uReplicator, Flink, AthenaX | Streaming |
| DOMA | Microservices and DOMA |
| M3, Jaeger | Observability |
| Multi-region failover, Cadence, Temporal | Reliability and workflows |
| Payments, idempotency | Payments |
| Exact knobs and messages | Mechanics |
| Code | Go, Laravel |
| Classic interview problems on this system | Solving the classic problems |
| What to copy into your own system | What you can copy, Choosing |
| Monolith to distributed system | In architecture |
| Runnable demo and drills | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The subsystems and what Uber published about each.
| Subsystem | What Uber published (short) | Year of the source | Generic mechanism |
|---|---|---|---|
| Location ingestion | Driver phones post location every four seconds; Geospatial holds the live positions in memory, not in a database | 2015 talk, 2016 post | Geospatial Indexing |
| Geospatial index | Google S2 cells to shard supply (2015); H3 hexagons for pricing and dispatch analysis (2018) | 2015, 2018 | Cell index, k-ring |
| Matching | Supply and demand services plus DISCO (Dispatch Optimization) which also considers drivers about to become free | 2015 | Bipartite matching on ETA (inference for the algorithm) |
| Membership and sharding | Ringpop: SWIM gossip, consistent hash ring with replica points, handle or forward over TChannel | 2016 | Gossip Protocols, Consistent Hashing |
| Geofences | A Go service answering point-in-geofence on every app request; p99 under 100 ms at hundreds of thousands of QPS | 2016 | Polygon containment, two-level index |
| ETA | A routing engine sums road-segment times; an ML model (DeepETA) predicts the residual | 2022 | Physical model plus learned correction |
| Pricing | Surge computed from supply and demand per hexagon; a Flink job per region | 2018, 2020 | Per-cell ratio over a stream (inference for the formula) |
| Trip storage | Mezzanine (2014) moved trips from one Postgres to Schemaless: append-only cells on sharded MySQL | 2015, 2016 | Sharding at System Level |
| Database engine | "Why Uber Engineering Switched from Postgres to MySQL": write amplification, physical replication, upgrades, connections | 2016 | MVCC, Replication |
| Docstore | Schemaless evolved into a transactional, schema-enforcing store: MySQL plus Raft per partition | 2021 | Distributed SQL |
| Push | RAMEN: Fireball decides when, SSE delivers with sequence-number acks (2015); later gRPC bidirectional over QUIC | 2020, 2022 | Real-Time Communication |
| Streaming | Kafka with trillions of messages per day, uReplicator across regions, Flink and FlinkSQL (AthenaX) | 2016 to 2021 | Kafka, Stream Processing |
| Service architecture | About 2,200 critical microservices grouped into domains, layers, gateways and extensions (DOMA) | 2020 | Microservices |
| Observability | M3 metrics platform (Prometheus remote storage); Jaeger distributed tracing | 2017, 2018 | Observability |
| Reliability | Active-active Kafka, region failover of surge; Cadence workflows (Temporal's predecessor) | 2020, 2023 | Durable Workflows |
| Payments | Active-active, exactly-once by idempotency and strong consistency, double-entry bookkeeping | 2018 | Payment Processing |
Numbers that come from Uber's own sources.
| Fact | Value | Source (see References) |
|---|---|---|
| Driver location update rate | Every four seconds | InfoQ write-up of Matt Ranney's QCon London 2015 talk |
| Geospatial write target | One million writes per second, a much higher read rate | Same talk write-up |
| S2 cell size used for sharding | 3.31 km2 | Same talk write-up |
| Schemaless shards | Fixed, "typically 4096" | Mezzanine post 2015, Schemaless part two 2016 |
| Trip growth in early 2014 | About 20% a month | Mezzanine post 2015 |
| Microservices | About 500 in fall 2015, over 2,000 in early 2017, around 2,200 critical in 2020 | Jaeger post 2017, DOMA post 2020 |
| Geofence service | p99 under 100 ms, hundreds of thousands of QPS, tens of thousands of geofences | Geofence post 2016 |
| H3 | 16 resolutions (0 to 15), 122 base cells, 12 pentagons, each finer level one seventh the area | H3 post 2018 |
| Kafka | Trillions of messages and petabytes per day | Kafka DR post 2020, Real-time infra paper 2021 |
| M3 | 6.6 billion time series, 500 million metrics per second aggregated, 20 million persisted per second | M3 post 2018 |
| Docstore partition | 3 to 5 nodes, each in an independent zone, Raft per partition | Docstore post 2021 |
| Polling share before push | 80% of API gateway requests were polling calls | RAMEN post 2020 |
| Cadence | Over a thousand services at Uber; teams wrote 40% less code (internal 2021 survey) | Cadence 1.0 post 2023 |
| Toy demo on this page | 60,000 pings in 15 ms, match in 22 µs, ring add moved 24.5% of keys | Lab, measured on one laptop |
The problems and the decision Uber published.
| Problem | Decision | Section |
|---|---|---|
| Location data is huge and useless after seconds | Keep it in memory in sharded workers; do not store each ping in a database | Location |
| Sharding by city became hard to operate | Shard by geography cell (S2), workers on a hash ring (Ringpop) | Geo index, Ringpop |
| A datacenter fails mid-trip | The driver phone holds an encrypted state digest; the new datacenter asks for it | Location, Reliability |
| Trips outgrow one Postgres | Build Schemaless: append-only cells on 4096 MySQL shards | Schemaless |
| Primary MySQL master down at write time | Buffered writes to a random secondary master | Schemaless |
| Polling melts the API gateway | Push platform (RAMEN), then gRPC streams | Push |
| Surge must survive a region loss | Active-active Kafka; each region recomputes from input events | Pricing, Reliability |
| Thousands of services, nobody sees the whole call | DOMA layers and gateways; Jaeger traces | DOMA, Observability |
| Double charges on retries | Idempotency and strong consistency in payments | Payments |
The picture puts the published pieces on one page. The left column is the phones, the top row is the request path (edge, supply, demand, the geospatial index, DISCO and the routing engine), the band in the middle is Kafka, and the bottom row is what consumes the events: surge pricing, the trip store, payments and the platforms. Arrows between boxes are my reading of several posts written in different years (inference); no single Uber diagram shows all of this.
Why it exists
Uber is the standard interview example for a reason: it contains almost every hard part of system design in one product. Location is a write-heavy, short-lived stream; matching is a latency-bound query over that stream; pricing is a streaming aggregation per area; trip storage is a durable, append-mostly record that must never lose a write; payments must never charge twice. Each part has a different consistency need, and Uber's posts say which side of each trade-off it chose.
| Part | Favours | Gives up | Evidence |
|---|---|---|---|
| Live location | Freshness, write throughput | Durability of each ping | Ringpop post: "database storage would be useless" for fleeting location data |
| Surge pricing | Freshness and availability | Cross-region consistency | Real-time infra paper: "we must therefore prioritize freshness ahead of consistency" |
| Trip writes | Write availability | Short-term read-your-write after a failure | Schemaless posts: buffered writes, "favoring write availability over read-your-write semantics" |
| Docstore | Strict serializability per partition | Availability under a partition | Docstore post: "favors consistency over availability" |
| Payments | Exactly-once effect | Simplicity | Payments post: idempotency and strong consistency |
One analogy, reused through the page: a taxi radio office in a city divided into honeycomb tiles. Cars radio their tile every few seconds (location pings). The dispatcher keeps a board of tiles with magnets (the in-memory index), and several dispatchers split the board between them (Ringpop shards). When a call comes in, the dispatcher looks at the caller's tile and the ring of tiles around it, and also at cars that will drop off nearby in two minutes (DISCO). A tile with many calls and few magnets gets a higher fare sign (surge). Every finished ride is written in ink in a ledger that is never erased, only appended (Schemaless cells). If the office burns down, each driver carries a sealed card with the trip state and hands it to the next office (state digest).
Three common misunderstandings, up front
- "Uber stores every GPS point in a geospatial database and queries it." The 2016 Ringpop post says the opposite for the live path: Geospatial workers hold the ephemeral state in memory and distribute it. History is a separate, offline concern.
- "Uber moved from Postgres to MySQL because MySQL is a better database." The 2016 post argues about specific mechanics (physical WAL replication, index write amplification, upgrade path, connection model) at Uber's scale and on Postgres 9.2, and the trip store it moved to is Schemaless, a layer that uses MySQL as a storage engine. PostgreSQL developers replied with counter-points (see Postgres to MySQL).
- "H3 is the dispatch index." The 2018 H3 post describes H3 as the grid for "analysis and optimization", with surge as the example; the 2015 talk describes S2 cells for sharding supply. That H3 replaced S2 everywhere in dispatch is not stated in the posts I read (inference if you assume it).
Where it comes from
Every row was read on the saved page named in References.
| Date | Source (Uber unless noted) | What it states | Used for |
|---|---|---|---|
| March 2015 | Matt Ranney, Scaling Uber's Real-time Market Platform, QCon London (talk, slides, InfoQ write-up) | Supply, demand and DISCO services; S2 cells; Ringpop; TChannel; pings every four seconds; state digest on the phone for datacenter failover | Location, matching, failover |
| 28 Jul 2015 | Project Mezzanine: The Great Migration | 2014 migration of trips from one PostgreSQL to Schemaless; 4096 shards; append-only; trip-id to UUID; shadow writes and validation | Trip storage |
| 12 and 15 Jan 2016 | Designing Schemaless and The Architecture of Schemaless | Cell model (row key, column, ref key), triggers, worker and storage nodes, buffered writes, MySQL entity table | Trip storage |
| 4 Feb 2016 | How Ringpop from Uber Engineering Helps Distribute Your Application + Ringpop docs | SWIM, FarmHash, red-black tree, replica points, handle or forward, Geospatial as the first use case | Sharding, membership |
| 24 Feb 2016 | How We Built Uber Engineering's Highest Query per Second Service Using Go | Geofence lookup service, city-level two-step scan, in-memory index refreshed in the background | Geofences |
| 26 Jul 2016 | Why Uber Engineering Switched from Postgres to MySQL | Postgres 9.2 tuple layout, write amplification, WAL replication, upgrade pain, process per connection; InnoDB comparison | Database choice |
| Aug 2016 | Robert Haas (PostgreSQL committer, not Uber), Uber's move away from PostgreSQL | Logical replication missing in core, HOT updates, hot_standby_feedback | Critique |
| 4 Aug 2016 | uReplicator: Uber Engineering's Robust Apache Kafka Replicator | MirrorMaker rebalancing problems; Apache Helix assignment; zero data loss goal | Streaming |
| 2 Feb 2017 | Evolving Distributed Tracing at Uber Engineering | Merckx, then Jaeger; 500 services in 2015, 2,000+ in 2017; OpenTracing | Observability |
| 5 Sep 2017 | Meet Michelangelo | ML-as-a-service platform | ETA, ML |
| 9 Oct 2017 | Introducing AthenaX | SQL compiled to Flink jobs on YARN | Streaming |
| 27 Jun 2018 | H3: Uber's Hexagonal Hierarchical Spatial Index | Hexagons, 122 base cells, 12 pentagons, 16 resolutions; surge from supply and demand in hexagons | Geo index, pricing |
| 7 Aug 2018 | M3: Uber's Open Source, Large-scale Metrics Platform for Prometheus | M3DB, coordinator, aggregation, numbers | Observability |
| 5 Dec 2018 | Engineering Uber's Next-Gen Payments Platform | Active-active, idempotency, double-entry bookkeeping | Payments |
| 23 Jul 2020 | Introducing Domain-Oriented Microservice Architecture | Domains, five layers, gateways, extensions; 2,200 services | Services |
| 18 Dec 2020 | Uber's Real-Time Push Platform | RAMEN, Fireball, SSE with sequence numbers; 80% polling | Push |
| 21 Dec 2020 | Disaster Recovery for Multi-Region Kafka at Uber | Regional and aggregate clusters, active/active and active/passive, surge failover | Reliability |
| 23 Feb 2021 | Evolving Schemaless into a Distributed SQL Database | Docstore: schemas, partitions of 3 to 5 nodes, Raft, MySQL engine | Docstore |
| 2021 | Real-time Data Infrastructure at Uber (SIGMOD '21 paper, arXiv 2104.00087) | Kafka, Flink, FlinkSQL, Pinot; dynamic pricing favours freshness | Streaming, pricing |
| 10 Feb 2022 | DeepETA: How Uber Predicts Arrival Times Using Deep Learning | Routing engine plus residual model; Transformer-style encoder | ETA |
| 16 Aug 2022 | Uber's Next Gen Push Platform on gRPC | SSE to gRPC bidirectional streaming over QUIC | Push |
| 22 Jun 2023 | Announcing Cadence 1.0 | Six-year workflow project; over a thousand services | Workflows |
What changed over time
| Area | Earlier (dated source) | Later (dated source) | Why it changed, per the later post |
|---|---|---|---|
| Backend shape | Two monolithic services, circa 2012 to 2013 (DOMA 2020) | Close to 100 services in early 2014 (Mezzanine 2015), about 2,200 critical in 2020 (DOMA) | Team independence; later complexity led to DOMA |
| Live supply search | One system holding all vehicles in memory and scanning them (Ringpop 2016) | Geospatial workers sharded on a Ringpop ring (2016) | Growth made the scan "unsustainable" |
| Data sharding in dispatch | Sharded by city (talk write-up 2015) | Sharded by S2 cell (2015) | Big cities became hard to manage |
| Trip storage | One PostgreSQL instance (Mezzanine 2015) | Schemaless on MySQL (2014 launch) | Storage volume, IOPS, downtime for schema changes |
| Schemaless | Append-only, no schema (2016) | Docstore, schema-on-write, transactions, Raft (2021) | Restrictive API; Cassandra tried in between and found lacking at Uber scale |
| App updates | Polling dozens of APIs (RAMEN 2020) | SSE push (from 2015, RAMEN 2020), then gRPC over QUIC (2022) | Load, battery, data cost; bidirectional acks |
| Tracing | Merckx for the Python monolith | Jaeger (2017) | No distributed context propagation |
| Metrics | Graphite and Carbon with manual resharding | M3 (since 2015, open-sourced 2018) | Single-node disk failure lost metrics |
| ETA | XGBoost ensembles over the routing engine | DeepETA neural network (2022) | XGBoost size became untenable |
The concept catalogue
The catalogue follows the four steps of the method. Steps 1 and 2 are mine (inference) because Uber does not publish an interview-style requirements list; steps 3 and 4 are built from the published posts. Each subsystem block follows the usual order: plain words, the usual wrong belief, a definition, a sequence, scenarios, a comparison, and what to do.
Step 1: scope the problem Must-know
In plain words: before drawing boxes, agree on what the system must do (request a ride, see the driver move, pay) and how well (seconds, not minutes; never lose a trip).
Common misunderstanding: "Uber is one system." It is a set of systems with different promises. Treating location and payments with the same consistency model leads to either a slow map or double charges.
Definition: scope is the list of functional requirements, non-functional requirements and explicit non-goals for this design. The list below is my inference, built to match the subsystems Uber describes.
Rider and driver flow (scope for this chapter, inference)
1 driver app goes online -> starts sending location pings
2 rider opens app -> sees nearby cars, an ETA and a price (with surge)
3 rider requests -> demand created; matcher offers the trip to one driver
4 driver accepts -> both apps get the state by push
5 trip in progress -> driver location streams to the rider
6 trip ends -> fare computed, card charged, driver paid; trip record keptReal scenario: an airport at midnight (many drivers, few riders), a stadium after a match (the reverse), a city-wide storm (surge everywhere), a datacenter outage during peak hour.
| Requirement | Target (inference unless cited) | Owner subsystem |
|---|---|---|
| See nearby cars and ETA | Seconds; map can be slightly stale | Location, geo index, ETA |
| Match a request | A few seconds end to end | DISCO, supply, demand |
| Price before request | Reflects the area's current supply and demand | Pricing |
| Never lose a trip | Write must succeed even when one database master is down (Schemaless goal, cited) | Trip store |
| Never charge twice | Exactly-once effect (payments post, cited) | Payments |
| Survive a datacenter or region loss | Continue trips; recompute surge elsewhere (cited) | Reliability |
| Non-goals here | Maps production, fraud models, Eats logistics | Other chapters |
How to use it: write the non-functional column first; it decides the data store and the consistency model for each box. The method is in The 4-Step Approach.
Step 2: estimate the load Must-know
In plain words: turn "millions of drivers" into writes per second, bytes per second and machines, so you know which box is the bottleneck.
Common misunderstanding: "Requests per second is the number that matters." Here the dominant load is not rider requests but driver pings; reads of the location index (every app open, every matching round) multiply it again.
Definition: a back-of-the-envelope estimate with stated assumptions. The ping interval and the million-writes target are cited (2015 talk write-up); the driver count and sizes are my assumptions, so the results are inference.
Back-of-envelope (assumptions marked A, cited facts marked C)
1 A: 3,000,000 drivers online at global peak
2 C: one ping every 4 s -> 750,000 pings/s (the 2015 target was 1,000,000 writes/s, C)
3 A: 100 bytes per ping on the wire -> 75 MB/s ingress, about 6.5 TB/day if every ping were kept
4 A: 20,000 ride requests/s at peak -> each reads the rider cell plus 1-2 rings: 7 to 19 cells
5 A: app opens 10x requests -> 200,000 "nearby cars" reads/s, cacheable per cell for 1-2 s
6 A: one in-memory worker handles 50,000 updates/s -> about 15 workers by CPU, x3 for headroom and replicas
7 trip records: A 20,000 trips/min x 10 cells each -> 3,300 cell writes/s, small but must be durableReal scenario: this estimate says the location tier is the write hot spot (hundreds of thousands per second, tiny and disposable), the trip tier is the durability hot spot (thousands per second, never lose), and the read side of "nearby cars" is a caching problem.
| Load | Order of magnitude | Kind | Where it lands |
|---|---|---|---|
| Location pings | 10^5 to 10^6 per second | Write, ephemeral | In-memory geospatial workers |
| Nearby-car reads | 10^5 per second | Read, stale-tolerant | Same workers, per-cell cache |
| Ride requests | 10^4 per second | Read plus write | Demand service, DISCO |
| Trip cell writes | 10^3 to 10^4 per second | Write, durable | Schemaless or Docstore |
| Events to Kafka | Trillions per day (cited) | Append | Kafka clusters |
How to use it: do the arithmetic with your own numbers in Back-of-the-Envelope Capacity Estimation, and keep cited and assumed numbers visibly apart, as above.
Step 3: high-level design Must-know
In plain words: draw the boxes and arrows for one ride; every later section zooms into one box.
Common misunderstanding: "A high-level design is a list of technologies." It is a flow: who calls whom, what is stored where, what happens when one box is down.
Definition: the high-level design is the set of components and data flows that meets the scope. For Uber it is assembled from the posts in Where it comes from and shown in the architecture diagram above; the wiring is inference.
One ride through the published components (wiring is inference)
1 driver app -> edge gateway -> supply service : location ping, every 4 s (2015)
2 supply -> Geospatial worker (owner by Ringpop) : update the driver's cell
3 rider app -> edge gateway -> geofence service : which products and rules apply here (2016)
4 rider app -> demand service -> DISCO : request; DISCO asks geo for supply near the rider
5 DISCO -> routing / ETA : ETA for each candidate, including drivers finishing soon
6 DISCO -> supply: offer to driver; Fireball -> RAMEN push to driver app
7 trip events -> Kafka -> Flink surge job : supply and demand per hexagon
8 trip events -> Schemaless trip store (cells) : BASE, STATUS, FARE ADJUSTMENT
9 trip end -> payments (idempotent) ; traces to Jaeger, metrics to M3Real scenario: an interviewer asks "what happens when the geospatial worker for this area dies?" The answer comes from step 3: Ringpop's membership marks it faulty, its arc of the ring moves to neighbours, and the next pings (four seconds later) rebuild the state there (inference from the Ringpop and talk material).
| Component | State | Store | Consistency need |
|---|---|---|---|
| Geospatial workers | Live driver positions | Memory | Fresh, lossy is fine |
| Supply / demand services | Driver and request state machines | Memory plus phone state digest (2015) | Per-entity ordering |
| DISCO | Matching decisions | Transient | Single owner per area at a time (inference) |
| Pricing | Multipliers per hexagon | Flink state, fast key-value store (paper) | Fresh over consistent |
| Trip store | Trip cells | Schemaless / Docstore on MySQL | Durable, idempotent |
| Payments | Ledger | Strongly consistent store (post) | Exactly-once effect |
How to use it: for each box, write the state column first. Stateless boxes scale behind a load balancer; stateful ones need a sharding plan, which is where Ringpop and Schemaless come in.
Location ingestion and driver tracking Must-know
In plain words: every online driver's phone sends its position every few seconds; the backend keeps only the latest position per driver in memory and throws the rest away on the hot path.
Common misunderstanding: "Each ping is a row update in the drivers table." At hundreds of thousands of pings per second that is a database write storm for data that is worthless ten seconds later. Uber's 2016 post says database storage "would be useless because of how fleeting the location data is".
Definition: location ingestion is the path from the mobile client (driver app) to the live supply index: a periodic location update (four seconds in the 2015 talk write-up), routed to the worker that owns the driver or the area, which overwrites the previous position and refreshes a last-seen time. The 2015 talk adds a reliability twist: the server periodically replies with an encrypted state digest that the phone keeps, so a new datacenter can recover the driver's state from the phone after a failover.
Datacenter failover with the phone as carrier (2015 talk, slides "State Digest")
1 driver app -> DC1 dispatch : location update (every 4 s)
2 DC1 -> driver app : ack + encrypted state digest (periodically)
3 DC1 fails
4 driver app -> DC2 dispatch : location update
5 DC2 -> driver app : state request (DC2 knows nothing about this driver)
6 driver app -> DC2 : last state digest
7 DC2 resumes the driver's trip state; no cross-DC database replication was neededReal scenario: a driver in a tunnel sends no pings for 40 seconds (the matcher must stop offering them: a TTL); a driver's phone sends a late packet from five seconds ago (ignore out-of-order updates); a datacenter loss at 18:00 (the digest path above); a phone on 2G in a developing market (small payloads, see Push).
| Design | Write cost per ping | Survives worker loss | Survives datacenter loss | Used by Uber (source) |
|---|---|---|---|---|
| Row update in a SQL table | High (index, WAL, MVCC) | Yes | With cross-DC replication | No, per Ringpop post |
| In-memory worker, sharded | Very low | State rebuilt from next pings (inference) | Phone state digest | Yes, 2015 talk and 2016 post |
| Redis GEO per city | Low | Depends on Redis replication | Depends | Not described by Uber; common alternative |
| Append to Kafka, consumers build the index | Low append | Replay | Aggregate clusters | Kafka carries driver app events (uReplicator post); exact use for live index not stated |
How to use it: keep live positions in memory or Redis with a TTL, drop out-of-order pings by timestamp, rate-limit the client, and send history to a log in batches. The Go dispatch package implements Update with exactly these rules; the Laravel LiveLocations class does the same on Redis.
Geospatial indexing at Uber: S2, then H3 Must-know
In plain words: cut the Earth into cells with ids, so "drivers near this rider" becomes "drivers in these few cells", and so a cell id can be a shard key.
Common misunderstanding: "Uber invented H3 for finding nearby drivers." The H3 post presents it as the grid "for analysis and optimization throughout our marketplaces", for example surge. The 2015 dispatch rewrite used Google's S2 library for sharding and coverage.
Definition: S2 maps the sphere onto a cube and numbers square-ish cells along a Hilbert curve with 64-bit ids; the talk write-up says Uber used 3.31 km2 cells to shard and S2's region coverage to find candidate drivers. H3 (Uber, open-sourced 2018) projects the Earth onto an icosahedron and lays hexagons on its faces: 122 base cells, 12 pentagons placed in water, 16 resolutions, each finer one about one seventh of the area. The post's reason for hexagons: "hexagons have only one distance between a hexagon centerpoint and its neighbors", which makes k-rings approximate circles and smooths gradients.
Rider near a cell edge: why both indexes query neighbours
1 rider point -> cell X (S2 level for 3.31 km2, or H3 res r)
2 drivers in X only -> may miss a driver 30 m away across the edge in cell Y
3 S2: covering of a disc -> X plus the cells the disc touches
4 H3: k-ring(X, 1) -> X plus its 6 neighbours, all at the same centre distance
5 exact distance / ETA -> rank the union; drop those beyond the radiusReal scenario: sharding supply by cell so one worker owns a downtown area; computing surge per hexagon; clustering hexagons into neighbourhoods by set membership (the H3 post's alternative to hand-drawn zones); analytics roll-ups by truncating an H3 id to a coarser parent.
| Property | Google S2 | Uber H3 | Geohash (for comparison) |
|---|---|---|---|
| Cell shape | Quadrilateral on a cube face | Hexagon (12 pentagons per resolution) | Rectangle in lat/lon |
| Hierarchy | 4 children, exact | 7 children, approximate containment | 32 children per character, exact |
| Neighbour distance | Edge and corner neighbours differ | One distance for all 6 | Edge and corner neighbours differ |
| Id | 64-bit, Hilbert order | 64-bit, truncatable to parent | Base32 string |
| Uber use (source) | Sharding and coverage for dispatch (2015 talk) | Surge, dispatch analysis, marketplace optimisation (2018 post) | Not described |
How to use it: choose S2 when you need exact coverings of arbitrary regions and sortable ids, H3 when you aggregate and smooth over areas, geohash when the store only has strings. All three need the neighbour query and an exact-distance refine, as taught in Geospatial Indexing. The Go hexgrid package here is a flat local hexagon grid that keeps H3's one-distance property; it is not H3.
Matching and dispatch: supply, demand, DISCO Must-know
In plain words: one service knows the drivers (supply), one knows the requests (demand), and a third (DISCO) decides who gets which trip, looking a few minutes ahead.
Common misunderstanding: "Match the rider with the closest idle driver." The 2015 talk's examples show why not: a driver who will drop off a passenger two minutes away may reach the rider sooner than an idle driver eight minutes away. DISCO is described as able to "look into the future".
Definition: in the 2015 rewrite, supply and demand are services that "track all the capabilities and the state machines" of drivers and riders (seats, wheelchair access). DISCO (Dispatch Optimization) matches them, uses the geospatial index to find candidates (by supply and by demand), and calls routing and ETA. The goals on the slides: reduce waiting, reduce extra driving, lowest overall ETAs. The exact optimisation algorithm is not published in the sources I read; treating it as batched bipartite assignment on ETA is inference.
Slides 43-46 (QCon 2015), rewritten as a sequence
1 D1 requests pickup -> S1 idle, best ETA +8 min
2 S2 is on a trip, drop off in +2 min, then +1 min to D1 -> S2 total +3 min
3 DISCO offers D1 to S2 -> D1 waits 3 min instead of 8
4 D2 requests nearby -> S2 best ETA +1 min after D1 pickup
5 S2 plan: pickup D2, pickup D1, drop D1, drop D2 (a pool-style chain)Real scenario: an airport queue (fairness between drivers who waited longer); a rider at the edge of two cells; uberPOOL chaining (the H3 post mentions two ride requests near one driver on uberPOOL); a driver who declines (re-offer quickly, do not lock the rider).
| Strategy | Wait time | Extra driving | Compute | Published by Uber? |
|---|---|---|---|---|
| Nearest idle driver, greedy | Can be poor | Low | Cheap | Old system matched only currently available supply (talk write-up) |
| Include soon-free drivers (DISCO) | Better | Lower | More data, more reads | Yes, 2015 |
| Batched global assignment per area | Best on average | Lowest | Heavier, needs a short batching window | Not in the sources read (inference) |
| Pool chaining | Lower cost per rider | Higher per driver | Route planning | Slides 46 example |
How to use it: separate the state owners (supply, demand) from the decision maker (matcher), ask the index for candidates, rank by ETA, offer to one driver with a short timeout, and make the offer idempotent so a retry does not double-assign. The Go dispatch.Nearest widens rings until it has candidates and ranks by a crude ETA.
Ringpop: SWIM gossip, consistent hashing, handle or forward Important
In plain words: a library inside each worker process; the workers find each other, agree on who is alive, and split the keys (drivers, cells) with a hash ring, so a request that lands on the wrong worker is forwarded to the right one.
Common misunderstanding: "Consistent hashing alone is enough." Without a membership protocol, every worker needs the same list of live members at the same time; Ringpop pairs the ring with SWIM so that view converges, and keeps faulty members in the list to merge after a partition.
Definition: per the Ringpop post and docs, Ringpop has three parts: (1) a membership protocol, a SWIM variation over TCP that uses "ping" and "ping-req", states alive, suspect, faulty and leave, an incarnation number as logical clock, membership and ring checksums, and flap damping; (2) consistent hashing with FarmHash, a red-black tree for the ring and "a uniform number of replica points per node"; (3) forwarding: a handle-or-forward pattern over TChannel, Uber's RPC framing protocol, with HTTP packed inside. Its first use case was Uber's Geospatial service.
Three-node cluster (Ringpop docs walkthrough, condensed)
1 node A starts, reads bootstrap host list -> 1-node cluster
2 node B starts, pings A -> both hash their addresses onto the ring
3 node C pings B -> B knows C; next B->A ping disseminates C
4 request for driver-42 arrives at A -> ringpop.lookup(driver-42) = B
5 A forwards over TChannel -> B handles; client never knew the sharding
6 B stops answering A -> A sends ping-req via C; no answer -> suspect -> faulty
7 B's arcs move to the next points clockwise -> only B's keys moveReal scenario: adding Geospatial capacity before New Year's Eve (only about 1/n of keys move; the toy ring moved 24.5% when going from three to four workers); a slow node that flaps between alive and suspect (damping evicts it); a network partition that splits the cluster in two (retained faulty members make merging possible).
| Concern | Ringpop (docs) | Typical alternative | Where taught |
|---|---|---|---|
| Membership | SWIM gossip inside the app | ZooKeeper or etcd, Kubernetes endpoints | Gossip Protocols, Leader Election |
| Key placement | Hash ring, replica points, FarmHash | Rendezvous hashing, fixed shard map | Consistent Hashing |
| Routing | Handle or forward in the worker | Smart client, or a proxy (Envoy) | Service Discovery |
| Failure detection | ping, ping-req, suspect timeout | Health checks from a load balancer | Gossip Protocols |
| Transport | TChannel | gRPC | gRPC & Protocol Buffers |
How to use it: application-level sharding is worth it only when the state must live in the process (live positions, caches, request coalescing; the post lists these). For a stateless service use a load balancer instead. The Go ring package shows the ring and HandleOrForward; membership is static there.
Geofences: which rules apply at this point Important
In plain words: a geofence is a drawn area (a city, an airport, a surge zone); every request must know which areas its location falls into.
Common misunderstanding: "This needs a fancy spatial tree." Uber's 2016 post chose a two-level linear scan (first the city, then the geofences of that city) because the business is city-centric, and still reached p99 under 100 ms at hundreds of thousands of QPS.
Definition: a geofence lookup returns every polygon that contains a point. The 2016 service, written in Go, keeps all geofences in memory on every instance (stateless, any instance can answer), refreshes them from datastores with background polling, saves them to local disk for fast restart, builds new index segments on the side and swaps them in, and protects the index with a read-write lock.
Geofence service request (2016 post)
1 app request with lat/lon -> any instance (no partitioning, full world in memory)
2 scan city geofences -> city = the one containing the point
3 scan that city's fences -> airport, product areas, pricing neighbourhoods
4 return fence ids -> products shown, airport rules, pricing applied
5 background job -> poll sources, build new segment, swap atomically under a lockReal scenario: airport pick-up rules; which products (cars, bikes) to show; "dynamic pricing in neighborhoods where lots of people are requesting rides" (the post's words); regulatory zones.
| Design | Lookup | Update | Fits when |
|---|---|---|---|
| Linear scan of all fences | O(n) | Trivial | Hundreds of fences |
| City first, then city fences (Uber 2016) | O(cities + fences in city) | Background swap | City-centric rules, tens of thousands of fences |
| R-tree / PostGIS GiST | O(log n) | Index maintenance | Many overlapping shapes, ad-hoc queries |
| Cell to fence cache (S2 or H3 covering) | O(1) per cell plus exact check | Recompute covering | Very hot path, static fences |
How to use it: read-mostly data that every request needs belongs in every instance's memory, refreshed in the background. The polygon test itself is in Geospatial Indexing.
ETA and the routing engine Important
In plain words: the routing engine computes how long the drive will take from the road graph and live traffic; a machine-learning model corrects its typical error.
Common misunderstanding: "ETA is distance divided by speed." The DeepETA post says ETAs are used "to calculate fares, estimate pickup times, match riders to drivers, plan deliveries", so a crude ETA is a pricing and matching bug, not only a display bug.
Definition: per the DeepETA post, the routing engine divides the road network into segments represented as weighted edges and predicts an ETA as a sum of segment traversal times using map data and real-time traffic. A post-processing model predicts the residual between that and reality from spatial and temporal features. For years this was gradient-boosted trees (XGBoost); DeepETA replaced it with a low-latency neural network using self-attention. Training and serving ran on Michelangelo, Uber's ML platform (2017 post).
ETA for one candidate driver (DeepETA post, simplified)
1 DISCO asks: driver at A, rider at B
2 routing engine: shortest path A->B on the road graph, sum of segment times = 412 s
3 residual model: features (origin, destination, time, traffic, pickup vs dropoff) -> +37 s
4 ETA = 449 s, returned in milliseconds; DISCO ranks candidates by itReal scenario: pickup ETA on the request screen; ranking candidates in matching; upfront fares; delivery planning in Eats.
| Approach | Accuracy | Latency | Change cost |
|---|---|---|---|
| Straight-line distance / constant speed | Poor in cities | Microseconds | None (the toy dispatch uses this) |
| Routing engine on road graph with live traffic | Good | Milliseconds | High: the engine is complex |
| Routing engine plus tree residual (XGBoost) | Better | Low | Medium |
| Routing engine plus DeepETA residual | Best reported by Uber (2022) | Low, served at scale | Retrain the model, not the engine |
How to use it: keep the physical model and learn only the correction; the post notes it is easier to update the post-processing model than to refactor the routing engine. The ML serving side is in ML Systems.
Surge and dynamic pricing Must-know
In plain words: when an area has many more requests than free cars, the price in that area goes up for a while, which brings drivers in and lets riders choose to wait.
Common misunderstanding: "Surge is one city-wide multiplier." Uber's driver page says surge is "specific to different areas in a city", and the H3 post says surge is calculated "by measuring supply and demand in hexagons".
Definition: dynamic pricing (surge) is a per-area price adjustment from the ratio of demand to supply over a recent window. Per the Kafka disaster-recovery post, trip events go to regional Kafka clusters, are aggregated, and "a complex Flink job with a large-memory footprint computes the pricing" in each region. The 2021 paper describes dynamic pricing as multi-stage stream processing with ML and a fast key-value store, designed to favour freshness and availability over consistency, and calculates demand and supply ratios "per geo-fence". The formula, smoothing and caps are not published in the sources I read; the ones in the code are inference.
One pricing window (published flow; formula is inference)
1 T+0 s trip and app events -> regional Kafka -> aggregate clusters
2 T+0 s Flink job (per region) keys events by hexagon
3 T+30 s window closes: demand 120, supply 8 in the hot cell; neighbours add supply
4 T+30 s ratio over the k-ring -> raw multiplier, capped, rounded to 0.1, smoothed with the last window
5 T+31 s multiplier written to a fast key-value store; quote path reads it
6 region fails -> another region becomes primary and recomputes from input events (Flink state not replicated)Real scenario: a concert ends (one hexagon spikes); rain across the city (many hexagons rise together); a fake spike from one buggy client (rate limits and fraud filters, inference); the previous region dies (recompute from events, as published).
| Choice | Option A | Option B | What Uber published |
|---|---|---|---|
| Area unit | Hand-drawn zones | Grid cells | Hexagons (H3); geofences in the 2021 paper |
| Compute | Batch every few minutes | Stream with windows | Flink job per region |
| Consistency vs freshness | Same price in every region | Fresh price, region-local | Freshness first (paper) |
| Failover | Replicate Flink state | Recompute from input in the new region | Recompute (Kafka DR post) |
| Rider display | Multiplier | Upfront fare including surge | Varies by city (driver page) |
How to use it: treat price as a derived, recomputable value: key the stream by cell, window it, cap and smooth the output, store it in a fast cache with a short TTL, and make failover a recomputation, not a replication. The Go surge package and the Laravel SurgeCalculator show the knobs.
Trip storage: Mezzanine and Schemaless Must-know
In plain words: a trip is written in pieces over time (start, end, fare, each charge attempt, notes); Schemaless stores each piece as a new, never-changed cell, spread over thousands of MySQL shards.
Common misunderstanding: "Schemaless is a NoSQL database Uber wrote from scratch." It is "a relatively thin layer on top of MySQL" that routes requests to the right MySQL database (Schemaless part two).
Definition: Schemaless is an append-only sparse three-dimensional hash map. A cell is addressed by row key (a trip UUID), column name (BASE, STATUS, NOTES, FARE ADJUSTMENT) and ref key (a version). A cell is immutable; an update is a new cell with a higher ref key. Data is split into a fixed number of shards ("typically configured to 4096") by row key; each shard is a separate MySQL database with an entity table and index tables. Worker nodes route and aggregate; storage clusters have one master and minions (replicas) in several data centres. Inserts are idempotent: a second write to the same (row, column, ref) is rejected. Triggers consume each shard's cells in write order, like a partitioned log. Buffered writes send every write to the primary master and to a random secondary master, so a write survives a master failure before replication.
Mezzanine migration (2015 post), as a sequence
1 early 2014 trips in one PostgreSQL; growth about 20%/month; adding a column = downtime
2 step 1 trip id (auto-increment) -> trip UUID; several hundred SQLAlchemy queries rewritten
3 step 2 lib/tripstore API with a switch: Postgres or Schemaless behind the same calls
4 step 3 mirror all writes to Schemaless; replay queries and compare in the background (sampled)
5 step 4 backfill; build indexes; six-week "war room"
6 Oct 2014 Halloween target; reads switched to SchemalessReal scenario: a card is declined and retried (two STATUS cells, ref 1 failed, ref 2 ok); a driver adds a note days later (a NOTES cell); a fare is adjusted after support review (a FARE ADJUSTMENT cell); the master of shard 3877 dies during peak (buffered write; readable after recovery).
| Concern | Schemaless (2016) | One big PostgreSQL (before 2014) | Cassandra (evaluated 2014, used later elsewhere) |
|---|---|---|---|
| Scale out | Add MySQL hosts, move shards | Vertical only | Add nodes |
| Write during master failure | Buffered writes to another master | No | Yes (leaderless) |
| Schema change | None in the store; columns are app-defined | ALTER caused downtime | Flexible |
| Change notification | Triggers per shard | Separate event system | Application level |
| Secondary indexes | Global, eventually consistent, MySQL tables | Native | Scatter-gather (per the post's comparison) |
| Read-your-write after failover | Not guaranteed while buffered | Yes | Tunable |
How to use it: model a long-lived business record as an append-only set of versioned facts with a natural idempotency key; shard by the entity id so one entity stays on one shard; publish changes from the store in write order. The Go tripstore package and the SQL trip_cells table are small versions of this.
Postgres to MySQL (2016) and its critiques Important
In plain words: in 2016 Uber explained why most of its databases had moved to MySQL (mostly under Schemaless). PostgreSQL experts answered that several problems had fixes or were tied to an old version.
Common misunderstanding: "The post proves PostgreSQL does not scale." It analyses Postgres 9.2 specifically, under Uber's workload (many indexes, frequent updates, cross-datacenter replication), and the trip store it replaced was a single instance.
Definition: the post's arguments: (1) Postgres tuples are immutable and every index points to the tuple's physical location (ctid), so an update creates a new tuple and every index needs a new entry: write amplification. (2) Streaming replication ships the physical WAL, so that amplification crosses the WAN, and a 9.2 bug caused replicas to misapply WAL records. (3) MVCC on replicas: a long query on a replica blocks WAL apply or gets cancelled. (4) Physical replication does not cross major versions, so upgrades took many hours. (5) Process per connection versus InnoDB's thread per connection; trouble above a few hundred active connections without pgbouncer. InnoDB secondary indexes point to the primary key, updates happen in place with old versions in the rollback segment, and the binlog is logical.
Update of one non-key column, per the post's example (birth_year of one user)
1 PostgreSQL 9.2: new tuple in heap -> write 1
2 primary key index entry -> write 2
3 (first, last) index entry -> write 3 (column did not change)
4 birth_year index entry -> write 4
5 each of the four also in WAL, shipped to replicas
6 InnoDB: row updated in place, old version to rollback segment; only the birth_year index changesReal scenario: a trips table with many secondary indexes and frequent status updates; a replica in another datacenter; a major version upgrade that must not stop writes; a burst of "idle in transaction" connections from a buggy service.
| Uber's argument (2016) | Critique or nuance (Robert Haas, Aug 2016, and PostgreSQL docs) | Status today (inference from later PostgreSQL releases, not from Uber) |
|---|---|---|
| Every index updated on every update | HOT updates touch no index when no indexed column changes; be conservative with indexes; clustered-index designs have their own costs | HOT still the main mitigation; fillfactor tuning |
| Physical WAL is verbose across the WAN | WAL can be compressed (SSL or archive_command with gzip) | wal_compression exists in newer releases |
| Replica queries cancelled or blocking replay | hot_standby_feedback=on prevents cancellation (trading bloat on the primary); max_standby_streaming_delay sets the grace | Same knobs |
| No cross-version replication | Logical replication was the missing piece; pglogical existed but not for 9.2 | Built-in logical replication since PostgreSQL 10 |
| pg_upgrade took many hours | Should not; fixed performance issues in newer releases | pg_upgrade with --link is fast |
| Process per connection | Use a pooler | pgbouncer remains standard |
How to use it: read the post as a case for logical replication, in-place updates and fewer indexes under a heavy update workload, not as a product ranking. The mechanics are in MVCC, VACUUM & Bloat, Replication & Failover and MySQL Storage Engines; the decision method in Choosing a Database.
Docstore: Schemaless grows up Good to know
In plain words: Uber turned Schemaless into a general-purpose database with tables, schemas and transactions, still on MySQL, with Raft keeping each partition's copies in sync.
Common misunderstanding: "Append-only was a mistake." The 2021 post keeps the reasons (less complexity, fewer errors) but says the restrictive API made it hard to use as a general-purpose database, and that Cassandra, adopted in between, lacked operational maturity and efficiency at Uber scale, with eventual consistency impeding developer productivity.
Definition: Docstore is a layered system (query engine, storage engine, control plane). Tables have primary keys and optional partition keys; shards of a few hundred gigabytes are assigned to partitions; a partition is 3 to 5 nodes in independent zones, replicated to other regions, running Raft with one leader. MySQL is the engine and the unit of replication is a MySQL transaction, giving strict serializability within a partition. It enforces schema-on-write while allowing schema evolution, and offers transactions, materialized views, associations and change data capture.
A write in Docstore (2021 post)
1 client -> query engine : insert into trips (partition key = trip_id)
2 query engine -> partition leader : MySQL transaction
3 leader -> followers : Raft log entry
4 majority acks : commit; reads through the leader see it
5 leader fails : Raft elects a new leader; ACID kept across the failoverReal scenario: a service that needs a transaction across several rows of one trip; a lookup by driver id (a materialized view partitioned by another column); downstream services subscribing to changes (CDC).
| Property | Schemaless (2016) | Docstore (2021) |
|---|---|---|
| Data model | Cells, schemaless JSON | Tables, schema-on-write, nested types |
| Updates | Append-only | Mutable rows |
| Replication | Async MySQL master to minions, buffered writes | Raft per partition |
| Consistency | Read-from-master default; eventual indexes | Strict serializability per partition |
| CAP lean | Write availability | Consistency over availability |
| Change stream | Triggers | Change data capture |
How to use it: a sharded SQL layer with consensus per shard is what CockroachDB, TiDB and Spanner productise; build it only at Uber's scale. See Distributed SQL, Consensus & 2PC and Change Data Capture.
Real-time push to mobile clients: RAMEN, SSE, gRPC Important
In plain words: instead of each app asking "anything new?" every few seconds, the server keeps one connection open to each phone and sends updates when they happen.
Common misunderstanding: "WebSocket is the obvious choice." In 2015 Uber compared HTTP/1.1 long polling, WebSockets and Server-Sent Events and chose SSE for security, mobile SDK support and binary size; it moved to gRPC bidirectional streaming over QUIC/HTTP3 later (2022 post).
Definition: RAMEN is Uber's push platform. Fireball decides "when to push a message" from system events and configuration; it calls API gateway endpoints to build the payload with device context; the RAMEN server keeps persistent connections to millions of apps. The SSE protocol adds at-least-once delivery: the client connects to /ramen/receive?seq=0, the server answers HTTP 200 with Content-Type: text/event-stream, and reconnecting with a higher sequence number acknowledges older messages. Before push, "80% of requests made to the backend API gateway were polling calls". The 2022 move to gRPC brought acknowledgements on the same stream, and QUIC had given "a 10-30 percent improvement in tail-end latencies" for HTTPS traffic.
RAMEN over SSE (2020 post), one driver offer
1 driver app -> RAMEN : GET /ramen/receive?seq=0
2 RAMEN -> app : 200 Content-Type: text/event-stream (connection held)
3 DISCO offer created -> event on the bus -> Fireball: push needed for driver d42
4 Fireball -> API gateway: build offer payload (locale, OS, app version)
5 RAMEN -> app : event seq=17 (offer)
6 network drops; app reconnects with ?seq=17 -> server flushes everything up to 17, resends newer
7 2022: same flow on a gRPC bidirectional stream; the ack travels back on the stream immediatelyReal scenario: a driver offer that must arrive in a second; the rider's map of the driver approaching; app cold start (send the current state once, not dozens of polls); 2G networks where every retry costs the driver data.
| Option | Direction | Acks | Mobile fit | Uber's use |
|---|---|---|---|---|
| Short polling | Client pulls | Implicit | Battery and data heavy | Before 2015, 80% of gateway traffic |
| Long polling | Client pulls, held | Implicit | Better | Considered in 2015 |
| WebSocket | Both | Application | Good; extra SDK weight then | Considered in 2015 |
| SSE | Server to client | Sequence number on reconnect | Good on HTTP + JSON stack | Chosen in 2015 |
| gRPC bidirectional over QUIC | Both | On the stream | Best latency on lossy networks | 2022 |
| APNs / FCM | Server to OS | OS-level | Wakes a closed app | Not discussed in these posts |
How to use it: add sequence numbers and resend-from-sequence to any push channel, decide "when to push" in one place, and keep payloads small. Mechanics and scaling of connections: Real-Time Communication, HTTP evolution.
Streaming: Kafka, uReplicator, Flink, AthenaX Important
In plain words: almost every event (app events, trip updates, logs) goes into Kafka; other systems read it to compute prices, metrics, ML features and the data lake.
Common misunderstanding: "Kafka's MirrorMaker handles multi-datacenter copying." Uber's 2016 post describes MirrorMaker 0.8.2 consumers rebalancing for 5 to 10 minutes, giving up after 32 attempts, and a static whitelist that needed restarts, which is why uReplicator exists.
Definition: Uber runs "one of the largest deployments of Apache Kafka in the world, processing trillions of messages and multiple petabytes of data per day" (2020). Producers write to a local regional cluster; uReplicator (Apache Helix assigns partitions to workers, zero-data-loss goal) copies to aggregate clusters in each region. Consumers run active/active (each region consumes its aggregate independently) or active/passive (one consumer in the primary region; offsets synchronised for failover). Stream processing runs on Apache Flink; AthenaX (2017) compiles SQL to Flink jobs, later contributed as FlinkSQL; Apache Pinot serves low-latency OLAP (2021 paper). The insurance team built retries and dead-letter queues on Kafka topics (2018 post).
Event path for one trip update (Kafka DR post + paper)
1 service in region A -> regional Kafka (A) : produce locally; on failure produce to region B
2 uReplicator -> aggregate Kafka (A, B) : asynchronous copy
3 Flink (surge) -> reads aggregate in each region (active/active)
4 payments consumer -> reads in the primary region only (active/passive), offset synced to B
5 region A fails -> surge in B recomputes; payments consumer resumes in B from the synced offsetReal scenario: surge failover (published); a financial consumer that cannot lose or duplicate (active/passive, published); a city operations dashboard built in SQL by non-engineers (AthenaX, published); retrying failed insurance charges without blocking the main topic (published).
| Need | Uber's component (source) | Generic alternative |
|---|---|---|
| Cross-region copy | uReplicator (2016) | MirrorMaker 2, Confluent Replicator |
| Partition assignment for copiers | Apache Helix | Kafka Connect group protocol |
| Stream processing | Flink, FlinkSQL (paper) | Kafka Streams, Spark Structured Streaming |
| Streaming SQL for analysts | AthenaX (2017) | ksqlDB, Flink SQL |
| Real-time OLAP | Pinot (paper) | Druid, ClickHouse |
| Retry and DLQ | Retry topics plus DLQ (2018 post) | Dead-Letter Queue |
How to use it: produce locally, replicate asynchronously, and choose per consumer between active/active (recomputable state) and active/passive (exact progress). Broker details in Kafka in Depth; windows and state in Stream Processing.
Microservices and DOMA Important
In plain words: Uber split two monoliths into thousands of services, found that too hard to understand, and grouped them into domains with one front door each, arranged in layers that may only call downward.
Common misunderstanding: "DOMA means going back to a monolith." The post says few people advocate "an outright rejection of microservice architectures"; DOMA keeps services and adds structure.
Definition: DOMA (Domain-Oriented Microservice Architecture, 2020): a domain is a collection of one or more microservices around a logical grouping of functionality (fare services, matching platform, map search); domains are grouped into five layers (infrastructure, business, product, presentation, edge) where layers depend only on layers below; each domain exposes a gateway as its single entry point; extensions let other teams add logic at defined points instead of editing the domain. Reported effects: onboarding time for platforms cut by 25 to 50%, 2,200 microservices classified into 70 domains (per the post), microservice half-life of 1.5 years.
Investigating an incident, before and after (DOMA post)
1 before: engineers traced through about 50 services across 12 teams to find a root cause
2 after: product calls the matching domain gateway (one entry), not five matching services
3 a latency spike inside the domain stays behind the gateway contract
4 a team needing custom validation registers an extension, not a code change in the domainReal scenario: a new line of business (Freight) reusing "request a ride" logic in the product layer; a migration inside a domain hidden by its gateway; a pricing team adding a rule to the matching domain through an extension.
| DOMA layer (2020 post) | Provides | Example |
|---|---|---|
| Edge | Safe exposure to the outside, app-aware | Mobile API gateway |
| Presentation | Consumer-facing features and apps | Rider app screens |
| Product | Logic for one line of business, app-agnostic | "Request a ride" logic |
| Business | Uber-wide functionality, not tied to one product | Accounts, marketplace trips |
| Infrastructure | Anything an engineering organisation could use | Storage, networking |
How to use it: the same ideas exist as bounded contexts and context maps in DDD and as modular monolith modules; see Microservices Architecture, Service Boundaries, API Gateway & BFF and Bounded Context.
Observability: M3 and Jaeger Good to know
In plain words: M3 stores billions of metric series so dashboards and alerts work across data centres; Jaeger records the path of each request through hundreds of services.
Common misunderstanding: "Logs are enough." The Jaeger post describes Merckx, a profiler for the Python monolith that could not go "more than one level deep" because it had no distributed context propagation.
Definition: M3 (internal since 2015, open-sourced 2018) is a metrics platform: M3DB (distributed time-series store with a reverse index), M3 Coordinator (a Prometheus sidecar for remote storage, downsampling, retention and rollup rules), aggregation; quorum writes to three replicas per region; retention from days to years. Jaeger (2017) is Uber's distributed tracing system: client libraries for the OpenTracing standard, backend in Go, at first reusing Zipkin's UI and storage format, then its own data model (key-value logging, span references) on Cassandra, with backend-controlled adaptive sampling.
One slow ride request, traced (generic flow, Jaeger concepts from the post)
1 edge creates trace id, span "POST /rides"
2 -> demand service span; -> DISCO span; -> routing span (slow: 800 ms)
3 spans reported via jaeger-agent; sampling rate set by the backend
4 engineer opens the trace: the routing span dominates; M3 dashboard shows its p99 rose at 18:02Real scenario: a p99 regression after a deploy; finding which of 50 services added latency; capacity planning from long-retention metrics.
| Signal | Uber system (source) | Open-source default today | Taught in |
|---|---|---|---|
| Metrics | M3 (2018) | Prometheus plus remote storage (M3, Thanos, Mimir) | Observability |
| Traces | Jaeger (2017) | OpenTelemetry plus Jaeger or Tempo | Same |
| Alerting | Graphite threshold checks, then M3-based | Prometheus Alertmanager | Alerting That Works |
How to use it: propagate a trace context through every hop from day one; keep high-cardinality metrics under a retention policy; control sampling centrally.
Reliability: multi-region failover and Cadence workflows Important
In plain words: plan for a whole region to vanish: keep data needed to continue somewhere else, and run long processes (a trip's billing, a payout) as durable workflows that resume after crashes.
Common misunderstanding: "Replicate every database synchronously across regions." The 2015 talk write-up says the dispatch design replicated no data across data centres for this path and used the driver's phone instead; the 2020 post says surge's Flink state is too large to replicate synchronously and is recomputed.
Definition: multi-region failover at Uber, per the posts: services deployed with backups in geographically distributed data centres; Kafka producers fail over to another region; active/active consumers switch regions; active/passive consumers resume from a synchronised offset; dispatch state recovered from the phone's state digest. Cadence (open source, from Uber; v1.0 announced 2023 after more than six years) runs workflows written as ordinary code; execution history lets a workflow resume from the point of failure. Temporal's founders say they "co-created Cadence (Temporal's predecessor) at Uber" (Temporal's own about page).
A trip's post-processing as a durable workflow (Cadence model; the steps are inference)
1 workflow start (trip_id) -> history: started
2 activity: compute fare -> history: completed
3 activity: charge card -> timeout -> retried per policy with the same idempotency key
4 worker crash -> another worker replays history, skips done steps
5 activity: charge ok; activity: pay driver; workflow completedReal scenario: region loss during peak; a payout that needs several bank calls over days; a promotion that ends in a week (a timer in a workflow).
| Failure | Published response | Source |
|---|---|---|
| Dispatch datacenter loss | Driver app sends last state digest to the new datacenter | 2015 talk |
| Kafka cluster loss | Producers fail over to another region's regional cluster | 2020 Kafka DR |
| Region loss for surge | Another region becomes primary and recomputes | 2020 Kafka DR |
| Exact-progress consumer failover | Active/passive with offset sync | 2020 Kafka DR |
| Storage master loss | Buffered writes (Schemaless), Raft failover (Docstore) | 2016, 2021 |
| Worker crash in a long process | Cadence replays history | 2023 Cadence |
How to use it: decide per state whether to replicate, recompute or carry it on the client; for long multi-step processes use a workflow engine; see Durable Workflows & Jobs and Capacity Planning & Disaster Recovery.
Payments and idempotency Must-know
In plain words: a payment request may be retried many times (timeouts, crashes); the system must make the money move once.
Common misunderstanding: "Exactly-once delivery solves it." The 2018 post names "exactly-once payment processing by the means of idempotency and strong consistency": the effect is exactly once because repeated requests are recognised, not because the network delivers once.
Definition: Uber's next-generation payments platform (2018) had design goals of high reliability through active-active, exactly-once processing by idempotency and strong consistency, auditability via double-entry bookkeeping, and extensibility to new lines of business and payment methods; it has two parts, collections (charging riders) and disbursements (paying drivers), and supported over ten ways to pay. The internal data model details are in talks linked from the post, which I did not transcribe.
Charge with an idempotency key (generic pattern consistent with the post; details inference)
1 trip ends -> charge(trip_id, attempt_key = trip_id + "/charge/1", amount)
2 processor times out -> client retries with the SAME key
3 payments service: key seen, result stored -> returns the first result, no second charge
4 ledger: debit rider receivable, credit Uber revenue and driver payable (double entry)
5 STATUS cell ref 1 = charged (Schemaless-style append), never editedReal scenario: a network timeout after the processor charged the card; a second tap on "pay"; a regional payment method (Paytm, iDEAL, named in the post) with slow callbacks.
| Mechanism | What it prevents | Where taught |
|---|---|---|
| Idempotency key per operation | Double charge on retry | API Idempotency |
| Strong consistency for the ledger | Two regions applying the same charge | Consistency Models |
| Double-entry bookkeeping | Money appearing or vanishing | Payment Processing Architecture |
| Append-only trip STATUS cells | Lost history of attempts | Schemaless |
| Idempotent consumers | Duplicate events from Kafka | Idempotent Consumers |
How to use it: generate the key where the intent is created (the trip end), store key and result in the same transaction as the effect, and return the stored result on repeats.
Mechanics
Knobs and numbers, per published component
| Component | Knob or fact | Value in the source | What it controls |
|---|---|---|---|
| Driver app | Location update interval | Four seconds (2015 talk write-up) | Write load, freshness, failover recovery granularity |
| S2 (2015) | Cell size for sharding | 3.31 km2 | Supply per shard, hot shards |
| H3 | Resolution | 0 (coarsest) to 15 (finest) | Cell size; each step one seventh the area |
| H3 | Base cells, pentagons | 122, 12 per resolution (in water) | Edge cases in k-ring code |
| Ringpop | Replica points per node | A uniform number per node (docs; value configurable) | Balance of keys over workers |
| Ringpop | Member states | alive, suspect, faulty, leave (docs) | Failure detection, ring changes |
| Ringpop | Hash, ring structure | FarmHash, red-black tree (log n lookups) | Lookup cost |
| TChannel | Benchmarks quoted in docs | 20,000 to 40,000 operations per second | Forwarding overhead |
| Geofence service | Latency target | p99 under 100 ms at hundreds of thousands QPS | In-memory, stateless design |
| Schemaless | Shards | Fixed, typically 4096; each a MySQL database | Placement unit; expand by splitting servers |
| Schemaless | Cell address | (row key, column name, ref key) | Idempotency and versioning |
| Schemaless | Read target | Master by default, minion per request | Read-your-write vs load |
| Docstore | Partition | 3 to 5 nodes, independent zones, Raft | Durability and failover |
| RAMEN (SSE) | Session start | /ramen/receive?seq=0, Content-Type: text/event-stream | At-least-once delivery |
| Kafka multi-region | Consumption modes | active/active, active/passive | Recompute vs exact progress |
| uReplicator | Assignment | Apache Helix, SimpleConsumer workers | No group rebalances |
| M3 | Write path | Quorum write to three replicas per region | Durability of metrics |
| M3 | Retention examples | Two days to five years, 1 s to 10 min resolution | Storage cost |
| PostgreSQL (critique) | hot_standby_feedback, max_standby_streaming_delay | Docs: delay WAL apply or cancel conflicting queries | Replica query cancellation |
What goes wrong, verbatim where a source gives the words
| Symptom | Words from the source | Source |
|---|---|---|
| MirrorMaker stall | "we've observed about 5–10 minutes of inactivity" during rebalance | uReplicator 2016 |
| MirrorMaker stuck | "the consumers can give up after 32 rebalancing attempts and get stuck forever" | uReplicator 2016 |
| Postgres replica corruption | Replicas "misapply some WAL records" after a 9.2 bug during master promotion | Postgres to MySQL 2016 |
| Postgres connections | "significant problems scaling Postgres past a few hundred active connections" | Postgres to MySQL 2016 |
| Standby conflict | Conflicting queries "will be canceled once it has taken longer than the relevant delay setting" | PostgreSQL docs, Hot Standby |
| Duplicate cell in MySQL | ERROR 1062 (23000): Duplicate entry ... for key ... without INSERT IGNORE (shape of the MySQL message; not fetched) | MySQL error reference |
| Polling overload | "At some point, 80% of requests made to the backend API gateway were polling calls." | RAMEN 2020 |
| Incident debugging | "around 50 services across 12 different teams" to find a root cause | DOMA 2020 |
The location path, step by step
Inside one Geospatial worker (published pieces + inference for the internals)
1 ping arrives at worker W (any worker: the edge does not know the sharding)
2 W: owner = ring.lookup(driver_id or cell_id) (Ringpop handle or forward)
3 owner != W -> forward over TChannel; else continue
4 drop if ping.time <= stored.time (out of order, inference)
5 move driver from old cell set to new cell set; set last_seen
6 every 4 s the next ping overwrites; no database write on this path
7 a sweeper or a read-time TTL check hides drivers silent for N seconds (inference)Go
The Go module is a set of small packages that re-implement the mechanisms above in memory, with tests. None of it is Uber code.
Before
The single-process scan the Ringpop post describes as the predecessor of Geospatial: correct, simple, O(n) per request.
// Before: the "hold every vehicle in memory and scan" matcher the 2016
// Ringpop post describes as the system that preceded Geospatial. It is
// correct and simple; it is O(n) per request and lives on one process.
package main
import (
"fmt"
"math"
"sort"
)
type vehicle struct {
id string
lat, lng float64
}
func haversineM(lat1, lng1, lat2, lng2 float64) float64 {
const r = 6371008.8
p1, p2 := lat1*math.Pi/180, lat2*math.Pi/180
dp, dl := p2-p1, (lng2-lng1)*math.Pi/180
a := math.Sin(dp/2)*math.Sin(dp/2) + math.Cos(p1)*math.Cos(p2)*math.Sin(dl/2)*math.Sin(dl/2)
return 2 * r * math.Asin(math.Sqrt(a))
}
// nearest computes the distance to every vehicle in the world, then sorts.
func nearest(all []vehicle, lat, lng float64, n int) []vehicle {
sorted := append([]vehicle(nil), all...)
sort.Slice(sorted, func(i, j int) bool {
return haversineM(lat, lng, sorted[i].lat, sorted[i].lng) <
haversineM(lat, lng, sorted[j].lat, sorted[j].lng)
})
if len(sorted) > n {
sorted = sorted[:n]
}
return sorted
}
func main() {
fleet := []vehicle{{"a", 35.701, 51.400}, {"b", 35.710, 51.400}, {"c", 48.85, 2.35}}
fmt.Println(nearest(fleet, 35.700, 51.400, 2))
}After
A hexagon grid with the one-distance neighbour property (a flat stand-in for H3, not H3):
// Package hexgrid is a small teaching stand-in for a hexagonal grid.
// It is NOT Uber's H3: it projects a city onto a flat local plane
// (equirectangular around an origin) and lays pointy-top hexagons on it.
// It keeps the property the H3 post stresses: every neighbour centre is
// the same distance away, so k-rings approximate circles.
package hexgrid
import "math"
// earthRadiusM is the mean Earth radius used for the local projection.
const earthRadiusM = 6371008.8
// Cell is an axial hexagon coordinate (q, r) inside one city grid.
type Cell struct{ Q, R int }
// Grid maps latitude/longitude to hexagons of a fixed edge length.
type Grid struct {
originLat, originLng float64
edgeM float64
cosLat float64
}
// New returns a grid centred on a city origin with hexagons of edgeM metres.
func New(originLat, originLng, edgeM float64) *Grid {
return &Grid{originLat, originLng, edgeM, math.Cos(originLat * math.Pi / 180)}
}
// toXY projects lat/lng to metres east (x) and north (y) of the origin.
func (g *Grid) toXY(lat, lng float64) (float64, float64) {
x := (lng - g.originLng) * math.Pi / 180 * earthRadiusM * g.cosLat
y := (lat - g.originLat) * math.Pi / 180 * earthRadiusM
return x, y
}
// CellOf returns the hexagon containing the point.
func (g *Grid) CellOf(lat, lng float64) Cell {
x, y := g.toXY(lat, lng)
q := (math.Sqrt(3)/3*x - y/3) / g.edgeM
r := (2.0 / 3 * y) / g.edgeM
return round(q, r)
}
// round converts fractional axial coordinates to the nearest hexagon
// using cube rounding (x + y + z = 0).
func round(q, r float64) Cell {
x, z := q, r
y := -x - z
rx, ry, rz := math.Round(x), math.Round(y), math.Round(z)
dx, dy, dz := math.Abs(rx-x), math.Abs(ry-y), math.Abs(rz-z)
switch {
case dx > dy && dx > dz:
rx = -ry - rz
case dy > dz:
// y is recomputed implicitly; only q and r are kept
default:
rz = -rx - ry
}
return Cell{int(rx), int(rz)}
}
// directions are the six axial neighbour offsets.
var directions = [6]Cell{{1, 0}, {1, -1}, {0, -1}, {-1, 0}, {-1, 1}, {0, 1}}
// Distance is the number of hexagon steps between two cells.
func Distance(a, b Cell) int {
dq, dr := a.Q-b.Q, a.R-b.R
return (abs(dq) + abs(dr) + abs(dq+dr)) / 2
}
// KRing returns every cell within k steps of c (k = 0 is c itself).
// The count is 1 + 3k(k+1): 1, 7, 19, 37 ...
func KRing(c Cell, k int) []Cell {
out := make([]Cell, 0, 1+3*k*(k+1))
for dq := -k; dq <= k; dq++ {
lo, hi := max(-k, -dq-k), min(k, -dq+k)
for dr := lo; dr <= hi; dr++ {
out = append(out, Cell{c.Q + dq, c.R + dr})
}
}
return out
}
// Neighbors returns the six cells that share an edge with c.
func Neighbors(c Cell) []Cell {
out := make([]Cell, 0, 6)
for _, d := range directions {
out = append(out, Cell{c.Q + d.Q, c.R + d.R})
}
return out
}
// HaversineM is the great-circle distance in metres.
func HaversineM(lat1, lng1, lat2, lng2 float64) float64 {
p1, p2 := lat1*math.Pi/180, lat2*math.Pi/180
dp, dl := p2-p1, (lng2-lng1)*math.Pi/180
a := math.Sin(dp/2)*math.Sin(dp/2) + math.Cos(p1)*math.Cos(p2)*math.Sin(dl/2)*math.Sin(dl/2)
return 2 * earthRadiusM * math.Asin(math.Sqrt(a))
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}An in-memory supply index and matcher: cells, TTL for ghosts, out-of-order pings dropped, rings widened until there are candidates, ranking by a crude ETA:
// Package dispatch is a toy supply index and matcher in the spirit of the
// published Uber designs (supply keyed by cell, query the rider's cell and
// its rings, rank by ETA). It is a teaching re-implementation, not Uber code.
package dispatch
import (
"sort"
"sync"
"time"
"academy/case-study-uber/hexgrid"
)
// Driver is the live state the matcher needs. History lives elsewhere.
type Driver struct {
ID string
Lat, Lng float64
Cell hexgrid.Cell
SeenAt time.Time
Busy bool
}
// Candidate is a driver with an estimated time to pickup.
type Candidate struct {
ID string
DistM float64
ETA time.Duration
RingStep int
}
// Index holds online drivers bucketed by hexagon, in memory only.
type Index struct {
mu sync.RWMutex
grid *hexgrid.Grid
ttl time.Duration
speedMS float64 // crude straight-line speed; a real system asks a routing engine
drivers map[string]*Driver
cells map[hexgrid.Cell]map[string]struct{}
}
// New builds an index. ttl removes drivers that stopped sending updates.
func New(g *hexgrid.Grid, ttl time.Duration, speedMS float64) *Index {
return &Index{grid: g, ttl: ttl, speedMS: speedMS,
drivers: map[string]*Driver{}, cells: map[hexgrid.Cell]map[string]struct{}{}}
}
// Update records one location ping and moves the driver between cells.
// Out-of-order pings (older than the stored one) are ignored.
func (ix *Index) Update(id string, lat, lng float64, at time.Time) {
c := ix.grid.CellOf(lat, lng)
ix.mu.Lock()
defer ix.mu.Unlock()
d, ok := ix.drivers[id]
if ok && at.Before(d.SeenAt) {
return
}
if !ok {
d = &Driver{ID: id}
ix.drivers[id] = d
} else if d.Cell != c {
delete(ix.cells[d.Cell], id)
}
d.Lat, d.Lng, d.Cell, d.SeenAt = lat, lng, c, at
if ix.cells[c] == nil {
ix.cells[c] = map[string]struct{}{}
}
ix.cells[c][id] = struct{}{}
}
// SetBusy marks a driver as on a trip (not offered new requests).
func (ix *Index) SetBusy(id string, busy bool) {
ix.mu.Lock()
defer ix.mu.Unlock()
if d, ok := ix.drivers[id]; ok {
d.Busy = busy
}
}
// Nearest returns up to n idle, fresh drivers, widening the ring one step
// at a time until it has n candidates or reaches maxRing.
func (ix *Index) Nearest(lat, lng float64, n, maxRing int, now time.Time) []Candidate {
origin := ix.grid.CellOf(lat, lng)
ix.mu.RLock()
defer ix.mu.RUnlock()
var out []Candidate
for k := 0; k <= maxRing; k++ {
for _, c := range ring(origin, k) {
for id := range ix.cells[c] {
d := ix.drivers[id]
if d.Busy || now.Sub(d.SeenAt) > ix.ttl {
continue // ghost or busy driver
}
dist := hexgrid.HaversineM(lat, lng, d.Lat, d.Lng)
out = append(out, Candidate{ID: id, DistM: dist,
ETA: time.Duration(dist / ix.speedMS * float64(time.Second)), RingStep: k})
}
}
// One extra ring after the first hit: a closer driver can sit just
// across a cell edge in ring k+1.
if len(out) >= n && k > 0 {
break
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].ETA != out[j].ETA {
return out[i].ETA < out[j].ETA
}
return out[i].ID < out[j].ID
})
if len(out) > n {
out = out[:n]
}
return out
}
// Sweep deletes drivers whose last ping is older than ttl and returns the count.
func (ix *Index) Sweep(now time.Time) int {
ix.mu.Lock()
defer ix.mu.Unlock()
removed := 0
for id, d := range ix.drivers {
if now.Sub(d.SeenAt) > ix.ttl {
delete(ix.cells[d.Cell], id)
delete(ix.drivers, id)
removed++
}
}
return removed
}
// CellCounts returns how many fresh idle drivers each cell holds (supply).
func (ix *Index) CellCounts(now time.Time) map[hexgrid.Cell]int {
ix.mu.RLock()
defer ix.mu.RUnlock()
out := map[hexgrid.Cell]int{}
for _, d := range ix.drivers {
if !d.Busy && now.Sub(d.SeenAt) <= ix.ttl {
out[d.Cell]++
}
}
return out
}
// ring returns only the cells exactly k steps from c.
func ring(c hexgrid.Cell, k int) []hexgrid.Cell {
if k == 0 {
return []hexgrid.Cell{c}
}
var out []hexgrid.Cell
for _, x := range hexgrid.KRing(c, k) {
if hexgrid.Distance(c, x) == k {
out = append(out, x)
}
}
return out
}A consistent-hash ring with replica points and handle-or-forward (membership is static here; Ringpop adds SWIM):
// Package ring is a minimal consistent-hash ring with replica points and a
// handle-or-forward helper, modelled on what the Ringpop docs describe.
// Ringpop itself uses FarmHash, a red-black tree and SWIM membership; this
// sketch uses FNV-1a plus a mixer, a sorted slice and a static member list.
package ring
import (
"fmt"
"hash/fnv"
"sort"
)
// Ring maps keys (a driver id, a cell id) to the member that owns them.
type Ring struct {
replicas int
points []uint32
owner map[uint32]string
members map[string]bool
}
// New creates a ring with the given number of replica points per member.
func New(replicas int) *Ring {
return &Ring{replicas: replicas, owner: map[uint32]string{}, members: map[string]bool{}}
}
// hash is FNV-1a 64 followed by a murmur3-style finaliser: plain FNV on
// near-identical strings ("geo-a#1", "geo-a#2") clusters on the ring.
func hash(s string) uint32 {
h := fnv.New64a()
_, _ = h.Write([]byte(s))
x := h.Sum64()
x ^= x >> 33
x *= 0xff51afd7ed558ccd
x ^= x >> 33
x *= 0xc4ceb9fe1a85ec53
x ^= x >> 33
return uint32(x)
}
// Add places a member on the ring at `replicas` points.
func (r *Ring) Add(member string) {
if r.members[member] {
return
}
r.members[member] = true
for i := 0; i < r.replicas; i++ {
p := hash(fmt.Sprintf("%s#%d", member, i))
r.owner[p] = member
r.points = append(r.points, p)
}
sort.Slice(r.points, func(i, j int) bool { return r.points[i] < r.points[j] })
}
// Remove takes a member off the ring (it was declared faulty or it left).
func (r *Ring) Remove(member string) {
if !r.members[member] {
return
}
delete(r.members, member)
kept := r.points[:0]
for _, p := range r.points {
if r.owner[p] == member {
delete(r.owner, p)
continue
}
kept = append(kept, p)
}
r.points = kept
}
// Lookup returns the owner of key: the first point clockwise from hash(key).
func (r *Ring) Lookup(key string) string {
if len(r.points) == 0 {
return ""
}
h := hash(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i] >= h })
if i == len(r.points) {
i = 0 // wrap around
}
return r.owner[r.points[i]]
}
// HandleOrForward tells the receiving member what to do with a request.
// It returns ("", true) when self owns the key, or (owner, false) when the
// request must be forwarded to owner.
func (r *Ring) HandleOrForward(self, key string) (string, bool) {
o := r.Lookup(key)
if o == self {
return "", true
}
return o, false
}Surge per cell (the formula is an inference; the per-hexagon input is what Uber published):
// Package surge computes a per-cell price multiplier from demand and supply.
// The Uber posts say surge is computed from supply and demand per hexagon;
// the formula below (ratio, neighbour smoothing, EWMA, step and cap) is an
// illustrative inference, not Uber's pricing model.
package surge
import (
"math"
"academy/case-study-uber/hexgrid"
)
// Config holds the knobs every surge-like system needs in some form.
type Config struct {
Sensitivity float64 // multiplier added per unit of excess demand ratio
Cap float64 // maximum multiplier, for example 3.0
Step float64 // round to 0.1 so prices do not flicker
Alpha float64 // EWMA weight of the newest window (0..1]
SmoothK int // include neighbours within k rings
}
// Engine keeps the previous multiplier per cell for smoothing over time.
type Engine struct {
cfg Config
prev map[hexgrid.Cell]float64
}
// New returns an engine with no history.
func New(cfg Config) *Engine { return &Engine{cfg: cfg, prev: map[hexgrid.Cell]float64{}} }
// Compute returns the multiplier per cell for one window of counts.
func (e *Engine) Compute(demand, supply map[hexgrid.Cell]int) map[hexgrid.Cell]float64 {
out := map[hexgrid.Cell]float64{}
for c := range demand {
d, s := 0, 0
for _, n := range hexgrid.KRing(c, e.cfg.SmoothK) {
d += demand[n]
s += supply[n]
}
ratio := float64(d) / math.Max(float64(s), 1)
raw := 1.0
if ratio > 1 {
raw = 1 + e.cfg.Sensitivity*(ratio-1)
}
raw = math.Min(raw, e.cfg.Cap)
old, ok := e.prev[c]
if !ok {
old = 1
}
m := e.cfg.Alpha*raw + (1-e.cfg.Alpha)*old
m = math.Max(1, math.Round(m/e.cfg.Step)*e.cfg.Step)
e.prev[c] = m
out[c] = m
}
return out
}A Schemaless-style cell store: immutable cells, 4096 shards, idempotent inserts, buffered writes, a per-shard change feed:
// Package tripstore is a teaching model of the Schemaless cell model as the
// 2016 Uber posts describe it: immutable cells addressed by (row key, column
// name, ref key), a fixed shard count, idempotent inserts and buffered writes
// to a secondary master. Everything runs in memory; it is not Uber code.
package tripstore
import (
"errors"
"hash/fnv"
"sync"
)
// NumShards is fixed at setup time; the posts say "typically 4096".
const NumShards = 4096
// ErrExists is returned when a cell with the same address was already written.
// The client treats it as success: the write is idempotent.
var ErrExists = errors.New("cell already exists")
// ErrMasterDown signals that the primary master did not accept the write.
var ErrMasterDown = errors.New("primary master unavailable")
// Cell is immutable once written. Body is opaque JSON for the store.
type Cell struct {
RowKey string // for example a trip UUID
Column string // BASE, STATUS, NOTES, FARE_ADJUSTMENT
RefKey int64 // version: the highest ref key is the latest
Body string
Seq int64 // per-shard write order (what triggers consume)
}
type addr struct {
row, col string
ref int64
}
// Cluster is one storage cluster (a master; minions omitted in this sketch).
type Cluster struct {
mu sync.Mutex
Up bool
cells map[addr]Cell
log map[int][]Cell // shard -> cells in write order
seq map[int]int64
}
func newCluster() *Cluster {
return &Cluster{Up: true, cells: map[addr]Cell{}, log: map[int][]Cell{}, seq: map[int]int64{}}
}
func (c *Cluster) insert(shard int, cell Cell) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.Up {
return ErrMasterDown
}
a := addr{cell.RowKey, cell.Column, cell.RefKey}
if _, ok := c.cells[a]; ok {
return ErrExists
}
c.seq[shard]++
cell.Seq = c.seq[shard]
c.cells[a] = cell
c.log[shard] = append(c.log[shard], cell)
return nil
}
// Store routes cells to clusters by shard and keeps a buffer for writes that
// could not reach their primary.
type Store struct {
clusters []*Cluster
bufMu sync.Mutex
buffer []bufferedCell
}
type bufferedCell struct {
shard int
cell Cell
}
// New creates a store with n clusters; shards are spread round-robin.
func New(n int) *Store {
s := &Store{}
for i := 0; i < n; i++ {
s.clusters = append(s.clusters, newCluster())
}
return s
}
// ShardOf maps a row key to its shard. All cells of a trip share a shard.
func ShardOf(rowKey string) int {
h := fnv.New32a()
_, _ = h.Write([]byte(rowKey))
return int(h.Sum32() % NumShards)
}
// Cluster returns the cluster that owns a shard.
func (s *Store) Cluster(shard int) *Cluster { return s.clusters[shard%len(s.clusters)] }
// Put writes a cell. If the primary is down the cell goes to the buffer
// (standing in for a randomly chosen secondary master) and Put returns
// buffered=true: the write is durable but not yet readable.
func (s *Store) Put(c Cell) (buffered bool, err error) {
shard := ShardOf(c.RowKey)
err = s.Cluster(shard).insert(shard, c)
switch {
case err == nil, errors.Is(err, ErrExists):
return false, nil // idempotent: a retry of a done write is success
case errors.Is(err, ErrMasterDown):
s.bufMu.Lock()
s.buffer = append(s.buffer, bufferedCell{shard, c})
s.bufMu.Unlock()
return true, nil
default:
return false, err
}
}
// Drain replays buffered cells to primaries that are back up. Replaying the
// same cell twice is harmless because inserts are idempotent.
func (s *Store) Drain() (replayed int) {
s.bufMu.Lock()
defer s.bufMu.Unlock()
kept := s.buffer[:0]
for _, b := range s.buffer {
err := s.Cluster(b.shard).insert(b.shard, b.cell)
if errors.Is(err, ErrMasterDown) {
kept = append(kept, b)
continue
}
replayed++
}
s.buffer = kept
return replayed
}
// Latest returns the cell with the highest ref key for (row, column).
func (s *Store) Latest(row, col string) (Cell, bool) {
shard := ShardOf(row)
c := s.Cluster(shard)
c.mu.Lock()
defer c.mu.Unlock()
var best Cell
found := false
for _, cell := range c.log[shard] {
if cell.RowKey == row && cell.Column == col && (!found || cell.RefKey > best.RefKey) {
best, found = cell, true
}
}
return best, found
}
// Since returns cells of a shard written after seq: a trigger-style change
// feed that a consumer (billing, analytics) reads with its own cursor.
func (s *Store) Since(shard int, seq int64) []Cell {
c := s.Cluster(shard)
c.mu.Lock()
defer c.mu.Unlock()
var out []Cell
for _, cell := range c.log[shard] {
if cell.Seq > seq {
out = append(out, cell)
}
}
return out
}The tests pin the behaviour the page claims (ring moves about one quarter of keys when a fourth worker joins; a retried cell never overwrites; a buffered cell is not readable until drained):
package ring
import (
"fmt"
"testing"
)
func keys(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = fmt.Sprintf("driver-%d", i)
}
return out
}
func TestAddingMemberMovesAboutOneNth(t *testing.T) {
r := New(100)
for _, m := range []string{"geo-a", "geo-b", "geo-c"} {
r.Add(m)
}
ks := keys(30000)
before := map[string]string{}
for _, k := range ks {
before[k] = r.Lookup(k)
}
r.Add("geo-d")
moved := 0
for _, k := range ks {
now := r.Lookup(k)
if now != before[k] {
if now != "geo-d" {
t.Fatalf("key %s moved between old members", k)
}
moved++
}
}
frac := float64(moved) / float64(len(ks))
if frac < 0.15 || frac > 0.35 { // ideal is 1/4
t.Fatalf("moved fraction %.3f", frac)
}
}
func TestRemoveHandsKeysToSurvivors(t *testing.T) {
r := New(50)
r.Add("geo-a")
r.Add("geo-b")
r.Remove("geo-a")
for _, k := range keys(1000) {
if o := r.Lookup(k); o != "geo-b" {
t.Fatalf("key %s -> %s", k, o)
}
}
}
func TestHandleOrForward(t *testing.T) {
r := New(50)
r.Add("geo-a")
r.Add("geo-b")
owner := r.Lookup("driver-7")
if _, local := r.HandleOrForward(owner, "driver-7"); !local {
t.Fatal("owner should handle")
}
other := "geo-a"
if owner == "geo-a" {
other = "geo-b"
}
if to, local := r.HandleOrForward(other, "driver-7"); local || to != owner {
t.Fatalf("expected forward to %s, got %s %v", owner, to, local)
}
}package tripstore
import "testing"
func TestLatestRefKeyWins(t *testing.T) {
s := New(4)
trip := "9b2c1f00-0000-4000-8000-000000000001"
mustPut(t, s, Cell{RowKey: trip, Column: "STATUS", RefKey: 1, Body: `{"charge":"failed"}`})
mustPut(t, s, Cell{RowKey: trip, Column: "STATUS", RefKey: 2, Body: `{"charge":"ok"}`})
got, ok := s.Latest(trip, "STATUS")
if !ok || got.RefKey != 2 {
t.Fatalf("got %+v", got)
}
}
func TestRetryIsIdempotent(t *testing.T) {
s := New(2)
c := Cell{RowKey: "trip-1", Column: "BASE", RefKey: 1, Body: `{"fare":1250}`}
mustPut(t, s, c)
c.Body = `{"fare":9999}` // a retry must not rewrite history
mustPut(t, s, c)
got, _ := s.Latest("trip-1", "BASE")
if got.Body != `{"fare":1250}` {
t.Fatalf("cell was overwritten: %s", got.Body)
}
}
func TestBufferedWriteThenDrain(t *testing.T) {
s := New(2)
row := "trip-2"
cl := s.Cluster(ShardOf(row))
cl.Up = false
buffered, err := s.Put(Cell{RowKey: row, Column: "BASE", RefKey: 1, Body: "{}"})
if err != nil || !buffered {
t.Fatalf("expected buffered write, got %v %v", buffered, err)
}
if _, ok := s.Latest(row, "BASE"); ok {
t.Fatal("buffered cell must not be readable yet")
}
cl.Up = true
if n := s.Drain(); n != 1 {
t.Fatalf("replayed %d", n)
}
if _, ok := s.Latest(row, "BASE"); !ok {
t.Fatal("cell missing after drain")
}
}
func TestChangeFeedOrder(t *testing.T) {
s := New(1)
row := "trip-3"
mustPut(t, s, Cell{RowKey: row, Column: "BASE", RefKey: 1})
mustPut(t, s, Cell{RowKey: row, Column: "STATUS", RefKey: 1})
feed := s.Since(ShardOf(row), 0)
if len(feed) != 2 || feed[0].Column != "BASE" || feed[1].Seq != 2 {
t.Fatalf("feed %+v", feed)
}
if len(s.Since(ShardOf(row), 2)) != 0 {
t.Fatal("cursor not respected")
}
}
func mustPut(t *testing.T, s *Store, c Cell) {
t.Helper()
if _, err := s.Put(c); err != nil {
t.Fatal(err)
}
}The demo wires everything together; its output is in the Lab:
// Command demo wires the toy pieces together: ingest pings, match a rider,
// compute surge per cell, store the trip as immutable cells, and show how
// many keys move when a geospatial worker joins the ring.
package main
import (
"fmt"
"math/rand/v2"
"time"
"academy/case-study-uber/dispatch"
"academy/case-study-uber/hexgrid"
"academy/case-study-uber/ring"
"academy/case-study-uber/surge"
"academy/case-study-uber/tripstore"
)
func main() {
rng := rand.New(rand.NewPCG(7, 7))
now := time.Date(2026, 11, 26, 18, 0, 0, 0, time.UTC)
g := hexgrid.New(35.70, 51.40, 350)
ix := dispatch.New(g, 30*time.Second, 8)
// 1. ingest: 20,000 drivers, 3 pings each 4 s apart
const drivers = 20000
start := time.Now()
for p := 0; p < 3; p++ {
at := now.Add(time.Duration(p*4) * time.Second)
for i := 0; i < drivers; i++ {
lat := 35.60 + rng.Float64()*0.20
lng := 51.25 + rng.Float64()*0.30
ix.Update(fmt.Sprintf("d%05d", i), lat, lng, at)
}
}
fmt.Printf("ingest: %d pings in %v\n", 3*drivers, time.Since(start).Round(time.Millisecond))
// 2. match one rider
t := now.Add(8 * time.Second)
start = time.Now()
c := ix.Nearest(35.70, 51.40, 3, 8, t)
fmt.Printf("match: %d candidates in %v\n", len(c), time.Since(start).Round(time.Microsecond))
for _, x := range c {
fmt.Printf(" %s %.0f m eta %v ring %d\n", x.ID, x.DistM, x.ETA.Round(time.Second), x.RingStep)
}
// 3. surge: demand concentrated around one cell
supply := ix.CellCounts(t)
hot := g.CellOf(35.70, 51.40)
demand := map[hexgrid.Cell]int{hot: 120}
for _, n := range hexgrid.Neighbors(hot) {
demand[n] = 30
}
m := surge.New(surge.Config{Sensitivity: 0.5, Cap: 3, Step: 0.1, Alpha: 1, SmoothK: 1}).Compute(demand, supply)
fmt.Printf("surge: hot cell supply %d demand %d multiplier %.1f\n", supply[hot], demand[hot], m[hot])
// 4. trip cells with a retry and a master outage
s := tripstore.New(8)
trip := "6f1d2a00-0000-4000-8000-00000000abcd"
_, _ = s.Put(tripstore.Cell{RowKey: trip, Column: "BASE", RefKey: 1, Body: `{"driver":"d00042"}`})
_, _ = s.Put(tripstore.Cell{RowKey: trip, Column: "BASE", RefKey: 1, Body: `{"driver":"d00042"}`}) // retry
s.Cluster(tripstore.ShardOf(trip)).Up = false
buf, _ := s.Put(tripstore.Cell{RowKey: trip, Column: "STATUS", RefKey: 1, Body: `{"charge":"ok"}`})
_, readable := s.Latest(trip, "STATUS")
s.Cluster(tripstore.ShardOf(trip)).Up = true
fmt.Printf("trip: shard %d, buffered=%v readable=%v, drained=%d\n", tripstore.ShardOf(trip), buf, readable, s.Drain())
// 5. ring: add a fourth geospatial worker
r := ring.New(100)
for _, w := range []string{"geo-a", "geo-b", "geo-c"} {
r.Add(w)
}
before := map[string]string{}
for i := 0; i < drivers; i++ {
k := fmt.Sprintf("d%05d", i)
before[k] = r.Lookup(k)
}
r.Add("geo-d")
moved := 0
for k, o := range before {
if r.Lookup(k) != o {
moved++
}
}
fmt.Printf("ring: %d of %d keys moved (%.1f%%)\n", moved, drivers, 100*float64(moved)/drivers)
}The Go angle
Go is a published part of this story: the geofence service (2016) was written in Go for CPU-bound point-in-polygon work and background refresh, using a sync.RWMutex and building index segments on the side before swapping them in, which is the same pattern as dispatch.Index. Jaeger's backend is Go (2017 post) and Cadence ships a Go client (Cadence site). For production geometry use github.com/uber/h3-go (cgo bindings to the C library) or github.com/golang/geo/s2; this module stays on the standard library so it builds anywhere (go 1.24, math/rand/v2, hash/fnv, sort, sync).
Laravel
The Laravel side shows the same ideas with framework features: Redis GEO for live positions, a named rate limiter for pings, an append-only cell table with insertOrIgnore, and a cached surge value.
Before
Every online driver loaded and sorted in PHP; one SQL row update per ping elsewhere in the app.
<?php
namespace App\Http\Controllers;
use App\Models\Driver;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
// Before: load every online driver and sort by distance in PHP.
// Correct for a few hundred drivers; O(n) per request and one database row
// update per GPS ping, which is what hurts first.
class MatchController extends Controller
{
public function nearest(Request $request): JsonResponse
{
$lat = (float) $request->query('lat');
$lng = (float) $request->query('lng');
$drivers = Driver::query()->where('online', true)->get();
$sorted = $drivers->sortBy(
fn (Driver $d) => $this->haversineM($lat, $lng, $d->lat, $d->lng)
)->take(3)->values();
return response()->json($sorted);
}
private function haversineM(float $lat1, float $lng1, float $lat2, float $lng2): float
{
$p1 = deg2rad($lat1);
$p2 = deg2rad($lat2);
$dp = $p2 - $p1;
$dl = deg2rad($lng2 - $lng1);
$a = sin($dp / 2) ** 2 + cos($p1) * cos($p2) * sin($dl / 2) ** 2;
return 2 * 6371008.8 * asin(sqrt($a));
}
}After
Live positions in Redis with a last-seen sorted set (pipelined writes, GEOSEARCH through Redis::command, TTL filtering and a sweep):
<?php
namespace App\Dispatch;
use Illuminate\Support\Facades\Redis;
// Live driver positions in Redis: one GEO key per city plus a sorted set of
// last-seen timestamps so ghosts can be filtered and swept. Positions are
// ephemeral; history goes to a log (Kafka or a table) in batches, not here.
class LiveLocations
{
public function __construct(private int $ttlSeconds = 30)
{
}
public function record(string $city, string $driverId, float $lat, float $lng, int $at): void
{
Redis::pipeline(function ($pipe) use ($city, $driverId, $lat, $lng, $at) {
// GEOADD takes longitude first.
$pipe->geoadd("drivers:geo:{$city}", $lng, $lat, $driverId);
$pipe->zadd("drivers:seen:{$city}", $at, $driverId);
});
}
/**
* @return list<array{id: string, meters: float}>
*/
public function nearby(string $city, float $lat, float $lng, int $radiusM, int $count, int $now): array
{
$raw = Redis::command('GEOSEARCH', [
"drivers:geo:{$city}", 'FROMLONLAT', $lng, $lat,
'BYRADIUS', $radiusM, 'm', 'ASC', 'COUNT', $count * 3, 'WITHDIST',
]);
$fresh = [];
foreach ($raw as [$id, $dist]) {
$seen = Redis::zscore("drivers:seen:{$city}", $id);
if ($seen !== false && $seen !== null && $now - (int) $seen <= $this->ttlSeconds) {
$fresh[] = ['id' => (string) $id, 'meters' => (float) $dist];
}
if (count($fresh) === $count) {
break;
}
}
return $fresh;
}
public function sweep(string $city, int $now): int
{
$stale = Redis::zrangebyscore("drivers:seen:{$city}", '-inf', $now - $this->ttlSeconds);
foreach ($stale as $id) {
Redis::zrem("drivers:geo:{$city}", $id);
Redis::zrem("drivers:seen:{$city}", $id);
}
return count($stale);
}
}The ping and nearby endpoints with validation:
<?php
namespace App\Http\Controllers;
use App\Dispatch\LiveLocations;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
// Driver app pings land here. Validation and a rate limit protect the
// live index; the response is tiny because drivers pay for mobile data.
class LocationController extends Controller
{
public function __construct(private LiveLocations $live)
{
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'city' => ['required', 'string', 'max:32'],
'lat' => ['required', 'numeric', 'between:-85.05,85.05'],
'lng' => ['required', 'numeric', 'between:-180,180'],
'sent_at' => ['required', 'integer'],
]);
$this->live->record(
$data['city'],
(string) $request->user()->id,
(float) $data['lat'],
(float) $data['lng'],
min((int) $data['sent_at'], now()->getTimestamp()),
);
return response()->json(['ok' => true], 202);
}
public function nearby(Request $request): JsonResponse
{
$data = $request->validate([
'city' => ['required', 'string', 'max:32'],
'lat' => ['required', 'numeric'],
'lng' => ['required', 'numeric'],
]);
return response()->json($this->live->nearby(
$data['city'], (float) $data['lat'], (float) $data['lng'], 3000, 5, now()->getTimestamp()
));
}
}Routes with a named limiter sized for one ping every four seconds:
<?php
use App\Http\Controllers\LocationController;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
// About one ping every 4 seconds is 15 per minute; allow bursts to 30.
RateLimiter::for('driver-pings', function (Request $request) {
return Limit::perMinute(30)->by($request->user()?->id ?: $request->ip());
});
Route::middleware(['auth:sanctum', 'throttle:driver-pings'])
->post('/driver/location', [LocationController::class, 'store']);
Route::middleware(['auth:sanctum', 'throttle:api'])
->get('/rider/nearby', [LocationController::class, 'nearby']);The cell table and the store (idempotent append, latest version, change feed by cursor):
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('trip_cells', function (Blueprint $table) {
$table->id('added_id'); // write order inside this shard
$table->uuid('row_key'); // trip UUID
$table->string('column_name', 64); // BASE, STATUS, NOTES ...
$table->unsignedBigInteger('ref_key'); // version
$table->json('body');
$table->timestamp('created_at');
$table->unique(['row_key', 'column_name', 'ref_key']);
});
}
public function down(): void
{
Schema::dropIfExists('trip_cells');
}
};<?php
namespace App\TripStore;
use Illuminate\Support\Facades\DB;
// A Schemaless-style cell table on MySQL: cells are never updated, a new
// version gets a higher ref_key, and the unique key makes retries harmless.
// A teaching model of the published design, not Uber code.
class CellStore
{
public const SHARDS = 4096;
public static function shardOf(string $rowKey): int
{
return crc32($rowKey) % self::SHARDS;
}
/**
* Returns true when the cell was inserted, false when it already existed.
*/
public function put(string $rowKey, string $column, int $refKey, array $body): bool
{
$shard = self::shardOf($rowKey);
$inserted = DB::connection($this->connectionFor($shard))
->table('trip_cells')
->insertOrIgnore([
'row_key' => $rowKey,
'column_name' => $column,
'ref_key' => $refKey,
'body' => json_encode($body, JSON_THROW_ON_ERROR),
'created_at' => now(),
]);
return $inserted === 1;
}
public function latest(string $rowKey, string $column): ?array
{
$row = DB::connection($this->connectionFor(self::shardOf($rowKey)))
->table('trip_cells')
->where('row_key', $rowKey)
->where('column_name', $column)
->orderByDesc('ref_key')
->first();
return $row === null ? null : json_decode($row->body, true, 512, JSON_THROW_ON_ERROR);
}
/**
* Change feed for one connection: cells after a cursor, in write order.
*/
public function since(string $connection, int $afterId, int $limit = 500): array
{
return DB::connection($connection)
->table('trip_cells')
->where('added_id', '>', $afterId)
->orderBy('added_id')
->limit($limit)
->get()
->all();
}
// Shards are mapped to a small number of MySQL connections (config/database.php).
private function connectionFor(int $shard): string
{
return 'trips_'.($shard % 4);
}
}Surge per cell cached for the quote path:
<?php
namespace App\Pricing;
use Illuminate\Support\Facades\Cache;
// Illustrative per-cell multiplier (inference, not Uber's model): demand over
// supply, a cap, a 0.1 step, an EWMA against the previous window, cached per
// cell for the quote path to read.
class SurgeCalculator
{
public function __construct(
private float $sensitivity = 0.5,
private float $cap = 3.0,
private float $alpha = 0.5,
) {
}
/**
* @param array<string, int> $demand cell id => ride requests in the window
* @param array<string, int> $supply cell id => idle drivers in the window
* @return array<string, float>
*/
public function compute(array $demand, array $supply, int $ttlSeconds = 120): array
{
$out = [];
foreach ($demand as $cell => $d) {
$ratio = $d / max($supply[$cell] ?? 0, 1);
$raw = $ratio > 1 ? min(1 + $this->sensitivity * ($ratio - 1), $this->cap) : 1.0;
$previous = (float) Cache::get("surge:{$cell}", 1.0);
$m = max(1.0, round(($this->alpha * $raw + (1 - $this->alpha) * $previous) * 10) / 10);
Cache::put("surge:{$cell}", $m, $ttlSeconds);
$out[$cell] = $m;
}
return $out;
}
}The Laravel angle
The Laravel 13 Redis docs say the facade "supports dynamic methods", so Redis::geoadd and Redis::zadd pass straight to the client, Redis::command('GEOSEARCH', [...]) sends any command by name, and Redis::pipeline batches the two writes of each ping. RateLimiter::for with Limit::perMinute(...)->by(...) and the throttle:driver-pings middleware come from the routing docs. The query builder's insertOrIgnore "will ignore errors while inserting records", which turns the unique key into an idempotency check (the docs warn it may ignore other errors on some engines, so log the return value). Cache::put with a TTL keeps surge values short-lived. For a push channel, Laravel Reverb (WebSockets) or SSE from a streamed response play RAMEN's role at small scale; see Real-Time Communication. Long-running trip post-processing maps to queued jobs and Bus::chain, covered in Durable Workflows & Jobs.
The SQL behind the cell store, and a PostgreSQL script that shows the HOT-update effect from the 2016 debate:
-- MySQL 8 / InnoDB: a Schemaless-style entity table (teaching model).
-- One such table lives in each shard database (trips_0000 .. trips_4095).
CREATE TABLE trip_cells (
added_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, -- write order in this shard
row_key BINARY(16) NOT NULL, -- trip UUID
column_name VARCHAR(64) NOT NULL, -- BASE, STATUS, NOTES ...
ref_key BIGINT UNSIGNED NOT NULL, -- version, highest wins
body JSON NOT NULL,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
PRIMARY KEY (added_id),
UNIQUE KEY uq_cell (row_key, column_name, ref_key)
) ENGINE=InnoDB;
-- Idempotent write: a retried insert of the same cell is a no-op.
INSERT IGNORE INTO trip_cells (row_key, column_name, ref_key, body)
VALUES (UUID_TO_BIN('6f1d2a00-0000-4000-8000-00000000abcd'), 'STATUS', 2, '{"charge":"ok"}');
-- Without IGNORE the duplicate fails with:
-- ERROR 1062 (23000): Duplicate entry '...' for key 'trip_cells.uq_cell'
-- Latest version of one column of one trip.
SELECT body FROM trip_cells
WHERE row_key = UUID_TO_BIN('6f1d2a00-0000-4000-8000-00000000abcd')
AND column_name = 'STATUS'
ORDER BY ref_key DESC
LIMIT 1;
-- Trigger-style change feed: a consumer keeps its own cursor per shard.
SELECT added_id, BIN_TO_UUID(row_key) AS trip, column_name, ref_key
FROM trip_cells
WHERE added_id > 81234
ORDER BY added_id
LIMIT 500;-- PostgreSQL: measure the write amplification the 2016 Uber post describes.
-- An UPDATE that touches an indexed column cannot be a HOT update, so every
-- index on the table gets a new entry.
CREATE TABLE users (
id bigserial PRIMARY KEY,
first text NOT NULL,
last text NOT NULL,
birth_year int NOT NULL,
note text
) WITH (fillfactor = 90); -- free space on each page helps HOT updates
CREATE INDEX users_name_idx ON users (first, last);
CREATE INDEX users_birth_idx ON users (birth_year);
UPDATE users SET birth_year = 770 WHERE id = 4; -- indexed column: non-HOT
UPDATE users SET note = 'estimate' WHERE id = 4; -- no indexed column: can be HOT
SELECT relname, n_tup_upd, n_tup_hot_upd
FROM pg_stat_user_tables WHERE relname = 'users';
-- Replica query cancellation that the post complains about is controlled by
-- hot_standby_feedback (on the standby) and max_standby_streaming_delay.
SHOW hot_standby_feedback;-- The one query every trip page runs: latest STATUS of a trip (MySQL 8).
SELECT body FROM trip_cells
WHERE row_key = UUID_TO_BIN(?) AND column_name = 'STATUS'
ORDER BY ref_key DESC LIMIT 1;Solving the classic problems
Interview questions about Uber, answered with the published decision first and a generic fallback.
Find nearby drivers at a million updates per second
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Sharded in-memory index by cell (Uber 2015-16) | S2 cells, Ringpop ring, handle or forward | No database on the hot path; scales by adding workers | State lost on crash until next pings; app-level sharding to operate |
| Redis GEO per city | GEOADD, GEOSEARCH, TTL set | Simple, managed | One key per city on one node; hot cities |
| PostGIS row per driver | UPDATE plus GiST | SQL, joins | Update storms, bloat |
| Kafka log plus stream-built index | Consumers maintain cells | Replayable | Lag between truth and index |
Ghost drivers and late pings
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| TTL check at read time | Skip if now - last_seen > ttl | Always correct | Index still holds ghosts |
| Periodic sweep | Remove silent drivers | Keeps memory bounded | Work per sweep |
| Drop out-of-order pings | Compare client timestamps | No jumping back | Needs sane client clocks; cap by server time |
A hot cell (stadium, airport)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Finer cells in dense areas | Higher H3 resolution or S2 level there | Fewer drivers per cell | Mixed resolutions complicate code |
| Split the owner | More replica points or a dedicated worker | Spreads CPU | Rebalancing |
| Limit candidates | Stop after n per ring | Bounded work | Might miss a slightly better ETA |
Datacenter or region failure mid-trip
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| State digest on the phone (Uber 2015) | Encrypted digest returned periodically, replayed to new DC | No cross-DC replication on the hot path | Client trust and version handling |
| Recompute derived state (Uber 2020 surge) | New primary region consumes input events | No huge state replication | Warm-up time |
| Active/passive with offset sync (Uber 2020) | Consumer resumes at a synced offset | No loss, bounded duplicates | Offset mapping across clusters |
Write a trip while a database master is down
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Buffered writes (Schemaless) | Write to primary and a random secondary master | Durable immediately | Not readable until recovery |
| Raft per partition (Docstore) | Majority commit, automatic leader change | Read-your-write kept | Write needs a majority |
| Queue the write | Outbox or Kafka, apply later | Simple | Read path must tolerate delay |
Never charge twice
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Idempotency key + stored result | Unique key, return stored result on repeat | Exactly-once effect | Key storage and TTL policy |
| Append-only STATUS cells | One cell per attempt with a unique address | Auditable | Readers must take the latest |
| Double-entry ledger | Every movement is balanced | Detects errors | More rows, stricter model |
Surge that does not flicker
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Neighbour smoothing | Sum over k-ring | Fewer edge effects | Blurs very local spikes |
| Time smoothing (EWMA) | Blend with previous window | Stable prices | Slower reaction |
| Step and cap | Round to 0.1, cap at a maximum | Predictable UX | Policy, not physics |
Change the schema of a huge, hot table
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Schemaless columns (Uber 2014) | App-defined columns, no DDL | No downtime | No schema enforcement |
| Docstore schema evolution (2021) | Records of different schemas co-exist | Enforcement plus evolution | A custom database |
| Online DDL tooling | gh-ost, pt-online-schema-change, expand/contract | Standard databases | Operational care; see Zero-Downtime Schema Migrations |
What you can copy
Each Uber subsystem maps to a generic chapter that teaches the reusable mechanism without Uber's scale.
| Uber subsystem | Reusable idea | Read next |
|---|---|---|
| Geospatial workers, S2, H3 | Cell index, k-ring, filter then refine | Geospatial Indexing |
| Ringpop membership | SWIM, suspicion, incarnation numbers | Gossip Protocols |
| Ringpop ring | Consistent hashing with virtual nodes | Consistent Hashing, Sharding at System Level |
| Handle or forward | Request routing to the owner | Service Discovery |
| Supply, demand, DISCO | Separate state owners from the decision maker | Service Boundaries |
| Geofence service | Read-mostly data in every instance, background refresh | Caching |
| ETA residual model | Physical model plus ML correction | ML Systems |
| Surge on Flink | Windowed per-key aggregation, recompute on failover | Stream Processing |
| Schemaless cells | Append-only versioned facts, idempotent writes | API Idempotency, Event Sourcing & CQRS |
| Schemaless triggers | Change feed from the store | Change Data Capture, Outbox |
| Mezzanine migration | Shadow writes, compare, switch | Strangler Fig |
| Postgres vs MySQL debate | Replication and MVCC trade-offs | Replication Topologies, MVCC |
| Docstore | Consensus per shard | Distributed SQL |
| RAMEN push | Sequence-numbered push, SSE vs WebSocket vs gRPC | Real-Time Communication |
| Kafka multi-region | Local produce, async replicate, active/active vs passive | Kafka in Depth, Disaster Recovery |
| DOMA | Domains, layers, gateways | Microservices Architecture, Bounded Context |
| M3, Jaeger | Metrics at scale, distributed tracing | Observability |
| Cadence | Durable workflows | Durable Workflows & Jobs |
| Payments | Idempotency, double entry | Payment Processing Architecture |
| Rate limits on pings | Token bucket per driver | Rate Limiting |
Choosing
Copy, adapt or skip
| Your situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Under 10,000 moving objects | Redis GEO or PostGIS, one region | TTL, rate limit | Uber's custom tier solves a scale you do not have |
| 100,000+ updates per second | In-memory sharded workers keyed by cell | Consistent hashing, handle or forward or a smart client | Matches the published design |
| Need area analytics, pricing, heatmaps | H3 | k-ring smoothing, parent roll-ups | Hexagon one-distance property |
| Need exact region coverings | S2 | Coverer with level bounds | Square hierarchy, exact containment |
| Long-lived business records | Append-only versioned rows on a sharded SQL store | Unique (id, column, version) as idempotency | Schemaless lesson |
| Many indexes, heavy updates, PostgreSQL | Check HOT ratio, drop unused indexes, fillfactor | Logical replication for upgrades | Answers most of the 2016 complaints |
| Need transactions and scale | Distributed SQL (CockroachDB, TiDB, Spanner) or Vitess | Partition keys that keep entities together | Docstore lesson without building one |
| Mobile real-time updates | SSE or WebSocket with sequence numbers; gRPC streams for bidirectional | One decision point for "when to push" | RAMEN lesson |
| Multi-region streaming | Local produce, async replication | Classify consumers: recompute vs exact | Kafka DR lesson |
| Hundreds of services | Group into domains with gateways | Layer rules enforced in CI | DOMA lesson |
| Multi-step money flows | Workflow engine (Temporal, Cadence) | Idempotency keys in every activity | Cadence and payments lessons |
Build or buy, per component
| Component | Uber built | Off-the-shelf today (inference, not Uber's advice) |
|---|---|---|
| Hex grid | H3 (open source) | Use H3 |
| App-level sharding | Ringpop | Orleans-style actors, Akka Cluster, a shard manager |
| Trip store | Schemaless, Docstore | Vitess, CockroachDB, DynamoDB |
| Kafka replication | uReplicator | MirrorMaker 2 |
| Streaming SQL | AthenaX | Flink SQL |
| Metrics | M3 (open source) | Prometheus with M3, Thanos or Mimir |
| Tracing | Jaeger (open source) | OpenTelemetry with Jaeger |
| Workflows | Cadence (open source) | Temporal or Cadence |
In architecture: from a single process to a distributed system
Monolith: one process, one database
This is where Uber started: a Python monolith on PostgreSQL (the 2016 post), two monolithic services around 2012 to 2013 (DOMA post). A small ride or delivery app should look like this: drivers table, trips table with a status column and an append-only trip_events table, a Redis GEO key for live positions, one background worker for billing. The Laravel LiveLocations and CellStore classes fit here unchanged with one connection. The first scaling pain Uber reported was not CPU but the trips table: volume, IOPS, and DDL downtime.
Modular monolith: boundaries without the network
Separate the modules that have different consistency needs: Location (ephemeral, in Redis), Dispatch (reads Location, writes offers), Pricing (reads events, writes multipliers to cache), Trips (append-only store), Payments (ledger, idempotency). Each module owns its tables and exposes one interface, which is DOMA's gateway idea inside one process. Mezzanine's lib/tripstore switch (one API, two backends) is exactly the seam that lets a module change storage later. See Modular Monolith.
Microservices: every arrow is a decision
The published flow: driver app to supply, supply to Geospatial (forwarded by Ringpop), rider request to demand, demand to DISCO, DISCO to routing/ETA, offer to driver through Fireball and RAMEN, trip events to Kafka, consumers for surge, trip store and payments. What survives the boundaries: ids (trip UUID, not an auto-increment, which Mezzanine had to replace), idempotency keys, sequence numbers on push, and events. What does not: transactions across services; Uber's answers are append-only cells, idempotent writes, and workflows (Cadence) for multi-step processes. DOMA appeared when about 2,200 services made the call graph unreadable.
Distributed data: replicas, caches, regions
Each kind of state takes a different consistency choice, and the posts say which. Live location: in memory, lossy, rebuilt by the next pings. Dispatch state across datacenters: carried by the phone. Surge: region-local and recomputed, freshness over consistency (2021 paper). Trips: Schemaless with asynchronous MySQL replication and buffered writes (may be stale or not yet readable after a failure), then Docstore with Raft and strict serializability per partition. Payments: strong consistency. Kafka: regional clusters with asynchronous aggregate copies. The general rules are in CAP and PACELC and Consistency Models.
Scaling path: 1x, 10x, 100x
| Load | Design (Uber's path where published) | First thing that breaks |
|---|---|---|
| 1x: one city, thousands of drivers | Monolith, one PostgreSQL, scan or Redis GEO | The trips table and its DDL |
| 10x: dozens of cities | Services; shard dispatch by city; trip store moved off the main database (Mezzanine 2014) | Big cities overload their shard; polling load at the gateway |
| 100x: hundreds of cities, global | Cell-based sharding (S2) on Ringpop; Schemaless with 4096 shards; Kafka everywhere; push platform; M3 and Jaeger | Service sprawl (DOMA), Schemaless API limits (Docstore), MirrorMaker (uReplicator) |
| Beyond: multi-region, many lines of business | Active-active Kafka, region failover of surge, Docstore with Raft, gRPC push over QUIC, Cadence | Cost and operational complexity, which the later posts address |
Lab: run the toy system, then break it
Run the Go demo (run on the author's laptop)
cd docs/snippets/system-design/case-study-uber/go
go test ./...
go run ./cmd/demoOutput from one run (Apple laptop, Go 1.2x; timings vary):
ingest: 60000 pings in 15ms
match: 3 candidates in 22µs
d19837 95 m eta 12s ring 0
d10108 195 m eta 24s ring 0
d17108 209 m eta 26s ring 0
surge: hot cell supply 8 demand 120 multiplier 2.4
trip: shard 3877, buffered=true readable=false, drained=1
ring: 4899 of 20000 keys moved (24.5%)Read it against the page: ingest is cheap because nothing touches disk (the Ringpop post's point); the match reads only a few cells; surge uses the k-ring sum (demand 120 + 6 x 30 = 300 against the supply in seven cells); the buffered write is durable but not readable until the master returns (Schemaless's trade-off); adding a fourth worker moved about one quarter of keys (consistent hashing).
Drills (expected, not run)
- Ghost drivers. In
dispatch_test.go, set the TTL to 5 seconds and advancenowby 10 seconds between ping and match. Expected:Nearestreturns zero candidates;Sweepreturns the number of drivers. - Hot cell. Put 5,000 drivers inside one 350 m cell and time
Nearestwithn = 3. Expected: time grows linearly with the cell population; reducing the edge length to 150 m (a finer resolution) brings it back down. - Ring without replica points. Call
ring.New(1)and repeat the move test. Expected: the moved fraction swings far from 25% (for example 5% or 60%) because three points cut the ring unevenly. - Retry storm on the trip store. Call
Putfor the same cell 1,000 times. Expected: one cell,Latestunchanged, no error. - Laravel ping limit (expected, not run). With the routes file and a Sanctum token, send 40 pings in a minute. Expected: the 31st gets
429 Too Many RequestswithRetry-AfterandX-RateLimit-Remaining: 0headers. - PostgreSQL HOT (expected, not run). Run
postgres-hot-updates.sqlon PostgreSQL 16 with four rows inserted. Expected:n_tup_upd = 2,n_tup_hot_upd = 1(thenoteupdate is HOT, thebirth_yearupdate is not).
Common misconceptions
| Belief | Reality (with the source) |
|---|---|
| Uber stores every GPS ping in a database for matching | Live positions are held in memory by Geospatial workers (Ringpop 2016) |
| H3 is Uber's dispatch index | H3 is described for analysis and optimisation, surge being the example; 2015 dispatch sharding used S2 |
| The closest idle driver always gets the trip | DISCO also considers drivers about to finish a trip (2015 talk) |
| Ringpop is a service you call | It is a library embedded in the application process (2016 post) |
| Schemaless is a new NoSQL engine | It is a thin routing layer over sharded MySQL (2016) |
| Uber proved PostgreSQL cannot scale | The post is about Postgres 9.2 mechanics at Uber's workload; PostgreSQL developers answered with HOT, hot_standby_feedback and logical replication |
| Append-only means no updates are possible | Updates are new cells with a higher ref key |
| Uber uses WebSockets for the app | It chose SSE in 2015 and gRPC bidirectional streaming over QUIC later |
| Multi-region means synchronous replication of everything | Surge recomputes; dispatch used the phone; Kafka replicates asynchronously |
| DOMA is a return to the monolith | It keeps microservices and adds domains, layers, gateways, extensions |
| Exactly-once payments means exactly-once delivery | It means idempotency plus strong consistency (2018 post) |
| Everything on this page describes Uber today | Each fact is dated; later posts replaced earlier designs |
Cheat sheet
| Topic | What to remember |
|---|---|
| Pings | Every 4 s (2015); in memory; TTL; drop out-of-order |
| Failover trick | Phone keeps an encrypted state digest for the next datacenter |
| S2 | 2015 dispatch sharding, 3.31 km2 cells, coverings |
| H3 | Hexagons, 16 resolutions, 122 base cells, 12 pentagons; surge per hexagon |
| DISCO | Matches supply and demand, includes soon-free drivers, ranks by ETA |
| Ringpop | SWIM gossip + hash ring with replica points + handle or forward over TChannel |
| Geofences | Go, in-memory everywhere, city then fence, p99 under 100 ms |
| ETA | Routing engine sum of segments + ML residual (DeepETA 2022) |
| Surge | Supply and demand per area, Flink per region, freshness over consistency |
| Schemaless | Immutable cells (row, column, ref), 4096 MySQL shards, buffered writes, triggers |
| Postgres to MySQL | Write amplification, physical WAL, upgrades, connections; critiques: HOT, logical replication |
| Docstore | MySQL + Raft per partition, schemas, transactions, CDC |
| Push | RAMEN, Fireball; SSE with seq acks (2015) then gRPC over QUIC (2022) |
| Kafka | Regional + aggregate clusters, uReplicator, active/active vs active/passive |
| DOMA | Domains, five layers, gateways, extensions; 2,200 services, 70 domains |
| Observability | M3 for metrics, Jaeger for tracing (OpenTracing) |
| Workflows | Cadence (Uber), Temporal (successor by Cadence's creators) |
| Payments | Idempotency, strong consistency, double-entry, active-active |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does the 2016 Ringpop post say database storage is useless for live driver locations? Must-know
Answer
Answer: Because the data is fleeting: a position is stale within seconds, so persisting every ping costs write throughput for data nobody reads. The Geospatial workers keep the ephemeral state in memory and distribute it with Ringpop.
2 — How did the 2015 dispatch design survive a datacenter failure without replicating data across datacenters? Important
Answer
Answer: The server periodically returned an encrypted state digest to the driver's phone along with location updates. After a failover, the new datacenter knew nothing about the driver, asked for the digest, and resumed from it.
3 — Name the two Uber uses of cells and which grid each source names. Good to know
Answer
Answer: Sharding and candidate search in dispatch used Google S2 cells (3.31 km2, per the 2015 talk write-up). Surge and marketplace analysis use H3 hexagons (2018 post).
4 — Why can DISCO beat "nearest idle driver"? Important
Answer
Answer: It also considers drivers who will become free soon. A driver dropping off two minutes away may reach the rider in three minutes, while the nearest idle driver needs eight.
5 — What are Ringpop's three parts? Must-know
Answer
Answer: A SWIM-based membership protocol (ping, ping-req, suspect, faulty, incarnation numbers), consistent hashing (FarmHash, red-black tree, replica points), and forwarding with a handle-or-forward pattern over TChannel.
6 — How does a Schemaless update work if cells are immutable? Important
Answer
Answer: The application writes a new cell with the same row key and column name and a higher ref key. Readers take the cell with the highest ref key. Writing the same address twice is rejected, which makes retries idempotent.
7 — What is a buffered write and what does it trade away? Important
Answer
Answer: The worker writes the cell to the primary master and to a randomly chosen secondary master, and acknowledges only if both succeed. If the primary fails before replication, the data still exists; the trade is that it cannot be read until the primary recovers or a minion is promoted.
8 — Give two of Uber's 2016 arguments against Postgres and the matching critique. Good to know
Answer
Answer: Write amplification (every index updated on each update) was answered with HOT updates and being careful with indexes. Replica query cancellation was answered with hot_standby_feedback. Cross-version replication was answered by logical replication, then missing from core.
9 — Why did Uber choose SSE in 2015, and what did gRPC add later? Important
Answer
Answer: SSE fit the existing HTTP + JSON stack and had good security, mobile SDK support and small binary impact. It is one-way, so acks needed reconnects with sequence numbers. gRPC bidirectional streams carry acks on the same stream, and QUIC improved tail latency on mobile networks.
10 — How does surge survive a region failure according to the 2020 Kafka post? Good to know
Answer
Answer: Surge consumes Kafka in active/active mode. When the primary region fails, another region becomes primary and its Flink job recomputes pricing from the input events, because the Flink state is too large to replicate synchronously.
11 — What problem did DOMA solve and with which four ideas? Good to know
Answer
Answer: The complexity of about 2,200 microservices, where debugging could span 50 services and 12 teams. DOMA groups services into domains, arranges domains in layers with downward-only dependencies, gives each domain a gateway, and offers extension points.
12 — Which parts of this page are inference rather than Uber's published design? Must-know
Answer
Answer: The scope and estimate steps, the wiring between components in the architecture diagram, DISCO's exact algorithm, the surge formula, the internal handling of late pings and sweeps, and the Laravel and Go code, which are re-implementations.
Glossary
| Term | Meaning |
|---|---|
| Uber | Ride-hailing and delivery marketplace whose engineering posts are the sources of this page |
| Driver location / location update | One position report from the driver app; every four seconds in 2015 |
| Location update rate | How often the mobile client sends position; sets write load and freshness |
| Mobile client | The rider or driver app; also a carrier of state digests in Uber's failover design |
| State digest | Encrypted snapshot of dispatch state returned to the phone for datacenter failover |
| Geospatial index | Structure mapping positions to cells so nearby search reads few cells |
| S2 | Google's spherical geometry library: cube-face cells on a Hilbert curve, 64-bit ids |
| H3 | Uber's hexagonal hierarchical grid: 16 resolutions, 122 base cells, 12 pentagons |
| Hexagonal grid | Tiling with hexagons; every neighbour centre is the same distance away |
| k-ring | All cells within k steps of a cell |
| Supply / demand | Drivers and their capabilities; riders and their requests |
| Matching / dispatch | Assigning a request to a driver |
| DISCO | Dispatch Optimization, the 2015 service that matches supply and demand |
| ETA | Estimated time of arrival; used for matching, pickup times, fares |
| Routing engine | Road-graph engine summing segment travel times with live traffic |
| DeepETA | Uber's neural network predicting the routing engine's residual error |
| Michelangelo | Uber's ML-as-a-service platform (2017) |
| Ringpop | Uber's library for app-level sharding: SWIM membership, hash ring, forwarding |
| SWIM | Scalable Weakly-consistent Infection-style Membership protocol; ping and ping-req |
| Gossip | Spreading membership changes by piggybacking on periodic peer messages |
| Consistent hashing | Key placement on a ring so adding a node moves only about 1/n of keys |
| Replica points | Several ring positions per node to even out the key distribution |
| Handle or forward | Process the request if this node owns the key, otherwise forward to the owner |
| TChannel | Uber's RPC framing protocol, Ringpop's transport |
| FarmHash | Google's fast non-cryptographic hash used by Ringpop |
| Geofence | A polygon that defines rules for an area (city, airport, pricing zone) |
| Surge pricing / dynamic pricing | Per-area price increase when demand exceeds supply |
| Trip | The business record of one ride, written in pieces over time |
| Mezzanine | Uber's 2014 project moving trips from PostgreSQL to Schemaless |
| Schemaless | Uber's append-only cell store on sharded MySQL |
| Cell (Schemaless) | Immutable JSON blob addressed by row key, column name and ref key |
| Ref key | Version number of a cell; the highest is the latest |
| Buffered writes | Writing to a primary and a secondary master so a write survives master loss |
| Triggers (Schemaless) | Consumers that read each shard's cells in write order |
| Sharding | Splitting data across databases by a key; 4096 fixed shards in Schemaless |
| Docstore | Uber's transactional successor of Schemaless: MySQL plus Raft per partition |
| Raft | Consensus protocol with one leader replicating a log to followers |
| MySQL / InnoDB | Relational database and its engine; clustered primary key, in-place updates |
| Postgres / PostgreSQL | Relational database; heap tuples, physical WAL replication |
| Write amplification | One logical change causing many physical writes |
| HOT update | PostgreSQL heap-only tuple update that touches no index |
| hot_standby_feedback | PostgreSQL setting that stops the primary removing rows a standby query needs |
| pglogical | Extension providing logical replication for older PostgreSQL versions |
| Kafka | Distributed log used as Uber's event backbone |
| uReplicator | Uber's Kafka cross-cluster replicator built on Apache Helix |
| Aggregate cluster | Kafka cluster holding copies of all regional clusters' data |
| Active/active, active/passive | Consumers in every region vs one consumer in the primary region |
| Flink | Stream processing framework; runs surge and FlinkSQL jobs at Uber |
| AthenaX | Uber's SQL-on-Flink streaming analytics platform (2017) |
| Streaming | Continuous processing of unbounded event sequences |
| Pinot | Real-time OLAP store used at Uber |
| RAMEN | Uber's real-time push platform |
| Fireball | RAMEN component deciding when to push |
| Push | Server-initiated delivery to the app |
| WebSocket | Full-duplex protocol over one TCP connection (RFC 6455) |
| SSE | Server-Sent Events, one-way event stream over HTTP |
| gRPC / QUIC | RPC framework with bidirectional streaming; UDP-based transport behind HTTP/3 |
| Microservices | Independently deployed services with network interfaces |
| DOMA / domain-oriented | Domain-Oriented Microservice Architecture: domains, layers, gateways, extensions |
| Gateway (DOMA) | Single entry point into a domain |
| M3 | Uber's metrics platform and Prometheus remote storage |
| Metrics | Numeric time series for dashboards and alerts |
| Jaeger | Uber's distributed tracing system, OpenTracing-compatible |
| Tracing | Recording the spans of one request across services |
| Cadence | Uber's workflow engine; workflows as code with durable history |
| Temporal | Workflow engine by Cadence's co-creators, its successor |
| Workflow | Durable multi-step process that survives crashes |
| Multi-region / failover | Running in several regions and moving traffic when one fails |
| Payments | Collections (charging riders) and disbursements (paying drivers) |
| Idempotency | Repeating an operation has the same effect as doing it once |
| Double-entry bookkeeping | Every money movement recorded as balanced debit and credit |
| Inference | A statement on this page not taken from an Uber source |
References
Uber engineering blog and papers (all fetched and saved):
- Ringpop post (4 Feb 2016): https://www.uber.com/blog/ringpop-open-source-nodejs-library/
- Ringpop documentation: https://ringpop.readthedocs.io/en/latest/ and https://ringpop.readthedocs.io/en/latest/architecture_design.html
- H3 (27 Jun 2018): https://www.uber.com/blog/h3/ ; H3 docs: https://h3geo.org/docs/
- Project Mezzanine (28 Jul 2015): https://www.uber.com/blog/mezzanine-codebase-data-migration/
- Designing Schemaless (12 Jan 2016): https://www.uber.com/blog/schemaless-part-one-mysql-datastore/
- The Architecture of Schemaless (15 Jan 2016): https://www.uber.com/blog/schemaless-part-two-architecture/
- Why Uber Engineering Switched from Postgres to MySQL (26 Jul 2016): https://www.uber.com/blog/postgres-to-mysql-migration/
- Evolving Schemaless into a Distributed SQL Database (23 Feb 2021): https://www.uber.com/blog/schemaless-sql-database/
- Highest QPS service using Go, geofences (24 Feb 2016): https://www.uber.com/blog/go-geofence-highest-query-per-second-service/
- DeepETA (10 Feb 2022): https://www.uber.com/blog/deepeta-how-uber-predicts-arrival-times/
- Michelangelo (5 Sep 2017): https://www.uber.com/blog/michelangelo-machine-learning-platform/
- Real-Time Push Platform (18 Dec 2020): https://www.uber.com/blog/real-time-push-platform/
- Next Gen Push Platform on gRPC (16 Aug 2022): https://www.uber.com/blog/ubers-next-gen-push-platform-on-grpc/
- uReplicator (4 Aug 2016): https://www.uber.com/blog/ureplicator-apache-kafka-replicator/
- Disaster Recovery for Multi-Region Kafka (21 Dec 2020): https://www.uber.com/blog/kafka/
- Reliable Reprocessing and Dead Letter Queues with Kafka (16 Feb 2018): https://www.uber.com/blog/reliable-reprocessing/
- AthenaX (9 Oct 2017): https://www.uber.com/blog/athenax/
- Real-time Data Infrastructure at Uber (SIGMOD '21): https://arxiv.org/abs/2104.00087 (full text read at https://ar5iv.labs.arxiv.org/html/2104.00087)
- Domain-Oriented Microservice Architecture (23 Jul 2020): https://www.uber.com/blog/microservice-architecture/
- M3 (7 Aug 2018): https://www.uber.com/blog/m3/
- Evolving Distributed Tracing, Jaeger (2 Feb 2017): https://www.uber.com/blog/distributed-tracing/
- Engineering Uber's Next-Gen Payments Platform (5 Dec 2018): https://www.uber.com/blog/payments-platform/
- Announcing Cadence 1.0 (22 Jun 2023): https://www.uber.com/blog/announcing-cadence/ ; Cadence site: https://cadenceworkflow.io/
- How surge pricing works (Uber driver site): https://www.uber.com/us/en/drive/driver-app/how-surge-works/
Talks by Uber engineers:
- Matt Ranney, Scaling Uber's Real-time Market Platform, QCon London 2015: https://www.infoq.com/presentations/uber-market-platform/ ; slides: https://qconlondon.com/ln2018/london-2015/system/files/presentation-slides/QCon 2015.pdf ; InfoQ write-up of the talk: https://www.infoq.com/news/2015/03/uber-realtime-market-platform/
Not Uber (used only for the critique and product mechanics, labelled where used):
- Robert Haas, Uber's move away from PostgreSQL (Aug 2016): https://rhaas.blogspot.com/2016/08/ubers-move-away-from-postgresql.html
- PostgreSQL docs, Hot Standby: https://www.postgresql.org/docs/current/hot-standby.html
- Temporal, About (founders and Cadence origin): https://temporal.io/about
- Laravel 13 docs: https://laravel.com/docs/13.x/redis , https://laravel.com/docs/13.x/queries , https://laravel.com/docs/13.x/routing , https://laravel.com/docs/13.x/cache