الانتقال إلى المحتوى
تطبيقات الموبايلApp Architecture· 8 دقائق للقراءة

Offline-First Isn't a Cache: The Local Database as the Source of Truth

A cached response lets users look at old data. Offline-first lets them keep working: reads come from the database, writes go through a durable sync queue, and conflicts follow a rule.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

An inspection app is used in underground car parks with no signal. The team added "offline support" by saving the last API response and showing it when a request fails, so inspectors can see their checklists underground. They tick items, the screen updates, and the app keeps the failed requests in a list to retry. Back above ground, the app refreshes, the server's copy replaces the saved one, and every tick is gone. On days when the phone killed the app underground, the retry list was gone too.

The common misconception

The belief: offline support means caching the last API response and showing it when there's no network. Writes can wait until the connection comes back.

It's an easy belief to hold because it works for reading. A news feed or a weather screen that shows the last known data is far better than an error. Flutter's own offline-first guide starts with exactly this approach, using local data "as a fallback" when a network call fails. It's also cheap to add to an existing app. The half-truth: a fallback cache is a fine choice for data users only read. The moment they write while offline, a cache is the wrong model, because a cache is a copy of the server, and nothing in it is allowed to be newer than the server.

What actually happens

Offline-first flips which copy the app reads

Android's guide states the core rule: "The local data source is the canonical source of truth for the app. It should be the exclusive source of any data that higher layers of the app read." Writes go there too: "Write any updates to the local data source first". The network still holds "the actual state of the application", and the local copy may lag behind it or run ahead of it until they sync.

That's the difference from a cache. With a cache, the UI asks the network and falls back to disk. Offline-first, the UI reads only the database, and the network's only job is to update the database. The repository stays the , which Flutter's guide describes as combining local and remote data "in a single access point, independently of the connectivity state of the device." An app that reads this way is the same online and offline, and a screen that observes the database updates by itself when sync writes new rows.

Writes need a durable queue

Android lists three write strategies. Online-only writes suit things like a bank transfer. Queued writes suit analytics and logging, where losing one isn't critical. For data that matters to the user, it calls "lazy writes" the correct choice: "Write to the local data source first, then queue the write to notify the network at the earliest opportunity." Flutter's guide shows the same idea with a synchronized flag on each record and a sync task that sends unsynchronized records, run by a Timer or the workmanager plugin.

The queue, often called an outbox, has to live in the database, in the same transaction as the change. A list in memory dies with the process, as the article on the app lifecycle and process death explains. Each entry in the also needs an ID created on the device, because a request can succeed on the server while its response is lost, and the retry must not apply it twice. That's on the server side, which ReadIn's article on idempotent consumers covers in depth.

Conflicts are a decision, not an accident

Two devices can edit the same record while offline. Android's guide is explicit: "you must resolve the conflict before synchronization can happen", and "Conflict resolution often requires versioning." It names a common approach for mobile apps, : devices attach a timestamp to each write, and the server discards anything older than its current state. It's simple, but it silently drops the losing edit, and it trusts device clocks.

The alternative is a version number on each record: the server rejects a write based on an old version, and the app shows the user a conflict. Which one fits is a product question. Your app has become an eventually consistent replica of the server, and ReadIn's article on eventual consistency as a product decision applies to it directly.

From a cache to a sync queue

Dart checklist_repository.dart
// "Offline support": show the last response when the network failsFuture<List<Item>> loadItems() async {  try {    final items = await api.fetchItems();    await cache.save(items); // overwrites edits made offline    return items;  } catch (_) {    return cache.load();  }}Future<void> checkItem(String id) async {  try {    await api.check(id);  } catch (_) {    pendingRetries.add(id); // in memory: gone after process death  }}

We ran both designs in a small Dart simulation: a fake server with two unchecked items, two ticks made offline, the process killed, then a restart with the network back and the first response deliberately lost. The cache version restarted with an empty retry list, and after the refresh both items showed unchecked on the screen and on the server. The offline-first version kept both ticks on screen throughout. Its first sync stopped when the first response was lost, leaving both entries queued; the second sync drained the queue. The server received three requests and applied each change exactly once. Without the server checking the op ID, the duplicate request applied the change twice: harmless for a checkbox, not for "add one to the stock count".

Cached responseOffline-first
Where the UI readsThe network, disk as a fallbackThe local database only
Where writes goThe network firstThe database and the sync queue, then the network
Edits made offlineBlocked or lost on the next refreshKept and sent later
After process deathIn-memory retries are goneThe queue is on disk
ConflictsThe server's copy overwrites silentlyAn explicit rule: versions or last write wins

How to apply it in your project

  1. Classify each featureRead-only data that changes rarely can use a fallback cache. Writes that must be confirmed now, like payments, stay online-only. Everything users expect to keep working offline gets the full treatment.
  2. Make the database the only read pathRepositories expose streams from the database. Network results are written into the database, never handed to the UI directly.
  3. Add a sync queue tableWrite each change and its queue entry in one transaction, with an ID created on the device. Drain the queue in order, with backoff, and remove an entry only after the server accepts it.
  4. Pick a conflict rule per entityUse version checks where losing an edit matters and last write wins where it doesn't. Decide what the user sees when a write is rejected.
  5. Test the bad pathsEdit in airplane mode, kill the app, drop responses on purpose, and edit the same record on two devices. Check the final state on the server and on screen.

Key takeaways

  • A cache is a copy for reading; offline-first makes the local database the only thing the UI reads.
  • Write locally first, in the same transaction as a sync queue entry, so nothing lives only in memory.
  • Give every queued write a device-made ID so the server can ignore retries it has already applied.
  • Push before you pull, and never let a pull overwrite rows with pending changes.
  • Choose a conflict rule on purpose; last write wins is simple but silently drops the losing edit.

📚 المصادر

  1. Offline-first support — Flutter docs
  2. Build an offline-first app — Android Developers
  3. Data layer — Android Developers

التعليقات (0)