/Learn
Modules · Mobile systems · System design

Live Location Tracking for a Driver App

PracticeSystem designTier 3 · Edge casesCreate45 minMobile systems

You will be able to: design driver location upload and rider tracking, and defend each trade-off between freshness and battery.

Source: Android foreground service and iOS Core Location documentation

Mobile engineeringAll mobile pages

A problem you haven't seen, built from parts you have: a buffer through a tunnel, a background service, sequence numbers and a socket. Start from the basics in Day 14 →

Study with AI

Part 1 of 5

Basics

The whole idea first, then the terms the rest of this page uses.

1.1Whole idea

A driver's phone produces a stream of GPS fixes, and riders watch a moving dot. Sending every fix would drain the battery and overload servers. So the phone filters and batches fixes, buffers through tunnels, and the server keeps only the latest position while archiving the rest.

Why it matters

A location stream combines every mobile constraint at once: battery, background limits, bad networks and scale.

1.2Key concepts

One idea per card, in plain words.

01Foreground service

Lets Android keep tracking while the app is in the background, with a visible notification.

02Distance filter

Keeps a fix only after real movement, which saves battery and data.

03Geospatial index

Finds nearby drivers quickly, using cells such as H3 or geohash.

04Dead reckoning

Animates the rider's map between updates, so the dot moves smoothly.

Part 2 of 5

Question

What exactly you must answer, and what to settle before you start.

2.1Question

Interviewer

Design location tracking for 500,000 concurrent drivers. Riders must see their driver move in near real time, and a shift must not drain the phone.

2.2Clarify first

Each answer removes a guess.

You askAnswer
How fresh for riders?Under 5 seconds behind, with smooth movement in between.
What about tunnels?Keep tracking, then upload the gap: disputes and fare calculation need the full route.
Battery target?Under 10% per hour with the screen off, on a mid-range phone.
Part 3 of 5

Detailed answer

How it works, and how to build or explain it.

3.1Architecture

The components and how they connect.

Driver appfilter · batch · bufferIngest gatewayauth · rate limitStreampartitioned by driverLive position storelatest per driver, TTLGeo indexH3 cell → driversRoute archivefares and disputesRider appsocket · smooth dotbatcheslatestcell movesall fixesupdates
ClientServiceData storeQueue / stream
Boxes are components; arrows show calls and data flow.

3.2Step by step

The mechanism, in the order you would explain it.

  1. Estimate the load

    500,000 drivers sending every 4 seconds is 125,000 writes per second. Only the latest position must stay hot.

  2. Filter on the phone

    Keep a fix after 25 metres of movement, or every 30 seconds when still, so a parked car stays visible but quiet.

  3. Batch the uploads

    Send every 15 seconds, or sooner when a rider is watching. Each radio wake-up costs far more battery than a few extra bytes.

  4. Buffer offline

    Store fixes on disk through tunnels and upload them later, marked as late, so they update the route but not the live dot.

  5. Keep latest hot

    Store each driver's latest position with a short expiry. Archive everything else to cheaper storage.

  6. Push to riders

    Riders subscribe to one driver over a socket, and animate between points. Dropping to polling keeps it working on bad networks.

3.3Code

Working code for the core of it.

Filtering and batching GPS fixes

This keeps the phone's radio asleep as long as possible, without losing the route.

LocationBatcher.ktKotlin
1data class Fix(val lat: Double, val lng: Double, val atMs: Long, val speedMps: Double)2 3/**4 * Decides which GPS fixes are worth keeping, and when to send them.5 * Moving fast: keep more points. Standing still: keep almost none. Offline: buffer, then flush.6 */7class LocationBatcher(8  private val minMeters: Double = 25.0,9  private val maxSilenceMs: Long = 30_000,10  private val maxBatch: Int = 20,11  private val flushEveryMs: Long = 15_000,12  private val maxBuffered: Int = 2_000,13) {14  private val buffer = ArrayDeque<Fix>()15  private var lastKept: Fix? = null16  private var lastFlushMs = 0L17 18  val pending: Int get() = buffer.size19 20  fun offer(fix: Fix) {21    val last = lastKept22    val moved = last == null || metersBetween(last, fix) >= minMeters23    val silent = last == null || fix.atMs - last.atMs >= maxSilenceMs24    if (!moved && !silent) return25    buffer.addLast(fix)26    lastKept = fix27    if (buffer.size > maxBuffered) buffer.removeFirst()   // a long tunnel: drop the oldest28  }29 30  /** Returns a batch to send now, or nothing. Call it on a timer and when the network returns. */31  fun drain(nowMs: Long, online: Boolean): List<Fix> {32    if (!online || buffer.isEmpty()) return emptyList()33    if (buffer.size < maxBatch && nowMs - lastFlushMs < flushEveryMs) return emptyList()34    lastFlushMs = nowMs35    return List(minOf(maxBatch, buffer.size)) { buffer.removeFirst() }36  }37}38 39/** Equirectangular distance: accurate enough at these short ranges, and cheap on battery. */40fun metersBetween(a: Fix, b: Fix): Double {41  val r = 6_371_000.042  val lat = Math.toRadians((a.lat + b.lat) / 2)43  val x = Math.toRadians(b.lng - a.lng) * Math.cos(lat)44  val y = Math.toRadians(b.lat - a.lat)45  return Math.hypot(x, y) * r46}
46 linesUTF-8Kotlin
if (!moved && !silent) return
Drops a fix unless the phone really moved, or 30 seconds have passed, so a parked car stays visible but quiet.
buffer.removeFirst()
A very long tunnel drops the oldest points, not the newest.
buffer.size < maxBatch && ...
Waits to fill a batch, because each radio wake-up costs far more than a few extra bytes.
metersBetween
A flat-earth approximation that is accurate at these distances and cheap on battery.

Compiled and tested by npm run test:mobile.

3.4More tested code

A working implementation, then what each part does and why.

The latest position, and nothing older

Fixes from a tunnel arrive late. The rider's dot must not jump backwards.

LiveStore.ktKotlin
1data class DriverFix(val driverId: String, val seq: Long, val lat: Double, val lng: Double)2 3/** Keeps only the latest fix per driver. A late fix from a tunnel must not move the dot back. */4class LiveStore {5  private val latest = HashMap<String, DriverFix>()6 7  fun accept(fix: DriverFix): Boolean {8    val current = latest[fix.driverId]9    if (current != null && current.seq >= fix.seq) return false10    latest[fix.driverId] = fix11    return true12  }13 14  fun positionOf(driverId: String): DriverFix? = latest[driverId]15}16 17/** The first number to say out loud. */18fun writesPerSecond(drivers: Long, everySeconds: Long): Long = drivers / everySeconds
18 linesUTF-8Kotlin
current.seq >= fix.seq
The cursor idea again: a number decides what's newer, not arrival time.
writesPerSecond
The first number to say out loud: 500,000 drivers every 4 seconds is 125,000 writes a second.

Compiled and tested by npm run test:mobile.

Part 4 of 5

Q&A

What interviewers ask next. Answer out loud, then open.

4.1Interview questions

Why not a socket from every driver?
Holding 500,000 radios awake costs battery, and sockets die in tunnels anyway. Batched HTTPS or a shared socket per burst suits uploads; riders get the socket.
How do you handle out-of-order fixes?
Each fix carries a device timestamp and sequence number. The live store ignores anything older than what it holds.
What does Android restrict?
Background location needs a foreground service and permission. Vendors may still kill it, so restart from a heartbeat and alert the driver.
Part 5 of 5

Extra depth

Edge cases, counterpoints and what to read next.

5.1Edge cases and counterpoints

Includes the strongest argument against this approach.

Show detailsHide details
GPS noise
Urban canyons produce jumps. Drop fixes that imply impossible speeds, and snap routes to roads on the server.
Privacy
Stop tracking when the shift ends, keep exact routes for a limited time, and limit who can read them.
Counterpoint
Most delivery apps only need updates every 30 seconds. Don't pay for real-time you don't need.
AI Engineer · Live Location Tracking for a Driver App