GuardAPI Logo
GuardAPI

Fix Lack of Resources & Rate Limiting in FastAPI

Unbounded endpoints are a prime target for DoS and resource exhaustion. Without rate limiting, an attacker can flood your FastAPI workers, saturate DB connection pools, and spike cloud costs. As an AppSec researcher, I look for these 'open doors' to knock over services with simple loop scripts. We must implement throttling to ensure availability and protect the underlying infrastructure.

The Vulnerable Pattern

from fastapi import FastAPI

app = FastAPI()

@app.get(“/api/heavy-resource”) async def get_data(): # Vulnerable: No throttling. # An attacker can call this 10,000 times/sec to exhaust server resources. return {“data”: “some_expensive_query_result”}

The Secure Implementation

To mitigate resource exhaustion, we use the 'slowapi' library—a FastAPI port of Flask-Limiter. We initialize a 'Limiter' instance using 'get_remote_address' as the key. By decorating the endpoint with '@limiter.limit("5/minute")', we enforce a strict threshold. When the limit is hit, the application automatically returns a 429 'Too Many Requests' response. In a distributed environment, the limiter should be backed by Redis to synchronize state across multiple worker nodes.

from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

Initialize limiter using client IP

limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get(“/api/heavy-resource”) @limiter.limit(“5/minute”) async def get_data(request: Request): # Secure: Throttled to 5 requests per minute per IP. return {“data”: “protected_resource”}

System Alert • ID: 3902
Target: FastAPI API
Potential Vulnerability

Your FastAPI API might be exposed to Lack of Resources & Rate Limiting

74% of FastAPI apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.