How-To Guide

How to Handle Large Request Bodies Without Memory Blowup

Stream large uploads and payloads safely: enforce size limits early, spool to disk, apply timeouts, and avoid buffering the whole body in memory.

On this page

  1. Introduction
  2. Reject oversized requests early
  3. Stream instead of buffering
  4. Bound time and concurrency
  5. Test the limits without running out of memory
  6. Common pitfalls
  7. Conclusion

Introduction

A request body that must be read before it can be handled invites a memory problem. The natural implementation collects the body into a buffer, parses it, and responds. That works until someone uploads a gigabyte, or sends many concurrent half-gigabyte uploads, and the process runs out of heap. Because a single request can crash a service, body handling is a robustness concern, not just a parsing concern. The fix is to stream, to cap, and to fail early.

This tutorial reworks a request handler to stream large bodies safely. It covers enforcing a size limit while reading rather than trusting the declared length, applying backpressure instead of accumulating bytes, bounding time and concurrency, and testing that oversized and unbounded bodies are rejected without exhausting memory. The examples use Node.js streams, but the approach is the same in any runtime with a streaming API.

Reject oversized requests early

If the request declares a Content-Length above your cap, reject immediately with 413 Content Too Large before reading the body. This is the cheap fast path and it avoids receiving bytes you will discard. But a client can lie about the length, or use chunked transfer encoding with no length at all, so the declared check is not sufficient on its own. Always enforce a hard cap while reading, counting bytes as they arrive and aborting the moment the total exceeds the limit.

Choose the cap from the largest legitimate payload, not from what happens to fit. A generous cap is still a cap. Return 413 with a clear message and, for uploads, the maximum allowed size so a client can correct the request. Abort the stream and destroy the socket when the limit is exceeded; leaving the stream open lets a client keep sending after the rejection.

function capBytes(stream, maxBytes) {
  let seen = 0;
  stream.on('data', (chunk) => {
    seen += chunk.length;
    if (seen > maxBytes) stream.destroy(new Error('body too large'));
  });
  return () => seen;
}

function rejectIfDeclaredTooLarge(req, res, maxBytes) {
  const declared = Number(req.headers['content-length']);
  if (Number.isFinite(declared) && declared > maxBytes) {
    res.writeHead(413, { 'content-type': 'text/plain' });
    res.end('Payload too large; maximum is ' + maxBytes + ' bytes');
    return true;
  }
  return false;
}

Stream instead of buffering

The core technique is to never hold the whole body. Read it as a stream and write it onward, to a file, an object store, or a parser, so memory use stays proportional to the chunk size rather than the body size. Node.js streams apply backpressure automatically when piped: if the destination is slower than the source, the source is paused. Respect that signal; ignoring it by buffering in a data listener reintroduces the memory problem you were trying to avoid.

For parsing structured bodies, use a streaming parser that emits events as it reads rather than a parser that expects a complete string. For writing, pipe to a stream you can abort. A streaming pipeline that fails midway can leave a partial file, so write to a temporary location and rename it atomically on success, or mark the object as incomplete until the final chunk arrives.

import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

async function receiveUpload(req, res, maxBytes) {
  if (rejectIfDeclaredTooLarge(req, res, maxBytes)) return;
  const count = capBytes(req, maxBytes);
  const tmp = 'uploads/' + Date.now() + '.part';
  try {
    await pipeline(req, createWriteStream(tmp));
    res.writeHead(201).end('stored ' + count() + ' bytes');
  } catch (err) {
    res.writeHead(err.message === 'body too large' ? 413 : 400).end(err.message);
  }
}

Bound time and concurrency

A large upload can also be slow, and a slow upload holds a connection and a stream open for a long time. Add a read timeout so a client that stops sending is disconnected, and count concurrent large uploads so a burst cannot exhaust connection slots or disk. Return 503 or 429 when the concurrency limit is reached, with a Retry-After hint, rather than accepting work you cannot finish.

Consider streaming directly to object storage rather than to local disk. This removes the local disk as a failure point and lets the client’s bytes flow to durable storage without passing through your heap or filesystem. If you must spool locally first, put it on a dedicated volume sized for the expected concurrency, and clean up partial files on failure so an abandoned upload does not consume space forever.

function limitConcurrency(max) {
  let active = 0;
  return (res) => {
    if (active >= max) {
      res.writeHead(503, { 'retry-after': '5' }).end('busy');
      return null;
    }
    active++;
    return () => { active--; };
  };
}

const acquireSlot = limitConcurrency(4);

Test the limits without running out of memory

Send a body larger than the cap with a correct Content-Length and assert 413 before the body is fully read. Send a chunked body with no Content-Length that exceeds the cap and assert 413, proving the streaming cap works. Run several oversized uploads in parallel and assert the process memory stays bounded and the server remains responsive. Finally, abort a slow upload and assert the partial file is cleaned up.

curl -s -o /dev/null -w '%{http_code}\n' -H 'content-length: 999999999' --data-binary @small.bin http://localhost:3000/upload
head -c 200000000 /dev/zero | curl -s -o /dev/null -w '%{http_code}\n' -X POST --data-binary @- http://localhost:3000/upload

Common pitfalls

Trusting the declared Content-Length, buffering the whole body in a data listener, having no read timeout, allowing unlimited concurrent large uploads, leaving partial files after a failure, and returning 500 instead of 413 are the recurring mistakes. The early declared check, the streaming cap, the timeout, the concurrency limiter, cleanup, and the right status code each address one.

Conclusion

Large bodies are a robustness problem solved by streaming and capping. Reject an oversized declared length immediately, enforce a hard cap while reading, stream to the destination with backpressure rather than buffering, bound time and concurrency, and clean up partial work. Self-check by sending a chunked body over the cap and asserting 413 and bounded memory. When the body never fully lands in the heap, a hostile upload is a slow request instead of a crash.

Sources: Node.js: Stream backpressure, MDN: 413 Content Too Large, RFC 9110: Content-Length.

FAQ

Why not just trust Content-Length?
A client can send a false Content-Length, or omit it entirely with chunked encoding. Only a hard cap enforced while reading the stream reliably protects the server, so check the declared length as a fast path but always count bytes as they arrive.
Is spooling to disk always better than memory?
No. Disk is slower and adds I/O, so for small bodies memory is fine. Choose based on the maximum expected size: bound memory for small payloads and spool the large ones, or stream large uploads straight to object storage without touching local disk.

Related Examples