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

推荐订阅源

云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cyberwarzone
Cyberwarzone
Hacker News: Ask HN
Hacker News: Ask HN
C
Cisco Blogs
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
A
Arctic Wolf
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
C
Cybersecurity and Infrastructure Security Agency CISA
G
GRAHAM CLULEY
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Vulnerabilities – Threatpost
小众软件
小众软件
博客园 - 司徒正美
腾讯CDC
AWS News Blog
AWS News Blog
Last Week in AI
Last Week in AI
T
Tenable Blog
I
Intezer
博客园_首页
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
AI
AI
V
V2EX
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Security Latest
Security Latest
F
Fortinet All Blogs
S
Secure Thoughts
T
Troy Hunt's Blog
T
The Blog of Author Tim Ferriss
Recorded Future
Recorded Future
M
MIT News - Artificial intelligence
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
L
LINUX DO - 最新话题
B
Blog RSS Feed
U
Unit 42
TaoSecurity Blog
TaoSecurity 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 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 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
OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident
The Practica · 2022-09-30 · via The Practical Developer

The user’s request hits seven services. One of them is slow. The logs say “everything is fine” because each service did its job in 200ms, but the request took 4 seconds end to end and nobody can point at the 3.4 seconds that disappeared. Twenty minutes into the incident, somebody pulls up Honeycomb / Tempo / Datadog APM, finds a 3-second span on a database call inside the auth service, and the whole team groans because it has happened three times this quarter.

Distributed tracing is the difference between “everything is fine and the user is angry” and “we know exactly which call inside which service is slow.” It is also the observability tool that pays back fastest because the auto-instrumented version covers 80% of what you need. This post is the OpenTelemetry-for-Node.js setup that gets you there in about 50 lines of code.

What tracing actually is

A trace is a tree of spans. Each span represents a unit of work (an HTTP handler, a database query, a fetch to another service) and has a start time, end time, and parent span ID. The root span is the original request; everything underneath is what the request caused to happen.

[ HTTP GET /api/orders/42                              ] 4200ms
   ├── [ DB: SELECT * FROM users WHERE id=$1 ]   12ms
   ├── [ HTTP GET auth-service/verify         ] 3400ms ←  the culprit
   │     └── [ DB: SELECT ... slow query      ] 3380ms
   ├── [ DB: SELECT * FROM orders WHERE ...   ]   45ms
   └── [ Redis: GET session:abc                ]    1ms

The point of tracing is that you read this tree once and see the slow call. Without tracing, you grep seven services’ logs by request ID (if you propagated a request ID) and reconstruct the timeline by hand.

OpenTelemetry in 50 lines

OpenTelemetry (OTel) is the vendor-neutral standard. The Node SDK auto-instruments most popular libraries (http, pg, mysql2, mongodb, redis, express, koa, fastify, aws-sdk, grpc) without any code changes. The setup file goes in tracing.ts and is loaded before anything else:

// tracing.ts - must be required before app code.
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';

const sdk = new NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: process.env.SERVICE_NAME ?? 'api',
    [SemanticResourceAttributes.SERVICE_VERSION]: process.env.GIT_SHA ?? 'dev',
    [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV ?? 'dev',
  }),
  traceExporter: new OTLPTraceExporter({
    // Where to send spans. Could be your own collector, or vendor's endpoint.
    url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? 'http://localhost:4318/v1/traces',
  }),
  instrumentations: [
    getNodeAutoInstrumentations({
      // Disable a few that produce noise; opt back in selectively.
      '@opentelemetry/instrumentation-fs': { enabled: false },
      '@opentelemetry/instrumentation-dns': { enabled: false },
      '@opentelemetry/instrumentation-net': { enabled: false },
    }),
  ],
});

sdk.start();

process.on('SIGTERM', () => {
  sdk.shutdown().finally(() => process.exit(0));
});

Load it from your entry point before anything else:

// index.ts
import './tracing'; // ← MUST be the first import
import express from 'express';
// ...

The reason it has to be first: OTel monkey-patches modules at require-time. If express loads before the SDK, the auto-instrumentation hook never fires and you get no spans for it. This catches everyone exactly once.

That is the entire setup. Run the app, point an OTel collector at it (Tempo, Jaeger, Honeycomb, Datadog all speak OTLP), and you will see traces for every HTTP request, every DB query, every outgoing fetch, automatically.

Adding the spans the auto-instrumentation misses

Auto-instrumentation knows about libraries. It does not know about your business logic. The two places you almost always want to add manual spans:

  1. The expensive operation that is not a DB or HTTP call: image processing, PDF generation, JWT signing, an in-process search.
  2. A logical boundary you want to see in the trace: “validate request,” “compute pricing,” “persist order,” even if it is not expensive, because it makes the trace readable.
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('orders');

async function createOrder(req: Request) {
  return tracer.startActiveSpan('orders.create', async (span) => {
    try {
      span.setAttribute('user.id', req.userId);
      span.setAttribute('cart.item_count', req.cart.length);

      const validated = await validateCart(req.cart);
      const priced    = await computePricing(validated);
      const order     = await persistOrder(priced);

      span.setAttribute('order.id', order.id);
      span.setAttribute('order.total_cents', order.totalCents);

      return order;
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: 2 /* ERROR */, message: (err as Error).message });
      throw err;
    } finally {
      span.end();
    }
  });
}

startActiveSpan is the right helper because it makes the new span the current context, so any DB calls or HTTP calls inside the callback automatically nest under it. setAttribute adds key/value metadata you can search by (“show me all orders.create spans where cart.item_count > 50”). recordException and setStatus flag failures so the trace UI highlights them.

Span attributes that pay rent

Throwing every variable onto a span as an attribute is a great way to blow up your trace storage cost. The attributes worth setting:

  • Identifiers you’ll search by. user.id, org.id, order.id, tenant.id. These let you filter to “all traces for user 42” in a real outage.
  • High-cardinality but informative facts. db.query.shape (a normalized version of the SQL with parameters stripped), http.route (the matched route, not the literal URL).
  • Decisions and outcomes. feature_flag.new_pricing.enabled, cache.hit, auth.method. These let you correlate behavior with codepaths.

Things to avoid:

  • PII. Email addresses, names, addresses. Tracing data ends up in many places (vendor systems, logs, debug exports). Treat traces as if a stranger will read them.
  • Massive values. A 200KB request body as a span attribute is going to cost you. If you need it, log it with a span ID for correlation.
  • Per-call random-looking values. Generated request IDs, raw timestamps. These create unique attribute combinations that explode the storage backend’s index.

Sampling: do not trace 100%

At low volume, sampling 100% of traces is fine. At ~50 RPS or higher, the cost (network egress, vendor ingest) becomes real. Three sampling strategies, in order of usefulness:

Head-based probability sampling. “Keep 10% of traces, dropping the rest entirely.” Cheap, simple, works.

import { TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-node';
new NodeSDK({ sampler: new TraceIdRatioBasedSampler(0.1) /* 10% */, ... });

The decision is made at the root span and propagated to all children, so if a trace is sampled in service A, every downstream call is also sampled. This is what trace context propagation is for.

Tail-based sampling. “Keep traces with errors or that took >1s; drop the rest.” Strictly better than head-based but requires a buffering collector (the OTel Collector supports it) because the decision happens at the end of the trace.

Always-sample for specific routes / users. “Always trace /checkout, always trace user 42, sample 1% otherwise.” Most production systems end up with a small allowlist of high-value endpoints sampled at 100% and a low rate for everything else.

Pick head-based to start. Move to tail-based when the bill is uncomfortable. Tail-based is harder to operate but gives you the best signal-to-noise ratio.

Trace context propagation across services

A trace only stays connected if every service forwards the trace ID. The OpenTelemetry SDK does this automatically for HTTP fetches via the traceparent header:

traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
              ^   ^                                ^                ^
              |   |                                |                trace flags
              |   |                                parent span id
              |   trace id
              version

If your services all use OTel SDKs, this is automatic. Edge cases that break it:

  • Custom HTTP clients. If you wrote your own fetch wrapper, the auto-instrumentation may not patch it. Use node:http directly, or wire propagation.inject(...) manually.
  • Message queues. The HTTP propagation does not apply. For Kafka / SQS / Redis Streams, inject the trace context into message headers/attributes and extract it on the consumer side.
  • Background jobs. A worker that pulls a job from a queue and processes it should continue the trace from the producer, not start a new one. Same fix: propagate via the job payload.

The smell of broken propagation is that traces look correct end-to-end inside one service and then “stop” at the network boundary, with the downstream service starting a fresh root trace.

What this earns you

Three concrete payoffs once tracing is in place:

Bottleneck identification. A trace UI sorts spans by duration. The slow span is visually obvious. The “we suspect it is the database” guesswork stops.

Cross-service request shape. “What does a typical POST /orders actually do?” Open one trace and the answer is a tree, not a slack thread.

Capacity planning by business action. Per-attribute aggregations let you ask “how does median checkout latency change with cart size?” or “are enterprise customers experiencing slower searches than free?”. This is the data engineering teams reach for during capacity reviews.

The cost is one config file, ~50 lines, and a backend (Tempo + Grafana works free; Honeycomb / Datadog if you want polish). The payback is the next time a multi-service incident happens, and you find the slow span in 60 seconds instead of 60 minutes.

The takeaway

Distributed tracing is one of the lowest-effort, highest-payoff observability investments you can make in a service that talks to more than one other service. Start with auto-instrumentation, add manual spans at logical boundaries, set the right attributes, sample with intent, and propagate context across queues. The full setup is half a day. The next time someone asks “where does the time go?”, you point at the trace.

Logs and metrics are still useful, but they answer different questions. “What happened to this request?” is what tracing answers, and nothing else does.


A note from Yojji

Wiring up tracing properly (propagating context through HTTP, queues, and background workers, sampling without losing the rare slow request, keeping span cardinality under control) is the kind of cross-cutting backend work that pays for itself the first incident in. It is the kind of engineering Yojji’s teams build into the production systems they deliver for clients.

Yojji is an international custom software development company founded in 2016, with offices across Europe, the US, and the UK. Their teams specialize in the JavaScript stack (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and microservices, including the observability work that decides whether your team is debugging a trace or a hunch at 3 a.m.