Observability
Failure modes and engineering practice: cardinality budgets, PII, and sampling
At 14:00 a developer added customer_email as a label to http_requests_total. By 14:03 Prometheus had OOM-killed itself: 9.24 million series, 14.3 GB of RAM, restart count 1. The WAL replay lagged 73 seconds; every alert fired stale or not at all. One label, three minutes, regional monitoring down.
Production failure modes per signal
Each signal type has a characteristic way of failing. Knowing the failure mode tells you where to put the guardrails.
| Signal | Failure mode | Detection metric | Mitigation |
|---|---|---|---|
| Metrics | Cardinality bomb — one unbounded label OOMs the TSDB | prometheus_tsdb_head_series rate spike | metric_relabel_configs labeldrop, then remove from code |
| Logs | Ingestion runaway — one chatty service 10x the daily bill | Ingest GB/day per service in vendor dashboard | Raise log level or route to sampled tier; durable: emit one summary per operation |
| Logs | Silent PII leak — user data in indexed log fields | Audit dashboard scanning high-cardinality string fields | Allow-list enforced at pipeline; regex redactor in Fluent Bit or Vector |
| Traces | Sampling gap — the interesting trace was dropped | refused_spans_total in collector; 0% error traces after incident | Tail-based policy: always keep ERROR + latency > SLO |
| Traces | Span explosion — loop emits 10k spans per request | Spans per trace histogram spike | Wrap loop body in one parent span; suppress child spans above threshold |
| Traces | Orphaned spans — context not propagated across async boundary | Traces with single-service spans only; no parent_span_id set | Pass W3C traceparent in message headers (Kafka, SQS, etc.) |
Each failure mode has a detection metric. Senior teams monitor the monitoring tier as carefully as the product tier.
Cardinality budgets as engineering practice
In any 1.0 metrics stack, cardinality discipline is an engineering practice, not a one-time choice at instrumentation time.
The Cloudflare 2022 pattern: every team owns a cardinality budget (e.g. 100k active series across all services in the team’s namespace). CI checks flag any PR that introduces a new label name exceeding the threshold. The budget is reviewed quarterly, resized based on actual usage. The tool suite: Grafana’s mimirtool, Datadog’s Custom Metrics Usage view, Prometheus’s prometheus_tsdb_head_series and count by (__name__) ({__name__=~".+"}).
The cultural payoff is that engineers think about label cardinality at write time — not after the OOM at 03:00.
The Prometheus OOM case study. At 14:02 prometheus_tsdb_head_series jumped from 824k to 9.24M in two minutes — 11x growth. At ~3 KB per active series, the head block needed ~27 GB; the server had 16 GB. Memory hit 14.3 GB (89% of limit) and the kernel OOM-killed Prometheus. On restart, the WAL replay was 412 segments, lagging 73 seconds behind scrape time.
Immediate mitigation (under 5 minutes, no deploy required): add metric_relabel_configs with action: labeldrop and regex: customer_email to the Prometheus scrape config of the affected service. Confirm prometheus_tsdb_head_series_created_total rate falls back toward baseline within one scrape interval. Memory does not reclaim until the next 2-hour block compaction; restart Prometheus only if memory continues to climb.
Durable fix: (a) remove customer_email from the metric; (b) replace with a bounded customer_segment label (free/pro/enterprise = 3 values); (c) use exemplars to attach a sampled trace_id so per-customer drill-through still works without paying the cardinality cost; (d) add a CI check (cardinality-lint.ts) that fails builds when new label names match a deny-list regex (email, user_id, request_id, session_id, customer_id); (e) add a Prometheus alert: rate(prometheus_tsdb_head_series_created_total[5m]) > 1000 pages on-call before OOM.
PII risk on metric and log surfaces
Both metric labels and log fields can leak PII into a less-audited datastore than the source database.
Real incidents:
- A payments company in 2021 leaked customer phone numbers as a metric label (
failed_phone="+1..."). Prometheus scraped the metric to all environments including dev; the phone numbers were visible in dashboards to the whole engineering org. - A SaaS company in 2023 ingested raw request bodies into logs (including session tokens) for two months before a customer noticed in a support thread. The logging pipeline had no PII filter.
- A marketplace in 2024 emitted user search queries as a
queryspan attribute, exposing demographic-segment information to the BI team who had Jaeger access but not production DB access.
Mitigations:
- Allow-list for labels and span attributes. Deny by default. Every new metric label or span attribute requires explicit approval in a reviewed config file checked in alongside the code.
- Redaction in the logging pipeline. Vector and Fluent Bit both ship with regex redactors for common PII patterns. The pattern list (
email,phone,ssn,token,password,session_id) should be maintained in a security-reviewed repo alongside the cardinality deny-list. - Audit dashboards. A dashboard that shows high-cardinality string fields per signal — sorted by distinct-value count — catches leaks before they reach a customer’s awareness.
Treat label review and field review as a security gate, not a performance gate.
OTel sampling configuration in practice
The OTel Sampler API provides head-based decisions at the SDK and tail-based at the collector.
SDK-level samplers:
AlwaysOn— 100% sampling. Use only in dev/test or for very low-volume critical paths.AlwaysOff— 0% sampling. Useful for internal health-check routes where traces add no signal.TraceIdRatioBased(p)— samplespfraction of root traces. Generates a random decision correlated with thetrace_id; must be uncorrelated with request properties (see below).ParentBased(root_sampler)— honours the parent’s sampling decision from the incomingtraceparentheader. Downstream services follow the root’s decision automatically via the W3Csampledflag.
Collector-level tail sampling (TailSamplingProcessor):
Policies applied after the trace completes. Common production layout:
policies:
- name: errors-policy
type: status_code
status_code: {status_codes: [ERROR]}
- name: slow-traces-policy
type: latency
latency: {threshold_ms: 1000}
- name: baseline-policy
type: probabilistic
probabilistic: {sampling_percentage: 2}The errors-policy and slow-traces-policy keep 100% of interesting traces. The baseline-policy keeps 2% of the rest, giving low-traffic services coverage when there are no errors.
The Elastic 2024 post-mortem on head sampling. Naive head sampling under-represents errors and slow tails because the sampling decision is made before the trace has any outcome. The post-mortem also flagged a subtler problem: TraceIdRatioBased generates a random decision from the trace_id. If the trace_id is not truly random (e.g., derived from a hash of the request path), the sampling decision correlates with request properties — slow endpoints may always be sampled or always dropped as a cohort. Production rule: use ParentBased(TraceIdRatioBased(0.2)) at the edge with a cryptographically random trace_id, and layer tail policies at the collector for the interesting cases.
Prometheus OOM: order the response steps from first to last:
- 1 Check prometheus_tsdb_head_series rate — confirm 11x jump in 2 min
- 2 Identify the new label: scan recent metric_relabel diff or git log on instrumentation code
- 3 Add metric_relabel_configs labeldrop for the offending label — no deploy needed
- 4 Confirm head_series_created_total rate falls back to baseline within one scrape interval
- 5 Remove the label from application code and replace with bounded alternative
- 6 Add CI cardinality-lint check and Prometheus alert on series creation rate
A team adds customer_email to http_requests_total. Prometheus OOMs in 3 minutes. What is the correct immediate mitigation that requires no application redeploy?
The Elastic 2024 post-mortem flagged that TraceIdRatioBased sampling can silently under-represent a specific endpoint. What is the root cause?
- Prometheus head series at OOM incident start
- 824k
- Prometheus head series after customer_email label (2 min)
- 9.24M (11x)
- RAM required at 9.24M series × 3KB/series
- ~27 GB
- Server RAM limit in incident
- 16 GB
- WAL segments on restart
- 412 (73s lag)
- Cardinality budget per team (typical 1.0 stack)
- 50k–500k active series
- Tail-sampling buffer window
- 30–60 s per trace
- Production baseline sampling: successful traces
- 0.5–5%
- Production baseline sampling: error traces
- 100%
- 01Name the five production failure modes (one per signal category) and state the detection metric for each.
- 02Describe the Prometheus OOM incident response sequence: immediate mitigation (no deploy) and durable fix.
- 03Explain why ParentBased(TraceIdRatioBased) is the recommended SDK sampler in production and what the Elastic 2024 post-mortem adds to this recommendation.
Each observability signal has a characteristic failure mode: metrics face cardinality bombs (one unbounded label OOMs the TSDB in minutes), logs face ingestion runaway and silent PII leaks, traces face sampling gaps and span explosions. The detection metric for each failure mode should be monitored as carefully as the product tier. Cardinality budgets are an engineering practice enforced via CI deny-lists and quarterly reviews, not a one-time choice. PII leaks on metric labels and span attributes are a security breach regardless of access controls — allow-lists and pipeline redactors are mandatory. OTel sampling in production uses ParentBased(TraceIdRatioBased) at the SDK to propagate head decisions via the W3C traceparent flag, and TailSamplingProcessor at the collector to keep 100% of ERROR and slow-tail traces — with the Elastic 2024 caveat that the trace_id seed must be cryptographically random and uncorrelated with request properties.
appears again in167
- The journey of a request: seven stops from socket to responsejunior
- Accept and parse: from kernel queue to a typed requestmiddle
- Routing and middleware: choosing what runs, and in what ordermiddle
- Handler and response: from business logic to bytes on the wiremiddle
- Streaming and backpressure: when the client reads slower than you writesenior
- Timeouts and tail latency: budgets, deadlines, and the fan-out trapsenior
- Middleware and DI: the two patterns that shape every backendjunior
- Writing middleware: signatures, next(), and the three framework modelsmiddle
- Inversion of control: how dependencies reach a classmiddle
- DI scopes and lifecycles: singleton, request, transientmiddle
- DI as a testing seam: fakes, mocks, and the boundary that matterssenior
- DI containers in production: resolution graphs, circular deps, and when not tosenior
- Blocking vs non-blocking I/O: two ways to waitjunior
- The event loop: one thread, ordered phasesmiddle
- What blocks the loop: CPU work and sync callsmiddle
- Offloading CPU work: worker threads and the libuv poolmiddle
- Backpressure and bounded concurrencysenior
- Throughput under load: tail latency and saturationsenior
- Why pool: the cost of creating a connectionjunior
- Pool sizing: why bigger is not fastermiddle
- Acquisition and timeouts: the wait queue is the real latency dialmiddle
- Retry strategies: backoff, jitter, and thundering herdmiddle
- Observability, production failures, and global-scale designsenior
- Tasks, microtasks, and scheduler.yield()middle
- Timer accuracy, throttling, and idle workmiddle
- Node.js event loop: phases, nextTick, and loop lagsenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- LCP: four phases, one dominant costmiddle
- INP: input delay, processing, presentationmiddle
- Lab vs field: why the two disagree and how to use eachmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What an index is and how it speeds up queriesjunior
- The leading-column rule and composite index designmiddle
- Partial, expression, and covering indexesmiddle
- Index types: GIN, GiST, BRIN, Hash, Bloom, and HOT updatesmiddle
- Index-only scans, the Visibility Map, and INCLUDEsenior
- Production failure modes and the index audit playbooksenior
- Index design exercise: full-text search strategysenior
- EXPLAIN and execution plans: what the planner decides and whyjunior
- Scan types: Seq, Index, Bitmap, Index-Onlymiddle
- Join algorithms and the row-estimate cascademiddle
- pg_statistic, ANALYZE, and production observabilitymiddle
- Extended statistics: fixing correlated-column estimate failuressenior
- Plan cache, cost-constant tuning, and planner internalssenior
- Production failure modes and plan stabilitysenior
- Connection pools: amortising the cost of a Postgres backendjunior
- PgBouncer session, transaction, and statement modesmiddle
- Pool sizing: the (cores × 2) + spindles formula and the two-layer stackmiddle
- Pool exhaustion and idle-in-transaction: the 3 AM failure modemiddle
- Migrating to transaction mode: rollout playbook and PgBouncer 1.21 prepared statementsmiddle
- The Postgres process model and why raising max_connections degrades throughputsenior
- Pooler landscape 2026, serverless connection storms, and the full failure-mode taxonomysenior
- ADD COLUMN: instant in PG 11+ vs rewrite in older Postgresjunior
- The lock-queue failure mode: why instant DDL can freeze the databasemiddle
- Safe DDL patterns: NOT VALID, CONCURRENTLY, and unsafe-op fixesmiddle
- Migration failure taxonomy and production disciplinesenior
- Shard-key selection: hash, range, list, and directory strategiesmiddle
- Co-location and Citus: the invariant that makes sharding usablemiddle
- The hot-shard failure mode: detection, isolation, and durable policymiddle
- Online resharding, 2PC, and the operational cost of shardingsenior
- The seven acts: from CREATE TABLE to Citusjunior
- Acts 1–3 in depth: schema, indexes, and planner statisticsmiddle
- Acts 4–6 in depth: MVCC bloat, connection pooling, and safe migrationsmiddle
- Act 7 in depth: sharding, co-location, and the seven-tier tradeoff cascademiddle
- Observability, anti-patterns, and production triagesenior
- Bits on the wirejunior
- Latency mathmiddle
- Bufferbloat and congestionsenior
- The physical frontiersenior
- Sequence numbers and connection statemiddle
- Flow control and congestion controlmiddle
- BBR, production observability, and beyond TCPsenior
- CDN: putting content next doorjunior
- Anycast and GeoDNS: routing to the nearest edgemiddle
- Tiered cache and Cache-Controlmiddle
- Vary header and cache keysmiddle
- Stale-while-revalidate and cache stampedesenior
- Edge workers and edge-side compositionsenior
- CDN operations and observabilitysenior
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket vs SSE vs long-polling: choosing the right transportmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Balancing algorithms: round-robin to power-of-two-choicesmiddle
- L4 vs L7 load balancing and client-IP preservationmiddle
- Health checks, connection draining, and slow startmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- QUIC streams and head-of-line blockingjunior
- Integrated handshake and 1-RTTmiddle
- Connection IDs and network migrationmiddle
- Loss detection and congestion controlmiddle
- 0-RTT resumption and packet encryptionsenior
- Deployment tradeoffs and CPU costsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- The twelve layers: one URL, seven actorsjunior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Critical render path and Core Web Vitalsmiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- Why profile first: measure where time actually goesjunior
- Amdahl''''s law and self-time: the ceiling on every speedup you can shipmiddle
- The measurement loop: microbench, macrobench, prod profile, observer effectmiddle
- Reading flame graphs: shapes, per-language profilers, and the 60-second scanmiddle
- Statistical baselines: why one run is not a measurementmiddle
- Profiler history and microbenchmark pitfalls: Knuth to GWPsenior
- Hardware counters, cold-start profiles, and profile securitysenior
- Continuous profiling at scale: costs, CI gates, trace correlation, and anti-patternssenior
- What makes a hot path: symptom vs causejunior
- Five shapes of hotspot: CPU, alloc, cache, lock, syscallmiddle
- Reading parent and child chains: where to apply the fixmiddle
- JIT deopt, the fix-and-verify loop, and PR-time profilingmiddle
- Hardware counters and Intel TMA: sub-category diagnosissenior
- False sharing and native-bridge hot pathssenior
- Hot paths in production: security, tail latency, and tooling lineagesenior
- Memory hierarchy: why the same O(N) loop can be 17x slowerjunior
- Row-major vs column-major: access order and the 9x gapjunior
- Branch prediction and branchless codemiddle
- Hardware prefetcher, TLB, and memory-level parallelismsenior
- GC basics: what the runtime taxes you forjunior
- GC algorithms: generational, concurrent, and per-runtimemiddle
- GC tradeoffs: pause, throughput, heap — and object poolingmiddle
- GC tuning: pacing, heap shape, and allocation observabilitymiddle
- GC internals: tri-color invariant, write barriers, and per-runtime deep-divessenior
- GC in production: observability, security, edge cases, and fleet governancesenior
- N+1: one logical operation, many round-tripsjunior
- Fix families: JOIN, IN, preload, and DataLoadermiddle
- Detecting N+1: query logs, APM traces, and CI gatesmiddle
- DataLoader: batching across resolver treesmiddle
- Cross-protocol N+1: HTTP fan-out and Redis MGETmiddle
- N+1 at scale: pool exhaustion, plan changes, and denormalisationsenior
- Batching: amortize fixed cost per operationjunior
- The batching window: size and wait timemiddle
- Batching in Kafka and Postgresmiddle
- io_uring and observability of batchingmiddle
- From Nagle to io_uring: evolution of batchingmiddle
- Backpressure, failure isolation, and batch security in productionsenior
- What a bundle actually costs: download, parse, compile, executejunior
- Core Web Vitals: LCP, INP, and CLSmiddle
- Code splitting: route-level, component-level, vendor splittingmiddle
- Tree shaking and compression: removing what you don''''t usemiddle
- Third-party scripts: the silent budget killermiddle
- CI enforcement and RUM: making budgets stickmiddle
- V8 JIT pipeline, HTTP priorities, and bundle securitysenior
- The performance loop: discipline, not a projectjunior
- Classify and fix: matching bottleneck families to remediesmiddle
- Observability stack and CI gates: catching regressions before they shipmiddle
- Incident to enforcement: SLO burn to verified fix in 35 minutesmiddle
- Culture, economics, and org-scale performancesenior