跪拜 Guibai
← All articles
Backend · Nginx

Nginx Under Observation: Metrics, Alerts, and a 30-Second Rollback Drill

By 知行砚 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Nginx config errors that pass nginx -t are a silent killer in production; a functional probe plus automatic rollback closes that gap, and the measured times make it a viable—even standard—practice. The article gives Western teams a concrete, tested playbook for turning Nginx from a black box into an instrumented, safely deployable service.

Summary

The article delivers a complete observability stack for Nginx: stub_status for liveness, nginx-module-vts for per-host and upstream dimensions, OpenResty+lua for custom business labels, and log-based metrics for full fields. It maps each metric to dashboards, including a P99 latency histogram that requires explicit bucket configuration. Alerts move from raw 5xx thresholds to error-budget burn rates, and a canary release flow uses weight-based traffic splitting with concrete rollback triggers.

The engineering half is a pipeline: render config with Jinja2 (StrictUndefined), run nginx -t, replace and reload, probe /healthz five times, and roll back to a backup if probing fails. Measured results: a missing semicolon is caught in 0.2 seconds with zero production impact; a syntactically valid but functionally broken config (changing listen port) passes -t but triggers a rollback that restores service in 9.5 seconds, with about 7 seconds of downtime. The article also calls out classic pitfalls: vts zone exhaustion silently drops new labels, histogram buckets must be explicit, and Prometheus queries without host="*" double-count requests (116 vs 58).

Takeaways
— stub_status exposes only connection counts and three cumulative counters; it cannot answer which upstream is slow or which status codes are rising.
— nginx-module-vts adds per-host, upstream, backend, and cache dimensions with a histogram, but requires compiling the module and consumes shared memory; zone size is 3547 bytes per node.
— OpenResty+lua prometheus allows arbitrary custom metrics with business labels, but runs Lua on every request; metric registration must happen in init_worker_by_lua_block, not init_by_lua_block.
— The deploy pipeline: render -> nginx -t -> backup -> reload -> probe /healthz (5x 200) -> rollback on failure; a syntax error stops in 0.2s, a functional error rolls back in 9.5s (about 7s downtime).
— Always add host="*" to Prometheus queries for vts metrics; without it, the same data is counted two or three times, making alerts misfire.
— vts histogram buckets must be explicitly enabled; without them, histogram_quantile() returns empty. Adding buckets costs label cardinality, not nginx memory.
— Canary release uses weight=1 for new members; the observed request share matches the weight ratio (3.3% vs 3.2%). Roll back by removing the line and reloading, effective in 1 second.
— For trace correlation, $request_id (>=1.11.0) handles in-gateway log correlation; traceparent (W3C) spans services. When the client omits traceparent, generate one from $request_id and use proxy_set_header to pass it.
Conclusions

The article's measured numbers show that most production Nginx failures are functional, not syntactic; nginx -t alone is a necessary but insufficient gate.

The 2x request-count discrepancy when mixing aggregation layers (host='_' and host='*') is a classic Prometheus data-artifact trap; it turns a simple alert into a source of false positives and missed ones.

Treating observability as a cost/benefit decision (four options with explicit trade-offs) is more honest than pushing one 'best' tool; the choice depends on whether you need dimensions, latency histograms, or business labels.

A 9.5-second rollback with 7 seconds of downtime is acceptable for a gateway, but the article's advice to sleep 2 seconds after reload before probing is a subtle fix for the async nature of worker termination.

Concepts & terms
stub_status
A built-in Nginx module that exposes minimal connection counts and cumulative counters; useful only as a liveness probe, with no per-host or status-code dimensions.
nginx-module-vts
A third-party Nginx module that adds per-host, upstream, backend, and cache metrics in Prometheus format, including latency histograms when buckets are configured.
error budget burn rate
The ratio of current 5xx proportion to the SLO-allowed error rate; alerting when it exceeds a threshold like 14.4 over an hour converts a static ratio alert into an SLO-aware one.
canary release
A deployment strategy that sends a small percentage of traffic to a new version via weighted upstreams, then progressively increases the weight while watching error rates and latency.
Jinja2 StrictUndefined
A Jinja2 undefined mode that raises an error instead of rendering an empty string when a template variable is missing, catching config drift during rendering.
From the discussion
Featured comments
星云PLUS团队 1 likes

As for rollback verification, there's an easily missed point: reload is a smooth switch, and the in-flight requests still on the old workers will write results into the same sequence according to the old config. So "rollback effective" is best observed by version slices — carry a config_version label in the conf, or log the hash of each nginx -T snapshot. Otherwise the 30 seconds of data after rollback will mix the two versions, and the recovery of the success rate gets misread as a successful rollback. Additionally, keepalive long connections mean that even after the weight is zeroed, traffic still hits the old upstream. For the verification window it's better to check whether the number of requests to new members within 60/120 seconds actually drops to zero, rather than whether it's zero out of 100 requests. In production it's not convenient to add cb= to bypass the cache; a more stable approach is to group by upstream in the same query and look at the change in the absolute count of 5xx errors.

知行砚

Excellent, excellent, excellent.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗