惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
腾讯CDC
G
Google Developers Blog
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
有赞技术团队
有赞技术团队
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
M
MIT News - Artificial intelligence
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
美团技术团队
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution
ETag, Last-Modified, and the Caching Headers Most APIs Ge...
The Practica · 2022-09-02 · via The Practical Developer

There is a free CDN, a free reverse-proxy cache, and a free per-user cache sitting in front of your API right now. They are called your CDN, your reverse proxy, and the user’s browser, and they all speak the same caching protocol. Most teams ignore that protocol entirely, ship a Cache-Control: no-cache everywhere, and then write a Redis layer that does the same thing worse.

This post is the cheat-sheet for using HTTP caching the way the protocol intended (Cache-Control, ETag, Last-Modified, conditional requests), applied to JSON APIs, not just static assets. By the end you will know when each header applies, how the 304 dance works, and the three pitfalls that turn a cache from a speedup into a correctness bug.

There are dozens of cache-related headers. Four of them carry 95% of the weight.

Cache-Control is the master switch. It tells who may cache the response, for how long, and under what rules. Examples:

  • Cache-Control: public, max-age=300: anyone may cache for 5 minutes.
  • Cache-Control: private, max-age=60: only the user’s browser may cache (not the CDN).
  • Cache-Control: no-store: do not cache at all (use for sensitive responses like password resets).
  • Cache-Control: no-cache: cache, but always revalidate before serving from cache.

no-cache is not “do not cache.” It is “cache and always check with the server first.” If you actually mean “do not cache,” use no-store.

ETag is a server-generated identifier for the current version of the resource. Could be a hash of the body, a database row’s updated_at + id packed together, or a version number. The client stores it and sends it back next time as If-None-Match.

Last-Modified is a timestamp for when the resource last changed. Less precise than ETag (1-second resolution). The client sends it back as If-Modified-Since.

Vary declares which request headers affect the response. The cache will only return a cached entry if those headers match. The classic miss is forgetting Vary: Accept-Language and serving English to French users.

The conditional request dance

Here is the protocol in action, for a /api/users/42 endpoint.

First request, full response with caching headers:

GET /api/users/42
Accept: application/json
HTTP/1.1 200 OK
ETag: "v3-abc123"
Last-Modified: Wed, 31 Aug 2022 14:22:11 GMT
Cache-Control: private, max-age=0, must-revalidate
Content-Type: application/json
Content-Length: 482

{"id":42,"name":"Mira","email":"..."}

max-age=0, must-revalidate is the combination for “do not serve from cache without checking,” useful for personalized JSON where the data may have changed. The client now has a copy and an ETag.

Subsequent request, client sends the ETag:

GET /api/users/42
Accept: application/json
If-None-Match: "v3-abc123"

If the resource has not changed, the server returns:

HTTP/1.1 304 Not Modified
ETag: "v3-abc123"
Cache-Control: private, max-age=0, must-revalidate

Empty body. Zero bytes of JSON over the wire. The browser returns the previously cached response to the JS code as if it were fresh.

If it has changed:

HTTP/1.1 200 OK
ETag: "v4-def456"
Last-Modified: Thu, 1 Sep 2022 09:08:55 GMT
Cache-Control: private, max-age=0, must-revalidate
Content-Type: application/json
Content-Length: 487

{"id":42,"name":"Mira","email":"...","plan":"pro"}

A 304 is two orders of magnitude cheaper than a 200 with a body. For JSON APIs that return repeatedly the same data (list views, user profiles, dashboard tiles), this turns a chatty client into a quiet one.

Implementing it on the server

Here is a minimal Express implementation that gets it right. The same pattern works in any framework.

import express from 'express';
import { createHash } from 'crypto';

const app = express();

app.get('/api/users/:id', async (req, res) => {
  const user = await db.users.findById(req.params.id);
  if (!user) return res.status(404).end();

  // Build an ETag from the row version. updated_at is fine; you can also
  // hash the serialized body if you want strong byte-equality semantics.
  const etag = `"v${user.version}-${user.id}"`;
  const lastModified = user.updatedAt.toUTCString();

  res.setHeader('ETag', etag);
  res.setHeader('Last-Modified', lastModified);
  res.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');

  // Conditional check: did the client already have this version?
  if (req.headers['if-none-match'] === etag) {
    return res.status(304).end();
  }
  if (req.headers['if-modified-since'] === lastModified) {
    return res.status(304).end();
  }

  res.json(user);
});

A few details that matter.

ETag must be quoted. The HTTP spec is clear: ETag: "abc" with quotes, not ETag: abc. Some clients reject the unquoted form silently and you spend two hours wondering why nothing caches.

Use a strong identifier. A hash of the body is strongest but you have to serialize the body to compute it. A row version (updated_at + id packed, or an integer version column) is fine for most APIs and cheaper. If two distinct responses can produce the same ETag, you have a bug.

Pick one of ETag and Last-Modified, not both. Both is harmless but redundant. ETag is more precise (sub-second changes). Last-Modified is more widely understood by intermediaries. For a JSON API, ETag alone is the best choice.

Cache-Control is mandatory. Without it, the browser uses heuristic caching, typically 10% of (Date - Last-Modified). That gets you wildly inconsistent behavior across user sessions.

Layered caching: browser, CDN, reverse proxy

The same headers that make the browser cache also instruct the CDN and your reverse proxy. A single response can be cached differently at each layer:

Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=60

Reading this:

  • public: any cache may store it.
  • max-age=60: browsers treat it as fresh for 60 seconds.
  • s-maxage=300: shared caches (CDN, reverse proxy) treat it as fresh for 5 minutes.
  • stale-while-revalidate=60: for 60 seconds past expiry, serve the stale copy and refresh in the background.

For a public list endpoint that is somewhat hot but not personalized (top posts, latest news), this header makes the CDN do all the work. Origin sees one request per 5 minutes; users see fresh content within 60 seconds.

For a personalized endpoint, drop public and s-maxage (you do not want a CDN serving Alice’s data to Bob) and lean on private, max-age=0, must-revalidate plus ETag.

Three pitfalls that turn caching into a bug

Forgetting Vary on language / auth / format. If your API responds differently based on Accept-Language, Authorization, or Accept, you must declare it:

Vary: Accept-Language, Accept

Without this, a CDN may serve French to English users, JSON to XML clients, or an authenticated response to a logged-out one. The vary on Authorization is implicit in most CDNs (they treat it specially), but I prefer to be explicit.

Returning user data with Cache-Control: public. The CDN now has Alice’s profile cached, and Bob requests the same URL and gets it. This is the only “caching is dangerous” story you actually need to be afraid of. Personalized responses must be private, or scoped by Vary: Authorization or by URL.

ETag changes on irrelevant fields. If your ETag is a hash of the full body and the body includes serverTime: now(), every response has a different ETag and the cache is useless. Strip volatile fields before hashing, or use a row-version-based ETag instead.

When to skip HTTP caching and reach for Redis

Some workloads do not fit conditional requests:

  • Aggregations that are expensive to compute and have no obvious freshness signal. “Top 100 trending posts” recalculated from a sliding 24h window. There is no updated_at for that. Cache it in Redis with a TTL.
  • Data that needs to be invalidated by external events. “Show this banner if the latest deploy succeeded.” The trigger is not a request; it is a job finishing somewhere. ETag-based caches do not have a way to push.
  • Cross-user precomputation. Anything that you compute once and serve to many users (homepage feed for logged-out visitors). Edge caching plus a stale-while-revalidate header gets you most of the way; Redis is the fallback when CDN behavior is too coarse.

The order matters: HTTP caching first, Redis only when HTTP caching cannot express what you need. The reverse (Redis first, HTTP headers an afterthought) is how teams end up with three copies of “the user record” in three places that disagree.

A 60-second debugging checklist

When the cache is not working, run through this:

  1. Open DevTools → Network. Click the request. Look at the response headers. Is ETag set? Is Cache-Control set? Is the value what you expect?
  2. Reload. Does the second request show If-None-Match going out? If not, the browser has thrown the cache away, usually because of Cache-Control: no-store or a missing ETag.
  3. Does the server return 304? If it returns 200 every time, the conditional check is wrong (often: ETag generation is non-deterministic, or the comparison is using == against the unquoted value).
  4. Behind a CDN? Use curl -v -H "If-None-Match: \"...\"" ... directly against the origin to confirm origin behavior, then against the CDN to see if it forwards the header.
  5. Vary set correctly? curl -H "Accept-Language: fr" ... and curl -H "Accept-Language: en" ... should produce different cache entries.

The takeaway

HTTP caching is not legacy. It is the most distributed cache layer you will ever own, present in every browser, every CDN, every reverse proxy, and it costs nothing to use beyond getting four headers right. Cache-Control sets the policy, ETag enables conditional revalidation, Vary scopes by request shape, and the 304 dance saves the body bytes.

Most “we need a cache” conversations end up at “we need to set ETag.” Try that before installing Redis. The protocol has been there since 1997 and is still under-used in 2022.


A note from Yojji

The category of work that takes a sluggish dashboard and turns it into one that feels instant (the right caching headers, conditional requests, CDN policies) is the kind of detail that shows up in a Lighthouse score and on the AWS bill, but rarely in a feature spec. It is the kind of work Yojji’s frontend and backend teams put into the products they ship for clients.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and full-cycle product engineering, including the performance work that decides whether a product feels fast or merely correct.