Use HTTP Validators Before Building Another Cache

A catalog screen downloads the same JSON every time you open it. The natural next step is a dictionary of responses and a timer that expires them after five minutes.

Before adding that timer, inspect the HTTP response. The server may already know exactly which version of the catalog you have and whether it can still be reused.

Our earlier AsyncImage caching post covers image loading in SwiftUI. This time, let’s follow a JSON response through HTTP validation and check the boundary between what the server sends and what the app receives.

Freshness and validation answer different questions

A fresh cached response can satisfy a request without contacting the server. A stale response may still contain perfectly good data; it needs validation before reuse under the response’s cache policy.

Here is a small example response:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: private, max-age=0
ETag: "catalog-v1"

{"revision":1,"titles":["A","B"]}

The entity tag is an opaque validator supplied by the server. On revalidation, the client can send If-None-Match: "catalog-v1". If the representation is unchanged, the server can answer 304 Not Modified without resending its body. The cache combines that validation with the representation it already holds. RFC 9111 specifies the validation flow.

An ETag is not necessarily a content hash, a revision number, or something the client should parse. Preserve its syntax, including quotes and any weak-validator prefix, if you ever need to handle it yourself.

Start with protocol caching

For this public catalog example, a small memory-only cache is enough to demonstrate the behavior:

import Foundation

func makeCatalogSession() -> URLSession {
    let configuration = URLSessionConfiguration.default
    configuration.urlCache = URLCache(
        memoryCapacity: 4 * 1024 * 1024,
        diskCapacity: 0,
        diskPath: nil
    )
    configuration.requestCachePolicy = .useProtocolCachePolicy
    return URLSession(configuration: configuration)
}

Keep this session for the lifetime of the catalog feature or its client. Creating a fresh memory-only session for every read would throw away the cache we just configured.

Apple’s cached-data guide explains the request policies. .useProtocolCachePolicy lets the protocol implementation make the cache decision. A cache capacity is room for eligible responses, not an instruction that every response must be stored forever.

Our app code still asks for the complete representation:

struct Catalog: Decodable, Equatable {
    let revision: Int
    let titles: [String]
}

func loadCatalog(from url: URL, session: URLSession) async throws -> Catalog {
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    let (data, response) = try await session.data(for: request)
    guard let http = response as? HTTPURLResponse,
        http.statusCode == 200
    else {
        throw URLError(.badServerResponse)
    }
    return try JSONDecoder().decode(Catalog.self, from: data)
}

There is no ETag dictionary here. URLSession’s cache owns the stored representation and its validation metadata.

If you manually add conditional headers while disabling that cache, you have taken on a different job. A raw 304 has no replacement JSON body to decode. You must retain the matching representation and implement the relevant update rules. That can be justified for an application-specific persistence design, but it should be an intentional decision.

Test two different observations

The server’s status code and the app’s usable result are not the same observation. A cache can validate over the network and still deliver the complete cached representation to the caller.

The local fixture exercises this sequence:

  1. The first request receives the JSON above with an immediately stale response and ETag.
  2. The second request presents that ETag. The server returns 304 and changes freshness to private, max-age=600.
  3. The third read can use the now-fresh cached response.

The test needs assertions on both sides: every app read decodes the catalog, while the server sees only the initial request and the conditional validation. A test that merely sees the same title three times cannot tell whether we saved any network traffic.

Also test a changed ETag with a new body, a response that cannot be stored, and a cache eviction. The feature must work when the cache is empty. It is an optimization, not the only copy of data the UI knows how to read.

Read the directives before changing the client

Two commonly confused directives are no-cache and no-store. The former requires validation before reuse; the latter prohibits storing the response under the HTTP caching rules. private restricts shared-cache storage; it does not encrypt application data. These distinctions come from the cache-control definitions.

For a personalized endpoint, review the full server/client contract: authentication, representation selection, cache policy, and account switching. If language changes the returned catalog, the cache must distinguish that variant, commonly through the server’s Vary metadata. Do not use a URL-only application dictionary that ignores those inputs.

Our demonstration cache has no disk persistence. That choice alone is not a privacy policy; a session still has other state such as cookies and credentials. Use the project’s existing account/session isolation and invalidate account-owned state on logout.

Measure what validation actually saves

A 304 still involves a request and a response. It can save body transfer, but it does not promise zero server work or instant UI. Our loader still decodes the JSON on each call. A fresh local hit avoids the network exchange entirely.

If the screen needs to display saved content while offline, design that user experience explicitly. An evictable HTTP cache and a durable offline catalog serve different purposes. Keep the durable model when the product requires it; use HTTP validation to avoid needlessly transferring its unchanged source.

September 2026 review: the URLSession example compiles with Swift 6.4 and Xcode 27. The loopback fixture passed the 200 → 304 → fresh-cache sequence: all three reads decoded the complete catalog, while the server received exactly two requests, including the expected conditional header. This verifies the local fixture on macOS 27; repeat the sequence against your endpoint and app configuration.

The first useful cache optimization is often a conversation with the endpoint owner: what makes this representation fresh, and how can the client prove it already has the current version? Answer that before writing another expiration timer.