Agent Wranglers

API-93Required

Cap the size of every request body

Set a byte limit on the body of every endpoint, such as 1 MB for JSON. Stop reading at the limit and answer 413 Content Too Large.

How to do it

A server that reads a body to the end before it checks the size can be stalled with one large request. Set the limit in the web server or framework, so it stops reading early. Count bytes after decompression too, since a small gzip body can expand to gigabytes. Give file uploads their own larger limit, set per kind as Define each kind of upload once says, or send them straight to storage. Name each limit in the contract. Message limits on live connections are in Limit the connections and messages of each client. The same ceiling idea covers every answer and every costly input. Cap list sizes as Cap the page size says. Cap GraphQL queries as Limit the depth and cost of every GraphQL query says. Cap pattern matching as Keep regular expressions from stalling the server says.

Examples

JavaScript example

import express from 'express';

const JSON_BODY_LIMIT = '1mb';

const app = express();
app.use(express.json({ limit: JSON_BODY_LIMIT }));

nginx example

server {
  server_name api.example.com;
  client_max_body_size 1m;
}

Go example

const maxBodyBytes = 1 << 20

func limitBody(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
		next.ServeHTTP(w, r)
	})
}

How to check

A contract test sends a body 1 byte over the limit to every write endpoint. Each answers 413 with problem details, and no row changes. A gzip body that expands past the limit gets 413 too.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/requests-and-responses/request-body-limit">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.