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

推荐订阅源

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 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 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
Request Hedging: Cut Tail Latency In Half Without Overprovisioning
The Practica · 2026-05-19 · via The Practical Developer

Your search service has ten replicas behind a load balancer. The median response time is 80 ms. The P95 is 150 ms. The P99 is 2.3 seconds. You have already ruled out slow queries, bad indexes, and GC pauses. The problem is one replica. Every minute, one pod gets a noisy neighbor on its VM, a brief CPU throttle, or a network blip, and every request routed to that pod pays the tax. The other nine pods are fine.

This is tail latency, and it is structural. The more hops a request takes through microservices, the worse it gets. If you call three services in parallel and each has a 1% chance of hitting a slow replica, your end-to-end P99 is now roughly 3%. Add five services and your P99 is ugly even when every individual service looks healthy.

Request hedging is the pattern that says: “If a request has not come back by the 95th-percentile time, send a duplicate to a different replica and take whichever arrives first.” It costs a small amount of extra load. It cuts your tail latency dramatically. And most teams do not use it because the naive implementation doubles your request volume and creates cancellation bugs.

This post is the safe implementation. The math for when it pays off. And the three guardrails that keep it from becoming a denial-of-service tool against your own service.

What hedging is, and what it is not

Hedging is not retrying. A retry waits for a failure (timeout, 5xx, connection error) and then sends a new request. Hedging does not wait for failure. It waits for a delay, then fires a second request in parallel while the first is still in flight. Whichever response arrives first wins. The loser is cancelled if possible.

This matters for read-heavy, latency-sensitive endpoints: search, recommendations, feature flags, user profile lookups, config reads. It does not work for mutations unless they are perfectly idempotent and your system can safely execute the same write twice. Do not hedge POST /charge.

The naive implementation and why it explodes

The first attempt most engineers write looks like this:

async function naiveHedgedFetch(url: string, delayMs: number) {
  const timer = new Promise((_, reject) =>
    setTimeout(() => reject(new Error('hedge')), delayMs)
  );
  return Promise.race([fetch(url), timer]).catch(() => fetch(url));
}

This is dangerous for four reasons.

  1. The first request is never cancelled. It keeps running on the target replica, consuming CPU, memory, and a connection slot, even though you already got the answer from the second request. You doubled the load on the slow replica instead of relieving it.

  2. No hedging delay tuning. If you hedge at the median (80 ms), you send two requests for most calls. That is nearly 2x load for a marginal latency win.

  3. No in-flight limit. If your service is already struggling, hedging sends more requests into the struggle. You turn a slow replica incident into a full cluster overload.

  4. No replica diversity. If both requests hit the same overloaded pod (sticky sessions, hash-based routing, or bad load balancing), hedging does nothing.

The safe version fixes all four.

Safe hedging in Node.js

Here is the practical version. It uses AbortController to cancel the loser, enforces a maximum hedging ratio, skips hedging when downstream is already unhealthy, and picks the hedging delay from a real percentile.

interface HedgingOptions {
  hedgeDelayMs: number;       // e.g. 150, your P95 or slightly above
  maxConcurrentHedges: number; // e.g. 20, hard limit on in-flight hedges
  hedgeRateLimit: number;      // e.g. 0.10, max 10% of requests hedged
}

interface HedgedResult<T> {
  winner: 'original' | 'hedge';
  result: T;
  loserCancelled: boolean;
}

class HedgingClient {
  private activeHedges = 0;
  private totalRequests = 0;
  private hedgedRequests = 0;

  constructor(private readonly opts: HedgingOptions) {}

  async fetch<T>(
    makeRequest: (signal: AbortSignal) => Promise<T>,
    isHealthy: () => boolean = () => true
  ): Promise<HedgedResult<T>> {
    this.totalRequests++;

    const shouldHedge =
      isHealthy() &&
      this.activeHedges < this.opts.maxConcurrentHedges &&
      this.hedgedRequests / this.totalRequests < this.opts.hedgeRateLimit;

    if (!shouldHedge) {
      const result = await makeRequest(new AbortController().signal);
      return { winner: 'original', result, loserCancelled: false };
    }

    const controller = new AbortController();
    let hedgeTimer: NodeJS.Timeout | null = null;
    let hedgeStarted = false;

    const original = makeRequest(controller.signal);

    const hedgePromise = new Promise<T>((resolve, reject) => {
      hedgeTimer = setTimeout(() => {
        if (controller.signal.aborted) return;
        hedgeStarted = true;
        this.activeHedges++;
        this.hedgedRequests++;

        const hedgeController = new AbortController();
        makeRequest(hedgeController.signal)
          .then((value) => {
            if (!controller.signal.aborted) {
              controller.abort(); // cancel the original
              resolve(value);
            }
          })
          .catch((err) => {
            if (!controller.signal.aborted) {
              reject(err);
            }
          })
          .finally(() => {
            this.activeHedges--;
          });
      }, this.opts.hedgeDelayMs);
    });

    return Promise.race([
      original.then((value) => {
        if (hedgeTimer) clearTimeout(hedgeTimer);
        if (hedgeStarted) this.activeHedges--;
        return { winner: 'original' as const, result: value, loserCancelled: hedgeStarted };
      }),
      hedgePromise.then((value) => {
        return { winner: 'hedge' as const, result: value, loserCancelled: true };
      }),
    ]).catch(async (err) => {
      if (hedgeTimer) clearTimeout(hedgeTimer);
      if (hedgeStarted) this.activeHedges--;
      throw err;
    });
  }
}

Key details in this implementation:

  • Cancellation. The winner aborts the loser via AbortController. Your makeRequest must forward the signal to fetch, http.request, or whatever client you use. The losing request should error with an AbortError and free its socket.
  • Delay placed at P95, not median. If your P95 is 150 ms, hedging at 150 ms means only ~5% of requests ever spawn a second call. The extra load is roughly 5%, not 100%.
  • Hard concurrency cap. maxConcurrentHedges prevents a hedge storm during an incident. If 50 requests are already hedged, new requests go single-shot.
  • Rate limiter over time. hedgeRateLimit is a safety valve. If you accidentally misconfigured the delay too low, the ratio guard caps the damage.
  • Health gate. The isHealthy callback lets you wire in a circuit breaker or a custom “downstream is struggling” signal. When downstream is red, stop hedging. You do not send more traffic into a fire.

Wiring it into your HTTP client

Most teams should not write the above from scratch in every service. Wrap your internal HTTP client once:

import { HedgingClient } from './hedging';

const hedging = new HedgingClient({
  hedgeDelayMs: 150,
  maxConcurrentHedges: 20,
  hedgeRateLimit: 0.10,
});

export async function searchProducts(query: string) {
  const { result } = await hedging.fetch(
    (signal) =>
      fetch(`https://search.internal/products?q=${encodeURIComponent(query)}`, {
        signal,
      }).then((r) => r.json()),
    () => circuitBreakerForSearch.isClosed() && loadShedder.allows()
  );
  return result;
}

Notice the isHealthy lambda checks both the circuit breaker and a load shedder. This is the pattern that keeps hedging safe: you only hedge when you are confident the downstream pool can absorb the extra request.

The math: when hedging pays off

Hedging is not free. It adds load. The break-even depends on your latency distribution.

Suppose your latency CDF looks like this:

PercentileLatency
P5080 ms
P90120 ms
P95150 ms
P992300 ms

If you hedge at 150 ms, 5% of requests spawn a duplicate. Expected extra load is roughly 5% (ignoring cancellation delays). The P99 drops from 2300 ms to roughly 150 ms plus the second-request tail, which is usually around the P95 again. Call it 300 ms in the worst case.

You traded 5% more load for a P99 that dropped from 2.3 s to 300 ms. That is usually an enormous win for user-facing latency.

But if your latency distribution is smooth (P95 150 ms, P99 170 ms), hedging at 150 ms adds 5% load and your P99 only improves to 170 ms anyway. The gain is not worth the cost. Hedging pays off when the tail is fat, when the slowest 1% is an order of magnitude worse than the P95.

How to decide: plot a histogram of your endpoint latency. If the 99th percentile is more than 3x the 95th, hedging is probably worth it. If the 99th is less than 2x the 95th, fix your outliers first (noisy neighbors, GC tuning, better load balancing) before adding hedging.

Guardrails you must have in production

Hedging without guardrails is a load multiplier with a random delay. Add these before shipping.

  1. Only hedge idempotent reads. Never hedge a charge, a state transition, or an email send. If executing twice is unsafe, do not hedge.

  2. Cancel the loser aggressively. If your HTTP client does not respect AbortController, fix that first. The loser must close its TCP connection and free the slot. Node.js fetch (undici) does this correctly. Old request libraries may not.

  3. Route hedges to a different replica. If your load balancer uses consistent hashing by user ID, the original and the hedge may land on the same pod. Use a different upstream URL, a different service discovery lookup, or add a hedge=true header that the load balancer uses to pick a different backend. Some teams run two identical internal DNS records and round-robin between them for hedges.

  4. Cap the hedge ratio and concurrency. The code above has both. You need both. The ratio prevents gradual config drift from increasing load over weeks. The concurrency cap prevents a thundering herd during recovery.

  5. Alert on hedge rate, not just latency. Emit two metrics: hedges_fired and hedges_won. If hedges_won is low, your delay is too short (you are hedging requests that would have finished soon anyway) or your replicas are all slow (hedging does not help if every pod is broken). If hedges_fired spikes, your tail latency got worse and you should investigate the root cause, not just enjoy the workaround.

Three cases where hedging makes things worse.

The whole fleet is slow. Hedging only helps when one replica is an outlier. If every pod is at 90% CPU, sending two requests means both take twice as long. You need horizontal scaling or query optimization, not hedging.

Your client does not support cancellation. If the losing request runs to completion on the server no matter what, you doubled the load on the slow replica. That is the opposite of what you want. Fix your client or your server middleware to support early aborts before hedging.

You are already at capacity limits. If your downstream has a strict rate limit (e.g., a third-party API with 100 req/s), hedging consumes two of those slots. You will hit the quota faster and get 429s for everyone. Use a local cache or a bulkhead instead.

The takeaway

Tail latency is not a tuning problem on the slow replica. It is a statistical inevitability in any large-enough fleet. Request hedging accepts that inevitability and works around it by betting that a second replica will be faster than the one outlier.

The safe version is small: delay at the P95, abort the loser, cap concurrent hedges, cap the hedge ratio, and skip hedging when downstream is unhealthy. It costs roughly 5% extra load for a P99 that can drop by an order of magnitude. For read-heavy, latency-sensitive microservices, that is one of the best load-to-latency trades you can make.

Measure your latency histogram first. If the tail is fat, add hedging with the guardrails above. If the tail is thin, fix the outliers. Either way, stop accepting 2-second P99s on a service whose healthy pods answer in 80 ms.


A note from Yojji

The kind of tail-latency engineering that turns a 2-second P99 into a 300 ms P99, request hedging, circuit breakers, and load-aware clients, is the kind of distributed systems work that separates a prototype from a production platform. Yojji’s backend teams build exactly this kind of resilience into the microservices they ship for clients across Europe, the US, and the UK.

Yojji is an international custom software development company founded in 2016, specializing in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and scalable microservices architecture. If your next project needs backend performance that holds up under real traffic, they are worth talking to.