Two-week programme · Day 14 of 14
A problem you haven't seen
Part 1Basics
Today's problem is one you haven't studied: tracking drivers' live locations. That's deliberate. The point of the last two weeks is that you don't need to have seen a problem before.
Ask the same three questions and the design starts to appear. Afterwards, the other half of the loop is talking about your own real decisions, so you'll prepare those stories too.
Words you need today
- Foreground service
- Android background work with a visible notification, which the OS is much less likely to stop.
- Distance filter
- Keeping a GPS reading only after real movement, which saves battery and data.
- Decision story
- A true account of a choice you made: the context, the options, what you chose and the result.
The story
The interviewer says: design live location tracking for 500,000 drivers, and don't drain the battery. You haven't studied this one. It doesn't matter, because you already know how to begin.
Where does a GPS fix live? In a buffer on disk through a tunnel, exactly like Priya's basement. Who runs the next step? A foreground service, a sibling of Day 3's worker. What if it runs twice? Each fix carries a sequence number, so the server ignores anything older than what it holds, a cousin of the cursor. A rider's live view is chat's socket with the push as fallback. Rollout gates come from Day 13. You've built nearly all of this already.
Part 2Today's question
Can you use all of this on something new, and tell the story of why?
By the end of this lesson, you should be able to:
- Apply the three questions to an unseen problem
- Reuse the six ideas by name
- Tell three decision stories with numbers
Part 3In detail
Step by step
- Ask the three questions. Where does a GPS reading live? Who runs the next step? What if it arrives twice?
- Clarify and estimate. 500,000 drivers sending every 4 seconds is 125,000 writes a second. Only the latest position must stay fast.
- Reuse what you know. A disk buffer for tunnels is an outbox. A sequence number per reading is a cursor. The rider's live view is chat's socket.
- Name the new trade-off. Fresher location costs more battery. Choose numbers, and defend them.
- Prepare three stories. A decision you'd defend, one you got wrong, and a time you moved people without authority.
Six ideas, not sixty facts
Local truth, durable queues, idempotency keys, cursors, the OS decides when, and you can't recall a phone. Almost every mobile design round is a new arrangement of these. The programme page shows where each one appeared.
What makes it principal
A senior answer has the right boxes. A principal answer names what you rejected and why, ties numbers to decisions, says what you'd measure, and notices the organisation: who owns this, and what happens when it goes wrong at 3 am.
Bring your own stories
Panels also score real decisions you've made. Prepare three: a decision you'd defend, one you got wrong, and a time you moved people without authority. Give each one the context, the options, what you chose, and the result in numbers.
The code, explained
This is the real code, and our tests run it. Read each block, then the notes under it.
Filtering and batching GPS fixes
This keeps the phone's radio asleep as long as possible, without losing the route.
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}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.
The latest position, and nothing older
Fixes from a tunnel arrive late. The rider's dot must not jump backwards.
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 / everySecondscurrent.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.
Priya's whole day, as a program
This runs the real engine against the real server code. The numbers in the story are what this function produces, and a test checks them.
1data class StoryResult(2 val firstRun: RunOutcome,3 val cursorAfterRun: Long,4 val ticks: Int,5 val amber: Int,6 val theirs: Theirs?,7 val writesBeforeRetry: Int,8 val writesAfterRetry: Int,9 val finalVersion: Int,10 val tabletSees: String?,11)12 13/** Priya's whole day, running against the real engine and the real server code. */14suspend fun priyasDay(): StoryResult {15 val server = SyncServer(startSeq = 88411)16 val jobIds = List(12) { "j-${73 + it}" } // twelve jobs, including j-81 and j-8417 jobIds.forEach { server.seedJob(it, version = 4) }18 19 fun phone(prefix: String): Pair<LocalDb, JobRepository> {20 val db = LocalDb(cursor = 88411)21 db.transaction { jobs = jobIds.associateWith { Job(it, version = 4) } }22 var n = 023 return db to JobRepository(db, { "$prefix-${++n}" }, by = prefix)24 }25 26 val (priya, priyaRepo) = phone("priya")27 val (tablet, devRepo) = phone("dev")28 val priyaSync = SyncEngine(priya, server)29 val devSync = SyncEngine(tablet, server)30 31 // 2:40 pm, underground. 37 edits, with no network involved at all.32 priyaRepo.setAnswer("j-84", "valve_3", "leaking")33 priyaRepo.setAnswer("j-81", "valve_3", "leaking")34 var edits = 235 outer@ for (q in 1..4) for (job in jobIds - "j-84") { // the other eleven jobs get the rest36 if (edits == 37) break@outer37 priyaRepo.setAnswer(job, "q$q", "ok")38 edits += 139 }40 41 // 3:30 pm, in the office. Dev changes one field she also changed, and one she did not.42 devRepo.setAnswer("j-84", "valve_3", "replaced")43 devRepo.setAnswer("j-81", "instructions", "Use the east stairs")44 devSync.run()45 46 // Everyone else's work during those hours: 102 more changes in the log.47 val others = List(102) { Op("other-$it", "j-other", "q$it", "ok", baseVersion = 0) }48 server.push(others)49 50 // 4:12 pm. Signal returns and the worker runs.51 val firstRun = priyaSync.run()52 val rows = jobIds.map { priya.jobs.value.getValue(it) }53 val ticks = rows.count { it.syncState == SyncState.SYNCED }54 val amber = rows.count { it.syncState == SyncState.CONFLICT }55 val theirs = priya.jobs.value.getValue("j-84").theirs56 57 // A lost reply: the same ops arrive again, and nothing is written twice.58 val writesBeforeRetry = server.writes59 val sentAgain = List(12) { i -> Op("priya-${i + 2}", "j-81", "q", "ok", 4) }60 server.push(sentAgain)61 val writesAfterRetry = server.writes62 val cursorAfterRun = priya.cursor63 64 // 4:14 pm. She looks at both values and keeps her own.65 priyaRepo.resolve("j-84", "leaking")66 priyaSync.run()67 68 // 4:15 pm. The push told Dev's tablet to look, so it pulls after its own cursor.69 devSync.run()70 71 return StoryResult(72 firstRun, cursorAfterRun, ticks, amber, theirs, writesBeforeRetry, writesAfterRetry,73 finalVersion = priya.jobs.value.getValue("j-84").version,74 tabletSees = tablet.jobs.value.getValue("j-84").answers["valve_3"],75 )76}SyncServer(startSeq = 88411)- The log starts where her cursor is, c_88411.
priyaRepo.setAnswer(...)- 37 edits underground. Nothing here talks to a network.
devSync.run()- Dev's 3:30 pm edit reaches the server first, which sets up the conflict.
server.push(others)- 102 changes from other people, which brings the pull to 140.
priyaSync.run()- The 4:12 pm run. A test asserts 36 applied, 1 conflict, 140 pulled and cursor c_88551.
priyaRepo.resolve(...)- Her choice is a new edit based on version 5, and it reaches version 6.
Compiled and tested by npm run test:mobile.
What can go wrong
- You freeze on an unfamiliar problem
- Ask the three questions out loud. They give you somewhere to start.
- They change a constraint halfway
- Say which decisions it affects, and redo only those.
- You don't know an answer
- Say so, reason from what you do know, and check your assumption.
Part 4Questions and answers
Answer out loud first, then open each one.
The interviewer changes the constraint halfway through. What do you do?
You don't know something they ask. What now?
Part 5Going further
The three questions, for today
- Where does it live?
- In a disk buffer of fixes, through the tunnel.
- Who runs the next step?
- A foreground service on the phone, and a stream on the server.
- What if it runs twice?
- A sequence number per fix, so anything older gets ignored.
Practise
- Mock45 minLive Location Tracking for a Driver App
Read only the prompt first. Spend 45 minutes on your own answer, then open the reference design.
Score yourself
Tick a line only if you did it without prompting.
0 of 8 Revisit the days behind what you missed, then run the round again.
Optional reference pages
You don’t need these for the lesson. They hold more detail if you want it later.
That's the programme. Revisit any day from the map, and keep the recall cards going until your loop.