Skip to main content

Write a rate limiter that allows each user at most 3 requests in any 60 second window. For example, requests at seconds 0, 10 and 20 are allowed, a request at second 30 is rejected, and a request at second 60 is allowed again.

Coding rounds · Intermediate 2

Short answer

Keep a deque of recent request timestamps per user. On each request, pop timestamps from the left while they are at least one full window old. If fewer than limit remain, append the new timestamp and allow; otherwise reject. Each timestamp is added and removed once, so it is O(1) amortised, with O(limit) memory per user.

Deeper answer

First clarify the rule. Ask whether the window slides or resets on fixed minutes, whether a rejected request counts toward the limit, and whether the limiter runs in one process or on several servers.

In one process, keep calls = defaultdict(deque). In allow(user, now), take q = calls[user]. Remove old entries with a loop: while q and now - q[0] >= window, call q.popleft(). Then if len(q) >= limit, return False. Otherwise run q.append(now) and return True. Using >= in the loop means a request at exactly 60 seconds after the first is allowed. Rejected requests are not stored, so a client that keeps trying is not locked out forever.

Each call is amortised O(1) and memory is at most limit timestamps per active user. Pass now as an argument, or use time.monotonic(), so tests do not need to sleep. Test the boundary at exactly 60 seconds, two users who must not affect each other, and a burst. Say that across several servers you would move the state to Redis.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Python for production

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.