Skip to main content
Python & FastAPI Interviews Coding P0 Medium

Implement an in-memory sliding-window rate limiter

Write allow_request(key: str, limit: int, window_sec: float) -> bool using a deque of timestamps and monotonic time.

Official Reference

Model Answer & Explanation

from collections import defaultdict, deque
import time

class SlidingWindowLimiter:
    def __init__(self, limit: int, window_sec: float):
        self.limit = limit
        self.window = window_sec
        self.hits = defaultdict(deque)

    def allow(self, key: str) -> bool:
        now = time.monotonic()
        q = self.hits[key]
        while q and now - q[0] >= self.window:
            q.popleft()
        if len(q) >= self.limit:
            return False
        q.append(now)
        return True

Store a deque of request timestamps per key. On each call, use time.monotonic() (never wall-clock time.time() which can jump), pop timestamps older than now - window_sec from the left, check len(q) < limit, and if allowed append now. Clean up empty keys periodically or bound dict size to avoid memory leaks.

Follow-up Interview Question · Why does this break across multiple Uvicorn/FastAPI workers, and how do you fix it with Redis?

Module Context & References

Python & FastAPI · Practice questions & drills High-frequency coding, FastAPI, concurrency and testing exercises
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.