Implementing Caching Strategies

1. Using Cache-Control Header

ScenarioHeader Value
Static assetpublic, max-age=31536000, immutable
API list endpointprivate, max-age=60, must-revalidate
User-specificprivate, no-cache
Sensitive datano-store

2. Implementing ETag-Based Caching

ETag Validation Flow

  1. Server returns response with ETag: "v1"
  2. Client caches body + ETag
  3. Next request: If-None-Match: "v1"
  4. If unchanged → 304 Not Modified (empty body)
  5. If changed → 200 OK + new body + new ETag

3. Implementing Last-Modified Header

HeaderFormat
Last-ModifiedHTTP-date: Sat, 15 May 2026 10:30:00 GMT
If-Modified-SinceSame format, sent by client
Granularity1 second (use ETag for finer)

4. Using If-None-Match Conditional Requests

HeaderServer Action
If-None-Match: "v1"Same → 304; different → 200 + body
If-None-Match: *POST: only if not exists (insert-only)

5. Using If-Modified-Since Conditional Requests

HeaderServer Action
If-Modified-Since: <date>Unchanged → 304; modified → 200
Combined with ETagETag takes precedence per RFC 7232

6. Returning 304 Not Modified Responses

RequiredForbidden
ETag, Cache-Control, Vary headersBody (must be empty)
Same Content-LocationContent-Length, Content-Type

7. Implementing Private vs Public Caching

DirectiveCached By
publicBrowser + shared caches (CDN, proxy)
privateBrowser only
Default (none)Cacheable per heuristics

8. Using Vary Header

Tells caches which request headers to include in cache key.

Vary ValueCache Key Considers
AcceptFormat negotiation
Accept-EncodingCompression variant
Accept-LanguageLanguage variant
AuthorizationPer-user response
CookiePer-session response

9. Implementing Cache Invalidation Strategies

StrategyDescription
TTL-basedExpire after max-age; simple, may serve stale
Event-drivenPURGE on write; complex but accurate
Versioned URLs/v2/users; bypass old cache
Tagged cache (Varnish)Invalidate by tag (e.g. user:42)
Stale-while-revalidateServe stale, refresh in background

10. Caching at Different Layers

Browser → Service Worker → CDN → API Gateway → App Cache → DB Cache → DB
 (1)        (2)             (3)   (4)            (5)         (6)        (7)
      
LayerTechnologyTTL Range
BrowserHTTP cacheMinutes-hours
Service WorkerCache APICustom logic
CDNCloudflare, Fastly, CloudFrontSeconds-days
AppRedis, MemcachedSeconds-hours
DBQuery cache, materialized viewsVariable

11. Handling No-Store Directive

Use CaseWhy no-store
Auth endpointsTokens never cached
Banking transactionsCompliance / privacy
PII responsesAvoid intermediary leakage

12. Understanding Cache-Control Directives

DirectiveMeaning
max-age=NFresh for N seconds
s-maxage=NShared cache override
no-cacheMust revalidate before serving
no-storeDon't cache anywhere
must-revalidateStale must revalidate
proxy-revalidateSame, for shared caches
immutableWon't change for max-age duration
stale-while-revalidate=NServe stale up to N sec while refreshing
stale-if-error=NServe stale on origin error