/Tracks

Two-week programme · Day 1 of 14

A leaking valve, two floors underground

Study with AI

Part 1Basics

A website runs on a server that stays on all day. A mobile app runs on a phone that may lose its network at any moment, and the operating system (Android or iOS) may close the app whenever it wants memory or battery back.

So the question for a mobile engineer is simple: when the user does something, how do we make sure it isn't lost if the network is gone or the app gets closed a second later?

Words you need today

Process
Your app while it is running. When the OS ends it, everything held in memory disappears.
Local database
A database file stored on the phone. Unlike memory, it survives the app being closed.
Source of truth
The one place you trust for the current value. Everything else is a copy.
Sync
Moving changes between the phone and the server, in both directions.
Offline-first
A design where the app always reads and writes the local database, and sync happens separately in the background.

The story

Priya inspects pump stations for a pipeline company. At 2:40 pm she stands two floors underground on job j-84, with no signal, and valve 3 is leaking. She opens the checklist and changes valve 3 from ok to leaking.

That single edit runs through this whole programme. By Day 8 you can say what happens to it at every step: where it sits on disk, who wakes the app, what the server decides, and how her supervisor's tablet finds out. Week 2 then reuses those same parts to design chat, checkout and a feed.

Part 2Today's question

Why can't a mobile app treat the server as its source of truth?

By the end of this lesson, you should be able to:

  • Explain why an API call on Save loses data
  • Describe offline-first in two sentences
  • Ask the three questions about any feature

Part 3In detail

Step by step

  1. The user taps Save. The app writes the change to the local database. This takes milliseconds and needs no network.
  2. The screen updates. The screen shows what the database holds, so it now shows the new value.
  3. The change waits. A record of the change stays in the database until the server has it. The app may be closed during this wait, and that is fine.
  4. Sync runs later. When the network returns, a background job sends the change to the server and fetches anything new.
  5. Everyone catches up. Other devices fetch the change from the server the next time they sync.

Two facts shape every mobile design

A server stays on and stays connected. A phone does neither. Networks drop without warning, and Android and iOS suspend or kill your process whenever they want memory or battery back.

So the ordinary design fails here. If tapping Save calls the API, Priya sees a spinner in a basement, and the edit disappears if the OS kills the app before the call returns.

The answer: read and write locally

The screen reads from a database on the phone, and a save writes to that database. A separate sync process moves changes to the server when the OS allows it. The screen never waits on the network, so the app feels instant with full signal or none. People call this design offline-first.

Three questions you will ask every day

Each day of this programme answers the same three questions for one more part of the system. A panel listens for them too, whether or not it says so.

Same tap, two designs

same-tap-two.ktKotlin
1// Loses the edit: the process can die before this call returns.2viewModelScope.launch {3  api.updateJob("j-84", mapOf("answers.valve_3" to "leaking"))4}5 6// Survives: the edit is on disk before the screen changes.7viewModelScope.launch {8  jobs.setAnswer("j-84", "valve_3", "leaking")   // local transaction9  // Nothing else here. Sync runs later, even with this screen gone.10}
10 linesUTF-8Kotlin

The second version has no network call at all. Day 2 opens up setAnswer.

The code, explained

This is the real code, and our tests run it. Read each block, then the notes under it.

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.ktKotlin
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.

What can go wrong

The network is gone when the user taps Save
Nothing changes for the user. The save is local, and sync waits.
The OS closes the app straight after the save
The change is already on disk, so it is not lost.
The phone and server now disagree
This is the cost of the design. Days 4 and 5 deal with it.

Decisions to defend

  • What does the screen read from? Local database, not aPI response cached in memory. A memory cache dies with the process and shows nothing in a basement.

Part 4Questions and answers

Answer out loud first, then open each one.

Priya's phone has full signal. Should the save still go through the local database first?
Yes. One write path means one set of bugs. With a single path, signal changes nothing the user can see, except how soon the change reaches the server.
What is the biggest cost of offline-first?
Two copies of the truth can disagree. You now owe a sync engine and a conflict policy, which is what Days 4 and 5 cover. It suits apps where people must work without signal, and it is overkill for a read-only news app.

Part 5Going further

The three questions, for today

Where does it live?
With a direct API call, only in memory, which is the problem to fix.
Who runs the next step?
Nobody. The call dies with the process.
What if it runs twice?
Unsafe. A blind retry could apply the edit twice.

Practise

  • Recall5 min
    Foundations reels

    Swipe through once. Say each answer before you reveal it.

Optional reference pages

You don’t need these for the lesson. They hold more detail if you want it later.

Priya's edit exists only as a tap so far. Tomorrow it reaches disk, in a way no crash can split in half.

AI Engineer · Day 1 of 14