How to Use tcp_nodelay in Nginx for Better TCP Performance
To use
tcp_nodelay in Nginx, add the directive tcp_nodelay on; inside the server or location block of your configuration. This disables Nagle's algorithm, allowing small packets to be sent immediately, which reduces latency for TCP connections.Syntax
The tcp_nodelay directive controls whether Nginx disables Nagle's algorithm on TCP sockets. It accepts on or off values.
tcp_nodelay on;- disables Nagle's algorithm, sending packets immediately.tcp_nodelay off;- enables Nagle's algorithm, buffering small packets.
This directive is typically placed inside server or location blocks for HTTP or stream modules.
nginx
server {
listen 80;
tcp_nodelay on;
location / {
proxy_pass http://backend;
}
}Example
This example shows how to enable tcp_nodelay in an Nginx HTTP server block to reduce latency by sending TCP packets immediately without delay.
nginx
http {
upstream backend {
server 127.0.0.1:8080;
}
server {
listen 80;
tcp_nodelay on;
location / {
proxy_pass http://backend;
}
}
}Common Pitfalls
Common mistakes when using tcp_nodelay include:
- Placing
tcp_nodelayoutside of valid contexts likeserverorlocationblocks, causing configuration errors. - Forgetting to reload or restart Nginx after changing the configuration, so changes don't take effect.
- Using
tcp_nodelayunnecessarily on connections where latency is not critical, which may increase network overhead.
Always test your configuration with nginx -t before reloading.
nginx
## Wrong placement example (will cause error):
server {
tcp_nodelay on;
listen 80;
}
## Correct placement:
server {
listen 80;
tcp_nodelay on;
}Output
nginx: [emerg] "tcp_nodelay" directive is not allowed here in /etc/nginx/nginx.conf:2
Quick Reference
tcp_nodelay directive summary:
| Directive | Context | Default | Description |
|---|---|---|---|
| tcp_nodelay | server, location | off | Disables Nagle's algorithm to send TCP packets immediately |
Key Takeaways
Enable tcp_nodelay with 'tcp_nodelay on;' inside server or location blocks to reduce TCP latency.
Place tcp_nodelay only in valid contexts like server or location to avoid configuration errors.
Reload Nginx after changes using 'nginx -s reload' to apply tcp_nodelay settings.
Use tcp_nodelay when low latency is important, such as real-time applications.
Test configuration syntax with 'nginx -t' before restarting Nginx.