Caching and offline reads

Learn Android caching and offline reads by comparing OkHttp HTTP cache with Room to implement stale-while-revalidate patterns in Kotlin apps. About 25 minutes.

Why it matters

  • Showing cached data instantly makes screens feel fast and keeps the app useful on a train or in a lift.
  • Skipping requests for data that is still fresh saves battery, mobile data and server load.
  • Without a clear freshness rule you get either a network call on every screen open, or data that is days old with no way to refresh it.
  • Interviewers ask you to compare HTTP caching with an offline-first database, to explain ETags and 304s, and to describe stale-while-revalidate and its failure cases.

The simple explanation

  • A café has a menu board (the cache) and a kitchen (the server).
  • HTTP caching is the board printed by the kitchen with a "valid until 2 pm" sticker: the kitchen decides how long it is good, and after that you ask "anything changed since this version?" and often hear "no, keep it" (a 304).
  • A database as the source of truth is your own notebook of the menu: you always read from it, you decide when to ask the kitchen for an update, and you still have it when the kitchen is closed.

There are two common layers of caching in an Android app.

HTTP cache (OkHttp). OkHttp has no cache until you give it one: OkHttpClient.Builder().cache(Cache(directory, maxSize)). It then stores responses on disk and follows the server's headers. A response with Cache-Control: max-age=60 is served from disk for 60 seconds without touching the network. After that, if the response had an ETag (or Last-Modified), OkHttp sends a conditional request with If-None-Match (or If-Modified-Since). The server answers 304 Not Modified with no body when nothing changed, and OkHttp hands your code the cached body. no-store forbids caching; no-cache means "store it, but revalidate before every use". The cache is transparent: your Retrofit call just returns a response.

Database cache (Room as single source of truth). The UI observes a Flow from Room, and the network only writes into Room. This is the offline-first pattern from the repository lesson: reads come from the database, network results go into it, and the screen shows whatever the database holds, even with no connection.

Freshness and stale-while-revalidate. The app decides when the database copy is too old. Store when each row was fetched (fetchedAt), and on screen open:

  1. Show the cached rows immediately (from the Room Flow).
  2. If they are older than a time-to-live (TTL) for that kind of data, or missing, fetch in the background and upsert. The Flow re-emits with the new data.
  3. If the fetch fails, keep showing the cached rows and tell the user they may be out of date.

Pull-to-refresh skips the TTL check and always fetches.

HTTP cache (OkHttp)Room as source of truth
Who decides freshnessServer headers (Cache-Control, ETag)App logic (TTL per data type, user refresh)
What you getA whole response, per URLRows you can query, filter, join and observe
Offline behaviourOnly if a stored response is usable for the requestAlways shows what is stored
Changes reach the UIOnly when you make the request againFlow re-emits after each write
EffortConfigure a Cache, needs correct headersEntities, DAOs, mapping, refresh logic

They work together: Room for data the user sees and works with offline, and the HTTP cache to make the refresh requests cheap (a 304 costs very little).

The screen reads only the database
The screen reads only the database The screen observes a Flow from the Room database and shows the cached rows at once. The repository fetches fresh data from the network and upserts it into Room. Room emits the updated rows and the screen updates. With no connection, the fetch fails but the cached rows stay on screen. Offline, the fetch fails but the cached rows stay OBSERVE A FLOW CACHED ROWS AT ONCE refresh() FETCH FRESH DATA RESPONSE UPSERT ROWS UPDATED ROWS Screen collects a Flow Repository refreshes data Room source of truth Network Retrofit
Network results go into Room and never straight to the screen, so the screen shows what the database holds even offline.

Notes

  • OkHttp caches nothing by default. Add Cache(File(context.cacheDir, "http_cache"), maxSize); the size limit is required, and OkHttp evicts old entries when it is reached.
  • The HTTP cache only follows what the server says. With missing or no-store headers it caches nothing, and rewriting headers in an interceptor is easy to get wrong.
  • A 304 Not Modified still makes a round trip, but it has no body, so it is cheap on slow connections.
  • CacheControl.FORCE_NETWORK on a request bypasses the cache (useful for pull-to-refresh); CacheControl.FORCE_CACHE returns only cached data, or a 504 if none is usable.
  • In offline-first, the UI reads only from the database. The network result is written to Room and never handed straight to the screen.
  • Store a fetchedAt timestamp per row or per query, and pick a TTL per data type: a user profile might be fine for an hour, prices for a minute.
  • Stale-while-revalidate: emit cached data first, refresh in the background, let the Room Flow deliver the update. A failed refresh must not clear the cache.
  • Distinguish the empty states: "no cached data and loading", "no cached data and offline" and "cached data that may be stale" need different UI.
  • Catch specific exceptions (IOException, HttpException) around refresh. A bare catch (e: Exception) also swallows CancellationException and real bugs.
  • Prune what you no longer need (old rows, deleted items) during refresh, or the database grows without limit.

Code example

A Room-backed repository with a freshness rule, plus a ViewModel that shows cached data immediately and refreshes in the background. The HTTP cache sits underneath in OkHttp.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import java.io.File
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.HttpException
import retrofit2.http.GET
import retrofit2.http.Path
 
// HTTP layer: a disk cache so revalidation can return a cheap 304
fun buildClient(cacheDir: File): OkHttpClient =
    OkHttpClient.Builder()
        .cache(Cache(File(cacheDir, "http_cache"), 20L * 1024 * 1024))
        .build()
 
data class User(val id: String, val name: String)
data class UserDto(val id: String, val name: String)
 
@Entity(tableName = "users")
data class UserEntity(
    @PrimaryKey val id: String,
    val name: String,
    val fetchedAt: Long,          // when this row came from the server
)
 
@Dao
interface UserDao {
    @Query("SELECT * FROM users WHERE id = :id")
    fun observe(id: String): Flow<UserEntity?>
 
    @Query("SELECT fetchedAt FROM users WHERE id = :id")
    suspend fun fetchedAt(id: String): Long?
 
    @Upsert
    suspend fun upsert(user: UserEntity)
}
 
interface UserApi {
    @GET("users/{id}")
    suspend fun fetchUser(@Path("id") id: String): UserDto
}
 
class UserRepository(
    private val api: UserApi,
    private val dao: UserDao,
    private val now: () -> Long = System::currentTimeMillis,
) {
    // The UI only ever reads the database
    fun observeUser(id: String): Flow<User?> =
        dao.observe(id).map { entity -> entity?.let { User(it.id, it.name) } }
 
    // Fetches only when the row is missing or older than maxAgeMillis. Throws on failure.
    suspend fun refreshIfStale(id: String, maxAgeMillis: Long = 60 * 60 * 1000L) {
        val fetchedAt = dao.fetchedAt(id)
        if (fetchedAt != null && now() - fetchedAt < maxAgeMillis) return
        val dto = api.fetchUser(id)
        dao.upsert(UserEntity(dto.id, dto.name, fetchedAt = now()))
    }
}
 
class ProfileViewModel(private val repo: UserRepository, private val userId: String) : ViewModel() {
    val user: StateFlow<User?> = repo.observeUser(userId)
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
 
    private val _refreshError = MutableStateFlow<String?>(null)
    val refreshError: StateFlow<String?> = _refreshError.asStateFlow()
 
    init { refresh(force = false) }
 
    fun refresh(force: Boolean) {
        viewModelScope.launch {
            try {
                repo.refreshIfStale(userId, maxAgeMillis = if (force) 0 else 60 * 60 * 1000L)
                _refreshError.value = null
            } catch (e: IOException) {
                _refreshError.value = "Offline: showing saved data"
            } catch (e: HttpException) {
                _refreshError.value = "Server error " + e.code()
            }
        }
    }
}
  • The screen shows the cached user as soon as Room emits; the refresh runs next to it, and its result arrives through the same Flow.
  • fetchedAt turns "is this fresh?" into a cheap query, and pull-to-refresh passes force = true, which skips the check.
  • A failed refresh only sets an error message; the cached row stays on screen. Catching IOException and HttpException, not Exception, lets cancellation and real bugs propagate.
  • No withContext(Dispatchers.IO): the Room and Retrofit suspend functions are main-safe.

Run the idea in plain Kotlin

A fake clock and a MutableStateFlow "table" show stale-while-revalidate: cached data first, a skipped refresh while fresh, a background update when stale, and a failed refresh that keeps the old data.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

data class CachedUser(val name: String, val fetchedAt: Long)

class FakeClock(var now: Long = 0)

class UserRepository(private val clock: FakeClock, private val ttl: Long) {
  private val table = MutableStateFlow<CachedUser?>(CachedUser("Ana (saved)", fetchedAt = 0))
  var online = true
  private var serverVersion = 0

  fun observe(): Flow<CachedUser?> = table

  suspend fun refreshIfStale(): String {
      val row = table.value
      if (row != null && clock.now - row.fetchedAt < ttl) return "fresh, no request"
      delay(10) // network call
      if (!online) return "offline, keeping cache"
      serverVersion++
      table.value = CachedUser("Ana v" + serverVersion, fetchedAt = clock.now)
      return "refreshed"
  }
}

fun main() = runBlocking {
  val clock = FakeClock()
  val repo = UserRepository(clock, ttl = 60)
  val ui = launch { repo.observe().collect { println("UI shows " + it?.name) } }
  yield()

  clock.now = 30
  println("t=30: " + repo.refreshIfStale()); yield()

  clock.now = 90
  println("t=90: " + repo.refreshIfStale()); yield()

  clock.now = 200
  repo.online = false
  println("t=200: " + repo.refreshIfStale()); yield()

  ui.cancel()
}

Expected output:

UI shows Ana (saved)
t=30: fresh, no request
t=90: refreshed
UI shows Ana v1
t=200: offline, keeping cache

In production

An old response overwrote a newer one
  • A search screen fired a refresh on every keystroke and upserted each result into Room.
  • On a flaky connection, the response for "ca" arrived after the response for "cat" and replaced it.
  • Users saw results that did not match the text in the search box.
The fix
  • The ViewModel now feeds the query through debounce(300) and collectLatest, which cancels the previous refresh before it can write.
  • Each cached result row stores the query it belongs to, and the screen observes rows for the current query only.
  • For entities edited on several devices, the upsert now runs in a transaction that skips a row whose server updatedAt is older than the stored one.
Prices stayed stale for a day
  • To cut traffic, a network interceptor rewrote every response to Cache-Control: max-age=86400.
  • That included the prices endpoint, so OkHttp served day-old prices from disk without asking the server, even after pull-to-refresh.
  • Checkout then rejected orders because the shown price no longer matched the server price.
The fix
  • Removed the blanket rewrite and asked the backend to send real headers per endpoint (short max-age plus an ETag for prices, longer for static content).
  • Pull-to-refresh now builds its request with CacheControl.FORCE_NETWORK.
  • Prices moved into Room with a one-minute TTL, and checkout always fetches the current price before confirming.

Common mistakes

  • Showing the network response directly in the UI. The screen is empty offline and flickers on slow networks. Write results to Room and observe Room.
  • Catching Exception around refresh and ignoring it. That hides real bugs and swallows CancellationException. Catch IOException and HttpException, and turn them into UI state.
  • Clearing the cache before the new data arrives. A delete-then-fetch leaves an empty screen if the fetch fails. Fetch first, then replace in one transaction.
  • One TTL for everything. A profile, a price and a feed go stale at different speeds. Choose per data type, and always let the user force a refresh.
  • Rewriting server cache headers in an interceptor. It is easy to cache data that must stay live. Fix the headers on the server, and rewrite in the client only for specific, safe endpoints.
  • Treating "no data" and "offline" as the same state. An empty list with no connection should say so and offer retry, not look like the user has no items.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between OkHttp's HTTP cache and using Room as a single source of truth?”

“How would you show data offline and keep it reasonably fresh?”

“What are ETags and how do they work?”

“What are the risks of a local database cache?”

Quiz

What does a server return to a conditional request with If-None-Match when the resource has not changed?

In an offline-first app, where does the UI read its data from?

OkHttp is built without calling cache(...). The server sends Cache-Control: max-age=600. What happens on the second identical request a minute later?

A refresh fails because the device is offline, and the screen has cached data. What should happen?

0 of 4 answered

Mini task

Task: a cached product list with a freshness rule

  1. Create a Room entity ProductEntity(@PrimaryKey val id: Long, val name: String, val fetchedAt: Long).
  2. Create a ProductDao with fun observeAll(): Flow<List<ProductEntity>>, @Query("SELECT MIN(fetchedAt) FROM products") suspend fun oldestFetch(): Long?, @Upsert suspend fun upsertAll(items: List<ProductEntity>) and @Query("DELETE FROM products WHERE id NOT IN (:ids)") suspend fun deleteAllExcept(ids: List<Long>).
  3. In ProductRepository, expose observeProducts(): Flow<List<Product>> mapped to a domain model.
  4. Add suspend fun refreshIfStale(maxAgeMillis: Long) that returns early when the cache is younger than maxAgeMillis; otherwise it fetches, then calls deleteAllExcept and upsertAll inside db.withTransaction.
  5. In the ViewModel, show the list with stateIn, call refreshIfStale in init, and force a refresh (maxAgeMillis = 0) on pull-to-refresh. Catch IOException into an "offline" message.
  6. Configure OkHttp with a Cache in context.cacheDir.

Done condition: in airplane mode the list still shows the saved products with an offline message; reopening the screen within the TTL makes no request; pull-to-refresh always makes one; products removed on the server disappear after a refresh.

Next: Why dependency injection