行動應用程式為何顯示舊資料:由回應標頭理解 HTTP 快取
The app shows yesterday's data and nobody wrote any cache code. HTTP caching on mobile, from the response headers up.
文章解釋,行動應用程式即使沒有自行編寫快取程式碼,也可能因網絡函式庫的 HTTP 快取和回應標頭而顯示舊資料。iOS 的 URLSession 預設使用 URLCache.shared,OkHttp 則須另行設定快取;兩者在回應只有 Last-Modified、沒有快取標頭時可能套用啟發式新鮮度,OkHttp 適用於沒有查詢字串的 URL。
The bug: a user changes something on the web, opens the app, and sees the old value. Pull to refresh doesn't help. Ten minutes later, or after reinstalling, it's fine. Nobody on the team wrote a cache, so everyone looks for a bug in the backend first.
Often there is a cache, and it's the HTTP cache built into the networking library. It follows the response headers your server sends, including the headers it doesn't send.
Who caches by default
-
iOS,
URLSession:URLSession.sharedand the default configuration useURLCache.shared, with the cache policy.useProtocolCachePolicy. So every app has an HTTP cache, in memory and on disk, unless someone turns it off. -
Android, OkHttp: no cache until you add one with
Cache(directory, maxSize)on theOkHttpClient.Builder. Many apps do, often copied from a setup guide. -
Android,
HttpURLConnection: no cache unlessHttpResponseCache.install()was called.
So "we never wrote cache code" is true, and on iOS it's also irrelevant.
The header that isn't there
If a response has Cache-Control: max-age=... or Expires, the cache does what it says. The surprise comes when a response has no caching headers but does have Last-Modified.
The HTTP caching spec (RFC 9111) lets a cache pick a freshness lifetime on its own in that case, called heuristic freshness. The common rule is 10% of the time since Last-Modified. A JSON response whose Last-Modified says it changed 10 days ago can be reused for about a day, without any request going to the server.
iOS's URL loading system applies this. OkHttp applies it too, for URLs without a query string. Frameworks and CDNs add Last-Modified to responses all the time, often for static files that later became API-like endpoints, so this shows up without anyone choosing it.
The directives, briefly
-
no-store: don't write it anywhere. Use this for tokens and personal data. -
no-cache: store it, but check with the server before every reuse. It does not mean "don't cache". -
max-age=60: fresh for 60 seconds, then check again. -
private: only the client may cache it, not shared caches like CDNs. -
ETag+If-None-Match: when the client checks again, the server can answer304 Not Modifiedwith no body, and the client uses its stored copy. That's cheap, and it's what you want for most API reads. -
Vary: the stored copy only matches requests with the same values for the listed headers. If responses depend onAuthorizationorAccept-Language, say so here, or one user's cached response can be served for another account on the same device.
Finding out whether a response came from the cache
-
iOS: collect
URLSessionTaskMetricsinurlSession(_:task:didFinishCollecting:). For each transaction,resourceFetchTypeis.localCachewhen nothing went over the network. -
OkHttp: on the
Response,cacheResponseis non-null when the cache was involved andnetworkResponseis non-null when the network was. Both non-null means a conditional request (usually a304). - In a debugging proxy: a response served from the cache never reaches the proxy. If the screen loads and the request isn't in the capture, that's the answer.
Fixing it
-
Fix the server first. Every API response should say what it wants:
Cache-Control: no-storefor sensitive data,no-cacheplus anETagfor data that must always be current, or a shortmax-agewhere a little staleness is fine. Explicit headers end the heuristic guessing on every client at once. -
Make pull to refresh mean it. On iOS, set
request.cachePolicy = .reloadIgnoringLocalCacheDatafor that request. On OkHttp, addCacheControl.FORCE_NETWORKto that request. -
Don't turn the cache off globally. Setting
urlCache = nilor removing the OkHttp cache fixes the symptom and makes every image and config fetch slower. Fix the headers instead. -
Clear it on logout.
URLCache.shared.removeAllCachedResponses()on iOS,cache.evictAll()on OkHttp, so the next account doesn't see the previous one's responses.
Testing it
Change a value on the server, then open the app's screen without reinstalling. Check the response headers of that request in a capture: if there's no Cache-Control and there is a Last-Modified, you've found the cause before reading any app code.
This article was created with the help of AI.
來源:DEV Community · dev.to