Validate HTTP upload boundaries: body limits, temporary storage and buffering

Validate HTTP upload boundaries: body limits, temporary storage and buffering

Validate HTTP upload boundaries: body limits, temporary storage and buffering

When small uploads succeed but large build artifacts or collected files fail to upload, bandwidth is not necessarily the cause. A request may be rejected at the proxy, exhaust the temporary storage for request bodies, or reach the backend without receiving a timely response. Start troubleshooting with reproducible requests around the size boundary, then identify which layer rejects them rather than increasing every limit at once.

1. Define the test scope and success criteria

This test is intended for Debian 12 and requires Nginx, Python 3 and curl to be installed beforehand. All listeners bind only to the loopback address, and all commands run on the same physical server. Run the isolated instances under a regular user account without changing the existing system Nginx configuration or reloading production services. The example ports are chosen for this test, not deployment parameters.

There are two success criteria: requests at or below the ingress limit return the number of bytes actually read; requests above the limit return 413, with logs showing which layer rejected them. The test only counts uploaded data and does not store it, so it cannot establish whether a real application's disk writes, validation or database commits have succeeded.

A request body limit is a resource boundary, not a file security check. The application must separately validate file extensions, content types, decompressed sizes and authorization for the operation.

First, use ss -ltn to confirm that 18080 and 18081 are not in use. Run the following commands in the same terminal so that the working-directory variable remains available:

umask 077
LAB=$(mktemp -d /tmp/upload-lab.XXXXXX)
mkdir "$LAB/body"
printf '%s\n' "$LAB"
df -h "$LAB"
df -i "$LAB"

Stop the test if the temporary directory has insufficient space. Do not deliberately fill a production data disk, and do not send test requests to a public production endpoint.

2. Create a receiver with its own limit

The backend should enforce its own read limit rather than relying entirely on the proxy in front of it. Save the following as $LAB/receiver.py. It accepts only POST requests with a valid Content-Length, caps reads at 16 MiB and sets a timeout for socket reads.

from http.server import BaseHTTPRequestHandler, HTTPServer

class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.headers.get("Content-Length", "")
        if self.headers.get("Transfer-Encoding") is not None:
            self.send_error(400)
            return
        if not raw.isascii() or not raw.isdecimal():
            self.send_error(411)
            return
        remaining = int(raw)
        if remaining > 16 * 1024 * 1024:
            self.send_error(413)
            return
        total = 0
        self.connection.settimeout(10)
        try:
            while remaining:
                block = self.rfile.read(min(65536, remaining))
                if not block:
                    self.send_error(400)
                    return
                total += len(block)
                remaining -= len(block)
        except TimeoutError:
            self.send_error(408)
            return
        body = f"received={total}\n".encode()
        self.send_response(200)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

HTTPServer(("127.0.0.1", 18081), Receiver).serve_forever()

This receiver is a single-threaded test tool, not a production upload service. It rejects requests that use transfer encoding and implements no authentication, concurrency control or file storage. These restrictions deliberately narrow the test scope so that incomplete protocol coverage is not mistaken for a production-ready solution.

3. Fix the proxy buffering and temporary directory settings

Save the following configuration as $LAB/nginx.conf. A separate prefix keeps logs, the PID file and temporary request body files inside the test directory. The 8m limit applies to the entire HTTP request body. If an application uses multipart forms, boundaries and form fields count toward that limit, so it is not equivalent to the attachment's net size.

worker_processes 1;
pid nginx.pid;
error_log error.log info;

events {
    worker_connections 128;
}

http {
    log_format upload '$request status=$status upstream=$upstream_status '
                      'length=$request_length time=$request_time';
    access_log access.log upload;
    client_body_temp_path body;

    server {
        listen 127.0.0.1:18080;
        client_max_body_size 8m;
        client_body_buffer_size 16k;
        client_body_timeout 10s;

        location / {
            proxy_pass http://127.0.0.1:18081;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_request_buffering on;
            proxy_read_timeout 15s;
        }
    }
}

client_body_buffer_size is not an upload size limit. When the request body exceeds the memory buffer, Nginx may write all or part of it to a temporary file. Check that the directory is writable and that its filesystem has sufficient free bytes and inodes.

client_body_timeout limits the wait between successive read operations, not the total time allowed to complete an upload. Likewise, proxy_read_timeout is not an overall budget for application processing. If an overall deadline is required, implement it separately in the application or at the task entry point.

4. Identify the rejecting layer with boundary-sized requests

Check the configuration syntax before starting. If startup fails, read the test logs rather than stopping other services to free up ports.

python3 "$LAB/receiver.py" >"$LAB/backend.log" 2>&1 &
BACKEND_PID=$!

nginx -p "$LAB/" -c nginx.conf -t
nginx -p "$LAB/" -c nginx.conf

for bytes in 1048576 8388608 8388609; do
    truncate -s "$bytes" "$LAB/input.bin"
    curl --silent --show-error --max-time 30 \
        -H 'Expect:' \
        --data-binary @"$LAB/input.bin" \
        -w 'status=%{http_code}\n' \
        http://127.0.0.1:18080/
done

cat "$LAB/access.log"
cat "$LAB/backend.log"

The expected results are 200 for both 1 MiB and exactly 8 MiB, with response counts of 1048576 and 8388608 respectively. The sample that exceeds the limit by one byte should return 413. These requests use raw bodies so that form encoding does not affect the boundary.

An oversized request with a known length can be rejected before its body is read. In that case, the upstream status in the access log is usually -, and the backend has no corresponding entry. If the upstream status is 413, investigate the backend limits next. request_length includes the request line and headers, and a rejection may occur before the entire body has been read. It must not be treated as the file's byte count.

This request set does not cover chunked uploads, slow clients or concurrent uploads. These samples establish only the size boundary for requests with an explicitly specified length.

5. Retest with different buffering and clean up

Once the baseline is confirmed, change only proxy_request_buffering on to off. Check the syntax, send a reload signal to the test instance, then repeat the same request set. Keep the ingress size limit unchanged. Disabling buffering changes when data is forwarded; it does not remove the size constraint. The upstream may occupy a connection sooner and may receive part of the body earlier.

Enabling buffering generally helps decouple slow clients from backend reads, but increases temporary storage requirements. Disabling buffering suits backends that can read continuously and handle failures or interrupted uploads. Base the choice on request size, concurrency and application behavior; “it is faster with buffering off” is not a substitute for acceptance testing.

Temporary files may disappear quickly, so an empty directory does not prove that no disk writes occurred. Capacity planning should account for the total volume of requests buffered simultaneously, separately from the space needed for final application files, copies and decompressed data.

When finished, stop both test processes. Confirm that the listeners are gone before deleting the directory:

nginx -p "$LAB/" -c nginx.conf -s quit
kill "$BACKEND_PID"
wait "$BACKEND_PID" 2>/dev/null || true
ss -ltn

Keep the configuration, boundary sample sizes, status codes and logs from both sides as a record for repeat testing. Production changes should also verify the conditions for actual storage completion and check whether client disconnects leave incomplete files behind. A successful proxy response does not automatically mean the application data has been reliably delivered.

Frequently asked questions

Does disabling request buffering bypass the upload limit?

No. proxy_request_buffering controls when the request body is forwarded. client_max_body_size still limits incoming bodies, and the backend needs its own read limit.

Does a 413 response mean the backend received the file?

Not necessarily. Nginx can reject an oversized request early using Content-Length. Check both proxy access logs and backend logs to establish whether it reached the backend.

AMD EPYC 7543P Dedicated Server

From $471.8/month

Configure an Mbps Dedicated Server View Mbps rental pricing

Clear paths to configuration and access

Rental pricing lists the hardware and options, while the connection guide explains SSH and RDP access after delivery.