Caching and rate limits
Three tasks deal with a slow or shared resource. A decorator keeps answers for a limited time, and a limiter lets each client send only so many requests per window. The third task is the other side of a limit: a client that reads every page of an API, waits when the server says “too many requests”, and retries server errors. Each task keeps a little state and depends on time, so the time comes from outside and the tests control it. They build on Decorators, Time windows and Errors and validation.
P01. TTL cache decorator
Section titled “P01. TTL cache decorator”A function calls a slow external service, for example to get an exchange rate. We want a cache: a decorator ttl_cache that remembers the result for ttl_seconds.
The first call with some arguments runs the function and stores the result. A call with the same arguments before ttl has passed returns the stored result without running the function. After ttl, run it again. Keyword arguments are part of the key, and f(a=1, b=2) is the same call as f(b=2, a=1). But f(1, b=2) and f(a=1, b=2) are different keys, as in functools.lru_cache.
If max_size is set and the cache is full, remove the entry that was used least recently. Exceptions are not cached. The wrapper has counters hits and misses. The time comes from clock — the tests pass a fake clock.
ttl = 10
rate('EUR') at t=0 → runs (miss)
rate('EUR') at t=5 → from cache (hit)
rate('EUR') at t=10 → runs again (an entry lives while less than 10 seconds have passed)Full statement (as in the task file)
Write a decorator `ttl_cache(ttl_seconds, max_size=None, clock=time.monotonic)`.
@ttl_cache(ttl_seconds=60)
def get_exchange_rate(currency): ...
- The first call with some arguments runs the function and stores the result.
- A call with the same arguments within `ttl_seconds` returns the stored result without running the function.
- After `ttl_seconds` the entry has expired: the next call runs the function again.
- Keyword arguments are part of the key: f(1, b=2) and f(1, b=3) are different; f(a=1, b=2) and f(b=2, a=1) are the same. As in functools.lru_cache, f(1, b=2) and f(a=1, b=2) are different keys: a positional argument is not a keyword one.
- `max_size`: when the cache is full, remove the least recently USED entry (LRU).
- The wrapper exposes counters: `wrapper.hits` and `wrapper.misses`.
- `clock` returns the current time in seconds; tests pass a fake clock.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Is an entry exactly at ttl_seconds still valid?
No — valid while now - stored_at < ttl_seconds.
Do we cache exceptions?
No, an exception is not stored.
Is f(1, b=2) the same entry as f(a=1, b=2)?
No. Like functools.lru_cache: positional and keyword arguments are different keys; only the order of keywords does not matter.
import time
def ttl_cache(ttl_seconds, max_size=None, clock=time.monotonic):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Store the time together with the value, so you can tell when an entry has expired. Which structure lets you move a key to the end and drop the oldest one in O(1)?
Say it: OrderedDict gives O(1) lookups and LRU eviction; expired entries are removed lazily on access.
Reference solution
import functoolsimport timefrom collections import OrderedDict
def ttl_cache(ttl_seconds, max_size=None, clock=time.monotonic): def decorator(func): cache = OrderedDict() # key -> (stored_at, value); order = recency of use
@functools.wraps(func) def wrapper(*args, **kwargs): key = (args, tuple(sorted(kwargs.items()))) now = clock() if key in cache: stored_at, value = cache[key] if now - stored_at < ttl_seconds: cache.move_to_end(key) wrapper.hits += 1 return value del cache[key] wrapper.misses += 1 value = func(*args, **kwargs) # an exception propagates and is not stored cache[key] = (now, value) if max_size is not None and len(cache) > max_size: cache.popitem(last=False) # least recently used return value
wrapper.hits = 0 wrapper.misses = 0 return wrapper return decoratorWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. A cache for the answers of a slow external service, for example an exchange rate, for a limited time.
The idea. An OrderedDict from key to (stored_at, value), whose order is the order of use. On a hit, move_to_end; when the cache is full, popitem(last=False) removes the least recently used entry. The key is (args, tuple(sorted(kwargs.items()))). An expired entry is removed when someone asks for it.
Traps.
- An entry is valid while
now - stored_at < ttl_seconds. Exactly atttl_secondsit has expired. - LRU means least recently used, not least recently added: a hit must move the key to the end.
- An exception is not cached. Store the value only after the function returns.
- The counters live on the wrapper:
wrapper.hitsandwrapper.misses.functools.wrapskeeps the name and docstring of the function. - Read the time from
clock(), not fromtime.monotonic()directly; the tests pass a fake clock.
Complexity. Every operation is O(1). Memory: at most max_size entries. Without max_size, expired entries stay until someone asks for them again.
Follow-up. “Is it thread-safe?” No: two threads can change the OrderedDict at the same time, or both miss and both call the function. A lock keeps the dict consistent; to call the function only once per key, hold a lock per key while it runs. A cache shared by several processes lives outside them, for example in Redis with a TTL.
P08. Rate limiter for a public API
Section titled “P08. Rate limiter for a public API”We have a public API, and one API client must not overload it. The rule: at most limit requests in any window of window_seconds seconds, for each key (a key is one API client).
Write a class SlidingWindowLimiter(limit, window_seconds). Its method allow(key, now) is called for every incoming request and answers: let it through (True) or reject it (False). The time now is passed as a parameter, so the tests can use any numbers. Time never goes backwards.
The window slides: at moment now, count the allowed requests from the last window_seconds seconds, that is in the interval (now − window, now]. Rejected requests do not count. Keys are independent. For keys that keep calling, do not keep old timestamps that can no longer change the answer; say what you would do for idle keys.
limit = 3, window = 10
allow('client_1', 0) → True
allow('client_1', 1) → True
allow('client_1', 2) → True
allow('client_1', 3) → False # already 3 in the last 10 seconds
allow('client_1', 9.999) → False
allow('client_1', 10) → True # the request at 0 left the window (0, 10]
allow('client_1', 10.5) → False
allow('client_2', 3) → True # another key, its own windowFull statement (as in the task file)
limiter = SlidingWindowLimiter(limit=3, window_seconds=10)
limiter.allow("client_1", now=0.0) # True
...
- `allow(key, now) -> bool`: True if this request is allowed. In ANY window of `window_seconds` there can be at most `limit` allowed requests per key. A request at time t counts inside the window (t - window_seconds, t] — so a request exactly window_seconds later is allowed again.
- Rejected requests do not count.
- Keys are independent. `now` never goes backwards.
- Memory: do not keep timestamps that can no longer matter, for keys that keep calling. Say what you would do for idle keys.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Fixed windows (per minute on the clock) or sliding?
Sliding. Then say the trade-off of a token bucket.
Do rejected requests count toward the limit?
No.
Is a request exactly window_seconds after another one inside the window?
No: the window is (now - window_seconds, now], so it is allowed again.
class SlidingWindowLimiter:
def __init__(self, limit, window_seconds):
raise NotImplementedError("your code")
def allow(self, key, now) -> bool:
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
For each key, keep the times of the requests you allowed, oldest first. On every call, drop the times that have left the window before you count.
Say it: A deque per key keeps at most `limit` timestamps; a token bucket uses constant memory but allows bursts.
Reference solution
from collections import defaultdict, deque
class SlidingWindowLimiter: def __init__(self, limit, window_seconds): if limit <= 0 or window_seconds <= 0: raise ValueError("limit and window must be positive") self.limit = limit self.window = window_seconds self._hits = defaultdict(deque) # key -> timestamps of allowed requests, oldest first
def allow(self, key, now) -> bool: hits = self._hits[key] while hits and hits[0] <= now - self.window: hits.popleft() # left the window: can never matter again if len(hits) >= self.limit: return False hits.append(now) return TrueWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Protect a public API: one client must not take all of its capacity.
Steps. A dict from key to a deque of the times of allowed requests. On each request:
- Drop from the left every time
<= now - window. - If fewer than
limitremain, appendnowand returnTrue. - Otherwise return
False.
Traps.
- Do not append rejected requests: they do not count.
- The window is
(now - window, now]. A request exactlywindowseconds later is allowed again, so the condition for dropping is<=. - Keep one deque per key: keys are independent.
Complexity. Amortised O(1) per request: each time is appended once and removed once. Memory: at most limit times per active key.
Follow-up.
- “A million clients call once and never come back. What happens to memory?” Old times are dropped only when the same key calls again, so an idle key keeps its deque in the
dictforever. Delete a key once its window is empty: for example, every N calls sweep out the keys whose newest time is<= now - window. - A token bucket uses constant memory per key but lets bursts through. A fixed window per clock minute is cheap but can let 2 ×
limitrequests through at the border of two windows. With several processes, the counter lives in a shared store such as Redis.
P13. Fetch every page from the payouts API
Section titled “P13. Fetch every page from the payouts API”Our payouts API returns a merchant's payouts page by page. Write fetch_all_payouts(client, merchant_id, since): it asks for the first page, then follows next_cursor until it is None, and returns every payout once, in the order they first appear. The same payout can come on two pages.
The API is not always friendly. A 429 means "too many requests": wait the Retry-After seconds and ask for the same page again. A 5xx is a server error: ask again after base_delay, then twice as long, and so on. Each page gets at most max_retries retries; then raise ApiError with the last status. Any other error status raises ApiError at once.
The client and the sleep function are given, so the tests use fakes and check every call and every wait. One more thing: the API sometimes sends back a cursor that was already used. Your loop must not run forever.
page 1: po_1, po_2 next_cursor 'c2' page 2: 429 Retry-After: 3 → sleep(3), ask for 'c2' again page 2: po_2, po_3 next_cursor None → ['po_1', 'po_2', 'po_3'], sleeps [3]
Full statement (as in the task file)
Our payouts API returns a merchant's payouts page by page. Fetch all of them, and survive rate limits and server errors.
payouts = fetch_all_payouts(client, "mer_03", since=date(2026, 9, 1))
The HTTP client is given (the tests pass a fake one):
client.get(path, params) -> Response(status, headers, json)
first page: client.get("/v1/payouts", {"merchant_id": "mer_03", "since": "2026-09-01"})
next pages: the same params plus "cursor": the next_cursor of the previous page
a 200 answer: json = {"data": [{"id": "po_1", ...}, ...], "next_cursor": "c2"} (None on the last page)
- Return every payout dict, in the order they first appear. The same payout can come on two pages (new payouts shift the pages while you read them): return it once.
- 429 Too Many Requests: wait the Retry-After seconds (a header, like "3"), then ask for the same page again.
- 500-599: ask for the same page again.
- Before retry k of a page (k = 1, 2, ...), wait Retry-After after a 429 that has it, otherwise base_delay * 2 ** (k - 1). Wait with the sleep function you get: the tests pass a fake one.
- A page gets at most max_retries retries. When they run out, raise ApiError with the last status. Do not wait after the last failure.
- Any other status: raise ApiError(status, ...) at once, without retries.
- The API has a bug: sometimes it sends back a cursor that was already used. Do not loop forever.Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Is the retry limit per page or for the whole run?
Per page: every page gets max_retries retries. 429s and 5xx share them, and k in the backoff is that same count.
Is the header always spelled Retry-After?
No. Header names are case-insensitive, as in HTTP; some servers send retry-after.
Can Retry-After be a date?
Not from this API: always whole seconds, like "3". In production you would also cap the wait.
The same payout on two pages: which copy do I keep?
The first one.
What should happen when a cursor comes back that was already used?
Raise ApiError with status None. A list that may be incomplete must not look complete.
Should I parse the amounts?
No. Return the payout dicts as the API sends them; a later step parses them.
import time
from typing import NamedTuple
class Response(NamedTuple):
status: int
headers: dict
json: dict | None
class ApiError(Exception):
def __init__(self, status, message=""):
super().__init__(f"HTTP {status}: {message}" if status is not None else message)
self.status = status
def fetch_all_payouts(client, merchant_id, since, max_retries=3, base_delay=0.5, sleep=time.sleep):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Split the work into two loops: one over the pages, one over the attempts of a single page. What stays the same when you retry a page, what starts again on the next page, and what must you remember to notice that the server sends you in circles?
Say it: Two loops: pages, and the attempts of one page. Retries reset on every page, a 429 waits what the server says, and a cursor I have already used stops the loop with an error.
Reference solution
import timefrom typing import NamedTuple
class ApiError(Exception): def __init__(self, status, message=""): super().__init__(f"HTTP {status}: {message}" if status is not None else message) self.status = status
class Response(NamedTuple): status: int headers: dict json: dict | None
PATH = "/v1/payouts"
def header(headers, name): """HTTP header names are case-insensitive: Retry-After and retry-after are the same header.""" for key, value in headers.items(): if key.lower() == name.lower(): return value return None
def get_page(client, params, max_retries, base_delay, sleep): """One page, with its own retry count. Returns the json of the 200 answer.""" retries = 0 while True: r = client.get(PATH, params) if r.status == 200: return r.json if r.status != 429 and not 500 <= r.status <= 599: raise ApiError(r.status, "not retried") # 400, 401, 404 …: retrying will not help if retries == max_retries: raise ApiError(r.status, f"still failing after {max_retries} retries") # no wait after the last one retries += 1 wait = header(r.headers, "Retry-After") if r.status == 429 else None sleep(int(wait) if wait is not None else base_delay * 2 ** (retries - 1))
def fetch_all_payouts(client, merchant_id, since, max_retries=3, base_delay=0.5, sleep=time.sleep): params = {"merchant_id": merchant_id, "since": since.isoformat()} payouts, seen_ids, used = [], set(), set() cursor = None while True: page = get_page(client, params if cursor is None else {**params, "cursor": cursor}, max_retries, base_delay, sleep) for item in page["data"]: if item["id"] not in seen_ids: # the first copy wins seen_ids.add(item["id"]) payouts.append(item) used.add(cursor) cursor = page["next_cursor"] if cursor is None: return payouts if cursor in used: raise ApiError(None, f"the API sent cursor {cursor!r} again: the pages loop")WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Every integration with a partner or with another service has this loop: pages, rate limits, and a server that fails now and then. The tests check every call and every wait, as an incident review would.
Steps.
- Two levels:
get_pagefor the attempts of one page, and the outer loop over the pages. The retry count lives inget_page, so it starts again for each page. - In
get_page: 200 → return the json. 429 or 5xx → if no retries are left, raiseApiError(status); otherwise wait and ask again. Any other status →ApiError(status)at once. - The wait before retry k: the
Retry-Afterof a 429, found without regard to case and turned into a number; otherwisebase_delay * 2 ** (k - 1). - The outer loop: the params with
since.isoformat(), and"cursor"from the second page on. Keep each payout whose id is new, and remember every cursor you sent. Stop whennext_cursor is None; a cursor that was already sent →ApiError(None, ...).
Traps.
- Checking only
next_cursor == cursorcatchesc1 → c1, but loops forever onc1 → c2 → c1. Keep a set of every cursor you used. sleep("3"): a header value is a string. Convert it.headers["Retry-After"]fails onretry-after. HTTP/2 sends every header name in lower case.- Retrying a 400 or a 404 only wastes time: the request itself is wrong, and it will be wrong next time too.
- One retry counter for the whole run: after one bad page, every later page has fewer retries.
- A wait after the last failure only delays the error.
- After a 429, asking for the next cursor skips a page: a 429 carries no data.
Check. Say the waits of a script before you run it: 503, then 429 with Retry-After: 4, then 503, then 200 gives [0.5, 4, 2.0].
Complexity. One request per page, plus at most max_retries more per page. Memory: one id per payout and one cursor per page.
Follow-up.
- “Ten workers share one rate limit. What changes?” Each one backs off on its own, and they all come back at the same moment. Add random jitter to the waits, or put a shared token bucket in front of the client (compare P08).
- “The job dies on page 400 of 1,000.” Save the last cursor and the ids seen so far as a checkpoint, and resume from it. Ask how long a cursor stays valid: an expired cursor means starting again.
- “Why not page by offset?” New payouts shift the offsets while you read, so items are skipped or repeated. A cursor marks a place in the data, and the dedupe by id covers the rest.
In production. Cap the Retry-After wait, log every retry with its status and page, and limit the time of the whole run, not only of each request.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.