Offline First Storage and Sync

Topics Covered

The Local Database as Source of Truth

What offline first actually means

The read path: observe the database

Choosing the local store

What to keep locally

The staleness question

What the interviewer listens for

Shared code and cross platform stores

Encrypting what you store

Step four of the framework is local storage and sync, and for many mobile prompts it is the heart of the interview. A chat app, a notes app, a field service tool, an email client or a to do list is only pleasant to use if it works on a plane, in a lift and on a weak signal. The interviewer wants to see how the client stores data, how the UI reads it, how writes leave the device and how changes from other devices come back. This lesson covers each of those in turn.

The lesson on app architecture introduced the repository pattern and the idea of a single source of truth. Offline first takes that idea to its conclusion: the single source of truth for everything the UI shows is the local database, and the network is a way to keep the database up to date, not something the UI waits on.

What offline first actually means

Offline first does not mean the app must do everything offline. Some actions genuinely need the server: paying, searching a catalogue of millions of items, booking a seat that someone else might take. It means that the app is designed around local data first, so that whatever can work offline does, and whatever cannot degrades clearly rather than spinning forever.

In practice, an offline first app has three properties. Reads come from local storage and appear instantly, whether or not the network is available. Writes are recorded locally first and sent to the server later, so the user never loses work because a request failed. And the app reconciles local and server state in the background, using a sync protocol that is efficient on a mobile network. Each section of this lesson covers one of those properties.

The read path: observe the database

In an offline first design, screens never call the network and render the response. Instead, screens observe a query on the local database, and the database notifies them when the rows behind that query change. A repository starts a network refresh when needed, and the refresh writes its result into the database. The screen redraws because the data changed, not because a request finished.

The network never talks to the screen directly: it fills the database, and the screen follows the database.

This pattern is sometimes called read through caching or stale while revalidate: show what you have immediately, fetch fresh data in the background, and update the view when the fresh data lands. It has several benefits beyond offline support. The screen has exactly one code path for drawing, whether the data came from cache or network. Two screens that show the same object stay consistent because they both read the same row. And when a write is made locally, every screen that observes the affected rows updates at once without any manual notification.

Both platforms make observation straightforward. On Android, Room DAOs can return a Kotlin Flow, which emits a new list whenever the underlying tables change, and the ViewModel exposes it as state. On iOS, SwiftData's query property wrapper keeps a SwiftUI view in step with the store, Core Data has fetched results controllers and change notifications, and libraries such as GRDB offer value observation for plain SQLite.

kotlin
1@Dao
2interface MessageDao {
3    @Query("SELECT * FROM message WHERE conversationId = :cid ORDER BY serverSeq DESC LIMIT :limit")
4    fun observeRecent(cid: String, limit: Int): Flow<List<MessageEntity>>
5
6    @Upsert
7    suspend fun upsertAll(items: List<MessageEntity>)
8}

Choosing the local store

In an interview you rarely need to defend a specific library, but you should say what kind of store you would use and why. For structured data that the app queries, sorts and observes, use a relational store on SQLite: Room on Android, SwiftData, Core Data or GRDB on iOS, and SQLDelight or Room in a Kotlin Multiplatform shared module. SQLite is on every device, it is transactional, and with write ahead logging it allows reads while a write is in progress. For small settings, use a key value store such as DataStore on Android or UserDefaults on iOS. For large binary objects such as images, video and downloaded documents, store files on disk and keep their paths and metadata in the database. Do not put megabytes of blobs in the database itself.

Say where each kind of data lives, because the operating systems treat directories differently. On iOS, the Caches directory can be purged by the system when the device is low on space, so it suits re-downloadable data, while Application Support persists and is included in backups unless you exclude it. On Android, the app's cache directory can be cleared by the system under storage pressure, while the files directory and databases persist until the app is uninstalled or the user clears its data. A message the user wrote but has not sent yet must never live in a location the system may purge.

What to keep locally

Not everything the server knows belongs on the phone. Choose a working set: the data the user is likely to need without a network. For a chat app, recent messages in recent conversations, plus anything the user has written. For an email client, the last few weeks of the inbox, with older mail fetched on demand. For a news feed, the last few pages and any saved articles. State the working set in the interview, with a rough size, because it drives storage budgets, sync cost and eviction later in the design.

It also helps to separate entities by how they behave. Some are owned by the user and edited on the device, such as notes and drafts. Some are owned by others and only read, such as other people's posts. Some are derived, such as unread counts. Owned data needs the full outbox and conflict machinery of the next sections; read only data only needs efficient download and eviction; derived data should be computed locally or treated as a hint, not synced as truth.

The staleness question

Showing cached data immediately raises a fair question: what if it is badly out of date? Store a fetched at timestamp with each cached collection and decide per screen how old is acceptable. A feed that is an hour old is fine to show while refreshing. An account balance or a ticket status may need a visible as of label or a spinner over the cached value until the refresh completes. A stock price may not be worth showing at all once it is minutes old. The interviewer is checking that you thought about the user's trust in the number on screen, not only about speed.

What the interviewer listens for

At this step, a strong candidate says something like: the UI observes the local database, which is the single source of truth; repositories refresh it from the API and write the results in; writes go to the database and an outbox first; and sync runs in the background. Then they name the store and the working set. Weak answers keep the network on the critical path of every screen and treat the database as an optional cache added later, which makes offline support, consistency between screens and fast start all harder.

Shared code and cross platform stores

Teams that share logic across platforms have a few extra options worth one sentence in an interview. In Kotlin Multiplatform, the data layer, including the repository, the sync engine and the outbox, can live in a shared module with SQLDelight or the multiplatform build of Room, so iOS and Android run the same sync and conflict code against the same schema. That removes an entire class of bugs where the two apps disagree about merge rules. React Native and Flutter apps usually reach SQLite through a plugin or use an embedded store with its own sync service. Whatever the stack, the shape of the design stays the same: one local store per account, observed by the UI, filled by sync.

Encrypting what you store

Offline data sits on the device even when the app is closed, so think briefly about protection. Both platforms encrypt the file system when the device is locked with a passcode, and iOS lets you choose a file protection class so that sensitive files are unreadable until the user first unlocks after a reboot, or whenever the device is locked. For most apps that is enough. Apps with stricter needs, such as health or finance, add database level encryption with a key held in the Keychain or the Android Keystore. Keep the trade-off in mind: a database that cannot be opened while the device is locked also cannot be synced by a background task at that moment.

The network fills the database, the UI reads the database

When screens only ever read from the local store, offline support, instant start and consistency between screens come from one rule instead of three separate features.