Full round 4 of 5

Full round 4 of 5 Medium Python

The API rate limiter

An API’s rate limiter in two files: free users get one request too many. Then a pro plan, then memory that never stops growing.

60:00

The real round is about an hour. Start the clock, do all four tasks out loud, and open an answer only when you’ve finished that task.

On this page

The handover

The interviewer

“Our public API is rate limited. api.py handles each request and limiter.py keeps a log of recent requests per user. Support has a ticket about the limits.”

The code

Read all 2 files before anything else. For each one, say in a sentence what it does, then follow one request through them.

2 files

api.py

from limiter import RateLimiter

limiter = RateLimiter(limit=5, window=60)

def handle(request, now):
    """Answers one API request: (status, body)."""
    if not limiter.allow(request["user"], now):
        return 429, "Too many requests"
    return 200, "ok"

limiter.py

from collections import defaultdict, deque

class RateLimiter:
    """At most limit requests per user in any window seconds."""

    def __init__(self, limit, window):
        self.limit = limit
        self.window = window
        self.log = defaultdict(deque)

    def allow(self, user, now):
        times = self.log[user]
        while times and times[0] <= now - self.window:
            times.popleft()
        if len(times) > self.limit:
            return False
        times.append(now)
        return True

Read every file first. After the report below, come back and click the line that causes it.

1Fix the bug

Bug report

The docs say free users get 5 requests a minute. A customer shows that they can make 6 before getting a 429, every minute.

Reproduce it

This example shows the report happening. Before reading on, work out why it prints what it does.

The example
from api import handle
print([handle({"user": "asha"}, now=t)[0] for t in range(7)])

It prints

[200, 200, 200, 200, 200, 200, 429]

It should print

[200, 200, 200, 200, 200, 429, 429]

Your hypothesis

Say it out loud, or write it here, before you hunt for the line: which file, what’s going wrong, and what you’d check to prove it.

It stays on this device.
Show the fix: the cause, the change and the test

The cause (limiter.py, line 15)

limiter.py line 15 refuses only when there are more than limit requests already logged. With 5 logged, 5 > 5 is false, so the sixth gets through. It should refuse once the count reaches the limit: >=.

The fix

limiter.py

12        times = self.log[user]13        while times and times[0] <= now - self.window:14            times.popleft()15        if len(times) > self.limit:15        if len(times) >= self.limit:16            return False17        times.append(now)18        return True

The test that proves it

It fails on the original code and passes once it’s fixed. Keep it, so the bug can’t come back.

from limiter import RateLimiter
rl = RateLimiter(limit=2, window=10)
assert [rl.allow("a", t) for t in (0, 1, 2)] == [True, True, False]
assert rl.allow("a", 10) is True

2Check the AI

The assistant in the side panel is allowed. Before you found the cause, you asked it about the report. Would you act on its answer?

You

Why can a free user make 6 requests a minute instead of 5?

Assistant

Your expiry check uses <=, so the oldest request expires one second early and lets an extra one in. Change it to <:

while times and times[0] < now - self.window:
Show what’s wrong with its answer

Test the claim: send six requests in the same second, when nothing can expire. All six pass, so expiry can’t be the cause. The count check is: with 5 logged, len(times) > 5 is false. The suggested change would also break the window, because a request exactly 60 seconds old should expire. Ask the assistant for a case that would prove its theory, then run it.

3Add a feature

The interviewer

We’re launching a pro plan. Requests now carry request["plan"], either "free" or "pro". Free users keep 5 requests a minute; pro users get 20. A request without a plan is free.

Start from your fixed code. Say the feature back as a contract, ask about its edges, then build it with a test.

Show one way to build it

The approach

Keep one limiter and one log per user; pass the limit for the request’s plan into allow. An unknown plan falls back to free, so a typo can’t give someone unlimited requests.

The change

api.py

1from limiter import RateLimiter2 3limiter = RateLimiter(limit=5, window=60)3PLAN_LIMITS = {"free": 5, "pro": 20}4limiter = RateLimiter(limit=PLAN_LIMITS["free"], window=60)4 5def handle(request, now):6    """Answers one API request: (status, body)."""7    if not limiter.allow(request["user"], now):8    limit = PLAN_LIMITS.get(request.get("plan", "free"), PLAN_LIMITS["free"])9    if not limiter.allow(request["user"], now, limit):8        return 429, "Too many requests"9    return 200, "ok"

limiter.py

1from collections import defaultdict, deque2 3class RateLimiter:4    """At most limit requests per user in any window seconds."""4    """At most limit requests per user in any window seconds (a request can bring its own limit)."""5 6    def __init__(self, limit, window):7        self.limit = limit8        self.window = window9        self.log = defaultdict(deque)10 11    def allow(self, user, now):11    def allow(self, user, now, limit=None):12        limit = self.limit if limit is None else limit12        times = self.log[user]13        while times and times[0] <= now - self.window:14            times.popleft()15        if len(times) >= self.limit:16        if len(times) >= limit:16            return False17        times.append(now)18        return True

The test

It fails before the feature and passes after; the bug’s test still passes too.

from api import handle
pro = [handle({"user": "ravi", "plan": "pro"}, now=t)[0] for t in range(21)]
assert pro.count(200) == 20 and pro[-1] == 429
free = [handle({"user": "asha"}, now=t)[0] for t in range(6)]
assert free.count(200) == 5
assert handle({"user": "kabir", "plan": "gold"}, now=0)[0] == 200

4Make it faster

The interviewer

The limiter keeps a log for every user who has ever called the API, even users who left hours ago, so the service’s memory grows until it’s restarted. Make it forget users whose requests have all expired, without making each request much slower.

First count what it does too much of. Then change it without changing what it returns, and say what the change costs.

Show the speed-up and why it works

Why it’s slow, and the fix

A user’s log only shrinks when that same user calls again, so users who never come back stay forever. Sweeping every user on every request would be slow, so sweep every 100 requests: one pass that drops users whose newest request is already outside the window. Memory now tracks active users, and each request still does a small, constant amount of work on average.

The change

limiter.py

3class RateLimiter:4    """At most limit requests per user in any window seconds (a request can bring its own limit)."""5 6    SWEEP_EVERY = 100  # requests between clean-ups of users who have gone quiet7 6    def __init__(self, limit, window):7        self.limit = limit8        self.window = window9        self.log = defaultdict(deque)12        self.calls = 010 11    def allow(self, user, now, limit=None):12        limit = self.limit if limit is None else limit16        self.calls += 117        if self.calls % self.SWEEP_EVERY == 0:18            self.sweep(now)13        times = self.log[user]14        while times and times[0] <= now - self.window:15            times.popleft()⋯17            return False18        times.append(now)19        return True26 27    def sweep(self, now):28        """Forgets users whose newest request is outside the window."""29        idle = [u for u, times in self.log.items() if not times or times[-1] <= now - self.window]30        for u in idle:31            del self.log[u]

The test

It fails on the code before the speed-up and passes after. Every earlier test still passes, so the behaviour didn’t change.

from limiter import RateLimiter
rl = RateLimiter(limit=5, window=60)
for i in range(1000):
    rl.allow("user" + str(i), now=0)
for i in range(200):
    rl.allow("active", now=1000 + i * 0.01)
assert len(rl.log) <= 2, len(rl.log)
assert rl.allow("someone-new", now=1003) is True

Sum it up

Score yourself

Tick what you really did. Interviewers score the process, so be honest: anything unticked is what to practise in the next round.

0 of 8

Your progress stays on this device.