0
0
FastAPIframework~20 mins

Rate limiting in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rate Limiting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when the rate limit is exceeded in this FastAPI endpoint?

Consider this FastAPI endpoint using a simple rate limiter that allows 3 requests per minute per client IP.

from fastapi import FastAPI, Request, HTTPException
from time import time

app = FastAPI()

request_times = {}

@app.get("/data")
async def get_data(request: Request):
    ip = request.client.host
    now = time()
    window = 60
    limit = 3
    times = request_times.get(ip, [])
    times = [t for t in times if now - t < window]
    if len(times) >= limit:
        raise HTTPException(status_code=429, detail="Too many requests")
    times.append(now)
    request_times[ip] = times
    return {"message": "Success"}

What will the client receive on the 4th request within one minute?

FastAPI
from fastapi import FastAPI, Request, HTTPException
from time import time

app = FastAPI()

request_times = {}

@app.get("/data")
async def get_data(request: Request):
    ip = request.client.host
    now = time()
    window = 60
    limit = 3
    times = request_times.get(ip, [])
    times = [t for t in times if now - t < window]
    if len(times) >= limit:
        raise HTTPException(status_code=429, detail="Too many requests")
    times.append(now)
    request_times[ip] = times
    return {"message": "Success"}
AThe client receives a JSON response with {"message": "Success"} on all requests.
BThe client receives an HTTP 429 error with detail "Too many requests" on the 4th request within one minute.
CThe client receives an HTTP 500 Internal Server Error on the 4th request.
DThe client receives an HTTP 404 Not Found error on the 4th request.
Attempts:
2 left
💡 Hint

Think about what happens when the number of requests exceeds the limit in the code.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this FastAPI rate limiting snippet

Which option correctly fixes the syntax error in this code snippet?

from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

@app.get("/limit")
async def limit(request: Request):
    ip = request.client.host
    if ip not in request_times
        request_times[ip] = []
    return {"status": "ok"}
FastAPI
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

@app.get("/limit")
async def limit(request: Request):
    ip = request.client.host
    if ip not in request_times
        request_times[ip] = []
    return {"status": "ok"}
AIndent the return statement inside the if block.
BReplace 'not in' with 'notin' in the if statement.
CAdd a colon at the end of the if statement line: if ip not in request_times:
DChange 'request_times' to 'request_times()' in the if statement.
Attempts:
2 left
💡 Hint

Python requires a colon at the end of if statements.

state_output
advanced
2:00remaining
What is the value of request_times after 3 requests from the same IP within 30 seconds?

Given this code snippet:

from fastapi import FastAPI, Request
from time import time

app = FastAPI()
request_times = {}

@app.get("/check")
async def check(request: Request):
    ip = request.client.host
    now = time()
    window = 60
    times = request_times.get(ip, [])
    times = [t for t in times if now - t < window]
    times.append(now)
    request_times[ip] = times
    return {"count": len(times)}

If the same client IP makes 3 requests within 30 seconds, what will be the value of request_times[ip] after the third request?

FastAPI
from fastapi import FastAPI, Request
from time import time

app = FastAPI()
request_times = {}

@app.get("/check")
async def check(request: Request):
    ip = request.client.host
    now = time()
    window = 60
    times = request_times.get(ip, [])
    times = [t for t in times if now - t < window]
    times.append(now)
    request_times[ip] = times
    return {"count": len(times)}
AA list of 4 timestamps including an extra one from before.
BA list of 1 timestamp, the last request time only.
CAn empty list because old timestamps are removed.
DA list of 3 timestamps, each less than 60 seconds old.
Attempts:
2 left
💡 Hint

Consider how the code filters timestamps and adds the current time.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI rate limiter not reset counts after 1 minute?

Consider this code snippet:

from fastapi import FastAPI, Request, HTTPException
from time import time

app = FastAPI()
request_counts = {}

@app.get("/limit")
async def limit(request: Request):
    ip = request.client.host
    count, start = request_counts.get(ip, (0, time()))
    if time() - start > 60:
        count = 0
        start = time()
    count += 1
    if count > 5:
        raise HTTPException(status_code=429, detail="Too many requests")
    request_counts[ip] = (count, start)
    return {"count": count}

Why might the count never reset after 1 minute?

FastAPI
from fastapi import FastAPI, Request, HTTPException
from time import time

app = FastAPI()
request_counts = {}

@app.get("/limit")
async def limit(request: Request):
    ip = request.client.host
    count, start = request_counts.get(ip, (0, time()))
    if time() - start > 60:
        count = 0
        start = time()
    count += 1
    if count > 5:
        raise HTTPException(status_code=429, detail="Too many requests")
    request_counts[ip] = (count, start)
    return {"count": count}
ABecause the start time is reset inside the if block but the dictionary is updated after incrementing count, causing inconsistent timing.
BBecause the count variable is never incremented.
CBecause the dictionary request_counts is never updated.
DBecause the time() function returns a constant value.
Attempts:
2 left
💡 Hint

Look at when the start time is updated and when the dictionary is updated.

🧠 Conceptual
expert
3:00remaining
Which approach best ensures accurate distributed rate limiting in FastAPI?

You want to implement rate limiting in a FastAPI app deployed on multiple servers behind a load balancer. Which approach below best ensures accurate rate limiting across all servers?

AUse a shared external store like Redis to track request counts and timestamps centrally.
BUse an in-memory dictionary on each server to track request counts per IP separately.
CUse client-side cookies to store request counts and enforce limits on the client.
DRely on the load balancer to block requests after a fixed number per server.
Attempts:
2 left
💡 Hint

Think about how to share state across multiple servers.