Originally published on PEAKIQ
Source: https://www.peakiq.in/blog/building-a-production-taxi-booking-app-the-architecture-behind-the-map
Below is the architecture we'd ship for a production taxi booking app — rider and driver, built on bare React Native with a TypeScript backend — organized around the three problems that actually decide whether the product holds up: real-time, geospatial matching, and consistency.
The stack
Two surfaces, one language family, one goal: get a ride matched in under a second and never lose a trip.
Mobile (bare React Native, no Expo)
| Package | Purpose |
|---|---|
| react-native-maps | Native Google/Apple map rendering |
| react-native-geolocation-service | Reliable foreground GPS |
| react-native-background-geolocation | Driver tracking while the app is backgrounded |
| react-navigation | Native-stack + bottom-tab navigation |
| zustand | Client state (tiny, fast, no boilerplate) |
| @tanstack/react-query | Server state, caching, retries, optimistic updates |
| react-native-reanimated | Smooth map/drag interactions |
| react-native-firebase + notifee | Push + rich local notifications |
| @stripe/stripe-react-native | PCI SAQ-A card capture + driver payouts |
| react-native-mmkv | Sub-ms local storage |
| op-sqlite | Offline trip history |
| sentry | Crash + performance |
Backend
| Piece | Choice | Why |
|---|---|---|
| Language/framework | NestJS (TypeScript) | Matches the RN team; DI + strict module boundaries |
| API | REST (CRUD) + raw WebSocket (realtime) | Standard + low-latency push |
| Database | PostgreSQL + PostGIS | Source of truth + geo persistence |
| Cache / geo index | Redis (GEO + pub/sub) | Sub-ms nearby-driver queries |
| Event backbone | Kafka (phase 1+), Redis pub/sub (phase 0) | Durable, replayable event stream |
| ORM | Prisma | Migrations + type-safe queries |
| Auth | OTP + JWT (access + refresh) via Twilio | Phone-verified, stateless |
| Payments | Stripe (Connect for payouts) | Riders pay, drivers get paid |
| Infra | Docker → Kubernetes, Terraform | Reproducible → scale |
The only genuinely "native" dependencies live where native behavior is unavoidable: camera-free but GPS-heavy, so background-geolocation, maps, and push are the non-negotiables. Everything else is plain application code.
The three hard problems
Strip away the UI and a taxi app is three problems:
- Real-time — a rider needs to see a driver move, and both need trip status pushed to them, without polling and without a chat-room framework.
- Geospatial matching — out of thousands of drivers, find the right few nearby, fast, and rank them sensibly.
- Consistency — under concurrency, exactly one driver gets assigned to exactly one ride, and the fare can't drift between quote and charge.
Everything else — auth, payments, ratings, admin — is well-trodden. These three are what separate a prototype from a dispatch system. We'll take each in turn.
Problem 1: Real-time, without Socket.io
The instinct is to reach for Socket.io. The big players don't, and there's a reason: Socket.io is a Node-centric layer with its own protocol, and it doesn't fit a Kafka-centric event architecture. Uber, Lyft, Grab, and Bolt converge on the same pattern instead:
- Raw WebSocket (or gRPC bidirectional streaming) for the client connection.
- Kafka as the durable event backbone — the source of truth that everything consumes from.
Here's the flow for a single ride, from request to dropoff:
Driver App (3–5s ping)
│ WebSocket
▼
Location Svc → Redis GEOADD drivers {id: lat,lng}
│ └─ Kafka topic `driver.location`
▼
Rider taps "Request"
│ REST POST /rides
▼
Ride Svc → Matching Svc
│ GEOSEARCH radius
▼
Candidate drivers ranked: ETA + rating + distance
│
▼
Offer to top-N drivers via WS (10s accept window)
│ accept → assign (transaction + lock)
│ decline/timeout → next candidate
▼
Ride status changes → Kafka → WS push to rider + driver
▼
Trip end → Pricing → Stripe charge → receipt → rating
The event contract is worth typing explicitly, because a shared type file between client and server is what keeps the two from drifting:
// packages/types/events.ts — shared by rider, driver, and backend
export type RideEvent =
| { type: 'ride.updated'; rideId: string; status: RideStatus; seq: number }
| { type: 'offer.new'; offerId: string; rideId: string; expiresAt: number }
| { type: 'ride.assigned'; rideId: string; driver: DriverBrief }
| { type: 'payment.receipt'; rideId: string; amount: number; currency: string };
export type DriverEvent =
| { type: 'driver.location'; lat: number; lng: number; ts: number }
| { type: 'driver.status'; status: 'offline' | 'available' | 'on_trip' }
| { type: 'offer.accept'; offerId: string }
| { type: 'offer.decline'; offerId: string };
Three rules make this production-grade rather than a demo:
-
Idempotency by
seq— every event carries a monotonic sequence number; the client drops anything out of order or already seen. Reconnects stop being scary. - REST for anything non-real-time — history, profile, fare estimate. Don't run your whole API over a socket.
- Kafka comes later, but the seam is decided now. Phase 0 runs on Redis pub/sub and a plain WS gateway. When volume justifies it, Kafka slots in behind the same topics — a refactor, not a rewrite.
Problem 2: Geospatial matching
"Find drivers near me" is a classic mistake factory: a SQL WHERE ... ORDER BY distance scan over a driver table works in staging and melts at a few thousand concurrent pings. The answer is to keep the hot index in memory and only persist what you must.
-
Hot path: Redis
GEOADDeach driver's current position,GEOSEARCHby radius. Sub-millisecond, and it only ever holds active drivers — the ones who can actually accept a ride.
GEOADD drivers 13.361389 38.115556 driver:1
GEOSEARCH drivers FROMLONLAT 13.37 38.11 BYRADIUS 3 km ASC
- Persistence: PostGIS stores trip geometry, saved places, and anything you need to analyze historically.
- At scale: swap the naive radius scan for H3 hexagonal indexing — the same trick Uber uses. Drivers are indexed by hex cell; matching queries only the cell and its neighbors, so query cost stays flat as the map fills up.
Ranking is where product sense enters. A nearby driver isn't automatically the right driver:
score = w1 · eta(driver, pickup) + w2 · (5 − rating) + w3 · distance
Then offer to the top-N sequentially with a hard timeout — first accept wins. Expanding the radius only after the window closes keeps riders from waiting forever while a driver one street over is free.
Surge pricing hooks into the same loop: measure demand/supply per area, derive a multiplier, apply it at the fare estimate, lock it at request, and honor it at completion. The number a rider is quoted is the number they pay — anything else erodes trust and invites chargebacks.
Problem 3: Consistency
A ride is a state machine, and state machines are where distributed bugs hide. Two drivers accepting the same ride is not a rare edge case — it's a Wednesday. The fix is to make the transition itself the guard.
export type RideStatus =
| 'REQUESTED' | 'MATCHING' | 'DRIVER_ASSIGNED' | 'EN_ROUTE'
| 'ARRIVED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED';
// Assign a driver only if the ride is still matching.
// The WHERE clause is the lock — a second concurrent accept updates 0 rows.
const assigned = await db.ride.updateMany({
where: { id: rideId, status: 'MATCHING' },
data: { status: 'DRIVER_ASSIGNED', driverId },
});
if (assigned.count === 0) throw new AlreadyAssignedError();
Every transition is idempotent, logged, and emitted as an event. REQUESTED → CANCELLED is a valid path from anywhere. The ride record is the single source of truth, and no module ever mutates another module's tables directly — it goes through that module's service.
The backend: a modular monolith
The professional move is to start as a monolith with hard module boundaries, not to start with microservices. Microservices before you have a scaling problem is paying the distributed-systems tax without collecting the benefit.
| Module | Responsibility |
|---|---|
auth |
OTP, JWT, refresh tokens, device registration |
user |
rider + driver profiles, documents, verification |
vehicle |
vehicle details, category, capacity |
location |
ingest driver pings, update Redis GEO, geofence |
ride |
lifecycle state machine (source of truth) |
matching |
candidate search, offer/accept, timeout |
pricing |
fare estimate, surge, final fare |
payment |
Stripe charges, refunds, driver payouts |
notification |
push/SMS dispatch, templates |
rating |
rider↔driver reviews, aggregate scores |
admin |
dashboards, ops, fraud review |
The folder structure enforces the rule — no module reaches across the boundary:
backend/src/
├── modules/
│ ├── auth/ # controller, service, repo, events — self-contained
│ ├── ride/
│ ├── matching/
│ └── ...
├── common/ # shared guards, interceptors, exceptions
├── events/ # topic names + payload types
└── main.ts
When (and only when) a module needs to scale independently, its service is extracted behind gRPC and its tables follow. The boundary was always there; you're changing the transport, not the design.
The mobile side: two apps, one core
Uber and Lyft ship separate rider and driver apps, and so should you — not one app that swaps roles. The driver app needs background location and different store permissions, and mixing them into one binary only invites review rejections and battery complaints.
A monorepo keeps duplication near zero:
ride-app/
├── apps/
│ ├── rider/
│ └── driver/
├── packages/
│ ├── core/ # api client, ws client, auth, config, types
│ └── ui/ # shared component kit
├── backend/
└── infra/
Inside each app, feature-first structure:
apps/rider/src/
├── app/ # navigation, root providers
├── core/ # api, ws, auth, storage, config, theme
├── features/
│ ├── auth/
│ ├── home/ # map + request flow
│ ├── ride/ # active ride screen
│ ├── trips/
│ ├── payments/
│ └── profile/
└── shared/ # ui components, hooks, utils
Patterns that matter: Zustand for UI/auth state, TanStack Query for all server data, a single shared core/ws client with heartbeat + exponential-backoff reconnect, and background location only in the driver app. Actions queue offline and replay; trip history reads from SQLite so the app isn't a blank screen on a flaky network.
Data model
The core tables, with indices tuned for the hot queries (rides(status), drivers(status), geo GiST on driver location):
users (id, role, phone, email, name, rating_avg, created_at)
drivers (user_id, status, vehicle_id, current_location POINT, documents_verified)
vehicles (id, driver_id, plate, make, model, color, category, capacity, year)
rides (id, rider_id, driver_id, status, pickup, dropoff, route_polyline,
distance_m, duration_s, fare, surge, currency, requested_at, completed_at)
ride_offers (id, ride_id, driver_id, status, expires_at)
payments (id, ride_id, amount, currency, status, stripe_charge_id, payout_id)
ratings (id, ride_id, from_user, to_user, score, comment)
otps (id, phone, code_hash, expires_at, attempts)
refresh_tokens(id, user_id, token_hash, device_id, expires_at, revoked)
Security & payments
- Auth: phone OTP + short-lived JWT (15 min) + rotating, revocable refresh tokens.
- Payments: the Stripe SDK lives on-device and only ever produces tokens — the backend never sees a raw card number, which keeps you in PCI SAQ-A scope instead of the expensive one.
- Fraud & safety: phone + document verification, device fingerprinting, an SOS button, ride-share links, geo-fenced no-go zones, and an admin review queue.
- Data: encrypt PII at rest, delete location history after N days (GDPR).
- Secrets: in a secrets manager, never in code or environment.
The scaling roadmap
| Phase | Scope | Architecture |
|---|---|---|
| 0 — MVP | 1 city, ~1k users | Modular monolith + Postgres + Redis GEO + WS gateway + Redis pub/sub |
| 1 — Traction | real driver volume | + Kafka backbone, extract matching, H3 indexing |
| 2 — Scale | multi-city / multi-region | microservices on K8s, read replicas, multi-region |
The rule: don't build Phase 1–2 machinery on day one. Build Phase 0 with clean boundaries so the split is a refactor, not a rewrite.
The gotchas worth their own paragraph
Double assignment isn't an edge case. Two drivers tapping accept within the same second is ordinary. The guard lives in the UPDATE ... WHERE status = 'MATCHING' transition, not in client-side checks — clients lie, race conditions don't wait.
Background GPS is a policy problem as much as a code problem. Both stores require foreground-service declarations and justification. Ship background location in the driver app only, and be explicit with the user about why — opaque background tracking is how apps get rejected and users get angry.
The fare must not drift. Quote, lock, and charge the same number. Surge recalculation mid-trip is a chargeback factory.
Reconnects are normal. A driver drives through a tunnel. Idempotent events with sequence numbers mean a reconnect replays cleanly instead of duplicating a trip.
Don't run your API over the socket. WebSocket is for push and events; REST is for everything else. Mixing them means you've built two API layers and one of them has no retry story.
Before calling it done
- A ride transitions
REQUESTED → COMPLETEDend-to-end with exactly one driver, under 1s matching. - Two concurrent accepts on the same ride produce exactly one assignment.
- Driver location updates survive backgrounding and resume on foreground.
- A rider and driver both see the same trip status after a reconnect.
- The quoted fare equals the charged fare.
- A cold launch on a mid-range Android phone opens the map and requests a ride without jank.
- Every ride carries a
traceIdfrom request through payment. - No raw card data ever touches the backend.
None of these pieces is exotic — a map, a socket, a state machine, a geo index. What makes a taxi app hard is that it has to behave identically across two camera-free-but-GPS-heavy platforms, under concurrency, while real money and real people are in motion. Decide the seams now, ship the monolith first, and it holds up the same on a 360dp Android phone in traffic as it does on a Pro Max.
Top comments (0)