nginx-c-module-perf
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesenginx.org C Module Performance & Reliability Best Practices
Nginx官方C模块性能与可靠性最佳实践
Comprehensive performance optimization and reliability guide for nginx C modules, derived from the official nginx development documentation and production engineering experience. Contains 43 rules across 8 categories, prioritized by impact to guide automated optimization and resilience improvements.
Companion skill: This skill complements nginx-c-modules which covers correctness (memory safety, request lifecycle, configuration). This skill covers performance optimization and operational reliability.
本指南是基于Nginx官方开发文档和生产工程经验整理的Nginx C模块全面性能优化与可靠性指南,包含8个类别共43条规则,按影响优先级排序,可指导自动化优化与弹性提升。
配套技能:本技能是nginx-c-modules(涵盖内存安全、请求生命周期、配置等正确性相关内容)的补充,专注于性能优化与运行可靠性。
When to Apply
适用场景
Reference these guidelines when:
- Optimizing nginx C module throughput and latency
- Reducing buffer copies and enabling zero-copy I/O paths
- Tuning connection pooling and socket options
- Minimizing shared memory lock contention across workers
- Implementing graceful error recovery and fallback responses
- Configuring upstream timeouts and retry strategies
- Building in-module response caches with shared memory
- Tuning worker process behavior under load
在以下场景中可参考本指南:
- 优化Nginx C模块的吞吐量与延迟
- 减少缓冲区拷贝并启用零拷贝I/O路径
- 调优连接池与套接字选项
- 降低工作进程间的共享内存锁竞争
- 实现优雅的错误恢复与降级响应
- 配置上游服务超时与重试策略
- 在模块内基于共享内存构建响应缓存
- 调优高负载下的工作进程行为
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Buffer & Zero-Copy I/O | CRITICAL | |
| 2 | Connection Efficiency | CRITICAL | |
| 3 | Lock Contention & Atomics | HIGH | |
| 4 | Error Recovery & Resilience | HIGH | |
| 5 | Timeout & Retry Strategy | MEDIUM-HIGH | |
| 6 | Response Caching | MEDIUM | |
| 7 | Worker & Process Tuning | MEDIUM | |
| 8 | Logging & Metrics | LOW-MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 缓冲区与零拷贝I/O | 关键 | |
| 2 | 连接效率 | 关键 | |
| 3 | 锁竞争与原子操作 | 高 | |
| 4 | 错误恢复与弹性 | 高 | |
| 5 | 超时与重试策略 | 中高 | |
| 6 | 响应缓存 | 中 | |
| 7 | 工作进程调优 | 中 | |
| 8 | 日志与指标 | 中低 | |
Quick Reference
快速参考
1. Buffer & Zero-Copy I/O (CRITICAL)
1. 缓冲区与零拷贝I/O(关键)
- - Reuse Buffer Chain Links Instead of Allocating New Ones
buf-chain-reuse - - Use File Buffers for Static Content Instead of Reading into Memory
buf-file-sendfile - - Avoid Copying Buffers When Passing Through Filter Chain
buf-avoid-copy - - Coalesce Small Buffers Before Output
buf-coalesce-small - - Use Shadow Buffers for Derived Data Instead of Full Copies
buf-shadow-reference - - Mark Buffers as Recycled for Upstream Response Reuse
buf-recycled-flag
- - 复用缓冲区链节点而非分配新节点
buf-chain-reuse - - 针对静态内容使用文件缓冲区而非读取到内存
buf-file-sendfile - - 在过滤器链传递时避免拷贝缓冲区
buf-avoid-copy - - 输出前合并小缓冲区
buf-coalesce-small - - 使用影子缓冲区存储派生数据而非完整拷贝
buf-shadow-reference - - 标记缓冲区为可回收以复用上游响应
buf-recycled-flag
2. Connection Efficiency (CRITICAL)
2. 连接效率(关键)
- - Mark Idle Connections as Reusable for Pool Recovery
conn-reusable-queue - - Handle Connection Drain Under Memory Pressure
conn-drain-pressure - - Control TCP_NODELAY for Latency-Sensitive Responses
conn-tcp-nodelay - - Size Connection Pool to Avoid Runtime Reallocation
conn-prealloc-pool - - Use Lingering Close for Graceful Connection Shutdown
conn-close-linger - - Enable SSL Session Caching in Upstream Connections
conn-ssl-session-reuse
- - 将空闲连接标记为可复用以便连接池回收
conn-reusable-queue - - 在内存压力下处理连接释放
conn-drain-pressure - - 针对延迟敏感型响应控制TCP_NODELAY
conn-tcp-nodelay - - 预分配连接池大小以避免运行时重新分配
conn-prealloc-pool - - 使用 linger 关闭实现优雅的连接终止
conn-close-linger - - 在上游连接中启用SSL会话缓存
conn-ssl-session-reuse
3. Lock Contention & Atomics (HIGH)
3. 锁竞争与原子操作(高)
- - Minimize Critical Section Duration in Shared Memory
lock-minimize-critical - - Use Atomic Operations for Simple Counters Instead of Mutex
lock-atomic-counters - - Use ngx_shmtx_trylock with Fallback to Avoid Worker Stalls
lock-trylock-fallback - - Aggregate Per-Worker Counters to Reduce Shared Memory Access
lock-per-worker-aggregate - - Perform Slab Allocation Outside Hot Path
lock-alloc-outside - - Use Read-Copy-Update Pattern for Read-Heavy Shared Data
lock-rw-pattern
- - 减少共享内存中的临界区时长
lock-minimize-critical - - 对简单计数器使用原子操作而非互斥锁
lock-atomic-counters - - 使用ngx_shmtx_trylock并配置降级策略以避免工作进程停滞
lock-trylock-fallback - - 聚合每个工作进程的计数器以减少共享内存访问
lock-per-worker-aggregate - - 在热点路径外执行Slab分配
lock-alloc-outside - - 针对读密集型共享数据使用读-拷贝-更新模式
lock-rw-pattern
4. Error Recovery & Resilience (HIGH)
4. 错误恢复与弹性(高)
- - Cache ngx_errno Immediately to Prevent Overwrite
err-cache-errno - - Return Fallback Response When Upstream Fails
err-fallback-response - - Handle Pool and Slab Allocation Exhaustion Gracefully
err-resource-exhaustion - - Use Blocked Counter to Prevent Premature Request Destruction
err-blocked-counter - - Check Connection Error Flag Before I/O Operations
err-connection-error-check - - Limit Repeated Error Logging to Prevent Log Storms
err-log-once-pattern
- - 立即缓存ngx_errno以防止被覆盖
err-cache-errno - - 上游服务故障时返回降级响应
err-fallback-response - - 优雅处理连接池与Slab分配耗尽的情况
err-resource-exhaustion - - 使用阻塞计数器防止请求被过早销毁
err-blocked-counter - - I/O操作前检查连接错误标记
err-connection-error-check - - 限制重复错误日志输出以避免日志风暴
err-log-once-pattern
5. Timeout & Retry Strategy (MEDIUM-HIGH)
5. 超时与重试策略(中高)
- - Set Separate Timeouts for Connect, Send, and Read Phases
timeout-upstream-phases - - Configure next_upstream Mask for Retriable Failures
timeout-retry-next-upstream - - Use Exponential Backoff for Upstream Reconnection Attempts
timeout-backoff-reconnect - - Set Client Body Timeout to Bound Slow-Client Resource Usage
timeout-client-body-limit
- - 为连接、发送、读取阶段分别设置超时
timeout-upstream-phases - - 配置next_upstream掩码以定义可重试的故障类型
timeout-retry-next-upstream - - 对重连尝试使用指数退避策略
timeout-backoff-reconnect - - 设置客户端请求体超时以限制慢客户端的资源占用
timeout-client-body-limit
6. Response Caching (MEDIUM)
6. 响应缓存(中)
- - Implement LRU Eviction in Shared Memory Cache Zones
cache-shm-lru - - Prevent Cache Stampede with Single-Flight Pattern
cache-stampede-lock - - Use ngx_hash for Fixed Cache Key Lookups
cache-key-hash - - Use Atomic Timestamp Comparison for TTL Expiry Checks
cache-ttl-atomic - - Cache Only Successful Responses to Avoid Negative Cache Pollution
cache-conditional-store
- - 在共享内存缓存区中实现LRU淘汰机制
cache-shm-lru - - 使用单请求模式防止缓存击穿
cache-stampede-lock - - 对固定缓存键使用ngx_hash进行查找
cache-key-hash - - 使用原子时间戳比较检查TTL过期
cache-ttl-atomic - - 仅缓存成功响应以避免负缓存污染
cache-conditional-store
7. Worker & Process Tuning (MEDIUM)
7. 工作进程调优(中)
- - Understand Accept Mutex Impact on Connection Distribution
worker-accept-mutex - - Use Pre-Allocated Free List for Module Data Structures
worker-connection-prealloc - - Handle Worker Shutdown Signal Without Data Loss
worker-graceful-shutdown - - Support Single-Process Mode for Debugging
worker-single-process-debug - - Access Configuration Through Cycle for Process-Level Operations
worker-cycle-conf
- - 理解Accept互斥锁对连接分配的影响
worker-accept-mutex - - 为模块数据结构使用预分配的空闲列表
worker-connection-prealloc - - 处理工作进程关闭信号时避免数据丢失
worker-graceful-shutdown - - 支持单进程模式以方便调试
worker-single-process-debug - - 通过Cycle访问配置以执行进程级操作
worker-cycle-conf
8. Logging & Metrics (LOW-MEDIUM)
8. 日志与指标(中低)
- - Guard Expensive Debug Argument Computation Behind Level Check
log-level-guard - - Attach Module Context to Connection Log for Tracing
log-connection-context - - Collect Metrics via Shared Memory Counters
log-shared-metrics - - Deduplicate Repeated Error Messages with Throttling
log-error-dedup - - Set Log Action String for Operation Context
log-action-string
- - 在日志级别检查后再执行开销较大的调试参数计算
log-level-guard - - 将模块上下文附加到连接日志以实现追踪
log-connection-context - - 通过共享内存计数器收集指标
log-shared-metrics - - 对重复错误消息进行去重并设置限流
log-error-dedup - - 设置日志操作字符串以记录操作上下文
log-action-string
How to Use
使用方法
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
阅读单个参考文件获取详细说明与代码示例:
- 章节定义 - 类别结构与影响级别说明
- 规则模板 - 添加新规则的模板
Reference Files
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 类别定义与排序说明 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |