Imagine: a user opens a mobile app on the subway, where the signal drops every 30 seconds. Without caching, every screen becomes an endless spinner, and on error — a blank void. The offline-first approach solves this: data loads once when connected and remains available locally. But cache isn't a magic wand: incorrect invalidation strategy leads to stale data, and disk overflow crashes the app. We've been designing multi-level caches for years, launched over 50 projects with offline-first architecture, and know the pitfalls. Our goal is to make users see data instantly and developers never wonder why the cache isn't updating.
Designing a Multi-Level Cache
A good cache architecture has several levels:
| Level |
Storage |
Speed |
Lifetime |
Tools |
| Memory |
RAM |
Instant |
App restart |
NSCache (iOS), LruCache (Android) |
| Disk |
Files/DB |
Fast |
Hours–days |
Room (Android), CoreData (iOS) |
| Network |
Server |
Slow |
Forever (source of truth) |
API with ETag |
We use the stale-while-revalidate strategy (cache-first, refresh-in-background): first display the cache instantly, then update data in the background. If data changed, the UI redraws. This gives the user a feeling of instant performance.
Choosing the right TTL is key. For API responses we set TTL from 5 to 30 minutes, for images up to 7 days. On unstable networks, we use ETag, saving up to 80% of traffic (average server cost savings up to 70%, e.g., $10k/month for high-traffic apps). Read time from Room is 1–3 ms, typical disk cache size is 10–50 MB.
On one project (a retail chain app), we implemented a three-level cache: list headers in LruCache (Android), details in Room with a 15-minute TTL, images in Coil with a 100 MB disk cache. Result: average screen load time dropped from 3 seconds to 200 ms, and server load fell by 65%. Contact us for a consultation to select optimal TTLs for your data.
| Data Type |
Recommended TTL |
Reason |
| Product list |
5–10 minutes |
Frequently changes, freshness critical |
| Product images |
24 hours–7 days |
Rarely change, large size |
| Configurations |
30 minutes |
Rarely change, loaded on start |
Implementing Offline-First API Response Cache
On Android we use Room as a persistent cache with timestamps and ETags. Example:
// Entity with timestamp for invalidation
@Entity(tableName = "products_cache")
data class ProductCacheEntity(
@PrimaryKey val id: String,
val categoryId: String,
val payload: String, // JSON string
val cachedAt: Long, // Unix timestamp
val etag: String? = null
)
// Repository: cache-first logic
class ProductRepository(
private val api: ProductApi,
private val dao: ProductCacheDao,
private val cacheMaxAge: Long = 5 * 60 * 1000L // 5 minutes
) {
fun getProductsByCategory(categoryId: String): Flow<List<Product>> = flow {
// 1. Emit cached data immediately
val cached = dao.getByCategory(categoryId)
if (cached.isNotEmpty()) {
emit(cached.map { it.toProduct() })
}
// 2. Check freshness
val oldestEntry = cached.minOfOrNull { it.cachedAt } ?: 0L
val needsRefresh = System.currentTimeMillis() - oldestEntry > cacheMaxAge
if (needsRefresh || cached.isEmpty()) {
try {
val fresh = api.getProducts(categoryId)
val entities = fresh.map { it.toCacheEntity(categoryId) }
dao.upsertAll(entities)
emit(fresh)
} catch (e: IOException) {
// Network unavailable — cache already emitted, do nothing
if (cached.isEmpty()) throw e // nothing to show — propagate
}
}
}
}
UI subscribes to the Flow and receives data twice: first cache, then fresh. This is the basis of offline-first.
ETag for Traffic Savings
Instead of time-based invalidation, you can use HTTP ETag. The server returns ETag: "v42", the next request sends If-None-Match: "v42" — if data hasn't changed, server returns 304 with no body. Traffic savings can reach 80%.
OkHttp (HTTP client for Android and React Native) supports HTTP cache out of the box:
val cache = Cache(
directory = File(context.cacheDir, "http-cache"),
maxSize = 10L * 1024 * 1024 // 10 MB
)
val client = OkHttpClient.Builder()
.cache(cache)
.build()
On iOS, URLSession works similarly through URLCache. But HTTP caching only works with correct Cache-Control headers from the server.
Image Caching: Battle-Tested Libraries
For images we use proven solutions:
-
Android: Coil — Kotlin-first, Compose-ready, memory + disk cache, placeholder/error states.
-
iOS: Kingfisher or SDWebImage — async loading, NSCache + disk, progressive JPEG.
-
React Native: react-native-fast-image (wrapper over SDWebImage/Glide).
// Coil in Compose
AsyncImage(
model = ImageRequest.Builder(context)
.data(product.imageUrl)
.memoryCacheKey(product.id)
.diskCacheKey(product.imageUrl)
.crossfade(true)
.build(),
contentDescription = product.title,
placeholder = painterResource(R.drawable.placeholder),
error = painterResource(R.drawable.error_image)
)
Coil is on average 2x faster than Glide when loading images from cache (tested on Android 12). Kingfisher on iOS provides disk access times under 10 ms.
Cache Invalidation Strategies: Which to Choose?
Invalidation is the hardest part. We use a combination of approaches:
- TTL (time-to-live) — automatic expiry after a set interval. Simple, predictable, but data ages between TTL.
- Event-based — push notification from server on data change. Instant, but requires server support.
- Version-based — server sends
dataVersion, number comparison. Precise without data transfer.
- Pull-to-refresh — user initiates update. Always needed as a fallback.
We combine TTL for basic data, event-based for critical data (e.g., account balance), and pull-to-refresh as a backup. Implementation takes 1–2 weeks depending on the number of data types.
How to Choose a Caching Strategy for Specific Data?
For frequently changing data (news feed), use TTL 5–10 minutes with event-based updates. For static reference data, versioning with a long TTL. Testing on real scenarios shows that the right combination of strategies improves user retention by 15–25%.
Steps to Implement Multi-Level Cache
- Audit current APIs and data.
- Design cache schema: choose layers, TTL for each type.
- Implement in-memory (NSCache/LruCache) and disk cache (Room/CoreData).
- Integrate HTTP cache and ETag.
- Set up invalidation (event-based + TTL).
- Test offline scenarios: network off, slow, drop.
- Documentation and team training.
Что входит в работу
- Audit of current APIs and data
- Design of cache architecture (layer schema, TTL selection)
- Implementation of in-memory and disk cache
- Integration of HTTP cache and ETag
- Configuration of invalidation (event-based + TTL)
- Testing offline scenarios (network off, slow, drop)
- Documentation and team training
- Support during App Store / Google Play release
Our team has developed over 50 mobile apps with offline-first architecture. We guarantee stable cache performance in unstable network conditions. All solutions undergo code review and load testing. Contact us for a project evaluation — we'll propose an optimal caching scheme for your data.
How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?
We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.
In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.
Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.
Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.
Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.
Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.
| Platform |
Solution |
Reactivity |
Synchronization |
| Android |
Room + Flow |
LiveData/Flow |
WorkManager |
| iOS |
Core Data |
NSFetchedResultsController |
CloudKit |
| Flutter |
Isar |
Streams |
Custom / Realm Sync |
| Cross-platform |
Realm |
RealmResults.observe |
Device Sync |
| Flutter (simple) |
Hive |
ValueListenable |
None |
Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.
Why Is Offline Synchronization the Hardest Part?
Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.
The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.
On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val pendingOps = syncDao.getPendingOperations()
for (op in pendingOps) {
try {
apiClient.send(op.payload)
syncDao.markSynced(op.id)
} catch (e: Exception) {
syncDao.markFailed(op.id, e.message)
return Result.retry()
}
}
return Result.success()
}
}
On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."
Conflicts in multi-device scenarios are resolved with one of three approaches:
- Last-write-wins based on
updated_at (simplest, loses data on concurrent edits)
- Server-wins (client always accepts server version)
- Three-way merge (complex, requires a common ancestor — suitable for documents)
For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.
How We Build the Storage Layer
The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.
For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:
class UserRepository {
final Isar isar;
final ApiClient api;
Future<User> getUser(String id) async {
// try from local storage first
final cached = await isar.user.where().idEqualTo(id).findFirst();
if (cached != null) return cached;
// otherwise from network
final remote = await api.fetchUser(id);
// save locally
await isar.writeTxn(() => isar.user.put(remote));
return remote;
}
}
Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.
What the Work Includes
We guarantee a transparent process and document each stage:
| Stage |
Result |
| Requirements audit |
Document analyzing data types, volumes, synchronization scenarios |
| Schema design |
ER diagram, migration files, conflict resolution plan |
| Repository layer development |
Code with unit tests (in-memory DB + network mocks) |
| Synchronization integration |
Operation queue, error handling, fallback logic |
| Profiling and optimization |
Report from Android Profiler / Core Data SQLDebug, recommendations |
| Deployment and documentation |
Deployment instructions, API description, repository access |
Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.
Stages of Work
We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.
Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.
Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).
The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.