How to answer
I'd build a two-level, cache-aside layer for API responses: an in-memory L1 and an on-disk L2 in Caches/, both behind one actor so concurrent access is safe and concurrent misses for the same key share one network request (single-flight). Every entry carries a timestamp, so the caller can choose a freshness policy: fresh-only, or stale-while-revalidate, which shows cached data now and refreshes in the background. Invalidation is by key prefix after mutations, plus a schema version in the key so an app update never decodes an old format. For images I'd use a dedicated pipeline (see Image Caching System), and for data the user creates, a real database, not a cache.
Key points (walk-through)
- Requirements: fast repeat reads, fewer requests, data on cold start or offline, bounded memory and disk, correct invalidation, per-user isolation
- Components: a
ResponseCacheactor (L1 dictionary orNSCache, in-flightTaskmap, TTL), aDiskStore(one file per hashed key, or SQLite), the repository that decides policy per endpoint, andURLCachefor responses whose HTTP caching headers you trust - Data flow: repository →
cache.value(for: key) { try await api.fetch() }→ L1 hit? → L2 hit and fresh? → join an in-flight task? → otherwise load, store in L1 and L2, return - Strategies: cache-aside (the default on clients), write-through (update the cache when a mutation succeeds), stale-while-revalidate (best perceived speed), HTTP caching (
ETag/Cache-ControlwithURLCache) when the backend sets headers correctly - Trade-offs: an actor serializes access (simple, async) whereas a
Mutexaround a dictionary gives synchronous reads;NSCacheevicts automatically under memory pressure but isn't LRU and doesn't enumerate; a custom LRU is predictable but you handle memory warnings yourself - Failure modes: cache stampede (single-flight solves it), unbounded disk growth (size cap plus LRU sweep at launch or in a
BGProcessingTask), corrupt or old-format entries (treat a decode failure as a miss), serving another user's data after logout (namespace keys by user and wipe on sign-out) - Privacy/offline:
Caches/can be purged by the system and isn't backed up, so only cache re-fetchable data; apply file protection; never cache tokens; offline mode reads stale entries deliberately and labels them as such - Testing: inject a clock and a fake loader; assert that two concurrent
value(for:)calls trigger one load, that TTL expiry causes a reload, and that invalidation removes entries
If they dig deeper
Cost-based eviction (NSCache.totalCostLimit with byte sizes). Negative caching (remember 404s briefly). Request coalescing across keys (batch endpoints). Why a cancelled caller shouldn't cancel the shared task other callers are awaiting. When to prefer URLCache alone (well-behaved HTTP APIs) vs an app-level cache (GraphQL, POST queries, derived models).
Common pitfalls
A class cache with a plain dictionary touched from several tasks (a data race; Swift 6 flags it). Caching with no TTL or size cap. Keys that ignore query parameters, locale or user. Treating the cache as the source of truth for user edits. Forgetting actor reentrancy: state can change across an await, so re-check the in-flight map after awaiting disk.
How to use it
A generic actor with TTL, an L1/L2 lookup and single-flight loading. The defer clears the in-flight entry whether the load succeeds or throws.
actor ResponseCache<Value: Codable & Sendable> {
private struct Entry: Codable { let value: Value; let storedAt: Date }
private var memory: [String: Entry] = [:] // L1 (bounded LRU in production)
private var inFlight: [String: Task<Value, any Error>] = [:]
private let disk: any DiskStore // L2: files in Caches/
private let ttl: TimeInterval
init(disk: any DiskStore, ttl: TimeInterval) { self.disk = disk; self.ttl = ttl }
/// Cache-aside with single-flight: concurrent callers for one key share one load.
func value(for key: String, load: @escaping @Sendable () async throws -> Value) async throws -> Value {
var cached = memory[key]
if cached == nil { cached = try? await disk.read(Entry.self, key: key) } // unreadable or old format = miss
if let cached, Date.now.timeIntervalSince(cached.storedAt) < ttl {
memory[key] = cached
return cached.value
}
if let running = inFlight[key] { return try await running.value }
let task = Task { try await load() }
inFlight[key] = task
defer { inFlight[key] = nil }
let value = try await task.value
let entry = Entry(value: value, storedAt: .now)
memory[key] = entry
try? await disk.write(entry, key: key) // L2 is best effort; L1 already has it
return value
}
func invalidate(prefix: String) async { // e.g. "user/42/" after a mutation
memory = memory.filter { !$0.key.hasPrefix(prefix) }
await disk.removeAll(prefix: prefix)
}
}Usage from a repository: try await cache.value(for: "user/\(id)/orders?v=2") { try await api.orders(for: id) }. For stale-while-revalidate, return the stale entry immediately and start a refresh that updates an @Observable model when it finishes.
Best practices
- Bound both levels (count or bytes) and sweep the disk periodically
- Version and namespace keys (schema version, user ID, locale)
- Deduplicate concurrent loads per key
- Choose a freshness policy per endpoint instead of one global TTL
- Invalidate on mutation and wipe user-scoped entries on logout
- Prefer HTTP caching via
URLCachewhen the server's headers are trustworthy
Related concepts
- NSCache, Caching Strategy, Response Caching /
URLCache, Request Deduplication, Image Caching System, Offline Mode Design, Actors and reentrancy