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
Related rules
- ARC-34 Cap every collection that grows with use in Clean code and architecture
- ARC-82 Limit how deep code recurses on input in Clean code and architecture
- API-12 Accept only fields you know in API design
- MED-1 Define each kind of upload once in Files and media
- API-73 Limit the connections and messages of each client in API design
- API-22 Cap the page size in API design
- API-96 Limit the depth and cost of every GraphQL query in API design
- APS-51 Keep regular expressions from stalling the server in Application security
- DAT-13 Page through long lists by key in Data and databases
- OPS-34 Set limits on memory and processes in Operations and observability
- AIF-43 Keep every request inside a token budget in AI features
- AGT-78 Limit bulk reads and scraping in Agents as users
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.