SlideShare a Scribd company logo
9
Most read
10
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

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

PPTX
Apply Rate Limiting Policy
Vince Soliza
 
PPTX
Protecting Your API with Redis by Jane Paek - Redis Day Seattle 2020
Redis Labs
 
PDF
Apidays New York 2024 - The subtle art of API rate limiting by Josh Twist, Zuplo
apidays
 
PDF
Rate limits and Performance
supergigas
 
PPTX
Rate-Limiting 30 Million requests by Vijay Lakshminarayanan and Girish Koundi...
Redis Labs
 
PPTX
Serverless lessons learned #7 rate limiting
Maik Wiesmüller
 
KEY
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Nick Galbreath
 
PPTX
Rate limiters in big data systems
Sandeep Joshi
 
PDF
Understanding how your ap is are being traffic controlled
Sanjeewa Malalgoda
 
PPTX
Rate Limiting - SLA Based Policy
Vince Soliza
 
PPTX
Scaling APIs: Predict, Prepare for, Overcome the Challenges
Apigee | Google Cloud
 
PDF
Resilient Design 101 (JeeConf 2017)
Avishai Ish-Shalom
 
PPTX
apidays LIVE Hong Kong - Art and Science of Rate Limits for APIs by Shahnawaz...
apidays
 
ODP
Attacking REST API
Siddharth Bezalwar
 
PPTX
Manage and consume the api
Achyuta Lakshmi Puvvala
 
PPTX
Secure rest api on microservices vws2016
Quý Nguyễn Minh
 
PDF
Resilient design 101 (BuildStuff LT 2017)
Avishai Ish-Shalom
 
PDF
Rest ful tools for lazy experts
ColdFusionConference
 
PDF
RESTFul Tools For Lazy Experts - CFSummit 2016
Ortus Solutions, Corp
 
PPTX
Making sense of AWS Serverless operations at Believe in Serverless community ...
Vadym Kazulkin
 
Apply Rate Limiting Policy
Vince Soliza
 
Protecting Your API with Redis by Jane Paek - Redis Day Seattle 2020
Redis Labs
 
Apidays New York 2024 - The subtle art of API rate limiting by Josh Twist, Zuplo
apidays
 
Rate limits and Performance
supergigas
 
Rate-Limiting 30 Million requests by Vijay Lakshminarayanan and Girish Koundi...
Redis Labs
 
Serverless lessons learned #7 rate limiting
Maik Wiesmüller
 
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Nick Galbreath
 
Rate limiters in big data systems
Sandeep Joshi
 
Understanding how your ap is are being traffic controlled
Sanjeewa Malalgoda
 
Rate Limiting - SLA Based Policy
Vince Soliza
 
Scaling APIs: Predict, Prepare for, Overcome the Challenges
Apigee | Google Cloud
 
Resilient Design 101 (JeeConf 2017)
Avishai Ish-Shalom
 
apidays LIVE Hong Kong - Art and Science of Rate Limits for APIs by Shahnawaz...
apidays
 
Attacking REST API
Siddharth Bezalwar
 
Manage and consume the api
Achyuta Lakshmi Puvvala
 
Secure rest api on microservices vws2016
Quý Nguyễn Minh
 
Resilient design 101 (BuildStuff LT 2017)
Avishai Ish-Shalom
 
Rest ful tools for lazy experts
ColdFusionConference
 
RESTFul Tools For Lazy Experts - CFSummit 2016
Ortus Solutions, Corp
 
Making sense of AWS Serverless operations at Believe in Serverless community ...
Vadym Kazulkin
 

More from techprane (17)

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

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Ad

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