Sub topic 14
Tuning workers, compression, and caching
This chapter assumes you can already serve a site with Nginx, edit files under /etc/nginx/, and run sudo nginx -t && sudo systemctl reload nginx to apply changes. It also assumes you know the http, server, and location contexts and have a working reverse proxy. Tuning changes how Nginx spends CPU, memory, and bandwidth. Measure before and after each change, and keep the defaults wherever you have no evidence they hurt.
How Nginx uses workers
Nginx runs one master process and several worker processes. The master reads the configuration and manages the workers. The workers accept connections and handle requests. Each worker is single-threaded and uses an event loop. That means one worker can handle thousands of idle or slow connections without a thread per client.
The practical consequence is that you do not tune Nginx by adding threads. You match the number of workers to the CPU cores and make sure the operating system lets each worker open enough connections.
Worker settings
The worker directives live in the main context and the events context of /etc/nginx/nginx.conf.
user www-data;
worker_processes auto;
worker_rlimit_nofile 16384;
events {
worker_connections 4096;
}worker_processes auto;starts one worker per CPU core. This is the right choice for almost every server.worker_connectionsis the maximum number of simultaneous connections per worker. The default is often 512 or 1024, depending on the package.worker_rlimit_nofileraises the open-file limit for the workers. Every connection uses a file descriptor, and every file Nginx serves uses one more. Set it to at least twiceworker_connections.
The ceiling on clients is roughly worker_processes × worker_connections. When Nginx acts as a reverse proxy, each client request uses two connections, one to the client and one to the upstream. Divide the ceiling by two for a proxy.
The values above give a four-core machine about 16,000 connections, or about 8,000 proxied clients. Check your core count with nproc. After a reload, confirm the limit that applies to a running worker:
nproc
pgrep -f "nginx: worker" | head -n 1 | xargs -I{} grep "open files" /proc/{}/limitsIf the log shows worker_connections are not enough or Too many open files, you have hit one of these limits. Raise them, reload, and check again.
Keep-alive and file transfer
Opening a TCP connection (and a TLS session on top of it) is expensive. Keep-alive lets a client reuse a connection for several requests. These directives go in the http context:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30s;
keepalive_requests 1000;
}sendfile on;lets the kernel copy file data straight to the socket instead of passing it through Nginx's memory.tcp_nopush on;works withsendfileand sends response headers and the start of a file in full packets.tcp_nodelay on;sends small final packets immediately on keep-alive connections.keepalive_timeoutis how long an idle connection stays open. A long timeout wastes connection slots, and a very short one throws away the benefit of reuse. Values between 15 and 65 seconds are typical.
Keep-alive also matters between Nginx and your application. The default for proxy_pass is HTTP/1.0 with a new connection per request. To reuse upstream connections, add a keepalive pool to the upstream group and set proxy_http_version 1.1; and an empty Connection header in the proxying location.
Compression
Compression trades CPU time for bandwidth. It helps text formats such as HTML, CSS, JavaScript, JSON, and XML, which usually shrink by 60 to 80 percent. It does not help formats that are already compressed, such as JPEG, PNG, MP4, ZIP, and WOFF2. Compressing those wastes CPU and can make them slightly larger.
http {
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_vary on;
gzip_proxied any;
gzip_types
text/plain
text/css
text/xml
application/json
application/javascript
application/xml
image/svg+xml;
}gzip_comp_levelruns from 1 (fast, larger output) to 9 (slow, smaller output). Levels above 5 or 6 cost much more CPU for very little extra saving.gzip_min_length 256;skips tiny responses, where the gzip header can outweigh the saving.gzip_vary on;addsVary: Accept-Encoding, so shared caches store compressed and uncompressed versions separately.gzip_proxied any;also compresses responses that come from an upstream. Without it, responses to requests that carry aViaheader are not compressed.gzip_typeslists the MIME types to compress.text/htmlis always included, so do not list it.
Test compression with curl. Ask for gzip and look at the response headers:
curl -s -o /dev/null -D - -H "Accept-Encoding: gzip" http://localhost/style.cssYou should see Content-Encoding: gzip and Vary: Accept-Encoding. If the header is missing, check that the file's MIME type appears in gzip_types and that the file is larger than gzip_min_length.
Caching
Nginx supports three kinds of caching that serve different purposes: browser caching, file descriptor caching, and proxy caching. Each one removes work at a different place.
Browser caching for static files
You can tell browsers and shared caches how long they may keep a file. This removes repeat requests entirely. Use long lifetimes only for files whose names change when their content changes, such as app.3f9a1c.js.
location ~* \.(css|js|woff2|png|jpg|svg)$ {
expires 30d;
add_header Cache-Control "public";
}The expires 30d; directive sets both Expires and Cache-Control: max-age. Be careful with this: add_header in a location replaces any add_header lines inherited from outer contexts. Repeat any security headers you still need inside the same block.
Caching file metadata
open_file_cache keeps open file descriptors and file metadata in memory, so Nginx does not call open() and stat() for every request to a hot file. It is mainly useful on servers with many small static files.
open_file_cache max=2000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;If you deploy by overwriting files in place, a stale entry can serve old content for up to open_file_cache_valid seconds. Deploying into a new directory and switching a symlink avoids this.
Proxy caching
A proxy cache stores responses from your application on disk, so repeated requests for the same URL are answered by Nginx without touching the application. The cache is defined once in the http context and then enabled per location.
proxy_cache_path /var/cache/nginx/app
levels=1:2
keys_zone=app_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_lock on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
}The parts of proxy_cache_path work as follows:
keys_zone=app_cache:10mnames the shared memory zone that holds cache keys and metadata. One megabyte holds roughly 8,000 keys.max_size=1gcaps disk use. Nginx's cache manager removes the least recently used entries when the cap is reached.inactive=60mremoves entries that nobody has requested for 60 minutes, even if they are still fresh.levels=1:2spreads cache files across subdirectories so no single directory grows huge.
In the server block, proxy_cache_valid sets how long responses with each status code stay fresh. proxy_cache_lock on; lets only one request fill a missing entry while others wait, which protects the application from a burst of identical misses. proxy_cache_use_stale serves an old copy when the application fails, which keeps the site up during short outages.
The X-Cache-Status header shows what happened. The common values are MISS, HIT, EXPIRED, STALE, UPDATING, and BYPASS.
flowchart TD
A[Client request] --> B{Entry in cache and fresh?}
B -- Yes --> C[Serve from cache: HIT]
B -- No --> D[Forward to application]
D --> E{Response cacheable?}
E -- Yes --> F[Store on disk, then serve: MISS]
E -- No --> G[Serve without storing]The default cache key is $scheme$proxy_host$request_uri. Only GET and HEAD responses are cached. By default Nginx also refuses to cache a response that has a Set-Cookie header or a Cache-Control value of private, no-cache, or no-store. That protects you from sharing one user's page with another. Do not override this with proxy_ignore_headers unless you have confirmed that the response is the same for every user.
Skip the cache for requests that carry credentials:
proxy_cache_bypass $http_authorization $cookie_session;
proxy_no_cache $http_authorization $cookie_session;proxy_cache_bypass makes Nginx fetch a fresh copy for those requests. proxy_no_cache stops the response from being stored. You usually need both. The cookie name session is an example, so use the name your application sets.
The cache directory must be writable by the Nginx worker user. On Debian and Ubuntu the package creates /var/cache/nginx, but you may need sudo mkdir -p /var/cache/nginx/app && sudo chown www-data:www-data /var/cache/nginx/app for a new subdirectory. Test twice with curl and watch the header change:
curl -s -o /dev/null -D - http://app.example.com/ | grep -i x-cache-status
curl -s -o /dev/null -D - http://app.example.com/ | grep -i x-cache-statusThe first request should print MISS and the second HIT. If you always see MISS, look for Set-Cookie or restrictive Cache-Control headers in the upstream response.
A safe tuning routine
- Record a baseline with a load tool or your own traffic, covering response time, CPU use, and error log counts.
- Change one group of settings.
- Run
sudo nginx -t && sudo systemctl reload nginx. - Repeat the measurement and keep the change only if the numbers improve.
Exercise
A server has 8 CPU cores and acts as a reverse proxy. You set worker_processes auto; and worker_connections 2048;. About how many clients can it serve at the same time, and which second directive should you raise so workers can actually open that many connections?
Show answer
Total connections are 8 × 2048 = 16,384. A proxy uses two connections per client (client side and upstream side), so about 8,192 clients. Raise worker_rlimit_nofile, to at least twice worker_connections (for example 4096 or more), because each connection and each served file needs a file descriptor.
Exercise
You enabled proxy_cache app_cache; but X-Cache-Status always shows MISS. The application sends Set-Cookie on every response. Why does this happen, and what is the safe fix?
Show answer
By default Nginx does not cache responses that contain Set-Cookie, because the response may be specific to one user. The safe fix is to change the application so it does not send cookies on cacheable public pages, or to cache only locations that never set cookies. Using proxy_ignore_headers Set-Cookie is only safe once you have confirmed the response is identical for all users.