Uber / Ola clone: ride booking with driver matching
Riders pick a destination, see a fare estimate and get matched to the nearest driver; both watch each other live on a map, the ride starts with an OTP and the final fare uses the actual route.
Educational project inspired by Uber and Ola. Skills101 is not affiliated with Uber and Ola. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Geospatial search in Redis (GEOADD, GEOSEARCH)
- ◆Matching with timeouts and race-safe accepts
- ◆Routing and fare calculation from real road distances
- ◆Trip safety features: OTP, live sharing
What you’ll build
- ✓Rider: pick drop on map, fare estimate, request, live driver
- ✓Driver: go online, accept within 15 s, navigate, start with OTP
- ✓Final fare from GPS distance and time
- ✓Ratings both ways and ride history
Before you start
What you need
- •React, Node.js and Socket.IO basics (see the WhatsApp guide).
- •Docker for Redis and PostgreSQL.
- •Two phones or browsers to test (one rider, one driver). HTTPS is required for GPS on phones.
How it fits together
- 1Drivers' apps send location every 4 seconds; available drivers are stored in a Redis GEO set for fast “nearest drivers” searches.
- 2Routes, distances and durations come from OSRM (an open-source routing engine) using OpenStreetMap roads.
- 3A matching service offers the ride to the nearest driver with a timeout, then the next; a Redis SET NX makes the accept race-safe.
- 4Rides and their states are stored in PostgreSQL; live positions flow through Socket.IO rooms per ride.
Project structure
rideon/
├─ server/
│ ├─ drivers.ts # location, GEO set, heartbeats
│ ├─ fare.ts # estimate + final fare
│ ├─ match.ts # offers, timeouts, accept
│ ├─ rides.ts # states, OTP
│ └─ routing.ts # OSRM
├─ web/ (React: rider + driver screens)
└─ sim/drivers.ts # fake drivers moving on roads for demosStep-by-step guide
Step 1
Plan the ride lifecycle
Goal: States, who changes them, and the rider and driver screens.
States: REQUESTED → ACCEPTED (driver assigned) → ARRIVED (at pickup) → STARTED (after OTP) → COMPLETED. CANCELLED is allowed before STARTED, by rider or driver (later you can add a cancellation fee after 2 minutes).
Rider screens: map with pickup (current location) and drop (tap on map or search), fare estimate, searching, driver on the way, in ride, receipt and rating. Driver screens: go online, incoming request with 15-second countdown, navigate to pickup, enter OTP, in ride, complete.
Name it (“RideOn”) and add “Educational project inspired by Uber and Ola. Not affiliated.” in the README.
✅ Check it works
You can say who may cancel at each state.
Step 2
Maps and real road routes with OSRM
Goal: A map where the rider picks a drop point and sees the road route, distance and time.
Use Leaflet with OpenStreetMap tiles (show the attribution). For routes, OSRM computes the fastest road route between points. Its public demo server is fine for light testing; for anything more, run OSRM yourself with Docker and an India extract from Geofabrik.
OSRM coordinates are
longitude,latitude. The response givesdistancein metres,durationin seconds and the route geometry, which you draw as a line on the map.For place search, OpenStreetMap's Nominatim has a strict usage policy (max 1 request per second, a real User-Agent); debounce the search box, or let users tap the map.
server/routing.tsconst OSRM = process.env.OSRM_URL ?? 'https://router.project-osrm.org' export async function route(from: { lat: number; lng: number }, to: { lat: number; lng: number }) { const url = OSRM + '/route/v1/driving/' + from.lng + ',' + from.lat + ';' + to.lng + ',' + to.lat + '?overview=full&geometries=geojson' const res = await fetch(url, { signal: AbortSignal.timeout(5000) }) const data = await res.json() if (data.code !== 'Ok' || !data.routes?.length) throw new Error('No route found') const r = data.routes[0] return { metres: r.distance as number, seconds: r.duration as number, line: r.geometry.coordinates as [number, number][] } }✅ Check it works
Picking two points across your city draws a route along real roads with a sensible distance and time.
Step 3
Fare estimate
Goal: Before booking, the rider sees “₹182–₹201” for each vehicle type.
Fare = base fare + per-km rate × km + per-minute rate × minutes, with a minimum fare, times a surge multiplier (step 9). Different vehicle types (bike, auto, mini, sedan) have different rates. Keep everything in paise.
Show a range (estimate to +10%) because traffic changes the real time. The final fare in step 7 uses the actual trip.
Store the estimate and rates on the ride when requested, so later rate changes do not affect it.
server/fare.tsconst RATES = { bike: { base: 2000, perKm: 600, perMin: 100, min: 3000 }, // paise auto: { base: 3000, perKm: 1100, perMin: 150, min: 4000 }, mini: { base: 5000, perKm: 1400, perMin: 200, min: 8000 }, } as const export function fare(type: keyof typeof RATES, metres: number, seconds: number, surge = 1) { const r = RATES[type] const raw = r.base + r.perKm * (metres / 1000) + r.perMin * (seconds / 60) return Math.round(Math.max(r.min, raw) * surge) } export function estimate(type: keyof typeof RATES, metres: number, seconds: number, surge = 1) { const low = fare(type, metres, seconds, surge) return { low, high: Math.round(low * 1.1) } }✅ Check it works
A 5 km, 15 minute auto trip estimates about ₹107–₹118 with these sample rates; check by hand.
Step 4
Track available drivers in Redis GEO
Goal: Online drivers report location every 4 seconds and “drivers within 3 km” is answered in milliseconds.
Redis GEO commands store members with coordinates and search by radius. When a driver is online and free,
GEOADD drivers:available <lng> <lat> <driverId>. When they accept a ride or go offline,ZREMthem (a GEO set is a sorted set underneath).Phones lose signal without saying goodbye. Also set
SET driver:alive:<id> 1 EX 15on every update; a job removes drivers whose alive key has expired, so riders are never matched to a ghost driver.Check the sender is a logged-in driver and ignore impossible jumps (more than 100 m in one second).
server/drivers.tssocket.on('driver:location', async ({ lat, lng }: { lat: number; lng: number }) => { const id: string = socket.data.driverId if (!id || !isValidCoord(lat, lng)) return await redis.set('driver:alive:' + id, '1', { EX: 15 }) await redis.hSet('driver:pos', id, JSON.stringify({ lat, lng, at: Date.now() })) if (await redis.sIsMember('drivers:free', id)) { await redis.geoAdd('drivers:available', { longitude: lng, latitude: lat, member: id }) } const rideId = await redis.get('driver:ride:' + id) if (rideId) io.to('ride:' + rideId).emit('driver:pos', { lat, lng }) }) export function nearestDrivers(lat: number, lng: number) { return redis.geoSearch('drivers:available', { longitude: lng, latitude: lat }, { radius: 3, unit: 'km' }, { SORT: 'ASC', COUNT: 10 }) }✅ Check it works
With 3 simulated drivers at different distances,
nearestDriversreturns them nearest first.Step 5
Match riders to drivers, race-free
Goal: A request is offered to the nearest driver for 15 seconds, then the next, and only one driver can win.
On request: create the ride (REQUESTED), find the nearest 10 drivers, and offer to the first via
user:<driverId>with the pickup, drop and fare. Start a 15-second timer. On decline or timeout, offer to the next. If nobody accepts, tell the rider “No drivers nearby”.Accept must be atomic: two drivers (or one driver double-tapping) can accept at the same instant.
SET ride:<id>:driver <driverId> NXsucceeds only for the first. Then update the ride to ACCEPTED in PostgreSQL with a condition on REQUESTED, and remove the driver from the available set.Do not offer one ride to all drivers at once (“broadcast”); it causes many drivers to rush for one ride and feels unfair. Sequential offers with a short timeout are how most apps work.
server/match.ts (accept)socket.on('ride:accept', async (rideId: string, ack) => { const driverId: string = socket.data.driverId const offered = await redis.get('ride:' + rideId + ':offer') if (offered !== driverId) return ack({ error: 'This request is no longer yours' }) const won = await redis.set('ride:' + rideId + ':driver', driverId, { NX: true, EX: 86400 }) if (!won) return ack({ error: 'Ride already taken' }) const res = await pool.query( "UPDATE rides SET status = 'ACCEPTED', driver_id = $2, accepted_at = now() WHERE id = $1 AND status = 'REQUESTED'", [rideId, driverId]) if (res.rowCount === 0) { await redis.del('ride:' + rideId + ':driver'); return ack({ error: 'Ride was cancelled' }) } await redis.zRem('drivers:available', driverId) await redis.sRem('drivers:free', driverId) await redis.set('driver:ride:' + driverId, rideId) clearOfferTimer(rideId) io.to('ride:' + rideId).emit('ride:accepted', await rideView(rideId)) ack({ ok: true }) })✅ Check it works
Simulate two drivers accepting the same ride in the same millisecond: exactly one succeeds.
Step 6
Live trip with OTP to start
Goal: Rider sees the driver approach; the ride starts only when the driver enters the rider's 4-digit OTP.
After accept, the rider sees driver name, vehicle number, rating and a moving marker with ETA (OSRM from driver to pickup, refreshed every 30 seconds).
Generate a random 4-digit OTP when the ride is accepted and show it only to the rider. The driver must enter it to move ARRIVED → STARTED. This proves the right rider got into the right car, a real safety feature.
Add “Share trip” for the rider: a link with a random token that shows the live map to a family member until the ride ends.
server/rides.ts (start)export async function startRide(rideId: string, driverId: string, otp: string) { const ride = (await pool.query('SELECT status, driver_id, otp, otp_tries FROM rides WHERE id = $1', [rideId])).rows[0] if (!ride || ride.driver_id !== driverId || ride.status !== 'ARRIVED') throw new Error('Cannot start this ride') if (ride.otp_tries >= 5) throw new Error('Too many wrong OTPs, ask the rider to contact support') if (otp !== ride.otp) { await pool.query('UPDATE rides SET otp_tries = otp_tries + 1 WHERE id = $1', [rideId]) throw new Error('Wrong OTP') } await pool.query("UPDATE rides SET status = 'STARTED', started_at = now() WHERE id = $1 AND status = 'ARRIVED'", [rideId]) io.to('ride:' + rideId).emit('ride:started') }✅ Check it works
A wrong OTP is refused (and counted); the right one starts the ride for both screens.
Step 7
Final fare from the actual trip
Goal: At the end, the fare uses the GPS distance driven and the real time taken.
During STARTED, save the driver's points for the ride. At COMPLETE, sum the distance between consecutive points with the haversine formula (distance on a sphere), skipping points with poor accuracy and impossible jumps.
Final fare =
fare(type, metres, seconds, surge)with the actual values. If it is far above the estimate (for example over 30% more), cap it at the estimate +30% and flag the ride for review, a simple rider-protection rule.Show a receipt with the breakdown: base, distance, time, surge, total, and the route drawn on a map.
server/fare.ts (distance)export function haversine(a: { lat: number; lng: number }, b: { lat: number; lng: number }) { const R = 6371000 // Earth radius in metres const toRad = (d: number) => (d * Math.PI) / 180 const dLat = toRad(b.lat - a.lat), dLng = toRad(b.lng - a.lng) const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng / 2) ** 2 return 2 * R * Math.asin(Math.sqrt(h)) } export function tripMetres(points: { lat: number; lng: number; at: number; accuracy: number }[]) { let total = 0 for (let i = 1; i < points.length; i++) { const p = points[i - 1], q = points[i] if (q.accuracy > 50) continue // poor GPS fix const d = haversine(p, q) const secs = (q.at - p.at) / 1000 if (secs > 0 && d / secs > 45) continue // faster than 160 km/h: a GPS jump total += d } return total }✅ Check it works
For a recorded test trip, your distance is within about 5% of the OSRM route distance.
Step 8
Payments, ratings and history
Goal: Pay by cash or test-mode online payment, rate each other, and see past rides and earnings.
Cash: the driver confirms “Cash collected”. Online: Razorpay test mode with server-side verification (Amazon guide).
After the ride, both rate 1–5 stars. Store averages as sum and count. Hide a driver's rating details from riders except the average.
Rider history: past rides with route maps and receipts. Driver dashboard: today's rides, earnings (after a platform commission you define, for example 20%), and online hours.
✅ Check it works
After 3 test rides, the driver dashboard totals match the sum of receipts minus commission.
Step 9
Simple, transparent surge pricing
Goal: Fares rise a little where many people request and few drivers are free, with a clear message.
Divide the city into cells (for example by rounding coordinates to 2 decimals, about 1 km, or with a geohash). Every minute, count requests in the last 5 minutes and free drivers per cell.
Multiplier = clamp(requests ÷ max(drivers, 1), 1, 2), rounded to 0.1. Cap it at 2× and show it before booking (“Fares are 1.4× higher due to demand”). The rider must confirm.
Write in your README why surge exists (to bring more drivers to busy areas) and its fairness risks. Good engineers discuss trade-offs.
✅ Check it works
With your simulator, 10 requests and 2 drivers in one cell show 2.0×; a quiet cell shows 1.0×.
Step 10
Simulate drivers, then deploy and demo
Goal: A demo city full of moving drivers and a public deployment.
Write
sim/drivers.ts: create 20 fake drivers, give each a random OSRM route in your city and move them along the route, sending locations like a real phone. They accept requests automatically after 3 seconds. This makes demos impressive and testing easy.Deploy the Node server with HTTPS and WebSockets, Redis and PostgreSQL; use your own OSRM container if you expect more than light traffic.
README: the lifecycle diagram, GEO search, the race-free accept, OTP and share-trip safety, fare formula and surge rules, and the not-affiliated note. Record a demo with two phones.
✅ Check it works
Opening the rider app shows cars moving around; a request gets matched and completed end to end.
🚀 Make it stand out
- +Scheduled rides for later
- +Pool/shared rides with two riders on one route
- +SOS button that shares location with an emergency contact
- +Driver heatmap of demand