Fix Unrestricted Resource Consumption in FastAPI
Unrestricted resource consumption in FastAPI occurs when endpoints allow attackers to exhaust CPU, memory, or disk space. This is typically achieved through massive payloads, high-frequency requests, or complex operations without constraints. To harden your API, you must enforce request body size limits and implement granular rate limiting at the application or gateway level.
The Vulnerable Pattern
from fastapi import FastAPI, Requestapp = FastAPI()
@app.post(“/process-data”) async def process_data(request: Request): # VULNERABILITY: request.body() reads the entire payload into RAM. # An attacker can send a 10GB stream to crash the worker (OOM). data = await request.body() return {“received_bytes”: len(data)}
The Secure Implementation
The secure implementation mitigates DoS vectors using three layers: 1. Rate Limiting: Uses 'slowapi' to prevent brute-force or flooding from a single IP. 2. Header Validation: Rejects large requests early based on 'Content-Length'. 3. Iterative Streaming: Reads the request body in chunks, enforcing a strict size threshold during the stream. This prevents the application from buffering massive payloads into memory, effectively neutralizing memory-exhaustion attacks.
from fastapi import FastAPI, Request, HTTPException, status
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
MAX_PAYLOAD_SIZE = 1024 * 1024 # 1MB limit
@app.post(“/process-data”)
@limiter.limit(“10/minute”)
async def process_data(request: Request):
# Check Content-Length header before processing
content_length = request.headers.get(‘content-length’)
if content_length and int(content_length) > MAX_PAYLOAD_SIZE:
raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=“Payload too large”)
# Stream chunks to prevent memory spikes
total_size = 0
chunks = []
async for chunk in request.stream():
total_size += len(chunk)
if total_size > MAX_PAYLOAD_SIZE:
raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="Payload too large")
chunks.append(chunk)
return {"status": "processed"}</code></pre>
Your FastAPI API
might be exposed to Unrestricted Resource Consumption
74% of FastAPI apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.