Offline-first inspection app with huge uploads

We’re building an app for 200,000 field technicians who inspect pipelines. They work underground for hours with no signal, capture 30 to 60…

Ready45:00
ClarifyEstimateHigh-level designDeep diveTrade-offs and wrap-up
Start the clockReset Practice mode
Part 1 of 5

Basics

Start with the product and the ideas it depends on. If these are clear, the design that follows will feel obvious rather than memorised.

1.1Product in plain words

Who uses it, what a normal day looks like, and why it is harder than it seems.

An app that pipeline technicians carry to inspection sites. They open a job, walk the site, answer a long checklist, take photos and short videos as evidence, and submit. Supervisors in the office watch jobs arrive on a web dashboard and send back corrections.

Who uses it

  • Technicians: a phone, gloves, bright sun or dark basements, and often no signal for hours.
  • Supervisors: a laptop with a live dashboard; they review evidence and change instructions.
  • Auditors: months later, they need to trust that each photo is genuine.

A day in the life

  1. 7:30 am on office Wi-Fi: the app quietly downloads today’s six jobs with their drawings.
  2. 10:00 am underground: no signal. The checklist saves every answer instantly; photos attach in under a second.
  3. 10:40 am: the technician taps Submit. The app says ‘Saved on this phone. Sending when you’re back online.’
  4. 11:05 am at street level: the phone finds signal. Records go first, then photos, all in the background.
  5. 11:07 am: the supervisor sees the job and thumbnails; she asks for one more photo, which pops up on the technician’s phone.

Why it is hard

No internet for hours

Every screen must work from the phone’s own database, not from the server.

Gigabytes of media

Uploads must survive weak signal, network switches and the app being closed.

Two people edit one job

The technician answers while the supervisor edits instructions; neither may overwrite the other.

Evidence must be trustworthy

We must prove a photo wasn’t replaced or edited after it was taken.

Think of it like this

Think of a courier’s paper notebook. At every stop he writes everything down, and the office copies the notebook whenever he passes a phone booth. The notebook is the truth; the phone booth is a bonus.

1.2Key concepts

The building blocks this design uses. Each one appears again in the answer.

01Offline-first

The phone's local database is the source of truth for the screen. The app reads and writes locally and syncs in the background, so having no signal is a normal state, not an error.

02Outbox

A table of pending local changes, written in the same transaction as the data. A sync job sends them in order when the network returns, so nothing the technician did is lost.

03Idempotency key

An id the device attaches to each change. If a send is retried after a lost response, the server recognises the id and applies the change only once.

04Multipart, resumable upload

Large files are split into parts that upload independently. A dropped connection costs only the part in flight, and the upload resumes from the last finished part.

05Conflict resolution

Two people can edit the same job while offline. Merging field by field, and flagging true clashes for review, is safer than letting the last write silently win.

06Background limits

Android and iOS stop apps that work in the background for too long. Sync has to be scheduled with the OS (WorkManager, BGTaskScheduler) and be safe to stop at any moment.

Learn them properly in the deep dives:

Part 2 of 5

Question

Now read the question closely. Agree on what you are building, ask what is unclear, and work out the numbers before you draw anything.

2.1Brief and scope

The question exactly as the interviewer asks it, and what they want to learn from your answer.

Interviewer

We’re building an app for 200,000 field technicians who inspect pipelines. They work underground for hours with no signal, capture 30 to 60 photos and short videos per job, and fill long forms. Supervisors must see results within minutes of a technician getting signal. Design the mobile and backend architecture.

What it tests: Process death, unreliable networks and large media, plus whether you size the backend before drawing it.

The answer in one sentence. A local-first app with an outbox for records and a resumable pipeline for files, synced by OS-scheduled jobs to a stateless backend that keeps an ordered change log.

How to spend the 45 minutes

  1. Clarify~5 minAsk questions, agree on scope and write down assumptions.
  2. Estimate~5 minRough numbers for users, data and traffic, and what they imply.
  3. High-level design~11 minComponents, data flow and the key API on the board.
  4. Deep dive~16 minThe two or three hardest parts, with real mechanisms.
  5. Trade-offs and wrap-up~9 minDecisions, failure modes, and what you would do next.

2.2Clarify the problem

The first five minutes. Each answer removes a guess from your design.

Your turn: Before drawing anything, list the questions you would ask the interviewer.Reveal model answer
You askInterviewer answers
How long can a device stay offline?Up to two weeks at remote sites.
Is a job edited by more than one person?A technician owns the inspection; supervisors can change job details and instructions.
Which platforms, and what does the team know?Android and iOS. The team is strong in React Native and Kotlin.
How big is the media?Photos 3 to 5 MB, videos up to 500 MB.
Any compliance needs?Photos are legal evidence, so integrity matters. Data must stay in-region.

2.3Estimate the scale

Say the arithmetic out loud. What matters is the order of magnitude and what it forces you to do.

Your turn: Write down the numbers that will drive the design.Reveal model answer
MetricEstimateHow
Active technicians per day120k60% of 200k
Jobs per day240k2 jobs each
Media ingress≈ 48 TB/day50 files × 4 MB × 240k jobs
Sync requests≈ 42 req/s avg, ~400 peak120k × 30 syncs ÷ 86,400, ×10 for peaks
Change log growth≈ 25 GB/day240k jobs × ~100 changes × 1 KB
Part 3 of 5

Detailed answer

The design itself, from the big picture down to the code: components first, then one request end to end, then the parts interviewers push hardest on.

3.1Architecture

The phone holds the truth for the technician’s work. Records sync through a small API; media goes straight to object storage; supervisors read the same change stream the phones write into.

Your turn: Sketch the components and arrows, then compare.Reveal model answer
DEVICECLOUD · IN-REGIONRN screensforms · cameraSQLitejobs · outbox ·partsOS schedulerWorkManager ·BGTaskSync enginenative moduleTransfer managermultipart · resumeSupervisor weblive dashboardNotifierFCM · APNsAPI gatewayauth · rate limitsSync servicepush · pull · mergeS3 + CDNpresigned partsPostgresjobs + change logMedia workershash · thumbs ·scanKafka (CDC)ordered changeswritecommitwakefilesHTTPSPUTobject createdCDCchangesAPIpush hint
ClientServiceData storeQueue / stream
Reference design. Boxes show components; arrows show who calls whom.
SQLite on device
The source of truth for screens. Jobs, form answers, an outbox of pending operations and a table of upload parts. Encrypted with SQLCipher because the phone can be lost.
Sync engine
Native code (Kotlin and Swift, or one KMP module) so it runs without the JS runtime. Pushes the outbox with op_ids, then pulls changes after its cursor.
Transfer manager
Hashes each file, asks the server whether it already exists, uploads 8 MB parts through presigned URLs and records each ETag.
Sync service
Stateless. Dedupes op_ids, applies field-level merge rules and writes every change to a per-tenant change log with a sequence number.
Media workers
React to object-created events: verify the hash, extract EXIF time and GPS, generate thumbnails, scan, then mark the media as evidence-grade.
Supervisor dashboard
Reads the same API. Kafka drives live updates, so a supervisor sees a job seconds after the technician’s phone finishes syncing.

3.2Key flow, step by step

One inspection, from the basement to the supervisor’s screen.

Your turn: Narrate one request end to end.Reveal model answer
TechnicianApp + SQLiteOSSync serviceS3Save inspectionrow + outbox, 1 txnSaved, shown offlineHours later the phone gets signalRun sync jobPOST /push ops + op_idsapplied · seq 88412POST /files/init {sha256}upload_id + part URLsPUT part 1…nETag per partPOST /files/completehash verified · linkedGET /pull?cursorchanges + next cursor
Solid arrows are requests; dashed arrows are responses.
  1. The save never waits for the network. One transaction writes the row and its outbox entry, so the intent survives a kill.
  2. When the OS runs the job, records go first. They are small and unblock the supervisor even before photos finish.
  3. Media uses multipart uploads. The app saves each part’s ETag, so a kill or network switch costs at most the parts in flight.
  4. The pull at the end brings back supervisor edits and the server’s view of the job, with the cursor saved in the same transaction.

3.3Front end

The technician app is the hardest part of this system to get right. It must be fast with gloves on, readable in sunlight, and honest about what has and has not reached the office. The team uses React Native for screens, with native modules for everything that runs in the background.

Your turn: Sketch the screens, the client layers and every UI state the user can see.Reveal model answer

Screen map

Today’s jobslist · sync badgesJob detailsite · drawings ·statusChecklistsectioned form ·autosaveCameracapture · annotateSign-in + devicedownload jobs onWi-FiResolve conflictmine vs supervisorReview + submitmissing itemsSync centrequeue · errors ·retrystartattachsubmitneeds reviewstatus
Client
Screens and how users move between them.
Today’s jobs
A FlashList of jobs read from SQLite with a status chip per row: draft, saved on phone, sending 23/52, synced, needs review. Pull-to-refresh asks for a sync but never blocks the list.
Checklist
A schema-driven form: the server sends a JSON definition of sections, questions, conditional rules and required photos, so new checklists ship without an app release. Each answer saves on change.
Camera
CameraX on Android and AVFoundation on iOS through a native module. Capture writes straight to app storage, hashes in native code and returns a thumbnail path to JavaScript.
Resolve conflict
Shows the technician’s value and the supervisor’s value side by side with who changed what and when; one tap keeps either.
Sync centre
Lists every pending record and file with progress, the last error in plain words and a Retry button. Support teams ask users to open this screen first.

Client layers

LayerTechnologyResponsibility
ScreensReact Native (New Architecture, Fabric), FlashListRender state, collect input, never call the network
View stateZustand stores + WatermelonDB observablesDerive what each screen shows from the database
Form engineJSON-schema checklist + react-hook-formConditional questions, validation, per-field autosave
RepositoryTypeScript moduleWrite row + outbox in one database transaction
Native modulesTurbo Modules: Sync, Transfer, CameraBackground sync, file transfer, hashing, capture
Local databaseWatermelonDB on SQLite (JSI)Jobs, answers, outbox, upload parts

Every state the user can see

StateWhat the user seesHow it works
Saved on phoneGrey clock icon and ‘Saved on this phone’sync_state = pending on the job row
SendingProgress ring with ‘Sending 23 of 52 photos’Reads transfer_part counts from SQLite
SyncedGreen tick and time syncedsync_state = synced
Needs reviewAmber badge; opens the conflict screensync_state = conflict with server values stored
FailedRed badge, the reason in plain words, RetryOutbox row status = failed
OfflineThin banner: ‘Offline · 12 changes waiting’Network state + outbox count
Storage lowWarning before the camera opensFree space below 1 GB

Code

Per-field autosave hook (React Native, TypeScript)

perfield-autosave-hook.tsTypeScriptCopy
1export function useAnswer(jobId: string, fieldId: string) {2  const answer = useObservable(() => answers.observeOne(jobId, fieldId), [jobId, fieldId]);3 4  const save = useMemo(() => debounce(async (value: string) => {5    await database.write(async () => {6      await answerRepo.upsert(jobId, fieldId, value);                     // the row7      await outboxRepo.add({ entity: 'answer', entityId: jobId + ':' + fieldId,8                             op: 'upsert', payload: { value } });        // the intent9    });10    SyncModule.requestSync('user_edit');                                   // native, returns at once11  }, 400), [jobId, fieldId]);12 13  return { value: answer ? answer.value : '', syncState: answer ? answer.syncState : 'synced', save };14}
14 linesUTF-8TypeScript

Capture, hash and queue without blocking the UI (Kotlin, CameraX)

capture-hash-queue.ktKotlinCopy
1fun capture(jobId: String) {2  val file = File(context.filesDir, "media/" + UUID.randomUUID() + ".jpg")3  val options = ImageCapture.OutputFileOptions.Builder(file).build()4  imageCapture.takePicture(options, cameraExecutor, object : ImageCapture.OnImageSavedCallback {5    override fun onImageSaved(result: ImageCapture.OutputFileResults) {6      scope.launch(Dispatchers.IO) {7        val sha = sha256(file)                                    // evidence hash at capture time8        repo.attachMedia(jobId, file.path, sha, bootTimeMs = SystemClock.elapsedRealtime())9        transfers.enqueue(file, owner = jobId, priority = Priority.BACKGROUND)10        events.emit(CameraEvent.Saved(thumbnailFor(file)))       // JS gets a small thumbnail path11      }12    }13    override fun onError(e: ImageCaptureException) { events.tryEmit(CameraEvent.Failed(e.message)) }14  })15}
15 linesUTF-8Kotlin

3.4Data model and APIs

The tables and contracts that make the design concrete.

Your turn: Write the schema or contract you would put on the board.Reveal model answer

Device schema (SQLite)

device-schema-sqlite.sqlSQLCopy
1CREATE TABLE job (2  id TEXT PRIMARY KEY,            -- UUIDv7, made on device3  site_id TEXT NOT NULL,4  status TEXT NOT NULL,           -- draft | submitted | approved5  answers_json TEXT NOT NULL,6  field_versions_json TEXT,       -- per-field version for merging7  sync_state TEXT NOT NULL,       -- pending | synced | conflict8  updated_at INTEGER NOT NULL9);10CREATE TABLE outbox (11  op_id TEXT PRIMARY KEY, entity TEXT, entity_id TEXT,12  op TEXT, payload_json TEXT, base_version INTEGER,13  attempts INTEGER DEFAULT 0, next_retry_at INTEGER, status TEXT14);15CREATE TABLE media_part (16  file_id TEXT, part_no INTEGER, etag TEXT,17  PRIMARY KEY (file_id, part_no)18);
18 linesUTF-8SQL

Sync API

sync-api.httpHTTPCopy
1POST /v1/sync/push2{ "device_id": "d-7f2", "ops": [3  { "op_id": "0192e0c4-…", "entity": "job", "id": "j-81",4    "op": "update", "base_versions": { "answers.valve_3": 4 },5    "fields": { "answers.valve_3": "leaking" } } ] }6→ { "results": [{ "op_id": "0192e0c4-…", "status": "applied", "seq": 88412 }] }7 8GET /v1/sync/pull?cursor=c_88411&limit=5009→ { "changes": [ … ], "next_cursor": "c_88460", "has_more": false }10 11POST /v1/files/init  { "sha256": "9f2c…", "size": 412000000, "mime": "video/mp4" }12→ { "exists": false, "upload_id": "u-55", "part_size": 8388608,13    "parts": [{ "n": 1, "url": "https://…?X-Amz-Expires=900" }, …] }
13 linesUTF-8HTTP

3.5Tested code, explained

The core of this design as working code, with what each part does and why.

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.

PriyasDay.ktKotlinCopy
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}
76 linesUTF-8Kotlin
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.

The save, and the conflict resolution

This is the code behind the tap. It's the only way a screen changes data, and it has no network call in it.

LocalDb.ktKotlinCopy
1/** The only way a screen changes data. Nothing here touches the network. */2class JobRepository(3  private val db: LocalDb,4  private val newOpId: () -> String,5  private val by: String = "device",6  private val requestSync: (Trigger) -> Unit = {},7) {8  fun setAnswer(jobId: String, field: String, value: String) {9    db.transaction {10      val job = jobs.getValue(jobId)11      jobs = jobs + (jobId to job.copy(12        answers = job.answers + (field to value),13        syncState = SyncState.PENDING,14      ))15      outbox = outbox + Op(newOpId(), jobId, field, value, job.version, by)16    }17    requestSync(Trigger.EDIT)            // only after the commit: the edit is already safe18  }19 20  /** The user chose a value in the conflict screen. It is a new edit, based on what they just saw. */21  fun resolve(jobId: String, value: String) {22    db.transaction {23      val job = jobs.getValue(jobId)24      val theirs = checkNotNull(job.theirs) { "$jobId has no conflict" }25      jobs = jobs + (jobId to job.copy(26        answers = job.answers + (theirs.field to value),27        syncState = SyncState.PENDING,28        theirs = null,29      ))30      outbox = outbox + Op(newOpId(), jobId, theirs.field, value, theirs.version, by)31    }32    requestSync(Trigger.EDIT)33  }34}
34 linesUTF-8Kotlin
db.transaction { ... }
The job row and the outbox row commit together. A crash can't leave one without the other.
SyncState.PENDING
Makes the row show its clock. The screen reacts by itself, because it watches this table.
job.version
Copied into the op as its base version: 4 in Priya's case.
requestSync(Trigger.EDIT)
Runs after the commit, so even if scheduling fails, the edit is already safe.
fun resolve
Choosing a value in the conflict screen creates a new edit, based on the version the user just saw. Nothing gets patched in place.

Compiled and tested by npm run test:mobile.

One sync run

This is the 2.1 seconds at 4:12 pm. Read it top to bottom: lock, push until empty, pull until caught up, report.

SyncEngine.ktKotlinCopy
1class SyncEngine(2  private val db: LocalDb,3  private val api: SyncApi,4  private val batchSize: Int = 25,5  private val pageSize: Int = 500,6) {7  private val lock = Mutex()8 9  suspend fun run(hasTime: () -> Boolean = { true }): RunOutcome {10    if (!lock.tryLock()) return RunOutcome.AlreadyRunning     // single flight11    var applied = 012    var conflicts = 013    var pulled = 014    try {15      while (db.outbox.isNotEmpty() && hasTime()) {16        val results = api.push(db.outbox.take(batchSize))     // may throw: ops stay queued17        applyResults(results)18        applied += results.count { it is OpResult.Applied }19        conflicts += results.count { it is OpResult.Conflict }20      }21      var more = true22      while (more && hasTime()) {23        val page = api.pull(db.cursor, pageSize)24        applyPage(page)25        pulled += page.changes.size26        more = page.hasMore27      }28      return RunOutcome.Finished(applied, conflicts, pulled, morePending = db.outbox.isNotEmpty() || more)29    } catch (e: TryLater) {30      return RunOutcome.RetryLater(e.afterMs)31    } catch (e: CursorTooOld) {32      return RunOutcome.RebuildNeeded(e.snapshotUrl)33    } finally {34      lock.unlock()35    }36  }37  // applyResults and applyPage follow38}
38 linesUTF-8Kotlin
lock.tryLock()
Single flight. If a run is already active, this one returns at once, because that run will see any new ops.
db.outbox.take(batchSize)
Takes 25 at a time, and reads them fresh each loop, so edits made during the run go out too.
api.push(...)
If this throws, nothing was removed locally. The ops wait for the next run.
while (more && hasTime())
Keeps pulling pages until the server has no more, or the budget ends.
finally { lock.unlock() }
Runs even after a failure, so one bad run can't block sync forever.

Compiled and tested by npm run test:mobile.

The decision for each field

This small function decides what happens when two people edit offline. The product team's table becomes code you can test.

FieldMerge.ktKotlinCopy
1enum class Policy { LAST_WRITE_WINS, ADD_ONLY, ASK_USER }2 3/** A field on the server, and the job version at which it last changed. */4data class Stored(val value: String, val version: Int, val by: String)5 6sealed interface Merge {7  data class Apply(val value: String) : Merge8  data class Refuse(val current: Stored) : Merge9}10 11/** The product team's table, written down as code. */12fun policyFor(field: String): Policy = when {13  field.startsWith("photos") -> Policy.ADD_ONLY14  field == "instructions" || field == "read_marker" -> Policy.LAST_WRITE_WINS15  else -> Policy.ASK_USER                 // the safe default for anything new16}17 18fun merge(field: String, incoming: String, baseVersion: Int, current: Stored?): Merge {19  // Nobody touched this field since the user read it: j-81 takes this path.20  if (current == null || current.version <= baseVersion) return Merge.Apply(incoming)21 22  return when (policyFor(field)) {23    Policy.LAST_WRITE_WINS -> Merge.Apply(incoming)24    Policy.ADD_ONLY -> Merge.Apply("${current.value},$incoming")25    Policy.ASK_USER -> Merge.Refuse(current)            // j-84 takes this path26  }27}
27 linesUTF-8Kotlin
policyFor(field)
The policy table. Anything not listed asks the user, the safe choice for a new field.
current.version <= baseVersion
Nobody changed this field since the user read it, so apply it. That's why j-81 merged with no conflict.
Policy.ADD_ONLY
Photos: both people's additions are kept, because they never disagree.
Merge.Refuse(current)
Valve 3 on j-84 lands here. The server applies nothing, and returns what it holds.

Compiled and tested by npm run test:mobile.

Sending parts that survive being killed

Arjun's upload. The receipts map stands for a table on disk, so a killed app loses almost nothing.

PartUploader.ktKotlinCopy
1/**2 * Sends only what the table says is missing. [receipts] stands for the transfer_part3 * table: a part number maps to its ETag once that part succeeds.4 */5class PartUploader(6  private val parts: List<Part>,7  private val receipts: MutableMap<Int, String>,8  private val freshUrls: suspend (List<Part>) -> Map<Int, String>,9  private val send: suspend (Part, url: String) -> String,10  private val parallel: Int = 4,11) {12  val remaining: List<Part> get() = parts.filter { it.no !in receipts }13 14  suspend fun run() {15    var urls = freshUrls(remaining)16    while (remaining.isNotEmpty()) {17      val outcomes = coroutineScope {18        remaining.take(parallel).map { part ->19          async { part to runCatching { send(part, urls.getValue(part.no)) } }20        }.awaitAll()21      }22      // Save every success first, so a failure next to it costs nothing.23      outcomes.forEach { (part, r) -> r.onSuccess { etag -> receipts[part.no] = etag } }24      val failure = outcomes.firstNotNullOfOrNull { (_, r) -> r.exceptionOrNull() }25      when (failure) {26        null -> Unit27        is UrlExpired -> urls = freshUrls(remaining)    // only the parts still missing28        else -> throw failure29      }30    }31  }32 33  /** The body of POST /files/complete, in part order. */34  fun manifest(): List<Pair<Int, String>> = receipts.toSortedMap().map { (no, etag) -> no to etag }35}
35 linesUTF-8Kotlin
parts.filter { it.no !in receipts }
What is left. This one line is why resuming needs no special case: a fresh start and a resume run the same code.
runCatching { send(...) }
One failed part doesn't cancel the others in flight.
outcomes.forEach { ... receipts[...] = etag }
Saves every success before looking at failures, so finished work always counts.
is UrlExpired -> urls = freshUrls(remaining)
Fetches new URLs only for the parts still missing, then carries on.
else -> throw failure
Anything else ends this run. The next run picks up from the receipts.

Compiled and tested by npm run test:mobile.

3.6Hard parts, in depth

Where interviewers spend the second half of the round.

Your turn: Pick two areas the interviewer will push on and explain them.Reveal model answer

Field-level merge instead of last-write-wins

A supervisor may change the instructions while the technician fills answers. Whole-record last-write-wins would let one overwrite the other. Instead each field carries its own version, and the push says which version each edit was based on.

The server applies a field when its base version matches, and returns a conflict only when both sides changed the same field. That happens rarely, so a simple ‘keep mine or theirs’ prompt is enough.

Evidence-grade media

Photos are evidence, so the app hashes each file at capture time and stores the hash in the job record before any upload. The server recomputes the hash when the upload completes and refuses a mismatch.

Capture time comes from the device clock, which can be wrong, so the app also records time since boot and the last server time it saw. Workers reconcile these with EXIF data, and the audit log stores all three.

Why sync lives in native code

The UI is React Native, but the OS wakes native code, not JavaScript. The sync engine and transfer manager are Turbo Modules backed by WorkManager on Android and BGTaskScheduler plus background URLSession on iOS.

Native code writes progress to SQLite and the RN screens observe it, so one source of truth remains and no file bytes cross the bridge.

Part 4 of 5

Q&A

The questions that come after the design, with model answers. Answer each one out loud before opening it.

4.1Follow-up questions

What the interviewer asks once the main design is on the board.

A technician uploads the same photo twice. What happens?
The hash matches an existing object, so /files/init returns exists: true and the app skips the upload. The record just references the same media.
How does the supervisor see results within minutes?
Records sync before media and are small. CDC streams the change to the dashboard over a WebSocket. Thumbnails follow when media arrives.
How do you prove a photo wasn’t edited?
Hash at capture, stored in the signed job record, re-verified server-side, and kept immutable with object lock. Any change produces a different hash.
What if the server rejects an operation permanently?
The outbox row moves to failed, the job shows a clear error with what to fix, and the rest of the outbox keeps syncing.

4.2Front-end follow-ups

Questions aimed at the client: rendering, state and devices.

How do you keep a 200-question form fast?
Sections mount lazily, each field autosaves with a short debounce, and validation runs on the visible section only, so typing never re-renders the whole form.
What does the technician see after killing the app mid-upload?
On the next open the job immediately shows ‘Sending 23 of 52’ because progress lives in SQLite, and uploading resumes without any tap.
How do you ship a new checklist without an app release?
Checklists are JSON definitions versioned on the server; the app renders them with a form engine and stores which version each answer used.

4.3Incidents, probes and traps

Realistic production incidents and pointed probes, grouped by topic.

The product 1

ProbeWhy not build a normal online app with a ‘retry later’ button?
Technicians are offline for hours, and a retry button loses work when the app is killed and relies on people remembering. Offline-first moves that burden from the user to the system. The price is owning a sync protocol, which is worth it when offline is the normal case, not the exception.
I can answer this

Requirements 1

TrapWhich two clarifying answers change the architecture most here?
How long devices stay offline (it sets tombstone retention, snapshot rebuilds and local storage) and whether a job is edited by more than one person (it decides merge rules). Candidates who skip these draw a design that breaks on day one.
I can answer this

Scale 1

ProbeYour estimate says about 48 TB of media a day. What does that number change?
It rules out sending bytes through the API, makes hash dedupe and storage lifecycle tiers mandatory, dominates cost in egress and storage, and forces per-region buckets for residency. Without the number most candidates quietly route media through their backend.
I can answer this

Architecture 2

IncidentAfter launch, supervisors see jobs but broken thumbnails for hours. What is wrong?
Records sync before media by design, but the dashboard links to media that has not uploaded yet. Give each media item a state (on device, uploading, processing, ready), show ‘uploading from device’ placeholders, emit an event when thumbnails are ready, and alert on media lag p95 per region.
I can answer this
ProbeWhy is the sync engine native when the app is React Native?
The OS wakes native code for background work, the JS runtime may not exist at that moment, and moving large files through the JS heap crashes low-memory phones. JavaScript only requests work and observes SQLite.
I can answer this

The key flow 1

IncidentA job shows ‘synced’ on the phone but the supervisor never received two answers. How can that happen?
Typical causes: the client deleted the whole outbox batch on HTTP 200 instead of reading per-op results, it marked rows synced before the transaction committed, or a migration dropped outbox rows. Fix with per-op acknowledgement, delete only on applied or duplicate, and a periodic reconciliation where the device sends a digest of its state for the server to compare.
I can answer this

Front end 2

IncidentUsers with 300+ photos say the checklist becomes sluggish and the app gets killed in the background. Why?
Full-size images are decoded for lists, or images pass through JavaScript as base64, or thumbnails are generated in JS. Generate thumbnails natively, pass only file paths, use fixed-size list items, cap memory caches by device RAM, and release the camera when the screen closes.
I can answer this
ProbeHow do you stop someone submitting incomplete evidence while offline?
Validation runs on the phone from the same checklist schema the server uses: required photos, conditional questions, ranges. The review screen lists what is missing. The server validates again; if rules changed meanwhile, the job comes back as ‘needs changes’ with a clear list.
I can answer this

Data and APIs 1

TrapWhy send base versions per field instead of one version per job?
With one job version, any concurrent edit by a supervisor becomes a conflict even when different fields changed. Per-field versions let non-overlapping edits merge automatically and leave only true clashes to the user, at the cost of a little metadata.
I can answer this

The hard parts 2

IncidentAuditors flag photos whose timestamps are three days before the job was assigned. What happened?
The device clock was wrong (manual time, battery reset) or photos were imported from the gallery. Allow evidence only from the in-app camera, record time since boot plus the last known server-time offset, compute trusted time on the server, flag gallery imports, and keep raw metadata in the audit log.
I can answer this
ProbeHow would you make evidence tamper-evident end to end?
Hash at capture, sign the hash and metadata with a hardware-backed key (Android Keystore, iOS Secure Enclave), verify signature and hash when the upload completes, store objects with object lock, and record every access in an append-only audit trail.
I can answer this

Trade-offs 1

ProbeThe CTO says ‘just use Firebase’. How do you respond?
Agree it is faster to start, then list the constraints it must meet: in-region residency, evidence integrity, field-level merges, 48 TB a day of media cost and lock-in. Propose a two-week spike against those criteria and record the decision in an ADR. For a smaller scope, buying may well be right.
I can answer this

Failures 2

IncidentAfter an update, 2% of devices crash on launch and cannot sync, and they hold unsynced inspections. What do you do?
Halt the staged rollout, turn off the new path with a kill switch, and ship a hotfix. The usual cause is a migration failing on old data. Prevent it with migration tests on real old databases, migrations that never touch the outbox, crash-loop detection that skips optional start-up work but still runs sync, and a support export for unsynced data.
I can answer this
IncidentPhones from one manufacturer stop syncing in the background for days.
Confirm with run telemetry by manufacturer, sync aggressively whenever the app opens, use push hints, and show affected users a one-time battery-settings guide. Accept that background execution is best-effort and make freshness visible on the supervisor dashboard.
I can answer this
Part 5 of 5

Extra depth

What turns a good answer into a strong one: the decisions you rejected, how the system fails, and the signals of seniority.

5.1Trade-offs and decisions

Every choice has a cost. Naming it is what interviewers listen for.

Your turn: State each decision, the alternative you rejected and why.Reveal model answer
Show detailsHide details
DecisionChosenRejectedWhy
UI frameworkReact Native, native sync coreFully native appsTeam skills and speed; the parts that must run in background are native anyway.
Conflict policyField-level mergeLast-write-winsSupervisor and technician edit the same job; whole-record overwrite would lose work.
Media pathDirect to S3 with presigned partsThrough the API48 TB/day through app servers would dominate cost and latency.
Sync engineBuild in-housePowerSync or similarIn-region data, evidence rules and custom merge logic outweigh speed of buying.

5.2Failure modes

What breaks in production, and how the design keeps working when it does.

Your turn: List what breaks and how the system degrades.Reveal model answer
Show detailsHide details
What breaksHow the design copes
Phone lost with unsynced workEncrypted DB, remote wipe on sign-out, and a supervisor view of devices with old unsynced data.
Storage nearly fullWarn before capture, compress video on device, evict synced media first.
OEM battery killer stops jobsTrack background runs per manufacturer, show a one-time guide, sync aggressively whenever the app is open.
Device offline longer than tombstone TTL410 Gone, push outbox first, keep unsynced rows, rebuild from snapshot.

5.3Performance and accessibility

The client-side details that separate a demo from a product.

Performance

  • The job list uses FlashList with fixed item heights, so 300 jobs scroll smoothly on a 3 GB Android phone.
  • The device generates 256 px thumbnails, and lists never decode full photos.
  • Checklist sections mount lazily; only the visible section renders.
  • Hashing, compression and copying run in native code off the JavaScript thread.

Accessibility and localisation

  • Touch targets of at least 48 dp for gloved hands, and a high-contrast theme for sunlight.
  • Every status uses an icon and words, never colour alone.
  • English and Hindi with correct font fallbacks; numbers and dates formatted for the locale.
  • Voice dictation in free-text notes fields.

5.4Senior versus principal

The same design, answered at two levels. Use the rubric to score yourself.

Senior answer

A senior answer gets offline storage, an upload queue and retries right.

Principal answer

A principal answer also sizes the system first, separates records from bytes, chooses merge rules per field, covers evidence integrity and the long-offline edge case, and explains why the sync core is native even in a React Native app.

Score yourself

Requirements Asked clarifying questions and stated assumptions. Numbers Estimated scale and used it to make a decision. Architecture Clear components with responsibilities and data flow. Depth Went deep on the hardest part with real mechanisms. Trade-offs Named alternatives and why they lost. Operations Covered failures, monitoring and rollout. Leadership Explained how the team would build and evolve it.

5.5Whiteboard

Draw the design here, in this order. It stays in this browser.

  1. Phone box with SQLite at the centre and an outbox
  2. OS scheduler waking a sync engine and transfer manager
  3. Arrow from phone straight to S3 that skips the API
  4. Sync service, Postgres change log, Kafka
  5. Supervisor dashboard fed from the same stream
PenBoxArrowTextEraserUndoClear
Tip: draw boxes first, then arrows, then label them with Text.