Limit Upload Sizes and Request Rates
🎯 Introduction
Suppose a notes website supports attachment uploads and note queries. A single attachment of several GB can consume substantial bandwidth and storage. Even queries carrying almost no data can overwhelm a backend when thousands arrive in a short period.
- Request body size limits control how much data one request may carry. The first experiment triggers
413with an oversized request. - Request rate limits control how frequently requests from the same source may be accepted. The second experiment triggers
429with rapid requests.
For a manually created setup, run cd "$HOME/nginx-course" in Bash. With the download, enter the extracted directory in Bash. The package already includes this article's size and rate rules, so inspect the existing configuration. You still need to create the temporary file and location for the first experiment.
🧱 Limit the Data in One Request
The request body contains data sent with a request, such as uploaded files or submitted form fields. Set the following inside server in conf/servers/site.conf. If an earlier exercise set it to 2m, change it to 1m.
client_max_body_size 1m;
1m is the Nginx default and means 1 MiB (1,048,576 bytes). Setting it explicitly makes it easy to change during the exercise. Nginx returns 413 Content Too Large when the body exceeds this limit. Older documentation calls this Payload Too Large, and the response line in this experiment may say Request Entity Too Large. Use the numeric 413 as the reference. Nginx size limit documentation · RFC 9110
This experiment only checks whether Nginx rejects oversized requests, so a static file URL is sufficient. Nginx can determine this POST body's size from Content-Length and return 413 before static file handling. Add this temporary location inside the same server; try_files $uri =404 looks for the corresponding file and returns 404 if absent.
location = /body-check.txt {
try_files $uri =404;
}
Create the static test file in the course directory, then use dd to generate 2 MiB of data for the request body.
mkdir -p temp
printf 'body check\n' > html/body-check.txt
dd if=/dev/zero of=temp/large.bin bs=1048576 count=2
For a manual setup, run ngx -t && ngx -s reload. For the download, run sh ./ngx -t && sh ./ngx -s reload. Use the same check-and-reload command after every subsequent configuration change. Send the request after reloading.
curl -i -H 'Expect:' --data-binary @temp/large.bin http://127.0.0.1:8080/body-check.txt
--data-binary @temp/large.bin puts the file's contents in the POST body. -H 'Expect:' removes the wait before sending the body. Expect 413, because 2 MiB exceeds 1 MiB. Keep the temporary location and files for the comparison at the end.
🧰 Apply Per-Source Rate Limits to the API
Suppose each IP may average two requests per second. When a new request arrives, Nginx considers how closely earlier requests from that IP arrived and how much time has passed, then decides whether to accept it. Different workers may handle requests from the same IP, so they need shared rate-limit records.
Define those records and the rate rule inside http in conf/nginx.conf.
limit_req_zone $binary_remote_addr zone=api_rate:10m rate=2r/s;
$binary_remote_addridentifies sources by the client IP connected to Nginx, tracking each IP separately.zone=api_rate:10mnames the shared memory zoneapi_rateand allocates 10 MiB for per-IP rate-limit records.rate=2r/ssets a long-term rate of two requests per second per IP, allowing roughly one excess request to drain every half second. State changes with elapsed time; it does not reset on whole-second boundaries.
The configuration above defines the rule. Apply it inside the existing location ^~ /api/ block in conf/servers/site.conf.
limit_req zone=api_rate burst=4 nodelay;
limit_req_status 429;
burst=4 allows four additional burst slots per IP. Suppose an IP has no accumulated excess requests and sends eight almost simultaneously. The first is accepted normally, the second through fifth occupy burst slots, and the sixth through eighth are rejected. Actual results depend on request spacing and the IP's existing rate-limit state.
Without nodelay, requests occupying burst slots queue and are released roughly one every half second. With nodelay, they may be forwarded immediately, but their slots still become available gradually at 2r/s. Thus five requests can pass at once while the long-term rate remains 2r/s. Nginx burst rate limiting example
Nginx returns 503 for rate-limit rejections by default. limit_req_status 429 changes that to 429 Too Many Requests. Nginx rate limiting module documentation
🧪 Verify Rate Limiting
Check and reload, wait a few seconds for occupied burst slots to become available, then send 20 successive requests to the local notes API. Run this in Bash: {1..20} expands to 1 through 20, while sh may execute the loop only once.
for n in {1..20}; do
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/api/notes
done
-w '%{http_code}\n' makes curl print one status code per request. The experiment produces two kinds of result.
200means the request passed the rate limit, Nginx forwarded it to the mock backend, and the backend responded successfully. The entry point's access log records an upstream address andus=200.429means requests from the same IP arrived too quickly and filled the burst allowance. Nginx rejected the request before forwarding it. The entry point's access log showsupstream=- us=-, and the error log recordslimiting requests.
The counts vary with actual request spacing. If you see only 200, confirm that the directives are active, then check whether requests arrive rapidly enough. If you see only 429, wait a few seconds and retry.
Users sharing one public IP also share this rate allowance. If another proxy sits in front of Nginx, these rules may count all users behind it under that proxy's IP.
❓ Questions and Answers
Is a frontend file size limit of 1 MiB enough?
No. Visitors can bypass the page and send requests directly. Both the server and application need appropriate limits.
🧪 Exercise
Temporarily change client_max_body_size to 3m, check and reload, then send the same 2 MiB request. Expect 405 Method Not Allowed: the request passed the size check, then the static file handler rejected POST. Compare the results and identify the stage that produces 413 versus 405.
Afterward, restore the limit to 1m, remove the temporary location = /body-check.txt block, and check and reload. Then delete the two temporary files from the course directory.
rm html/body-check.txt temp/large.bin
