Skip to main content

Application Layer Protocols

HTTP Headers and Caching

0:00
LearnStep 1/3

Deep Dive into HTTP Headers and Caching Mechanics

For senior engineers, HTTP headers are the control plane of web communication. Beyond simple data transport, they dictate performance (caching), security (CORS, HSTS), and content fidelity (negotiation).

1. Caching Strategies & Cache-Control

The Cache-Control header is the primary directive for caching policies in browsers and intermediate proxies (CDNs).

  • no-store: Absolutely no caching. Sensitive data.
  • no-cache: The response can be stored but must be validated with the origin server before reuse.
  • private vs. public: private prevents intermediate caches (CDNs) from storing the response; public allows it.
  • s-maxage: Overrides max-age for shared caches (CDNs) only.

Example: Validating Headers with cURL

bash

2. Conditional Requests & ETags

When a cache entry is stale (expired max-age) or `no-cache` is set, the client revalidates using Conditional Requests. This saves bandwidth if the content hasn't changed.

  • ETag / If-None-Match: The server sends an ETag (hash of content). The client sends it back in If-None-Match. If they match, server returns 304 Not Modified (body empty).
  • Last-Modified / If-Modified-Since: Timestamp-based. Less precise than ETags (1-second resolution).

3. Content Negotiation & The 'Vary' Header

The Vary header tells caches which request headers were used to determine the response representation. This is critical for compression and serving different formats to different clients from the same URL.

Scenario: If you serve Gzip content to clients sending Accept-Encoding: gzip, you MUST send Vary: Accept-Encoding. Otherwise, a cache might serve the compressed version to a client that doesn't support it.

4. Cookies & State Management

Set-Cookie directives control session persistence.

  • HttpOnly: Prevents JavaScript access (mitigates XSS).
  • Secure: Cookie sent only over HTTPS.
  • SameSite: Controls when cookies are sent with cross-site requests (Strict, Lax, None).