When a distributed web platform degrades under load, application-tier APM agents frequently go blind at the worst possible moment. Garbage-collection pauses, saturated Node.js event loops, or exhausted database pools delay or drop in-process telemetry right as tail latency spikes. Because HAProxy sits outside the application blast radius and terminates every client TLS session and upstream socket, well-engineered HAProxy observability gives operators an uncorrupted ground-truth ledger of every millisecond, queue stall, TCP reset, and protocol error across the stack.
1. Exposing Low-Overhead Metrics With the Native PROMEX Module
Historically, scraping HAProxy for Prometheus required deploying an external sidecar process that polled the CSV stats endpoint or Unix admin socket on every scrape interval and re-formatted thousands of rows in Go. On clusters routing hundreds of dynamic backends, that sidecar pattern introduced unnecessary socket contention and scrape jitter. Modern HAProxy 2.x and 3.x builds compile the C-native prometheus-exporter service directly into the proxy binary, reading internal thread counters in memory with near-zero CPU overhead.
Bind a dedicated internal management frontend so public internet traffic can never reach your telemetry or stats endpoints, and append no-maint to the query string if you have large pools of disabled maintenance slots that would otherwise bloat time-series cardinality:
global
log stdout format raw local0
stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
stats timeout 30s
profiling.tasks automatic
frontend fe_observability
bind 127.0.0.1:8404
mode http
http-request use-service prometheus-exporter if { path /metrics }
stats enable
stats uri /stats
stats refresh 10s
Architectural Caveat on Rolling Averages: Built-in gauge metrics such as haproxy_backend_response_time_average_seconds and haproxy_server_queue_time_average_seconds are rolling averages computed over the last 1,024 requests. A brief three-second upstream stall can hide inside a healthy-looking rolling average. Use PROMEX for real-time saturation and health alerting (haproxy_backend_queue_current, haproxy_server_status, haproxy_backend_connection_errors_total, and 5xx response counters), and compute exact p95 and p99 percentiles from structured per-request logs.
2. Reading the Five-Timer Waterfall and Termination Codes Like an X-Ray
Before reaching for flamegraphs or database query plans during an outage, inspect HAProxy's five millisecond timing measurements alongside the two-character session termination state (%tsc). Together, they isolate whether latency originates on the client radio network, inside HAProxy's own connection queue, across the datacenter network fabric, or inside your application worker.
| Log Token | Phase Measured | Primary Failure Signature | First Engineering Action |
|---|---|---|---|
%TR |
Time waiting for full client HTTP headers after TLS accept | Elevated TR paired with cR termination code |
Inspect mobile client uplinks, large cookie headers, or slow-request attacks; tighten timeout http-request. |
%Tw |
Milliseconds spent queued inside HAProxy awaiting a free server slot | Tw > 0 while haproxy_backend_queue_current climbs |
Upstream workers hit maxconn; scale backend replicas or tune worker concurrency before raising maxconn blindly. |
%Tc |
TCP SYN-to-ACK and backend TLS handshake duration | Spikes around 1,000 ms (kernel SYN retransmit) or SC state |
Check upstream kernel somaxconn accept queues, firewall conntrack tables, and HTTP keep-alive reuse (http-reuse safe). |
%Tr |
Backend server Time to First Byte (response headers received) | High Tr or sH termination on 504 Gateway Timeout |
Profile slow SQL queries, synchronous lock contention, or event-loop blocking inside the target upstream service. |
%Ta |
Total active HTTP transaction time from first byte in to last byte out | Normal Tr but huge Ta - Tr gap with cD state |
Large streaming payloads, SSE/WebSocket holds, or slow client downloads; offload static blobs to edge cache. |
%tsc |
Two-character client/proxy termination state + session mode | PH (proxy blocked invalid response) or SD (server reset mid-body) |
Run show errors on the HAProxy Runtime API socket to capture the exact offending wire payload. |
Note the capitalization distinction in HAProxy's termination flags: lowercase sH means HAProxy's timeout server expired while waiting for the application to respond, whereas uppercase SH means the upstream process abruptly closed or reset the TCP socket (for example, an out-of-memory kill or unhandled crash mid-request). Mixing up those two codes sends incident responders chasing timeout configs when a container is actually segfaulting.
3. Non-Blocking HAProxy JSON Logs Over In-Memory Ring Buffers
Traditional space-delimited syslog lines force log collectors to run brittle regular expressions, while UDP syslog silently drops packets on the floor during sudden traffic bursts—erasing forensic evidence of the exact 502 and 504 requests you need to inspect. Conversely, pointing HAProxy directly at a remote TCP syslog endpoint without buffering risks stalling worker threads if the downstream collector restarts.
HAProxy 3.x solves both problems natively. First, the %{+json}o log-format directive serializes and escapes every string field into valid JSON inside C without Lua overhead. Second, directing logs to an in-memory ring buffer decouples worker threads from network I/O, streaming RFC 5424 frames asynchronously over TCP to Vector, Fluent Bit, or Grafana Alloy for ingestion into Loki:
ring edge_json_ring
description "Non-blocking JSON access log buffer"
format rfc5424
maxlen 4096
size 1048576
timeout connect 5s
timeout server 10s
server loki_ingest loki-relay.internal:6514 check inter 5s
defaults http_edge
mode http
option httplog
option dontlognull
log ring@edge_json_ring local0 info
log-format "%{+json}o{\"ts\":\"%t\",\"host\":\"%[capture.req.hdr(0)]\",\"method\":\"%HM\",\"path\":\"%HP\",\"status\":%ST,\"bytes\":%B,\"tr_req_ms\":%TR,\"tw_queue_ms\":%Tw,\"tc_conn_ms\":%Tc,\"tr_app_ms\":%Tr,\"ta_total_ms\":%Ta,\"term_state\":\"%tsc\",\"fe\":\"%ft\",\"be\":\"%b\",\"srv\":\"%s\",\"actconn\":%ac,\"beconn\":%bc,\"retries\":%rc,\"tls_ver\":\"%sslv\",\"trace_id\":\"%[var(txn.trace_id)]\"}"
Once these structured HAProxy JSON logs land in Loki, operators can compute live tail-latency percentiles per backend or isolate upstream stalls in seconds without pre-defining high-cardinality Prometheus labels:
# Compute p99 upstream application TTFB (Tr) per backend in Loki LogQL
quantile_over_time(0.99,
{service="haproxy"} | json | status < 500 | unwrap tr_app_ms [5m]
) by (be, srv)
4. OpenTelemetry Trace Propagation at the Edge
Metrics tell you a backend queue is backing up, and JSON logs identify the slow endpoint, but distributed traces connect that edge delay to the exact downstream RPC or database query. Even before deploying full C-module span exporters, you should configure HAProxy to honor incoming W3C traceparent headers—or mint a compliant 128-bit trace identifier at the edge when clients omit one—so your access logs and backend OpenTelemetry SDKs share a single correlation key:
frontend fe_https_ingress
bind *:443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1
capture request header Host len 64
# Extract caller W3C traceId from traceparent (00-<32-hex-trace-id>-<16-hex-span-id>-01)
http-request set-var(txn.trace_id) req.hdr(traceparent),field(2,-) if { req.hdr(traceparent) -m found }
# Mint a deterministic 32-hex trace ID + W3C traceparent when absent
http-request set-var(txn.trace_id) uuid(),regsub(-,,g),lower if !{ var(txn.trace_id) -m found }
http-request set-header traceparent "00-%[var(txn.trace_id)]-%[rand(),hex,bytes(0,16),lower]-01" if !{ req.hdr(traceparent) -m found }
http-response set-header x-trace-id "%[var(txn.trace_id)]"
For full OTLP span and metric pipelines, pair OpenTelemetry trace propagation headers with either the OpenTelemetry Collector's haproxyreceiver (polling the Unix socket or stats endpoint into OTLP metrics) or HAProxy's native filter opentelemetry module to emit edge ingress spans directly to Grafana Tempo or Jaeger. Echoing x-trace-id on error responses also lets support engineers paste a single header from a browser HAR capture straight into Grafana Explore to view both the HAProxy timing breakdown and the downstream service trace.
5. Live Forensics With the HAProxy Runtime API
Some of the trickiest production bugs never show up cleanly in aggregate dashboards: an upstream proxy injecting duplicate Content-Length headers, a mobile SDK sending unencoded control bytes in a header, or a single complex regex ACL burning CPU cycles on worker threads. The HAProxy Runtime API over /run/haproxy/admin.sock exposes live internal state without restarting processes or running invasive packet captures:
- Pinpoint Wire-Level Protocol Rejections (
show errors): Whenever%tsclogsPHor unexpected400/502spikes appear, runecho "show errors" | socat stdio /run/haproxy/admin.sock. HAProxy prints the exact byte offset and character stream of the last malformed request or response buffer that violated RFC 9110/9112 framing. - Audit Task & Memory Hotspots (
show profiling): Withprofiling.tasks automaticenabled inglobal, executingshow profilingreveals per-task CPU wait and run times, immediately exposing expensive Lua scripts, oversized map lookups, or TLS handshake bottlenecks. - Inspect Stuck In-Flight Streams (
show sess): Ifscurstays pinned on a single upstream node during a deployment drain,show sesslists active client/server file descriptors, ages, and stream flags—commonly revealing long-lived WebSocket or Server-Sent Events connections missing an appropriatetimeout tunnelbudget.
Production Readiness Checklist
- Enable native
prometheus-exporteron a loopback or private management listener and alert onhaproxy_backend_queue_current > 0sustained over 60 seconds, backend5xxerror-budget burn, and TLS certificate expiration gauges. - Replace fragile regex text logs with
%{+json}ostructured HAProxy JSON logs routed through a sizedringbuffer over TCP RFC 5424 so bursts never drop forensic data or stall worker threads. - Dashboard
Tw,Tc, andTrseparately rather than relying on total duration alone, and group5xxalerts by%tscso responders immediately distinguish timeout expirations (sH) from upstream crashes (SH/SC). - Standardize W3C
traceparentpropagation at the frontend edge so every log line in Loki links directly to distributed backend spans.
Need High-Throughput Edge Routing & Full-Stack Observability?
Explore Robert Baindourov's production architecture experience across Linux edge load balancing, Prometheus, Grafana Loki, Node.js, TypeScript, and distributed microservices, or get in touch for principal engineering engagements.
