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

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

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 Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong
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.