SlideShare a Scribd company logo
10
Most read
11
Most read
14
Most read
Samuel Folasayo
Protect Your API from Abuse with Redis & FastAPI
technology for good
Joe Nyirenda
TechPrane
Advocacy | Consultancy | Enablement
Learning Objectives
● Understand the importance of rate limiting for API security
● Learn how to implement a rate limiter using FastAPI middleware
● Explore Redis as a real-time backend for managing request limits
● Master techniques for handling abusive API requests gracefully
Protecting APIs from DDoS Attacks
Definition: Distributed Denial of Service (DDoS) attacks flood an API with excessive
requests
Impact: Slower response times, downtime, or complete service unavailability
Why APIs are Targets: APIs are often public-facing and high-traffic points of entry
Visual: Illustration of a DDoS attack targeting an API
What is Rate Limiting?
Definition: Controlling the number of requests a client can make to an API within a
specified timeframe
Purpose: Prevent server overload and abusive behavior
Types of Rate Limiting:
○ Fixed Window
○ Sliding Window
○ Token Bucket
Why Rate Limiting is Essential
Protect API Resources: Prevent resource exhaustion
Improve User Experience: Ensure fair usage for all users
Enhance Security: Block malicious actors and bots
Rate Limiting: Fixed Window
Rate Limiting: Sliding Window
Rate Limiting: Token Bucket
Rate Limiting Vs Throttling
Controls the total number of
requests a client can make within
a specific timeframe
Focuses on long-term usage and
preventing abuse
Example: Allowing 100 requests
per hour per user
Once the limit is reached, all
subsequent requests are denied
(usually with a 429 Too Many
Requests response)
Enforces fairness and prevents
overuse of resources
Rate Limiting Implementation
Rate Limiting Vs Throttling
Regulates the rate of incoming requests
in real-time
Focuses on short-term burst control
and managing server load
Example: Limiting to 10 requests per
second per user
Temporarily blocks requests exceeding
the rate, but resumes when the rate
drops below the threshold
Prevents server overload and ensures
consistent performance
Throttling Implementation
Client-Side Throttling
Where? Implemented in the client application
How?
Limits the number of requests sent to the server
Uses libraries like Lodash for web apps or equivalent mechanisms in mobile apps
Commonly applied to user-triggered actions such as input fields or scrolling
Purpose: Reduces redundant server calls, especially in event-heavy applications
Example:
A search bar that waits for a user to stop typing before sending a request to the
server
Server-Side Throttling
Where? Implemented on server infrastructure
How?
Monitors and enforces rate limits on incoming requests
Tools like NGINX, HAProxy, or backend middleware (e.g., Django, Express.js) are used
Returns error codes such as 429 Too Many Requests when limits are exceeded
Purpose: Protects servers from overload or abuse due to high traffic volumes
Example:
An API that allows a maximum of 10 requests per second per user
Client vs. Server Throttling
Aspect Client-Side Throttling Server-Side Throttling
Location Client application Server Infrastructure
Purpose Optimize requests before
reaching server
Protect server resources
for overuse
Implementation Handled using frontend
logic or libraries
Handled using backend
tools or middleware
Implementation in FastAPI
Adding middleware for rate limiting
from fastapi import FastAPI, Request, HTTPException
from redis import Redis
app = FastAPI()
redis = Redis(host='localhost', port=6379)
@app.middleware("http")
async def rate_limiter(request: Request, call_next):
client_ip = request.client.host
key = f"rate_limit:{client_ip}"
count = redis.incr(key)
if count == 1:
redis.expire(key, 60) # Set expiration to 60
seconds
if count > 10:
raise HTTPException(status_code=429,
detail="Too many requests")
response = await call_next(request)
return response
Middleware processes each request
Redis tracks request counts per client
Limit set to 10 requests per minute
Using Redis for Real-time Rate Limiting
Why Redis?
High performance and low latency
Expiry feature for resetting limits
Redis Commands Used:
INCR: Increment request count
EXPIRE: Set expiration time for keys
Handling Abusive Requests Gracefully
Return Meaningful Responses: 429 Too Many Requests
Headers: Include Retry-After to inform clients when to retry
Logging: Track abusive IPs for monitoring
Example Response:
{
"detail": "Too many requests. Please try again in 60 seconds."
}
Conclusion
Rate limiting is essential for API security and user fairness
FastAPI and Redis provide an efficient way to implement rate limiting
Graceful handling of abusive requests enhances user experience
Advocacy | Consultancy | Training

More Related Content

PDF
Application DoS In Microservice Architectures
PDF
Introducing Cloudflare Workers
PDF
Server Monitoring (Scaling while bootstrapped)
PPT
Application Performance Lecture
PDF
"Surviving highload with Node.js", Andrii Shumada
PPTX
ConFoo 2017: Introduction to performance optimization of .NET web apps
PPT
Thick client application security assessment
PPTX
Building Realtime Web Applications With ASP.NET SignalR
Application DoS In Microservice Architectures
Introducing Cloudflare Workers
Server Monitoring (Scaling while bootstrapped)
Application Performance Lecture
"Surviving highload with Node.js", Andrii Shumada
ConFoo 2017: Introduction to performance optimization of .NET web apps
Thick client application security assessment
Building Realtime Web Applications With ASP.NET SignalR

Similar to REDIS + FastAPI: Implementing a Rate Limiter (20)

PPT
Building an web 2.0 blog RAPIDLY in Alpha Five v10 with Codeless AJAX
PDF
Defending against application level DoS attacks
PDF
Apidays New York 2024 - The subtle art of API rate limiting by Josh Twist, Zuplo
PPTX
REST & RESTful Web Services
PDF
Solution Brief
PPTX
Web technology.pptx
PDF
5 step plan to securing your APIs
PPTX
Web api scalability and performance
PPSX
Bluecoat Services
PPT
Remote invocation
PDF
Cloud testing: challenges and opportunities, TaaS, Integration Testing
PPT
gofortution
PPTX
Scaling APIs: Predict, Prepare for, Overcome the Challenges
PPTX
Attack Prevention Solution for RADWARE
PPTX
AWS를 활용한 웹, 모바일, 소셜 애플리케이션 구축 방법
PPTX
Redis Day Bangalore 2020 - Session state caching with redis
PPTX
Microservice 微服務
PPT
Alpha Five v10.NEW APPLICATION SERVER. CODELESS AJAX
PPTX
Real-time Communications with SignalR
PPT
SWsoft Hosting Solutions for SaaS
Building an web 2.0 blog RAPIDLY in Alpha Five v10 with Codeless AJAX
Defending against application level DoS attacks
Apidays New York 2024 - The subtle art of API rate limiting by Josh Twist, Zuplo
REST & RESTful Web Services
Solution Brief
Web technology.pptx
5 step plan to securing your APIs
Web api scalability and performance
Bluecoat Services
Remote invocation
Cloud testing: challenges and opportunities, TaaS, Integration Testing
gofortution
Scaling APIs: Predict, Prepare for, Overcome the Challenges
Attack Prevention Solution for RADWARE
AWS를 활용한 웹, 모바일, 소셜 애플리케이션 구축 방법
Redis Day Bangalore 2020 - Session state caching with redis
Microservice 微服務
Alpha Five v10.NEW APPLICATION SERVER. CODELESS AJAX
Real-time Communications with SignalR
SWsoft Hosting Solutions for SaaS
Ad

More from techprane (17)

PDF
Performance Optimization MongoDB: Compound Indexes
PPTX
SSO with Social Login Integration & FastAPI Simplified
PDF
A Beginner's Guide to Tortoise ORM and PostgreSQL
PDF
Boost Your API with Asynchronous Programming in FastAPI
PDF
Top 10 Network Troubleshooting Commands.pdf
PPTX
Using jq to Process and Query MongoDB Logs
PPTX
How to Integrate PostgreSQL with Prometheus
PPTX
10 Basic Git Commands to Get You Started
PPTX
Top Linux 10 Commands for Windows Admins
PPTX
Implementing full text search with Apache Solr
PPTX
How to Overcome Doubts as a New Developer(Imposter Syndrome)
PPTX
How to Use JSONB in PostgreSQL for Product Attributes Storage
PDF
A Beginners Guide to Building MicroServices with FastAPI
PDF
Implementing Schema Validation in MongoDB with Pydantic
PPTX
Storing Large Image Files in MongoDB Using GRIDFS
PPTX
Open Source Mapping with Python, and MongoDB
PPTX
Learning MongoDB Aggregations in 10 Minutes
Performance Optimization MongoDB: Compound Indexes
SSO with Social Login Integration & FastAPI Simplified
A Beginner's Guide to Tortoise ORM and PostgreSQL
Boost Your API with Asynchronous Programming in FastAPI
Top 10 Network Troubleshooting Commands.pdf
Using jq to Process and Query MongoDB Logs
How to Integrate PostgreSQL with Prometheus
10 Basic Git Commands to Get You Started
Top Linux 10 Commands for Windows Admins
Implementing full text search with Apache Solr
How to Overcome Doubts as a New Developer(Imposter Syndrome)
How to Use JSONB in PostgreSQL for Product Attributes Storage
A Beginners Guide to Building MicroServices with FastAPI
Implementing Schema Validation in MongoDB with Pydantic
Storing Large Image Files in MongoDB Using GRIDFS
Open Source Mapping with Python, and MongoDB
Learning MongoDB Aggregations in 10 Minutes
Ad

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Big Data Technologies - Introduction.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
KodekX | Application Modernization Development
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
KodekX | Application Modernization Development
Spectral efficient network and resource selection model in 5G networks
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf

REDIS + FastAPI: Implementing a Rate Limiter

  • 1. Samuel Folasayo Protect Your API from Abuse with Redis & FastAPI technology for good Joe Nyirenda TechPrane Advocacy | Consultancy | Enablement
  • 2. Learning Objectives ● Understand the importance of rate limiting for API security ● Learn how to implement a rate limiter using FastAPI middleware ● Explore Redis as a real-time backend for managing request limits ● Master techniques for handling abusive API requests gracefully
  • 3. Protecting APIs from DDoS Attacks Definition: Distributed Denial of Service (DDoS) attacks flood an API with excessive requests Impact: Slower response times, downtime, or complete service unavailability Why APIs are Targets: APIs are often public-facing and high-traffic points of entry Visual: Illustration of a DDoS attack targeting an API
  • 4. What is Rate Limiting? Definition: Controlling the number of requests a client can make to an API within a specified timeframe Purpose: Prevent server overload and abusive behavior Types of Rate Limiting: ○ Fixed Window ○ Sliding Window ○ Token Bucket
  • 5. Why Rate Limiting is Essential Protect API Resources: Prevent resource exhaustion Improve User Experience: Ensure fair usage for all users Enhance Security: Block malicious actors and bots
  • 9. Rate Limiting Vs Throttling Controls the total number of requests a client can make within a specific timeframe Focuses on long-term usage and preventing abuse Example: Allowing 100 requests per hour per user Once the limit is reached, all subsequent requests are denied (usually with a 429 Too Many Requests response) Enforces fairness and prevents overuse of resources Rate Limiting Implementation
  • 10. Rate Limiting Vs Throttling Regulates the rate of incoming requests in real-time Focuses on short-term burst control and managing server load Example: Limiting to 10 requests per second per user Temporarily blocks requests exceeding the rate, but resumes when the rate drops below the threshold Prevents server overload and ensures consistent performance Throttling Implementation
  • 11. Client-Side Throttling Where? Implemented in the client application How? Limits the number of requests sent to the server Uses libraries like Lodash for web apps or equivalent mechanisms in mobile apps Commonly applied to user-triggered actions such as input fields or scrolling Purpose: Reduces redundant server calls, especially in event-heavy applications Example: A search bar that waits for a user to stop typing before sending a request to the server
  • 12. Server-Side Throttling Where? Implemented on server infrastructure How? Monitors and enforces rate limits on incoming requests Tools like NGINX, HAProxy, or backend middleware (e.g., Django, Express.js) are used Returns error codes such as 429 Too Many Requests when limits are exceeded Purpose: Protects servers from overload or abuse due to high traffic volumes Example: An API that allows a maximum of 10 requests per second per user
  • 13. Client vs. Server Throttling Aspect Client-Side Throttling Server-Side Throttling Location Client application Server Infrastructure Purpose Optimize requests before reaching server Protect server resources for overuse Implementation Handled using frontend logic or libraries Handled using backend tools or middleware
  • 14. Implementation in FastAPI Adding middleware for rate limiting from fastapi import FastAPI, Request, HTTPException from redis import Redis app = FastAPI() redis = Redis(host='localhost', port=6379) @app.middleware("http") async def rate_limiter(request: Request, call_next): client_ip = request.client.host key = f"rate_limit:{client_ip}" count = redis.incr(key) if count == 1: redis.expire(key, 60) # Set expiration to 60 seconds if count > 10: raise HTTPException(status_code=429, detail="Too many requests") response = await call_next(request) return response Middleware processes each request Redis tracks request counts per client Limit set to 10 requests per minute
  • 15. Using Redis for Real-time Rate Limiting Why Redis? High performance and low latency Expiry feature for resetting limits Redis Commands Used: INCR: Increment request count EXPIRE: Set expiration time for keys
  • 16. Handling Abusive Requests Gracefully Return Meaningful Responses: 429 Too Many Requests Headers: Include Retry-After to inform clients when to retry Logging: Track abusive IPs for monitoring Example Response: { "detail": "Too many requests. Please try again in 60 seconds." }
  • 17. Conclusion Rate limiting is essential for API security and user fairness FastAPI and Redis provide an efficient way to implement rate limiting Graceful handling of abusive requests enhances user experience Advocacy | Consultancy | Training