Fix API Rate Limit Exhaustion in Flask
API Rate Limit Exhaustion (CWE-770) occurs when an endpoint lacks throttling, allowing attackers to perform Denial of Service (DoS), brute-force credentials, or scrape data at scale. In Flask, the default behavior is to process every incoming request until the worker pool is saturated. We solve this by implementing a middleware layer that tracks request frequency per client identity.
The Vulnerable Pattern
from flask import Flask, jsonifyapp = Flask(name)
@app.route(‘/api/v1/heavy-task’, methods=[‘GET’]) def heavy_task(): # VULNERABLE: No rate limiting. # An attacker can flood this endpoint to exhaust CPU/DB connections. return jsonify({‘status’: ‘processed’})
if name == ‘main’: app.run()
The Secure Implementation
The secure implementation utilizes 'Flask-Limiter' to wrap the application and specific routes. It identifies clients via 'get_remote_address' (IP-based) and enforces a '5 per minute' threshold on the sensitive endpoint. When the threshold is breached, the middleware intercepts the request and returns a HTTP 429 (Too Many Requests) status code, preventing the expensive business logic from executing. In production, 'storage_uri' should point to a Redis instance to maintain state across multiple Gunicorn/UWSGI workers.
from flask import Flask, jsonify from flask_limiter import Limiter from flask_limiter.util import get_remote_addressapp = Flask(name)
Secure: Initialize limiter with a memory or Redis backend
limiter = Limiter( get_remote_address, app=app, default_limits=[“200 per day”, “50 per hour”], storage_uri=“memory://”, )
@app.route(‘/api/v1/heavy-task’, methods=[‘GET’]) @limiter.limit(“5 per minute”) # Strict limit for expensive operations def heavy_task(): return jsonify({‘status’: ‘processed’})
@app.errorhandler(429) def ratelimit_handler(e): return jsonify(error=“ratelimit exceeded”, message=str(e.description)), 429
if name == ‘main’: app.run()
Your Flask API
might be exposed to API Rate Limit Exhaustion
74% of Flask 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.