Skip to content

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 forGo to
The whole system in three tablesEverything in one minute
Why study Uber at all, and the core trade-offWhy it exists
Which post says what, and whenWhere 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 digestLocation ingestion
S2 and H3Geospatial indexing at Uber
Supply, demand, DISCOMatching and dispatch
Ringpop, SWIM, consistent hashingRingpop
Geofences, ETA, routing engineGeofences, ETA and routing
Surge pricingPricing
Trip storage, Schemaless, Docstore, Postgres vs MySQLMezzanine and Schemaless, Postgres to MySQL, Docstore
Pushing to phonesPush to mobile clients
Kafka, uReplicator, Flink, AthenaXStreaming
DOMAMicroservices and DOMA
M3, JaegerObservability
Multi-region failover, Cadence, TemporalReliability and workflows
Payments, idempotencyPayments
Exact knobs and messagesMechanics
CodeGo, Laravel
Classic interview problems on this systemSolving the classic problems
What to copy into your own systemWhat you can copy, Choosing
Monolith to distributed systemIn architecture
Runnable demo and drillsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The subsystems and what Uber published about each.

SubsystemWhat Uber published (short)Year of the sourceGeneric mechanism
Location ingestionDriver phones post location every four seconds; Geospatial holds the live positions in memory, not in a database2015 talk, 2016 postGeospatial Indexing
Geospatial indexGoogle S2 cells to shard supply (2015); H3 hexagons for pricing and dispatch analysis (2018)2015, 2018Cell index, k-ring
MatchingSupply and demand services plus DISCO (Dispatch Optimization) which also considers drivers about to become free2015Bipartite matching on ETA (inference for the algorithm)
Membership and shardingRingpop: SWIM gossip, consistent hash ring with replica points, handle or forward over TChannel2016Gossip Protocols, Consistent Hashing
GeofencesA Go service answering point-in-geofence on every app request; p99 under 100 ms at hundreds of thousands of QPS2016Polygon containment, two-level index
ETAA routing engine sums road-segment times; an ML model (DeepETA) predicts the residual2022Physical model plus learned correction
PricingSurge computed from supply and demand per hexagon; a Flink job per region2018, 2020Per-cell ratio over a stream (inference for the formula)
Trip storageMezzanine (2014) moved trips from one Postgres to Schemaless: append-only cells on sharded MySQL2015, 2016Sharding at System Level
Database engine"Why Uber Engineering Switched from Postgres to MySQL": write amplification, physical replication, upgrades, connections2016MVCC, Replication
DocstoreSchemaless evolved into a transactional, schema-enforcing store: MySQL plus Raft per partition2021Distributed SQL
PushRAMEN: Fireball decides when, SSE delivers with sequence-number acks (2015); later gRPC bidirectional over QUIC2020, 2022Real-Time Communication
StreamingKafka with trillions of messages per day, uReplicator across regions, Flink and FlinkSQL (AthenaX)2016 to 2021Kafka, Stream Processing
Service architectureAbout 2,200 critical microservices grouped into domains, layers, gateways and extensions (DOMA)2020Microservices
ObservabilityM3 metrics platform (Prometheus remote storage); Jaeger distributed tracing2017, 2018Observability
ReliabilityActive-active Kafka, region failover of surge; Cadence workflows (Temporal's predecessor)2020, 2023Durable Workflows
PaymentsActive-active, exactly-once by idempotency and strong consistency, double-entry bookkeeping2018Payment Processing

Numbers that come from Uber's own sources.

FactValueSource (see References)
Driver location update rateEvery four secondsInfoQ write-up of Matt Ranney's QCon London 2015 talk
Geospatial write targetOne million writes per second, a much higher read rateSame talk write-up
S2 cell size used for sharding3.31 km2Same talk write-up
Schemaless shardsFixed, "typically 4096"Mezzanine post 2015, Schemaless part two 2016
Trip growth in early 2014About 20% a monthMezzanine post 2015
MicroservicesAbout 500 in fall 2015, over 2,000 in early 2017, around 2,200 critical in 2020Jaeger post 2017, DOMA post 2020
Geofence servicep99 under 100 ms, hundreds of thousands of QPS, tens of thousands of geofencesGeofence post 2016
H316 resolutions (0 to 15), 122 base cells, 12 pentagons, each finer level one seventh the areaH3 post 2018
KafkaTrillions of messages and petabytes per dayKafka DR post 2020, Real-time infra paper 2021
M36.6 billion time series, 500 million metrics per second aggregated, 20 million persisted per secondM3 post 2018
Docstore partition3 to 5 nodes, each in an independent zone, Raft per partitionDocstore post 2021
Polling share before push80% of API gateway requests were polling callsRAMEN post 2020
CadenceOver a thousand services at Uber; teams wrote 40% less code (internal 2021 survey)Cadence 1.0 post 2023
Toy demo on this page60,000 pings in 15 ms, match in 22 µs, ring add moved 24.5% of keysLab, measured on one laptop

The problems and the decision Uber published.

ProblemDecisionSection
Location data is huge and useless after secondsKeep it in memory in sharded workers; do not store each ping in a databaseLocation
Sharding by city became hard to operateShard by geography cell (S2), workers on a hash ring (Ringpop)Geo index, Ringpop
A datacenter fails mid-tripThe driver phone holds an encrypted state digest; the new datacenter asks for itLocation, Reliability
Trips outgrow one PostgresBuild Schemaless: append-only cells on 4096 MySQL shardsSchemaless
Primary MySQL master down at write timeBuffered writes to a random secondary masterSchemaless
Polling melts the API gatewayPush platform (RAMEN), then gRPC streamsPush
Surge must survive a region lossActive-active Kafka; each region recomputes from input eventsPricing, Reliability
Thousands of services, nobody sees the whole callDOMA layers and gateways; Jaeger tracesDOMA, Observability
Double charges on retriesIdempotency and strong consistency in paymentsPayments
Uber ride path, assembled from Uber's own posts (layout is a simplification)Driver appping every 4 s (2015)Rider apprequest, quoteEdge layer /API gatewayDOMA top layergeofence lookup(Go, every request)Supply serviceDemand serviceGeospatial indexS2 cells, Ringpop ringDISCOmatch supplyand demandRoutingengine + ETADeepETA (2022)Kafka (regional and aggregate clusters, uReplicator between regions): trip, location and app eventsFlink job: surgesupply and demandper H3 hexagonTrip storeSchemaless (2014) thenDocstore, on MySQLPayments, M3, Jaeger,Cadence workflows,Pinot, data lakeRAMEN pushFireball decideswhen to push;SSE (2015), thengRPC over QUIC(2022)Solid arrows: request and event flow. Dashed: push back to the apps. Each box is cited in the chapter; the wiring between boxesis an inference from several posts of different years, not one published diagram.

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.

PartFavoursGives upEvidence
Live locationFreshness, write throughputDurability of each pingRingpop post: "database storage would be useless" for fleeting location data
Surge pricingFreshness and availabilityCross-region consistencyReal-time infra paper: "we must therefore prioritize freshness ahead of consistency"
Trip writesWrite availabilityShort-term read-your-write after a failureSchemaless posts: buffered writes, "favoring write availability over read-your-write semantics"
DocstoreStrict serializability per partitionAvailability under a partitionDocstore post: "favors consistency over availability"
PaymentsExactly-once effectSimplicityPayments 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 ​

  1. "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.
  2. "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).
  3. "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.

DateSource (Uber unless noted)What it statesUsed for
March 2015Matt 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 failoverLocation, matching, failover
28 Jul 2015Project Mezzanine: The Great Migration2014 migration of trips from one PostgreSQL to Schemaless; 4096 shards; append-only; trip-id to UUID; shadow writes and validationTrip storage
12 and 15 Jan 2016Designing Schemaless and The Architecture of SchemalessCell model (row key, column, ref key), triggers, worker and storage nodes, buffered writes, MySQL entity tableTrip storage
4 Feb 2016How Ringpop from Uber Engineering Helps Distribute Your Application + Ringpop docsSWIM, FarmHash, red-black tree, replica points, handle or forward, Geospatial as the first use caseSharding, membership
24 Feb 2016How We Built Uber Engineering's Highest Query per Second Service Using GoGeofence lookup service, city-level two-step scan, in-memory index refreshed in the backgroundGeofences
26 Jul 2016Why Uber Engineering Switched from Postgres to MySQLPostgres 9.2 tuple layout, write amplification, WAL replication, upgrade pain, process per connection; InnoDB comparisonDatabase choice
Aug 2016Robert Haas (PostgreSQL committer, not Uber), Uber's move away from PostgreSQLLogical replication missing in core, HOT updates, hot_standby_feedbackCritique
4 Aug 2016uReplicator: Uber Engineering's Robust Apache Kafka ReplicatorMirrorMaker rebalancing problems; Apache Helix assignment; zero data loss goalStreaming
2 Feb 2017Evolving Distributed Tracing at Uber EngineeringMerckx, then Jaeger; 500 services in 2015, 2,000+ in 2017; OpenTracingObservability
5 Sep 2017Meet MichelangeloML-as-a-service platformETA, ML
9 Oct 2017Introducing AthenaXSQL compiled to Flink jobs on YARNStreaming
27 Jun 2018H3: Uber's Hexagonal Hierarchical Spatial IndexHexagons, 122 base cells, 12 pentagons, 16 resolutions; surge from supply and demand in hexagonsGeo index, pricing
7 Aug 2018M3: Uber's Open Source, Large-scale Metrics Platform for PrometheusM3DB, coordinator, aggregation, numbersObservability
5 Dec 2018Engineering Uber's Next-Gen Payments PlatformActive-active, idempotency, double-entry bookkeepingPayments
23 Jul 2020Introducing Domain-Oriented Microservice ArchitectureDomains, five layers, gateways, extensions; 2,200 servicesServices
18 Dec 2020Uber's Real-Time Push PlatformRAMEN, Fireball, SSE with sequence numbers; 80% pollingPush
21 Dec 2020Disaster Recovery for Multi-Region Kafka at UberRegional and aggregate clusters, active/active and active/passive, surge failoverReliability
23 Feb 2021Evolving Schemaless into a Distributed SQL DatabaseDocstore: schemas, partitions of 3 to 5 nodes, Raft, MySQL engineDocstore
2021Real-time Data Infrastructure at Uber (SIGMOD '21 paper, arXiv 2104.00087)Kafka, Flink, FlinkSQL, Pinot; dynamic pricing favours freshnessStreaming, pricing
10 Feb 2022DeepETA: How Uber Predicts Arrival Times Using Deep LearningRouting engine plus residual model; Transformer-style encoderETA
16 Aug 2022Uber's Next Gen Push Platform on gRPCSSE to gRPC bidirectional streaming over QUICPush
22 Jun 2023Announcing Cadence 1.0Six-year workflow project; over a thousand servicesWorkflows

What changed over time ​

What changed over time (dates are the posts' publication dates)20152016201720182020202120222023Mezzanine(trips off onePostgres, 2014)DISCO, S2,4 s pings(QCon talk)SchemalessRingpopGo geofencesPostgres toMySQLuReplicatorJaeger(2,000+services)AthenaXon FlinkMichelangeloH3 opensourcedM3 metricsPaymentsplatform:idempotencyDOMA(2,200services)RAMEN pushKafka multi-region DRDocstore:Schemaless+ Raft + SQLReal-timeinfra paperDeepETA(Transformerover routing)Push on gRPCover QUICCadence 1.0(6+ years,1,000+services)Pattern: build a narrow tool under growth pressure, open-source it, then generalise it (Schemaless to Docstore, SSE to gRPC).
AreaEarlier (dated source)Later (dated source)Why it changed, per the later post
Backend shapeTwo 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 searchOne 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 dispatchSharded by city (talk write-up 2015)Sharded by S2 cell (2015)Big cities became hard to manage
Trip storageOne PostgreSQL instance (Mezzanine 2015)Schemaless on MySQL (2014 launch)Storage volume, IOPS, downtime for schema changes
SchemalessAppend-only, no schema (2016)Docstore, schema-on-write, transactions, Raft (2021)Restrictive API; Cassandra tried in between and found lacking at Uber scale
App updatesPolling dozens of APIs (RAMEN 2020)SSE push (from 2015, RAMEN 2020), then gRPC over QUIC (2022)Load, battery, data cost; bidirectional acks
TracingMerckx for the Python monolithJaeger (2017)No distributed context propagation
MetricsGraphite and Carbon with manual reshardingM3 (since 2015, open-sourced 2018)Single-node disk failure lost metrics
ETAXGBoost ensembles over the routing engineDeepETA 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.

text
     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 kept

Real 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.

RequirementTarget (inference unless cited)Owner subsystem
See nearby cars and ETASeconds; map can be slightly staleLocation, geo index, ETA
Match a requestA few seconds end to endDISCO, supply, demand
Price before requestReflects the area's current supply and demandPricing
Never lose a tripWrite must succeed even when one database master is down (Schemaless goal, cited)Trip store
Never charge twiceExactly-once effect (payments post, cited)Payments
Survive a datacenter or region lossContinue trips; recompute surge elsewhere (cited)Reliability
Non-goals hereMaps production, fraud models, Eats logisticsOther 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.

text
     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 durable

Real 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.

LoadOrder of magnitudeKindWhere it lands
Location pings10^5 to 10^6 per secondWrite, ephemeralIn-memory geospatial workers
Nearby-car reads10^5 per secondRead, stale-tolerantSame workers, per-cell cache
Ride requests10^4 per secondRead plus writeDemand service, DISCO
Trip cell writes10^3 to 10^4 per secondWrite, durableSchemaless or Docstore
Events to KafkaTrillions per day (cited)AppendKafka 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.

text
     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 M3

Real 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).

ComponentStateStoreConsistency need
Geospatial workersLive driver positionsMemoryFresh, lossy is fine
Supply / demand servicesDriver and request state machinesMemory plus phone state digest (2015)Per-entity ordering
DISCOMatching decisionsTransientSingle owner per area at a time (inference)
PricingMultipliers per hexagonFlink state, fast key-value store (paper)Fresh over consistent
Trip storeTrip cellsSchemaless / Docstore on MySQLDurable, idempotent
PaymentsLedgerStrongly 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.

text
     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 needed

Real 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).

DesignWrite cost per pingSurvives worker lossSurvives datacenter lossUsed by Uber (source)
Row update in a SQL tableHigh (index, WAL, MVCC)YesWith cross-DC replicationNo, per Ringpop post
In-memory worker, shardedVery lowState rebuilt from next pings (inference)Phone state digestYes, 2015 talk and 2016 post
Redis GEO per cityLowDepends on Redis replicationDependsNot described by Uber; common alternative
Append to Kafka, consumers build the indexLow appendReplayAggregate clustersKafka 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.

text
     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 radius

Real 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.

PropertyGoogle S2Uber H3Geohash (for comparison)
Cell shapeQuadrilateral on a cube faceHexagon (12 pentagons per resolution)Rectangle in lat/lon
Hierarchy4 children, exact7 children, approximate containment32 children per character, exact
Neighbour distanceEdge and corner neighbours differOne distance for all 6Edge and corner neighbours differ
Id64-bit, Hilbert order64-bit, truncatable to parentBase32 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.

text
     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).

StrategyWait timeExtra drivingComputePublished by Uber?
Nearest idle driver, greedyCan be poorLowCheapOld system matched only currently available supply (talk write-up)
Include soon-free drivers (DISCO)BetterLowerMore data, more readsYes, 2015
Batched global assignment per areaBest on averageLowestHeavier, needs a short batching windowNot in the sources read (inference)
Pool chainingLower cost per riderHigher per driverRoute planningSlides 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.

Ringpop: hash ring + SWIM membership + handle or forwardABCABChash(driver-42)each worker ownsthe arc before eachof its replica points1. Ping for driver-42 arrives at worker A2. ringpop.lookup(driver-42) returns B3. A is not the owner: forwardWorker AWorker Bowns driver-42TChannelSWIM membership (per Ringpop docs)ping: random member, round after roundping-req: ask others to probe a silent onestates: alive, suspect, faulty, leaveincarnation number = logical clockAdding worker D takes over only the arcs before D's points; the toy ring in this chapter moved 24.5% of 20,000 keys (ideal 25%).
text
     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 move

Real 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).

ConcernRingpop (docs)Typical alternativeWhere taught
MembershipSWIM gossip inside the appZooKeeper or etcd, Kubernetes endpointsGossip Protocols, Leader Election
Key placementHash ring, replica points, FarmHashRendezvous hashing, fixed shard mapConsistent Hashing
RoutingHandle or forward in the workerSmart client, or a proxy (Envoy)Service Discovery
Failure detectionping, ping-req, suspect timeoutHealth checks from a load balancerGossip Protocols
TransportTChannelgRPCgRPC & 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.

text
     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 lock

Real 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.

DesignLookupUpdateFits when
Linear scan of all fencesO(n)TrivialHundreds of fences
City first, then city fences (Uber 2016)O(cities + fences in city)Background swapCity-centric rules, tens of thousands of fences
R-tree / PostGIS GiSTO(log n)Index maintenanceMany overlapping shapes, ad-hoc queries
Cell to fence cache (S2 or H3 covering)O(1) per cell plus exact checkRecompute coveringVery 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).

text
     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 it

Real scenario: pickup ETA on the request screen; ranking candidates in matching; upfront fares; delivery planning in Eats.

ApproachAccuracyLatencyChange cost
Straight-line distance / constant speedPoor in citiesMicrosecondsNone (the toy dispatch uses this)
Routing engine on road graph with live trafficGoodMillisecondsHigh: the engine is complex
Routing engine plus tree residual (XGBoost)BetterLowMedium
Routing engine plus DeepETA residualBest reported by Uber (2022)Low, served at scaleRetrain 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.

text
     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).

ChoiceOption AOption BWhat Uber published
Area unitHand-drawn zonesGrid cellsHexagons (H3); geofences in the 2021 paper
ComputeBatch every few minutesStream with windowsFlink job per region
Consistency vs freshnessSame price in every regionFresh price, region-localFreshness first (paper)
FailoverReplicate Flink stateRecompute from input in the new regionRecompute (Kafka DR post)
Rider displayMultiplierUpfront fare including surgeVaries 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.

Schemaless (2016 posts): immutable cells and buffered writesrow key (trip UUID)BASESTATUSNOTEStrip 6f1d...ref 112trip 9b2c...ref 1ref 1STATUS ref 1 = failed charge, ref 2 = retry succeeded. A cell is never updated;the latest is the highest ref key. Same address twice = rejected (idempotent).shard = f(row key) among a fixed 4096; each shard is a MySQL database.Client libraryretries other hostsWorker noderoutes by shard1. primary masterasync MySQL to minions2. secondary masterrandom, buffer tableAck to client only if both writes succeed.A background job deletes the buffered cell once itappears on the primary's minions. Master down: writeis durable but not readable until recovery.TriggersSingle writer per shard gives one cell order on allnodes, so billing and analytics consume the shardlike a partitioned log with their own cursor.Docstore (2021) keeps MySQL but replicates each partition with Raft and adds schemas, transactions and CDC.
text
     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 Schemaless

Real 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).

ConcernSchemaless (2016)One big PostgreSQL (before 2014)Cassandra (evaluated 2014, used later elsewhere)
Scale outAdd MySQL hosts, move shardsVertical onlyAdd nodes
Write during master failureBuffered writes to another masterNoYes (leaderless)
Schema changeNone in the store; columns are app-definedALTER caused downtimeFlexible
Change notificationTriggers per shardSeparate event systemApplication level
Secondary indexesGlobal, eventually consistent, MySQL tablesNativeScatter-gather (per the post's comparison)
Read-your-write after failoverNot guaranteed while bufferedYesTunable

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.

text
     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 changes

Real 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 updateHOT updates touch no index when no indexed column changes; be conservative with indexes; clustered-index designs have their own costsHOT still the main mitigation; fillfactor tuning
Physical WAL is verbose across the WANWAL can be compressed (SSL or archive_command with gzip)wal_compression exists in newer releases
Replica queries cancelled or blocking replayhot_standby_feedback=on prevents cancellation (trading bloat on the primary); max_standby_streaming_delay sets the graceSame knobs
No cross-version replicationLogical replication was the missing piece; pglogical existed but not for 9.2Built-in logical replication since PostgreSQL 10
pg_upgrade took many hoursShould not; fixed performance issues in newer releasespg_upgrade with --link is fast
Process per connectionUse a poolerpgbouncer 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.

text
     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 failover

Real 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).

PropertySchemaless (2016)Docstore (2021)
Data modelCells, schemaless JSONTables, schema-on-write, nested types
UpdatesAppend-onlyMutable rows
ReplicationAsync MySQL master to minions, buffered writesRaft per partition
ConsistencyRead-from-master default; eventual indexesStrict serializability per partition
CAP leanWrite availabilityConsistency over availability
Change streamTriggersChange 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.

text
     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 immediately

Real 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.

OptionDirectionAcksMobile fitUber's use
Short pollingClient pullsImplicitBattery and data heavyBefore 2015, 80% of gateway traffic
Long pollingClient pulls, heldImplicitBetterConsidered in 2015
WebSocketBothApplicationGood; extra SDK weight thenConsidered in 2015
SSEServer to clientSequence number on reconnectGood on HTTP + JSON stackChosen in 2015
gRPC bidirectional over QUICBothOn the streamBest latency on lossy networks2022
APNs / FCMServer to OSOS-levelWakes a closed appNot 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).

text
     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 offset

Real 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).

NeedUber's component (source)Generic alternative
Cross-region copyuReplicator (2016)MirrorMaker 2, Confluent Replicator
Partition assignment for copiersApache HelixKafka Connect group protocol
Stream processingFlink, FlinkSQL (paper)Kafka Streams, Spark Structured Streaming
Streaming SQL for analystsAthenaX (2017)ksqlDB, Flink SQL
Real-time OLAPPinot (paper)Druid, ClickHouse
Retry and DLQRetry 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.

text
     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 domain

Real 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)ProvidesExample
EdgeSafe exposure to the outside, app-awareMobile API gateway
PresentationConsumer-facing features and appsRider app screens
ProductLogic for one line of business, app-agnostic"Request a ride" logic
BusinessUber-wide functionality, not tied to one productAccounts, marketplace trips
InfrastructureAnything an engineering organisation could useStorage, 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.

text
     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:02

Real scenario: a p99 regression after a deploy; finding which of 50 services added latency; capacity planning from long-retention metrics.

SignalUber system (source)Open-source default todayTaught in
MetricsM3 (2018)Prometheus plus remote storage (M3, Thanos, Mimir)Observability
TracesJaeger (2017)OpenTelemetry plus Jaeger or TempoSame
AlertingGraphite threshold checks, then M3-basedPrometheus AlertmanagerAlerting 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).

text
     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 completed

Real 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).

FailurePublished responseSource
Dispatch datacenter lossDriver app sends last state digest to the new datacenter2015 talk
Kafka cluster lossProducers fail over to another region's regional cluster2020 Kafka DR
Region loss for surgeAnother region becomes primary and recomputes2020 Kafka DR
Exact-progress consumer failoverActive/passive with offset sync2020 Kafka DR
Storage master lossBuffered writes (Schemaless), Raft failover (Docstore)2016, 2021
Worker crash in a long processCadence replays history2023 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.

text
     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 edited

Real 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.

MechanismWhat it preventsWhere taught
Idempotency key per operationDouble charge on retryAPI Idempotency
Strong consistency for the ledgerTwo regions applying the same chargeConsistency Models
Double-entry bookkeepingMoney appearing or vanishingPayment Processing Architecture
Append-only trip STATUS cellsLost history of attemptsSchemaless
Idempotent consumersDuplicate events from KafkaIdempotent 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 ​

ComponentKnob or factValue in the sourceWhat it controls
Driver appLocation update intervalFour seconds (2015 talk write-up)Write load, freshness, failover recovery granularity
S2 (2015)Cell size for sharding3.31 km2Supply per shard, hot shards
H3Resolution0 (coarsest) to 15 (finest)Cell size; each step one seventh the area
H3Base cells, pentagons122, 12 per resolution (in water)Edge cases in k-ring code
RingpopReplica points per nodeA uniform number per node (docs; value configurable)Balance of keys over workers
RingpopMember statesalive, suspect, faulty, leave (docs)Failure detection, ring changes
RingpopHash, ring structureFarmHash, red-black tree (log n lookups)Lookup cost
TChannelBenchmarks quoted in docs20,000 to 40,000 operations per secondForwarding overhead
Geofence serviceLatency targetp99 under 100 ms at hundreds of thousands QPSIn-memory, stateless design
SchemalessShardsFixed, typically 4096; each a MySQL databasePlacement unit; expand by splitting servers
SchemalessCell address(row key, column name, ref key)Idempotency and versioning
SchemalessRead targetMaster by default, minion per requestRead-your-write vs load
DocstorePartition3 to 5 nodes, independent zones, RaftDurability and failover
RAMEN (SSE)Session start/ramen/receive?seq=0, Content-Type: text/event-streamAt-least-once delivery
Kafka multi-regionConsumption modesactive/active, active/passiveRecompute vs exact progress
uReplicatorAssignmentApache Helix, SimpleConsumer workersNo group rebalances
M3Write pathQuorum write to three replicas per regionDurability of metrics
M3Retention examplesTwo days to five years, 1 s to 10 min resolutionStorage cost
PostgreSQL (critique)hot_standby_feedback, max_standby_streaming_delayDocs: delay WAL apply or cancel conflicting queriesReplica query cancellation

What goes wrong, verbatim where a source gives the words ​

SymptomWords from the sourceSource
MirrorMaker stall"we've observed about 5–10 minutes of inactivity" during rebalanceuReplicator 2016
MirrorMaker stuck"the consumers can give up after 32 rebalancing attempts and get stuck forever"uReplicator 2016
Postgres replica corruptionReplicas "misapply some WAL records" after a 9.2 bug during master promotionPostgres to MySQL 2016
Postgres connections"significant problems scaling Postgres past a few hundred active connections"Postgres to MySQL 2016
Standby conflictConflicting queries "will be canceled once it has taken longer than the relevant delay setting"PostgreSQL docs, Hot Standby
Duplicate cell in MySQLERROR 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 causeDOMA 2020

The location path, step by step ​

text
     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.

go
// 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):

go
// 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:

go
// 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):

go
// 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):

go
// 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:

go
// 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):

go
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)
	}
}
go
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:

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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:

sql
-- 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;
sql
-- 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;
sql
-- 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 ​

SolutionHowAdvantageCost / limitation
Sharded in-memory index by cell (Uber 2015-16)S2 cells, Ringpop ring, handle or forwardNo database on the hot path; scales by adding workersState lost on crash until next pings; app-level sharding to operate
Redis GEO per cityGEOADD, GEOSEARCH, TTL setSimple, managedOne key per city on one node; hot cities
PostGIS row per driverUPDATE plus GiSTSQL, joinsUpdate storms, bloat
Kafka log plus stream-built indexConsumers maintain cellsReplayableLag between truth and index

Ghost drivers and late pings ​

SolutionHowAdvantageCost / limitation
TTL check at read timeSkip if now - last_seen > ttlAlways correctIndex still holds ghosts
Periodic sweepRemove silent driversKeeps memory boundedWork per sweep
Drop out-of-order pingsCompare client timestampsNo jumping backNeeds sane client clocks; cap by server time

A hot cell (stadium, airport) ​

SolutionHowAdvantageCost / limitation
Finer cells in dense areasHigher H3 resolution or S2 level thereFewer drivers per cellMixed resolutions complicate code
Split the ownerMore replica points or a dedicated workerSpreads CPURebalancing
Limit candidatesStop after n per ringBounded workMight miss a slightly better ETA

Datacenter or region failure mid-trip ​

SolutionHowAdvantageCost / limitation
State digest on the phone (Uber 2015)Encrypted digest returned periodically, replayed to new DCNo cross-DC replication on the hot pathClient trust and version handling
Recompute derived state (Uber 2020 surge)New primary region consumes input eventsNo huge state replicationWarm-up time
Active/passive with offset sync (Uber 2020)Consumer resumes at a synced offsetNo loss, bounded duplicatesOffset mapping across clusters

Write a trip while a database master is down ​

SolutionHowAdvantageCost / limitation
Buffered writes (Schemaless)Write to primary and a random secondary masterDurable immediatelyNot readable until recovery
Raft per partition (Docstore)Majority commit, automatic leader changeRead-your-write keptWrite needs a majority
Queue the writeOutbox or Kafka, apply laterSimpleRead path must tolerate delay

Never charge twice ​

SolutionHowAdvantageCost / limitation
Idempotency key + stored resultUnique key, return stored result on repeatExactly-once effectKey storage and TTL policy
Append-only STATUS cellsOne cell per attempt with a unique addressAuditableReaders must take the latest
Double-entry ledgerEvery movement is balancedDetects errorsMore rows, stricter model

Surge that does not flicker ​

SolutionHowAdvantageCost / limitation
Neighbour smoothingSum over k-ringFewer edge effectsBlurs very local spikes
Time smoothing (EWMA)Blend with previous windowStable pricesSlower reaction
Step and capRound to 0.1, cap at a maximumPredictable UXPolicy, not physics

Change the schema of a huge, hot table ​

SolutionHowAdvantageCost / limitation
Schemaless columns (Uber 2014)App-defined columns, no DDLNo downtimeNo schema enforcement
Docstore schema evolution (2021)Records of different schemas co-existEnforcement plus evolutionA custom database
Online DDL toolinggh-ost, pt-online-schema-change, expand/contractStandard databasesOperational 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 subsystemReusable ideaRead next
Geospatial workers, S2, H3Cell index, k-ring, filter then refineGeospatial Indexing
Ringpop membershipSWIM, suspicion, incarnation numbersGossip Protocols
Ringpop ringConsistent hashing with virtual nodesConsistent Hashing, Sharding at System Level
Handle or forwardRequest routing to the ownerService Discovery
Supply, demand, DISCOSeparate state owners from the decision makerService Boundaries
Geofence serviceRead-mostly data in every instance, background refreshCaching
ETA residual modelPhysical model plus ML correctionML Systems
Surge on FlinkWindowed per-key aggregation, recompute on failoverStream Processing
Schemaless cellsAppend-only versioned facts, idempotent writesAPI Idempotency, Event Sourcing & CQRS
Schemaless triggersChange feed from the storeChange Data Capture, Outbox
Mezzanine migrationShadow writes, compare, switchStrangler Fig
Postgres vs MySQL debateReplication and MVCC trade-offsReplication Topologies, MVCC
DocstoreConsensus per shardDistributed SQL
RAMEN pushSequence-numbered push, SSE vs WebSocket vs gRPCReal-Time Communication
Kafka multi-regionLocal produce, async replicate, active/active vs passiveKafka in Depth, Disaster Recovery
DOMADomains, layers, gatewaysMicroservices Architecture, Bounded Context
M3, JaegerMetrics at scale, distributed tracingObservability
CadenceDurable workflowsDurable Workflows & Jobs
PaymentsIdempotency, double entryPayment Processing Architecture
Rate limits on pingsToken bucket per driverRate Limiting

Choosing ​

Copy, adapt or skip ​

Your situationRecommendationExtra techniqueReason
Under 10,000 moving objectsRedis GEO or PostGIS, one regionTTL, rate limitUber's custom tier solves a scale you do not have
100,000+ updates per secondIn-memory sharded workers keyed by cellConsistent hashing, handle or forward or a smart clientMatches the published design
Need area analytics, pricing, heatmapsH3k-ring smoothing, parent roll-upsHexagon one-distance property
Need exact region coveringsS2Coverer with level boundsSquare hierarchy, exact containment
Long-lived business recordsAppend-only versioned rows on a sharded SQL storeUnique (id, column, version) as idempotencySchemaless lesson
Many indexes, heavy updates, PostgreSQLCheck HOT ratio, drop unused indexes, fillfactorLogical replication for upgradesAnswers most of the 2016 complaints
Need transactions and scaleDistributed SQL (CockroachDB, TiDB, Spanner) or VitessPartition keys that keep entities togetherDocstore lesson without building one
Mobile real-time updatesSSE or WebSocket with sequence numbers; gRPC streams for bidirectionalOne decision point for "when to push"RAMEN lesson
Multi-region streamingLocal produce, async replicationClassify consumers: recompute vs exactKafka DR lesson
Hundreds of servicesGroup into domains with gatewaysLayer rules enforced in CIDOMA lesson
Multi-step money flowsWorkflow engine (Temporal, Cadence)Idempotency keys in every activityCadence and payments lessons

Build or buy, per component ​

ComponentUber builtOff-the-shelf today (inference, not Uber's advice)
Hex gridH3 (open source)Use H3
App-level shardingRingpopOrleans-style actors, Akka Cluster, a shard manager
Trip storeSchemaless, DocstoreVitess, CockroachDB, DynamoDB
Kafka replicationuReplicatorMirrorMaker 2
Streaming SQLAthenaXFlink SQL
MetricsM3 (open source)Prometheus with M3, Thanos or Mimir
TracingJaeger (open source)OpenTelemetry with Jaeger
WorkflowsCadence (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 ​

LoadDesign (Uber's path where published)First thing that breaks
1x: one city, thousands of driversMonolith, one PostgreSQL, scan or Redis GEOThe trips table and its DDL
10x: dozens of citiesServices; 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, globalCell-based sharding (S2) on Ringpop; Schemaless with 4096 shards; Kafka everywhere; push platform; M3 and JaegerService sprawl (DOMA), Schemaless API limits (Docstore), MirrorMaker (uReplicator)
Beyond: multi-region, many lines of businessActive-active Kafka, region failover of surge, Docstore with Raft, gRPC push over QUIC, CadenceCost 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) ​

bash
cd docs/snippets/system-design/case-study-uber/go
go test ./...
go run ./cmd/demo

Output from one run (Apple laptop, Go 1.2x; timings vary):

text
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) ​

  1. Ghost drivers. In dispatch_test.go, set the TTL to 5 seconds and advance now by 10 seconds between ping and match. Expected: Nearest returns zero candidates; Sweep returns the number of drivers.
  2. Hot cell. Put 5,000 drivers inside one 350 m cell and time Nearest with n = 3. Expected: time grows linearly with the cell population; reducing the edge length to 150 m (a finer resolution) brings it back down.
  3. 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.
  4. Retry storm on the trip store. Call Put for the same cell 1,000 times. Expected: one cell, Latest unchanged, no error.
  5. 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 Requests with Retry-After and X-RateLimit-Remaining: 0 headers.
  6. PostgreSQL HOT (expected, not run). Run postgres-hot-updates.sql on PostgreSQL 16 with four rows inserted. Expected: n_tup_upd = 2, n_tup_hot_upd = 1 (the note update is HOT, the birth_year update is not).

Common misconceptions ​

BeliefReality (with the source)
Uber stores every GPS ping in a database for matchingLive positions are held in memory by Geospatial workers (Ringpop 2016)
H3 is Uber's dispatch indexH3 is described for analysis and optimisation, surge being the example; 2015 dispatch sharding used S2
The closest idle driver always gets the tripDISCO also considers drivers about to finish a trip (2015 talk)
Ringpop is a service you callIt is a library embedded in the application process (2016 post)
Schemaless is a new NoSQL engineIt is a thin routing layer over sharded MySQL (2016)
Uber proved PostgreSQL cannot scaleThe 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 possibleUpdates are new cells with a higher ref key
Uber uses WebSockets for the appIt chose SSE in 2015 and gRPC bidirectional streaming over QUIC later
Multi-region means synchronous replication of everythingSurge recomputes; dispatch used the phone; Kafka replicates asynchronously
DOMA is a return to the monolithIt keeps microservices and adds domains, layers, gateways, extensions
Exactly-once payments means exactly-once deliveryIt means idempotency plus strong consistency (2018 post)
Everything on this page describes Uber todayEach fact is dated; later posts replaced earlier designs

Cheat sheet ​

TopicWhat to remember
PingsEvery 4 s (2015); in memory; TTL; drop out-of-order
Failover trickPhone keeps an encrypted state digest for the next datacenter
S22015 dispatch sharding, 3.31 km2 cells, coverings
H3Hexagons, 16 resolutions, 122 base cells, 12 pentagons; surge per hexagon
DISCOMatches supply and demand, includes soon-free drivers, ranks by ETA
RingpopSWIM gossip + hash ring with replica points + handle or forward over TChannel
GeofencesGo, in-memory everywhere, city then fence, p99 under 100 ms
ETARouting engine sum of segments + ML residual (DeepETA 2022)
SurgeSupply and demand per area, Flink per region, freshness over consistency
SchemalessImmutable cells (row, column, ref), 4096 MySQL shards, buffered writes, triggers
Postgres to MySQLWrite amplification, physical WAL, upgrades, connections; critiques: HOT, logical replication
DocstoreMySQL + Raft per partition, schemas, transactions, CDC
PushRAMEN, Fireball; SSE with seq acks (2015) then gRPC over QUIC (2022)
KafkaRegional + aggregate clusters, uReplicator, active/active vs active/passive
DOMADomains, five layers, gateways, extensions; 2,200 services, 70 domains
ObservabilityM3 for metrics, Jaeger for tracing (OpenTracing)
WorkflowsCadence (Uber), Temporal (successor by Cadence's creators)
PaymentsIdempotency, strong consistency, double-entry, active-active

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
UberRide-hailing and delivery marketplace whose engineering posts are the sources of this page
Driver location / location updateOne position report from the driver app; every four seconds in 2015
Location update rateHow often the mobile client sends position; sets write load and freshness
Mobile clientThe rider or driver app; also a carrier of state digests in Uber's failover design
State digestEncrypted snapshot of dispatch state returned to the phone for datacenter failover
Geospatial indexStructure mapping positions to cells so nearby search reads few cells
S2Google's spherical geometry library: cube-face cells on a Hilbert curve, 64-bit ids
H3Uber's hexagonal hierarchical grid: 16 resolutions, 122 base cells, 12 pentagons
Hexagonal gridTiling with hexagons; every neighbour centre is the same distance away
k-ringAll cells within k steps of a cell
Supply / demandDrivers and their capabilities; riders and their requests
Matching / dispatchAssigning a request to a driver
DISCODispatch Optimization, the 2015 service that matches supply and demand
ETAEstimated time of arrival; used for matching, pickup times, fares
Routing engineRoad-graph engine summing segment travel times with live traffic
DeepETAUber's neural network predicting the routing engine's residual error
MichelangeloUber's ML-as-a-service platform (2017)
RingpopUber's library for app-level sharding: SWIM membership, hash ring, forwarding
SWIMScalable Weakly-consistent Infection-style Membership protocol; ping and ping-req
GossipSpreading membership changes by piggybacking on periodic peer messages
Consistent hashingKey placement on a ring so adding a node moves only about 1/n of keys
Replica pointsSeveral ring positions per node to even out the key distribution
Handle or forwardProcess the request if this node owns the key, otherwise forward to the owner
TChannelUber's RPC framing protocol, Ringpop's transport
FarmHashGoogle's fast non-cryptographic hash used by Ringpop
GeofenceA polygon that defines rules for an area (city, airport, pricing zone)
Surge pricing / dynamic pricingPer-area price increase when demand exceeds supply
TripThe business record of one ride, written in pieces over time
MezzanineUber's 2014 project moving trips from PostgreSQL to Schemaless
SchemalessUber's append-only cell store on sharded MySQL
Cell (Schemaless)Immutable JSON blob addressed by row key, column name and ref key
Ref keyVersion number of a cell; the highest is the latest
Buffered writesWriting 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
ShardingSplitting data across databases by a key; 4096 fixed shards in Schemaless
DocstoreUber's transactional successor of Schemaless: MySQL plus Raft per partition
RaftConsensus protocol with one leader replicating a log to followers
MySQL / InnoDBRelational database and its engine; clustered primary key, in-place updates
Postgres / PostgreSQLRelational database; heap tuples, physical WAL replication
Write amplificationOne logical change causing many physical writes
HOT updatePostgreSQL heap-only tuple update that touches no index
hot_standby_feedbackPostgreSQL setting that stops the primary removing rows a standby query needs
pglogicalExtension providing logical replication for older PostgreSQL versions
KafkaDistributed log used as Uber's event backbone
uReplicatorUber's Kafka cross-cluster replicator built on Apache Helix
Aggregate clusterKafka cluster holding copies of all regional clusters' data
Active/active, active/passiveConsumers in every region vs one consumer in the primary region
FlinkStream processing framework; runs surge and FlinkSQL jobs at Uber
AthenaXUber's SQL-on-Flink streaming analytics platform (2017)
StreamingContinuous processing of unbounded event sequences
PinotReal-time OLAP store used at Uber
RAMENUber's real-time push platform
FireballRAMEN component deciding when to push
PushServer-initiated delivery to the app
WebSocketFull-duplex protocol over one TCP connection (RFC 6455)
SSEServer-Sent Events, one-way event stream over HTTP
gRPC / QUICRPC framework with bidirectional streaming; UDP-based transport behind HTTP/3
MicroservicesIndependently deployed services with network interfaces
DOMA / domain-orientedDomain-Oriented Microservice Architecture: domains, layers, gateways, extensions
Gateway (DOMA)Single entry point into a domain
M3Uber's metrics platform and Prometheus remote storage
MetricsNumeric time series for dashboards and alerts
JaegerUber's distributed tracing system, OpenTracing-compatible
TracingRecording the spans of one request across services
CadenceUber's workflow engine; workflows as code with durable history
TemporalWorkflow engine by Cadence's co-creators, its successor
WorkflowDurable multi-step process that survives crashes
Multi-region / failoverRunning in several regions and moving traffic when one fails
PaymentsCollections (charging riders) and disbursements (paying drivers)
IdempotencyRepeating an operation has the same effect as doing it once
Double-entry bookkeepingEvery money movement recorded as balanced debit and credit
InferenceA statement on this page not taken from an Uber source

References ​

Uber engineering blog and papers (all fetched and saved):

Talks by Uber engineers:

Not Uber (used only for the critique and product mechanics, labelled where used):

Built by Morteza Negahi