tezvyn:

OkHttp Caching: Beyond Simple Hits and Misses

AI-drafted, machine-checkedSource: square.github.ioadvanced

OkHttp's cache acts like a browser's, saving network trips by storing responses on disk. It handles not just full hits and misses, but also validates stale data with the server. Use it for repeatable requests.

WHY IT EXISTS Mobile apps often make redundant network requests, wasting battery, data, and user time. A smart caching layer is needed to store responses locally and avoid re-fetching data that hasn't changed, making the app faster, more efficient, and usable offline.

THE MENTAL MODEL Think of OkHttp's cache not as a simple map, but as a tiny, private web browser cache living inside your app. It understands HTTP caching headers and can ask a server, "Is the version I have from last week still good?" This is a conditional GET. If the answer is yes, the server sends back an empty body with a 304 Not Modified status, and OkHttp serves the stored data, saving bandwidth.

HOW IT WORKS When enabled, every request is evaluated against the cache, leading to three outcomes. First, a cache hit: a valid response is in the cache and served immediately with no network call. Second, a cache miss: the data isn't cached or is expired, triggering a full network request. Third, a conditional cache hit: the cached item is stale, so OkHttp makes a network call to validate it. If the server confirms it's still valid, the cached body is used, avoiding a re-download.

WHEN TO USE IT Enable the cache for any client making repeated GET requests for resources like images, JSON APIs, or configuration files. It's configured on the OkHttpClient.Builder by providing a dedicated directory and a max size. By default, it honors standard HTTP cache headers from the server.

WHEN NOT TO USE IT Avoid caching for highly sensitive data that should never be written to disk. Be aware that the cache directory must be exclusively owned by a single OkHttp instance. Also, by default, OkHttp does not cache responses from URLs with query parameters unless the server provides explicit caching headers.

ONE CANONICAL EXAMPLE A common footgun is when caching appears to fail because the response body was never consumed. For a response to be written to the cache, its body must be fully read and closed. Code that only inspects headers and then discards the response will not trigger caching. You must call a method like response.body.string(), response.body.bytes(), or explicitly response.body.close().

Read the original → square.github.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.