Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Real-World Projects

Project: Ride-Sharing Matching Service

Build the core of a ride-sharing backend: a location index, nearest-driver matching, a ride state machine and an event stream, with a deterministic simulation.

Ride-sharing apps feel like magic: tap a button and a nearby driver appears. Behind it sits a handful of cooperating services. A location service tracks where thousands of drivers are, updated every few seconds. A matching service finds good candidates for each request and asks them in turn. A ride service keeps the trip's lifecycle honest. And an event stream records everything that happens so that pricing, analytics, payments and support can react without being called.

This project builds a small version of each part and runs them together in a simulation. It is a good test of the ideas in this course: data ownership, events, state machines, and the difference between a hot, ephemeral data set (driver positions) and a durable one (rides). Everything runs as plain JavaScript in the browser console editor, so the structure, not the infrastructure, is what you study.

The services and their data

Who owns what

Location Driver positions. Changes constantly, can be lost.
Matching Finds and offers drivers. Keeps no history.
Rides Durable trip state and its transitions.
Event stream Append-only log of what happened.

Different data, different storage, different scaling.

1 / 2

Driver locations are written many times a second and are only interesting while fresh, so real systems keep them in an in-memory store (Redis geo indexes, or a custom service), not in the same database as rides. If the location service restarts, drivers simply report again within seconds. Rides, in contrast, represent money and promises: they are stored durably and every change is validated.

Step 1: the ride as a state machine

A ride moves through a few states, and only some moves make sense: you cannot complete a ride that was never matched, and you cannot cancel one that is already complete. Encoding that as an explicit table protects the data even when messages arrive late or twice.

stateDiagram-v2
    [*] --> requested
    requested --> matched
    requested --> cancelled
    matched --> arrived
    matched --> cancelled
    arrived --> in_progress
    arrived --> cancelled
    in_progress --> completed
    completed --> [*]
    cancelled --> [*]

Legal ride transitions: once a trip has started it can only complete.

Every legal move also appends an event (DriverMatched, TripStarted, ...) to a stream. The stand-in below shows both ideas: illegal transitions are rejected, and a consumer can rebuild the current state of every ride purely by replaying the stream, which is the heart of Event Sourcing and CQRS. Consumers also remember an offset, so a new consumer can catch up from zero while an old one reads only what is new.

JS Ride state machine and an event stream you can replay

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rides 1 and 2 followed legal paths. Ride 3 refused to jump from requested to completed, and ride 1 refused to be cancelled after completion. Rebuilding states from the stream matched the live objects exactly, which is what lets other services keep their own read models without ever querying the rides database.

Step 2: location index, matching and a simulation

Now the whole flow. The program below contains:

  • a location service with a grid index: drivers are filed under the cell they stand in, and a search scans the rider's cell, then rings of cells around it;
  • a matching service that offers the ride to the nearest free driver, handles a decline by trying the next nearest (at most three offers), and cancels the ride if nobody accepts;
  • scheduled trip progress (arrival, trip, completion), driven by a virtual clock;
  • an analytics consumer reading the event stream.

Two modelling details deserve attention. First, the nearest-driver search looks one ring past the first ring that contains a candidate, because a driver in the next ring can be closer than one in the corner of the current ring. Skipping that detail is a classic bug that gives slightly wrong matches. Second, random choices (driver positions, declines, requests) come from a seeded generator, so the simulation is the same every time.

JS Nearest-driver matching on a grid, with an event stream

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output. Eight requests produced 11 offers: three drivers declined and the next-nearest driver was offered the ride, so no request ended cancelled. Seven trips completed within the 14 ticks and the eighth was still in progress, so its completion event does not exist yet. The grid examined 194 driver records where scanning all 30 drivers for each of the 11 offers would have meant 330 checks. With only 30 drivers the saving is modest; with 50,000 drivers in a large city, the gap between "look near the rider" and "look at everyone" is the difference between milliseconds and an overloaded service. The story of ride 1 shows the events another service (billing, say) would consume.

What is real, what is simulated

Real ideas: spatial indexing by cells, expanding-ring search, offer-and-decline matching, an explicit state machine, an append-only event stream and independent consumers with offsets. Simulated: the city is a 20 by 20 grid of integers, the clock is a loop counter, drivers answer by a random number, and all services share one process. Production systems use geohashes or H3 hexagons instead of square grids, travel time from a routing engine rather than straight-line distance, and a durable broker such as Kafka for the stream (Asynchronous Messaging and Events).

Things that go wrong in real life

  • Two riders, one driver. Matching must reserve a driver atomically (compare-and-set on status, or a lock per driver); otherwise two concurrent requests both offer the same driver. In the simulation this cannot happen because everything runs one step at a time.
  • Stale locations. A driver who lost signal still appears free. Give positions a time-to-live and ignore stale ones.
  • Surge and hotspots. One stadium empties and thousands of requests hit a single cell. Shard the location service by region and add backpressure (Rate Limiting, Load Shedding and Backpressure).
  • Timeouts on offers. A driver who never answers must not block the rider: put a timeout on each offer and treat silence as a decline (Timeouts, Retries and Exponential Backoff).
  • Duplicate and late events. Consumers of the stream must be idempotent and tolerate out-of-order delivery, using the state machine to reject impossible transitions (The Transactional Outbox and Idempotent Consumers).
  • Payments. Charging the rider after TripCompleted is a saga with its own failure handling: what if the card is declined?

When two pieces of data change at very different rates, give them different owners and different stores. Putting driver pings next to financial records makes both worse.

Extending the project

  1. Add a timeout to offers using the virtual clock, and treat a missing answer as a decline.
  2. Add rider cancellation at random ticks and free the matched driver; check that no driver stays busy forever.
  3. Replace the 30 drivers with 3,000 and compare examined with the full-scan count.
  4. Add a pricing consumer that listens to RideRequested and DriverMatched events and raises a surge multiplier when open requests outnumber free drivers.
  5. Add idempotency so that a duplicated DriverMatched event cannot charge a driver twice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are driver locations kept separately from ride records?

    Different change rates and durability needs call for different owners and stores.
  2. 2. What does an explicit ride state machine protect against?

    Rejecting impossible transitions keeps the data valid, even when events arrive late or twice.
  3. 3. Why does the grid search look one ring past the first ring containing a candidate?

    Cells are squares, so distance inside a ring varies; checking one more ring guarantees the nearest candidate is not missed.
  4. 4. What lets a new service rebuild the current state of all rides?

    An append-only stream contains every change, so state can be derived by replaying it.
  5. 5. Which real-world risk does the simulation NOT show?

    The simulation handles requests one step at a time. Real systems need an atomic reservation of the driver.

Summary

  • Split data by how it behaves: fast-changing driver locations in a location service, durable trips in a rides service.
  • A grid (or geohash/H3) index lets matching examine only nearby drivers; search expanding rings, and look one ring beyond the first hit.
  • An explicit state machine keeps ride data valid, and each transition emits an event.
  • An append-only event stream lets consumers (analytics, billing, pricing) work independently and replay history.
  • Real systems add atomic driver reservation, offer timeouts, stale-location handling and regional sharding.

Next: Project: Strangling a Monolith.