Skip to content

Request Size Limiting for APIs — Complete DoS Prevention Guide

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Request Size Limiting for APIs. We cover key concepts, practical examples, and best practices to help you master this topic.

Request size limiting restricts the maximum size of incoming requests and outgoing responses. Without limits, attackers can send oversized payloads to exhaust memory, CPU, and bandwidth.

What You'll Learn

You'll learn how to implement request size limits at the application, server, and gateway level to prevent resource exhaustion.

Why It Matters

An attacker sending a 1GB JSON payload to a 100MB RAM server will crash the service. Request size limits are a simple, effective defense against resource exhaustion attacks.

Real-World Use

A file upload API limits requests to 10MB. An attacker attempts to upload a 100MB ZIP bomb that expands to 10GB. The API rejects it before processing, preventing disk and memory exhaustion.

flowchart LR
    A[Incoming Request] --> B{Check Content-Length}
    B -->|> Limit| C[413 Payload Too Large]
    B -->|< Limit| D{Check After Decompression}
    D -->|> Limit| C
    D -->|< Limit| E[Process Request]
    C --> F[Log Incident]
    F --> G[Notify Security Team]

Teacher's Mindset

Request size limiting is like a mailbox slot. A slot prevents someone from stuffing a mattress through your mail slot. Your API needs similar physical limits for its inputs.

Implementing Size Limits

from flask import Flask, request, jsonify
from werkzeug.exceptions import RequestEntityTooLarge

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024  # 10MB

@app.errorhandler(RequestEntityTooLarge)
def handle_too_large(error):
    return jsonify({
        "error": "Request too large",
        "max_size_mb": app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
    }), 413

@app.route("/api/upload", methods=["POST"])
def upload_file():
    file = request.files.get("file")
    if file and file.content_length > app.config["MAX_CONTENT_LENGTH"]:
        return jsonify({"error": "File too large"}), 413
    return jsonify({"message": "Upload received"})
# Per-endpoint size limits
from functools import wraps

def limit_request_size(max_bytes):
    def decorator(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            content_length = request.content_length or 0
            if content_length > max_bytes:
                return jsonify({
                    "error": "Request too large",
                    "limit_mb": max_bytes // (1024 * 1024)
                }), 413
            return f(*args, **kwargs)
        return decorated
    return decorator

@app.route("/api/small-payload", methods=["POST"])
@limit_request_size(1024)
def small_payload():
    return jsonify({"message": "Small payload processed"})
# NGINX request size limits
server {
    client_max_body_size 10M;
    client_body_buffer_size 128k;
    client_body_timeout 30s;

    location /api/upload {
        client_max_body_size 50M;
    }

    location /api/query {
        client_max_body_size 1K;
    }
}

Common Mistakes

Mistake Why It's Wrong Fix
No size limit on request body Attackers send arbitrary large payloads Set MAX_CONTENT_LENGTH based on endpoint needs
No limit on response size Large responses consume bandwidth Implement pagination and response size limits
Ignoring compressed payload size Compression bombs expand after decompression Limit both compressed and uncompressed size
Inconsistent limits across layers Gateway allows but application rejects Coordinate limits across all layers
No limit per user or endpoint One user can exhaust resources for all Implement per-user request size limits

Practice Questions

  1. Why is request size limiting important for security?
  2. What is a ZIP bomb or compression bomb?
  3. How do you limit request size in NGINX?
  4. Why should you limit response size?
  5. What happens when a request exceeds the size limit?

Challenge

Implement a Flask API with global and per-endpoint size limits. Create endpoints for small JSON payloads (1KB), medium (1MB), and file uploads (10MB). Test with oversized requests.

FAQ

What is the maximum request size I should allow?

Depends on your use case. JSON APIs: 1-10MB. File uploads: 10-100MB. Video: 1-10GB. Each endpoint should have its own appropriate limit.

Does request size limiting prevent DDoS?

It mitigates resource exhaustion attacks but does not stop volumetric DDoS. Use WAF and DDoS protection for network-level attacks.

How do I set limits for GraphQL APIs?

GraphQL allows complex nested queries. In addition to size limits, implement query depth limiting and cost analysis to prevent abusive queries.

Should I limit response size too?

Yes. Large responses can exhaust server memory and network bandwidth. Implement pagination, field selection, and response size limits.

What is the 413 status code?

413 Payload Too Large indicates the request entity is larger than the server is willing or able to process.

Mini Project

Build a file upload API with tiered limits: 1KB for metadata endpoints, 1MB for JSON data, 10MB for document uploads. Implement compression bomb detection by checking decompressed size.

What's Next

Learn about IP whitelisting to restrict API access to trusted network sources.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro