nginx-c-module-perf
nginx.org C Module Performance & Reliability Best Practices
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.
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
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Buffer & Zero-Copy I/O | CRITICAL | buf- |
| 2 | Connection Efficiency | CRITICAL | conn- |
| 3 | Lock Contention & Atomics | HIGH | lock- |
| 4 | Error Recovery & Resilience | HIGH | err- |
| 5 | Timeout & Retry Strategy | MEDIUM-HIGH | timeout- |
| 6 | Response Caching | MEDIUM | cache- |
| 7 | Worker & Process Tuning | MEDIUM | worker- |
| 8 | Logging & Metrics | LOW-MEDIUM | log- |
Quick Reference
1. Buffer & Zero-Copy I/O (CRITICAL)
buf-chain-reuse- Reuse Buffer Chain Links Instead of Allocating New Onesbuf-file-sendfile- Use File Buffers for Static Content Instead of Reading into Memorybuf-avoid-copy- Avoid Copying Buffers When Passing Through Filter Chainbuf-coalesce-small- Coalesce Small Buffers Before Outputbuf-shadow-reference- Use Shadow Buffers for Derived Data Instead of Full Copiesbuf-recycled-flag- Mark Buffers as Recycled for Upstream Response Reuse
2. Connection Efficiency (CRITICAL)
conn-reusable-queue- Mark Idle Connections as Reusable for Pool Recoveryconn-drain-pressure- Handle Connection Drain Under Memory Pressureconn-tcp-nodelay- Control TCP_NODELAY for Latency-Sensitive Responsesconn-prealloc-pool- Size Connection Pool to Avoid Runtime Reallocationconn-close-linger- Use Lingering Close for Graceful Connection Shutdownconn-ssl-session-reuse- Enable SSL Session Caching in Upstream Connections
3. Lock Contention & Atomics (HIGH)
lock-minimize-critical- Minimize Critical Section Duration in Shared Memorylock-atomic-counters- Use Atomic Operations for Simple Counters Instead of Mutexlock-trylock-fallback- Use ngx_shmtx_trylock with Fallback to Avoid Worker Stallslock-per-worker-aggregate- Aggregate Per-Worker Counters to Reduce Shared Memory Accesslock-alloc-outside- Perform Slab Allocation Outside Hot Pathlock-rw-pattern- Use Read-Copy-Update Pattern for Read-Heavy Shared Data
4. Error Recovery & Resilience (HIGH)
err-cache-errno- Cache ngx_errno Immediately to Prevent Overwriteerr-fallback-response- Return Fallback Response When Upstream Failserr-resource-exhaustion- Handle Pool and Slab Allocation Exhaustion Gracefullyerr-blocked-counter- Use Blocked Counter to Prevent Premature Request Destructionerr-connection-error-check- Check Connection Error Flag Before I/O Operationserr-log-once-pattern- Limit Repeated Error Logging to Prevent Log Storms
5. Timeout & Retry Strategy (MEDIUM-HIGH)
timeout-upstream-phases- Set Separate Timeouts for Connect, Send, and Read Phasestimeout-retry-next-upstream- Configure next_upstream Mask for Retriable Failurestimeout-backoff-reconnect- Use Exponential Backoff for Upstream Reconnection Attemptstimeout-client-body-limit- Set Client Body Timeout to Bound Slow-Client Resource Usage
6. Response Caching (MEDIUM)
cache-shm-lru- Implement LRU Eviction in Shared Memory Cache Zonescache-stampede-lock- Prevent Cache Stampede with Single-Flight Patterncache-key-hash- Use ngx_hash for Fixed Cache Key Lookupscache-ttl-atomic- Use Atomic Timestamp Comparison for TTL Expiry Checkscache-conditional-store- Cache Only Successful Responses to Avoid Negative Cache Pollution
7. Worker & Process Tuning (MEDIUM)
worker-accept-mutex- Understand Accept Mutex Impact on Connection Distributionworker-connection-prealloc- Use Pre-Allocated Free List for Module Data Structuresworker-graceful-shutdown- Handle Worker Shutdown Signal Without Data Lossworker-single-process-debug- Support Single-Process Mode for Debuggingworker-cycle-conf- Access Configuration Through Cycle for Process-Level Operations
8. Logging & Metrics (LOW-MEDIUM)
log-level-guard- Guard Expensive Debug Argument Computation Behind Level Checklog-connection-context- Attach Module Context to Connection Log for Tracinglog-shared-metrics- Collect Metrics via Shared Memory Counterslog-error-dedup- Deduplicate Repeated Error Messages with Throttlinglog-action-string- Set Log Action String for Operation Context
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 |
More from pproenca/dot-skills
zod
Zod schema validation best practices for type safety, parsing, and error handling. This skill should be used when defining z.object schemas, using z.string validations, safeParse, or z.infer. This skill does NOT cover React Hook Form integration patterns (use react-hook-form skill) or OpenAPI client generation (use orval skill).
2.0Kclean-architecture
Clean Architecture principles and best practices from Robert C. Martin's book. This skill should be used when designing software systems, reviewing code structure, or refactoring applications to achieve better separation of concerns. Triggers on tasks involving layers, boundaries, dependency direction, entities, use cases, or system architecture.
1.4Kemilkowal-animations
Emil Kowalski's animation best practices for web interfaces. Use when writing, reviewing, or implementing animations in React, CSS, or Framer Motion. Triggers on tasks involving transitions, easing, gestures, toasts, drawers, or motion.
918vitest
Vitest testing framework patterns for test setup, async testing, mocking with vi.*, snapshots, and test performance (formerly test-vitest). This skill should be used when writing or debugging Vitest tests. This skill does NOT cover TDD methodology (use test-tdd skill), API mocking with MSW (use test-msw skill), or Jest-specific APIs.
907typescript
This skill should be used when the user asks to "optimize TypeScript performance", "speed up tsc compilation", "configure tsconfig.json", "fix type errors", "improve async patterns", or encounters TS errors (TS2322, TS2339, "is not assignable to"). Also triggers on .ts, .tsx, .d.ts file work involving type definitions, module organization, or memory management. Does NOT cover TypeScript basics, framework-specific patterns, or testing.
821nuqs
nuqs (type-safe URL query state) best practices for Next.js applications. This skill should be used when writing, reviewing, or refactoring code that uses nuqs for URL state management. Triggers on tasks involving useQueryState, useQueryStates, search params, URL state, query parameters, nuqs parsers, or Next.js routing with state.
735