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

推荐订阅源

博客园 - 【当耐特】
Latest news
Latest news
IT之家
IT之家
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
LangChain Blog
腾讯CDC
J
Java Code Geeks
GbyAI
GbyAI
美团技术团队
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
Recorded Future
Recorded Future
U
Unit 42
Jina AI
Jina AI
月光博客
月光博客
罗磊的独立博客
I
InfoQ
有赞技术团队
有赞技术团队
B
Blog RSS Feed
The Register - Security
The Register - Security
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
NISL@THU
NISL@THU
S
Security Archives - TechRepublic
雷峰网
雷峰网
O
OpenAI News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LINUX DO - 热门话题
H
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Securelist
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 叶小钗
Security Latest
Security Latest
A
About on SuperTechFans
G
Google Developers Blog
T
Troy Hunt's Blog
小众软件
小众软件
H
Hacker News: Front Page
C
Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
LINUX DO - 最新话题
大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog

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 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 ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong 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
Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right
The Practica · 2026-05-02 · via The Practical Developer

Open a flame graph of any moderately busy Node.js API and you will find something embarrassing: a meaningful slice of the CPU is being spent on work for HTTP requests that the client closed three seconds ago. The browser navigated away. The mobile app retried. The load balancer hit its idle timeout. But your handler is still happily querying Postgres, calling a downstream service, parsing the JSON response, and writing a 200 OK to a socket nobody is listening on.

This is not a hypothetical. On a real production service I worked on, propagating cancellation end-to-end shaved 22% off median CPU during peak hours. Not because we wrote faster code. Because we stopped writing code at all for requests nobody wanted.

The fix is AbortController. It is in the Node.js standard library since 16, supported by fetch, supported by pg, supported by Express via req.signal, and almost nobody wires it through. Here is the pattern that does, the 60 lines that make it work, and the three traps that make teams give up halfway.

The shape of the problem

A normal Express handler that calls a database and a downstream API looks like this:

app.get('/api/orders/:id', async (req, res) => {
  const order = await db.query('SELECT * FROM orders WHERE id = $1', [req.params.id]);
  const shipping = await fetch(`https://shipping.internal/track/${order.tracking_id}`);
  const data = await shipping.json();
  res.json({ order, shipping: data });
});

Now imagine the client is on flaky 4G. They tap, wait two seconds, get bored, tap again. The first request is still mid-flight. Without cancellation:

  1. Postgres finishes the SELECT (300ms).
  2. The downstream fetch runs to completion (1.2s).
  3. JSON.parse runs.
  4. res.json writes to a closed socket and throws or silently swallows.
  5. Repeat for the second tap, which the client also abandons.

You did the work three times. You paid for three database queries, three downstream calls, three JSON parses. The client got nothing. Multiply by every flaky connection on the internet.

The AbortController pattern says: every async operation in the request takes a signal, and when the request closes, the signal fires, and every operation aborts cooperatively. No CPU spent on dead work, no connections held open against your downstreams, no event-loop time on JSON for nobody.

The 60 lines

Three pieces. The middleware that produces a signal from each request. The handler convention that uses it. A small wrapper for the few async APIs that still don’t accept a signal natively.

// abort-middleware.ts
import type { Request, Response, NextFunction } from 'express';

declare module 'express-serve-static-core' {
  interface Request {
    signal: AbortSignal;
  }
}

export function abortOnClientDisconnect(req: Request, res: Response, next: NextFunction) {
  const controller = new AbortController();

  // Express attaches the underlying socket; 'close' fires when the client
  // disconnects before the response is fully sent. 'aborted' is the older
  // event. Keep both for compatibility with proxies that emit one or the other.
  const onClose = () => controller.abort(new Error('client_disconnected'));
  req.on('close', onClose);
  req.on('aborted', onClose);

  // Cleanup so we don't leak listeners on long-lived servers.
  res.on('finish', () => {
    req.off('close', onClose);
    req.off('aborted', onClose);
  });

  req.signal = controller.signal;
  next();
}
// db.ts: pass the signal through to the database client
import { Pool } from 'pg';

const pool = new Pool({ /* ...config... */ });

export async function query<T>(sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {
  const client = await pool.connect();

  // Hook the abort to a server-side query cancel. This is the part most
  // teams skip, and it is the part that actually frees the database.
  const onAbort = () => {
    // pg exposes a low-level cancel via the connection. It sends a
    // CancelRequest to Postgres on a separate socket and the running query
    // aborts with code 57014 (query_canceled). Without this, the JS Promise
    // rejects but Postgres keeps churning.
    (client as any).connection?.cancel?.();
  };
  signal?.addEventListener('abort', onAbort, { once: true });

  try {
    const res = await client.query(sql, params);
    return res.rows as T[];
  } finally {
    signal?.removeEventListener('abort', onAbort);
    client.release();
  }
}
// handler.ts: the convention
import { query } from './db';

app.get('/api/orders/:id', async (req, res) => {
  try {
    const orders = await query<Order>(
      'SELECT * FROM orders WHERE id = $1',
      [req.params.id],
      req.signal,
    );
    if (!orders[0]) return res.status(404).json({ error: 'not_found' });

    // fetch supports AbortSignal natively. Just pass it through.
    const shipping = await fetch(
      `https://shipping.internal/track/${orders[0].tracking_id}`,
      { signal: req.signal },
    );

    res.json({ order: orders[0], shipping: await shipping.json() });
  } catch (err: any) {
    if (err.name === 'AbortError' || err.code === '57014') {
      // Client gave up. Don't bother responding; the socket is gone.
      // Don't log this as an error, either; it isn't one.
      return;
    }
    throw err;
  }
});

That is the entire pattern. Wire abortOnClientDisconnect once at the top of your middleware chain, take a signal parameter in any function that does async I/O, pass it through to fetch, pg, redis, mongodb, and your own service-to-service calls. Done.

Why each piece is there

This pattern looks deceptively simple, and the small choices in it are the difference between cancellation that actually frees resources and cancellation that just makes the JavaScript Promise reject while the database keeps grinding.

req.signal, not a parameter on every handler. You could pass signal explicitly through every layer. In a real codebase, half the layers will forget. Putting signal on the request object turns it into an ambient property: every handler has it, every util that takes a req has it, and there is no way to “forget” without obviously dropping it. (For non-Express stacks, use AsyncLocalStorage the same way structured logging does. The principle is identical.)

Both 'close' and 'aborted' events. Different proxies, different Node versions, and different HTTP/2 vs HTTP/1.1 paths fire one or the other inconsistently. Listening for both costs nothing and avoids the bug where cancellation works in dev (HTTP/1.1) and silently fails behind your edge proxy (HTTP/2). When a client disconnects you want to know, not maybe-know.

Cleanup on 'finish'. Without req.off, every long-lived process accumulates listeners on every closed request. In a service handling 1000 req/s, that is 1000 leaked listeners per second. Node will warn at 11 listeners on the same emitter, but the bigger issue is that those listeners hold references to the closed-over controller, which holds references to whatever else closed over the request. Memory creeps. Cleanup is one line, and you only forget it once before you learn.

The actual database cancel. This is where most teams’ “cancellation” is a lie. The Postgres protocol supports CancelRequest: a separate connection that tells the server “abort the query running on connection X.” Without sending it, your await client.query() will reject immediately when the abort signal fires, but the server-side query keeps running until it completes, holding its row locks and connection. You freed the JavaScript stack frame and nothing else. The 4-line onAbort block above is the entire reason this pattern actually saves real CPU and database load. Confirm it works by killing a long-running query from a client and running SELECT pid, state, query FROM pg_stat_activity. The row should disappear within a second.

Returning early on AbortError. When the signal fires, every promise in the chain rejects. You catch it and… do nothing. Don’t write to res (the socket is closed; you’ll throw ERR_STREAM_WRITE_AFTER_END). Don’t log it as an error (it’s a normal lifecycle event, and your error budget will look terrible if every flaky connection counts as a 5xx). Just return.

err.code === '57014'. Postgres returns SQLSTATE 57014 for query_canceled. Catching it as a non-error is the difference between a clean dashboard and one that lights up red every time someone closes their laptop on the train.

The three traps that kill the pattern

Most teams who try this give up about a week in, because the pattern looks like it works in dev and silently doesn’t work in production. The three reasons it silently doesn’t work:

Trap 1: A library swallows the signal. You pass signal to your wrapper, your wrapper calls some ORM, the ORM calls pg, but the ORM’s API doesn’t have a place to put a signal, so it doesn’t propagate. The query runs to completion. From your side, everything looks correct: the Promise rejects, the metric counts as an abort. Under the hood, you bought nothing.

The fix is to audit at the boundary. Pick one of your real endpoints, add a deliberate 5-second sleep on the database side (pg_sleep(5)), trigger the request, and Ctrl-C it. Then immediately query pg_stat_activity. If the sleep is still running, the signal isn’t reaching Postgres. Either drop the ORM for that hot path, contribute a PR upstream, or use the lower-level pg directly with the cancel hook above.

Trap 2: The signal arrives but the handler isn’t listening between awaits. This one is subtle. JavaScript is single-threaded. While your handler is await-ing one slow operation, the abort fires, but if the next operation does not itself accept a signal, it runs to completion before the chain can react. A common offender is a synchronous CPU-bound loop, like a 200ms JSON parse or a regex over a large payload. Cancellation has no effect on synchronous code. If you have a hot path with a slow synchronous step, break it up with setImmediate or move it to a worker that itself accepts a signal.

Trap 3: The downstream service doesn’t cancel either. You pass signal to fetch, the abort fires, your fetch Promise rejects, and the downstream HTTP server keeps processing the request anyway. From your service’s perspective, you saved local CPU. From the system’s perspective, you saved nothing: the downstream still ran the query, called the next downstream, etc. Cancellation is a chain. It only works if every link honors it.

The fix here is policy, not code: every internal service in your fleet should set up abortOnClientDisconnect on day one, the way every service ships with structured logging on day one. Otherwise you’re paying for cancellation locally and not seeing the system-wide win.

What to actually measure

The pattern is not done when the code merges. It is done when the metrics show the win. Three numbers to watch:

http.client_disconnected_during_handler per minute. This is your aborted-request rate. If it is 0, you are probably not detecting disconnects (Trap 1, on your own service). If it is 5–15% of total requests, that is normal for a public API on consumer internet. If it spikes during an outage, that is a leading indicator: clients are giving up because something is slow.

Database query_canceled rate. Pull this from pg_stat_database (xact_commit vs cancellations) or from your APM. Before this pattern, this number is near zero. After, it should roughly match your client_disconnected rate. If it doesn’t, Trap 1 is in play: your cancels aren’t reaching the database.

Median and p99 CPU during peak. This is the number that justifies the work. After full propagation, both should drop. The median drops because you’re not running pointless work on the average request. The p99 drops because the abandoned requests of one slow user no longer block the event loop’s attention from another user’s healthy request. On the production service I mentioned at the top, p99 latency dropped 40%, not because anything got faster, but because the queue behind it got shorter.

Common mistakes once it’s wired

A few small things that don’t break the pattern but waste its benefits:

Calling controller.abort() with a string instead of an Error. Some downstream libraries inspect err.name === 'AbortError'. If you abort with a string, they get a string at the catch site and your err.name check silently fails. Always abort with an Error (or no argument, in which case Node creates an AbortError for you). Don’t get clever.

Adding signal to a function that has no I/O. A pure CPU function with no async cannot cooperate with a signal. Adding signal to its parameters is harmless but misleading; the next person to read the code will assume it cancels and it won’t. Reserve the convention for functions that actually await something.

Forgetting that setTimeout doesn’t cancel by default. setTimeout(fn, 1000) keeps the event loop alive and the handler pinned. If you must wait, use setTimeout(fn, 1000, { signal }) (Node 17+) or await new Promise((r, j) => { const t = setTimeout(r, 1000); signal.addEventListener('abort', () => { clearTimeout(t); j(signal.reason); }); }). Yes, ugly. Yes, mandatory if you don’t want sleepers to outlive their requests.

Treating cancellation as the same thing as a timeout. They are not. A timeout is your policy: “this operation has 5s and then I give up.” A cancellation is the client’s policy: “I no longer want this.” A well-built service has both. Use AbortSignal.timeout(5000) for the first and AbortSignal.any([req.signal, AbortSignal.timeout(5000)]) (Node 20+) when you want either condition to fire. The combinator is what gives you both timeouts and cancellation in a single signal that everything downstream already knows how to handle.

When not to bother

This pattern earns its keep on services with:

  • High request volume (a few hundred req/s and up).
  • Slow downstream calls (anything that talks to another HTTP service or a non-trivial query).
  • Public-facing clients (browsers and mobile apps; internal callers usually retry deterministically).

If you run a small internal admin tool with three users a day, the wiring is overhead and the win is unmeasurable. If you run a public API hitting four-figure RPS with downstream calls in the half-second range, this is one of the highest-leverage refactors you can do. The 60 lines pay for themselves in the first peak hour.

The takeaway

Cancellation in Node.js is a complete, working, in-the-stdlib feature that almost nobody propagates end-to-end. The pattern is small: one middleware, one handler convention, one wrapper around any I/O library that doesn’t take a signal natively. The wins are real and measurable: less CPU, less database load, less downstream traffic, lower p99.

The reason teams skip it is that it works “well enough” without: the Promise rejects, the request looks done, the dashboards don’t scream. The hidden cost shows up as paying for compute that produces nothing. Once you flame-graph it once and see the wedge of dead work, you don’t go back.

Wire req.signal end-to-end. Verify the database actually cancels. Don’t log aborts as errors. The next time half your users are on a flaky train tunnel, your service will notice and stop working on requests they no longer want, which is the entire job.


A note from Yojji

The kind of work this post describes (propagating cancellation through an entire async stack, verifying the database actually frees its locks, reading a flame graph to find the wedge of dead CPU) is the difference between a service that survives a real production load and one that quietly burns money. It is also the kind of unglamorous backend craft Yojji has been shipping since 2016.

Yojji is an international custom software development company with offices in Europe, the US, and the UK. Their teams specialize in the JavaScript stack (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and microservices architectures, and they run dedicated senior outstaffed teams alongside full-cycle product engagements covering discovery, design, development, QA, and DevOps.

If you would rather hire the practice of building reliable, well-instrumented Node.js services than learn it the hard way after a peak-hour CPU alert, Yojji is worth a conversation.