HTTP caching with OkHttp

Networking Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

The app re-downloads a 2 MB catalog on every launch even though it changes weekly and the server sends an ETag. Fix?

Options
Hint 1 of 1

What does the client need for ETag to help?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Configure an OkHttp Cache so conditional requests return 304 when unchanged

Correct. With a cache, OkHttp sends If-None-Match and reuses the stored body.

Why not the others?
  • B Store the catalog in a static variable. Lost on process death.
  • C Compress the catalog. Still downloaded every time.
  • D Increase the read timeout. Unrelated.

30-second answer

Give OkHttpClient a Cache(directory, maxSize). Then OkHttp follows the server's Cache-Control headers: fresh responses come from disk without a request, and stale ones are revalidated with If-None-Match/If-Modified-Since, so an unchanged resource costs a 304 with no body. The server's headers decide behaviour; the client just needs the cache configured.

Practise saying it · 30 s. No recording, just a timer

Explain HTTP caching.

Say your answer out loud, then check which of these points you covered:

  • Configure an OkHttp Cache
  • Server headers decide
  • Revalidation with 304
  • Careful with private data

Deep dive

CacheControl.FORCE_CACHE can show cached data when offline.

OkHttp's cache is a private, per-app cache, so it does store private responses; servers send no-store for data that must never be written to disk.

A network interceptor that rewrites response cache headers is a workaround when you can't change the server.

Images usually have their own memory and disk cache in the image loader.

Common mistakes

  • Expecting caching without configuring a Cache.
  • Overriding server headers everywhere with an interceptor.
  • Caching responses that contain private data and not clearing on logout.

Senior take & follow-ups

Explain that the server's headers drive it, and mention 304s.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does ETag do?

    Show hint

    Lets the client ask 'has this changed?' and get a 304 if not.

  2. How do you show cached data offline?

    Show hint

    Request with CacheControl.FORCE_CACHE when there's no network.

Suggest a fix if something here is wrong or out of date.