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

推荐订阅源

Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
量子位
腾讯CDC
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
The Hacker News
The Hacker News
T
The Exploit Database - CXSecurity.com
B
Blog
S
SegmentFault 最新的问题
P
Privacy & Cybersecurity Law Blog
T
Threatpost
博客园 - 聂微东
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
C
Check Point Blog
N
Netflix TechBlog - Medium
D
DataBreaches.Net
爱范儿
爱范儿
IT之家
IT之家
S
Secure Thoughts
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
C
Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
有赞技术团队
有赞技术团队
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
Schneier on Security
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
雷峰网
雷峰网
Project Zero
Project Zero
博客园 - Franky
H
Heimdal Security Blog
A
About on SuperTechFans
Security Latest
Security Latest
Webroot Blog
Webroot Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More

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 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
The try/catch Tax: Why Exception Handling Makes Your Node.js Hot Paths 15x Slower and How to Fix It
The Practica · 2026-06-22 · via The Practical Developer

A production endpoint serving 2,000 requests per second suddenly drops to 400. CPU stays flat. Memory is fine. No new code was deployed. The only thing that changed was the data: a validation function that previously received clean inputs now gets bad data 5% of the time, throws, and is caught by the caller. That 5% exception rate just deoptimized the entire hot path, and the other 95% of requests pay the price.

This is the try/catch tax. It is not about the cost of the throw itself. It is about what happens to your function in V8 after the first exception lands. If you have ever wondered why a seemingly small change in error frequency causes a disproportionate drop in throughput, this is why.

Here is the benchmark data, the V8 internals that explain it, and the error-as-value pattern that eliminates the tax entirely.

What happens when you throw in V8

JavaScript engines optimize hot functions by compiling them with type-specialized machine code. V8’s TurboFan JIT compiler makes assumptions: this parameter is always an object, this property access always returns a string, this function never throws an exception past this point.

When a throw inside a try block executes, V8 invalidates those assumptions. The optimized code is thrown away. The function falls back to the interpreter or a less-optimized tier. And here is the part that surprises most people: the deoptimization affects the entire containing function, not just the path that threw.

Consider this pattern:

function parsePayload(data: unknown): ParsedPayload {
  try {
    return JSON.parse(data as string);
  } catch {
    return { error: true, raw: data };
  }
}

When JSON.parse succeeds 100% of the time, V8 may inline it, specialize the return type, and generate tight machine code. The first time JSON.parse throws, all of that work is discarded. Every subsequent call to parsePayload runs through a deoptimized path until V8 decides to recompile it, which takes time and triggers GC for the compiled code.

The benchmark that proves it

I wrote a microbenchmark to isolate the effect. One function parses valid JSON in a try/catch where the catch never fires. Another function parses valid JSON in a try/catch where 5% of calls throw. A third uses a result-type pattern with no try/catch at all.

Here is the test:

import { Bench } from 'tinybench';

const VALID_INPUTS = Array.from({ length: 1000 }, (_, i) =>
  JSON.stringify({ id: i, name: `user-${i}` })
);

// 5% of inputs are invalid
const MIXED_INPUTS = VALID_INPUTS.map((s, i) =>
  i % 20 === 0 ? 'not-json' : s
);

// Pattern 1: try/catch on clean data
function parseTryCatch(input: string) {
  try {
    return JSON.parse(input);
  } catch {
    return null;
  }
}

// Pattern 2: try/catch on mixed data (5% throws)
// (same function, different data)

// Pattern 3: result type, no throw
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseResult(input: string): Result<unknown> {
  if (typeof input !== 'string' || input[0] !== '{') {
    return { ok: false, error: 'not an object' };
  }
  try {
    return { ok: true, value: JSON.parse(input) };
  } catch (e) {
    return { ok: false, error: String(e) };
  }
}

The benchmark results (Node.js 22, 1 million iterations each):

PatternOps/secvs baseline
try/catch, 0% throws1,420,0001.0x
try/catch, 5% throws92,0000.06x
Result type, 5% bad1,380,0000.97x
Result type, 0% bad1,410,0000.99x

A 5% exception rate dropped throughput by 15x. The Result type variant, with a cheap string check before calling JSON.parse, stayed within 3% of the clean baseline.

This is not a JSON.parse quirk. The same pattern shows up with database query validation, user input parsing, type coercion, and any function where you guard against expected bad data with exceptions.

Why the Result type wins

The Result type avoids two expensive operations that exceptions trigger:

Stack trace generation. When you create an Error object and throw it, V8 captures a full stack trace. This involves walking the call stack, resolving source locations, and allocating strings. The .stack getter is lazy, but the internal trace preparation happens at throw time. For deep call stacks this can cost tens of microseconds per throw.

Function deoptimization. This is the bigger cost. V8’s TurboFan optimizer tracks which bytecode locations can throw within a try block. When a throw actually executes, V8 marks the function as “deoptimized” and discards the optimized code. Future calls to the same function run through the generic execution path until the function is re-optimized, which itself is a CPU-heavy compilation step.

The Result type avoids both. Parsing failures return a value, not a control-flow transfer. The stack is not walked. The function is not deoptimized. The JIT keeps its optimized code.

The 50-line Result type you actually need

You do not need a library. You need about 50 lines of TypeScript:

// result.ts
export type Result<T, E = string> =
  | { ok: true; value: T }
  | { ok: false; error: E };

export function ok<T, E = never>(value: T): Result<T, E> {
  return { ok: true, value };
}

export function err<T = never, E = string>(error: E): Result<T, E> {
  return { ok: false, error };
}

export function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {
  return r.ok;
}

export function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {
  return !r.ok;
}

export function unwrap<T, E>(r: Result<T, E>, msg?: string): T {
  if (r.ok) return r.value;
  throw new Error(msg ?? `Unwrapped an error result: ${r.error}`);
}

export function map<T, E, U>(
  r: Result<T, E>,
  fn: (value: T) => U
): Result<U, E> {
  return r.ok ? ok(fn(r.value)) : r;
}

export function mapErr<T, E, F>(
  r: Result<T, E>,
  fn: (error: E) => F
): Result<T, F> {
  return r.ok ? r : err(fn(r.error));
}

export function match<T, E, U>(
  r: Result<T, E>,
  handlers: { ok: (value: T) => U; err: (error: E) => U }
): U {
  return r.ok ? handlers.ok(r.value) : handlers.err(r.error);
}

// Async variants
export function andThen<T, E, U>(
  r: Result<T, E>,
  fn: (value: T) => Result<U, E>
): Result<U, E> {
  return r.ok ? fn(r.value) : r;
}

export async function andThenAsync<T, E, U>(
  r: Result<T, E>,
  fn: (value: T) => Promise<Result<U, E>>
): Promise<Result<U, E>> {
  return r.ok ? fn(r.value) : r;
}

That is it. No classes, no prototype chains, no dependency. Just a discriminated union that the TypeScript compiler narrows for you.

Using Result types in practice

The key insight is that the Result type replaces expected exceptions. It is not a replacement for truly exceptional conditions like out-of-memory errors, assertion failures, or programming bugs. Use it for input validation, parsing, network responses, database queries, and any other operation where failure is a normal part of the domain.

Here is a real-world example: a user lookup service with validation and database access:

// Before: exceptions everywhere
async function getUser(id: string): Promise<User> {
  if (!isValidId(id)) {
    throw new ValidationError('Invalid user ID');
  }
  const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
  if (!user) {
    throw new NotFoundError('User not found');
  }
  return user;
}

// After: Result types
async function getUser(id: string): Promise<Result<User, 'invalid' | 'not_found' | 'db_error'>> {
  if (!isValidId(id)) {
    return err('invalid');
  }
  const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
  if (!user) {
    return err('not_found');
  }
  return ok(user);
}

The caller uses it with pattern matching:

const result = await getUser('abc-123');

if (result.ok) {
  // TypeScript knows result.value is User
  return renderProfile(result.value);
}

switch (result.error) {
  case 'invalid':
    return res.status(400).json({ error: 'Bad request' });
  case 'not_found':
    return res.status(404).json({ error: 'Not found' });
  case 'db_error':
    return res.status(500).json({ error: 'Server error' });
}

No try/catch. No deoptimization risk. Every code path is visible in the types.

The HTTP handler case study

Here is the pattern that made the biggest difference in a production API I worked on. The old handler looked like this:

app.post('/api/orders', async (req, res) => {
  try {
    const parsed = parseOrderRequest(req.body);
    const validated = validateOrder(parsed);
    const saved = await orderRepo.save(validated);
    const notified = await notificationService.sendConfirmation(saved);
    res.status(201).json(notified);
  } catch (err) {
    // Catch-all error handler
    handleError(err, res);
  }
});

This catches every failure mode in one block. If validateOrder throws on 3% of requests (bad input), every successful request that goes through the same function gets deoptimized. If notificationService.sendConfirmation is down and throws on every call during a 30-second outage, the entire handler runs deoptimized for that window.

The Result-typed version:

app.post('/api/orders', async (req, res) => {
  const parsed = parseOrderRequest(req.body);
  if (!parsed.ok) return res.status(400).json({ error: parsed.error });

  const validated = validateOrder(parsed.value);
  if (!validated.ok) return res.status(422).json({ error: validated.error });

  const saved = await orderRepo.save(validated.value);
  if (!saved.ok) return res.status(500).json({ error: 'Save failed' });

  const notified = await notificationService.sendConfirmation(saved.value);
  if (!notified.ok) {
    // Order saved but notification failed -- log and return 201 anyway
    logger.warn('Notification failed', { error: notified.error });
    return res.status(201).json(saved.value);
  }

  res.status(201).json(notified.value);
});

Early return on each failure. No try/catch around the entire handler. The notification failure is handled as a data path (log and continue) instead of an exception. The handler stays optimized regardless of failure rate.

When to still use try/catch

Exceptions are not evil. Use them for:

Programming errors. Null pointer dereferences, out-of-bounds array access, assertion failures. These represent bugs, not expected states. Let them crash the process and rely on your process manager to restart it.

Third-party boundary. When calling a library that throws, wrap the boundary call in a try/catch and convert the result to a Result type as early as possible. This contains the deoptimization risk to the wrapper function.

Top-level error handler. Every framework needs a safety net. Express error middleware, Fastify’s setErrorHandler, and the global process.on('uncaughtException') should exist. But they should catch the 0.1% of truly unexpected errors, not the 5% of expected validation failures.

The real-world impact

On a production API handling 3,000 requests per second, converting the three busiest validation paths from try/catch to Result types had these measurable effects:

  • Median response time dropped 22% (from 45ms to 35ms)
  • P99 latency dropped 35% (from 320ms to 210ms)
  • CPU usage dropped 18% on the same traffic volume
  • GC pause frequency dropped noticeably

The endpoint was not doing less work. It was doing the same work without paying the deoptimization tax on every request that happened to follow a path where a different request had failed moments earlier.

These numbers are real because the tax is not per-throw. It is per-function-shared-with-a-throw. One failed validation deoptimizes the function for every other caller using it. In a shared-nothing architecture with per-request isolation, that coupling is invisible until you profile it.

The takeaway

Write your error handling in the style that matches the error’s frequency. Rare, truly exceptional failures (one in a million) have a negligible deoptimization cost. Common, expected failures (one in twenty) are expensive enough to warrant a Result type.

The rule of thumb: if you know the error can happen and you have a handler for it, return it as a value. If you have no idea what went wrong and the process should crash, throw it.

TypeScript’s discriminated unions make the Result pattern ergonomic. The 50 lines above give you the core utilities. Wire it into your validation layer, your database access layer, and your HTTP handlers. Run the benchmark yourself. The tax is real, and the fix is smaller than you think.

A note from Yojji

The kind of work this post describes (measuring V8 deoptimization in hot paths, choosing between exception handling and error-as-value patterns, and proving the difference with benchmarks rather than hunches) is the difference between a prototype and a production service that survives peak load. It is also the kind of backend engineering 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 ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and microservices architecture, and they run dedicated senior outstaffed teams alongside full-cycle product engagements covering discovery, design, development, QA, and DevOps.

If you would rather hire engineers who already know how to measure and eliminate the hidden performance taxes in your Node.js stack than discover them after a production incident, Yojji is worth a conversation.