bodyLimit: Adjusting maximum request body size for cost‑effective Fastify deployments
0 reputation · 09 Nov 2022, 09:06 UTC
0 reputation · 09 Nov 2022, 09:06 UTC
Reduce memory overhead on a low‑traffic Fastify server by limiting the size of incoming request bodies. A stricter bodyLimit can prevent large payloads from consuming RAM, but it must be tuned to avoid breaking legitimate traffic.
bodyLimit option is evaluated after decompression when fastify-compress is enabled, so the effective limit may differ for gzipped requests.onError hooks run, which may affect custom error handling or caching strategies.bodyLimit, potentially causing client errors that are hard to diagnose.bodyLimit value for a typical low‑traffic Fastify deployment that still accommodates occasional larger payloads?bodyLimit interact with fastify-compress when clients send gzip‑compressed bodies, and should the limit be adjusted accordingly?bodyLimit bypass application onError hooks, and how might this affect caching or logging of oversized requests?33275 reputation · 09 Nov 2022, 10:25 UTC
1. Recommended bodyLimit value
For a low‑traffic Fastify server that occasionally receives larger payloads, a pragmatic bodyLimit is 5 MB (5 * 1024 * 1024 bytes). This value keeps memory usage modest while still accommodating most legitimate uploads that exceed the default 1 MB.
2. Interaction with fastify‑compress
When fastify-compress is enabled, Fastify decompresses the request body before applying bodyLimit. Therefore the limit applies to the *uncompressed* size. A client that sends a 6 MB payload compressed to 1 MB will still be rejected because the decompressed size (6 MB) exceeds the 5 MB limit.
3. 413 bypasses onError hooks
If a request exceeds bodyLimit, Fastify immediately returns a 413 Payload Too Large response. This happens before any onError hook runs, so custom error handling, caching, or logging logic placed in onError will not see the request. To capture these events you need a global 413 handler or middleware that runs earlier.
Set the limit in the Fastify instance:
const fastify = require('fastify')({ bodyLimit: 5 * 1024 * 1024 })Register a global 413 handler if you need to log or cache these requests:
fastify.setErrorHandler((error, request, reply) => {
if (error.statusCode === 413) {
// custom logging or caching logic
}
reply.send(error)
})Test with plain and gzipped bodies to confirm behavior:
bodyLimit, leading to client errors that are hard to trace.onError, any middleware that relies on that hook will miss oversized requests unless you add a dedicated handler.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.