Contents
Key concepts
Asyncio essentials
The event loop is single-threaded, so any blocking call (time.sleep, a synchronous HTTP client, heavy CPU work) stalls every coroutine; use asyncio.sleep, async clients, or run_in_executor. Cap in-flight work with asyncio.Semaphore; prefer asyncio.TaskGroup (Python 3.11+) for structured concurrency (one failure cancels the siblings), or gather with return_exceptions=True when you want every outcome, failures included, as a result; use asyncio.timeout (3.11+) per request. gather returns results in input order regardless of completion order.
Rate limits, retries and backoff
Providers enforce requests per minute and tokens per minute; a token bucket (capacity plus refill rate) models both. Retry only transient failures (429, 5xx, timeouts), never 400s or auth errors; honour Retry-After; use capped exponential backoff with jitter, for example sleep = uniform(0, min(cap, base × 2^attempt)) (“full jitter”), so clients do not retry in lockstep; cap attempts and make retried actions idempotent.
Sequence · 5 stepsRetry and backoff request path
- First attempt The first attempt takes estimated tokens before entering the semaphore and timeout.
- Transient failure A 429 or 5xx is raised by call; 400s and auth errors are not retried.
- Backoff The backoff sleep happens outside the semaphore; honour Retry-After or capped exponential backoff with jitter.
- Retry bucket take Every attempt calls bucket.take(est_tokens(p)) again, so the retry respects the TPM limit.
- Retry call The retry re-enters the semaphore and timeout; gather preserves input order.
Data
| Step | From | To | Message |
|---|---|---|---|
| 1 | Client | Token bucket | take est tokens |
| 1 | Token bucket | Client | tokens granted (reply) |
| 1 | Client | API | call(p) |
| 2 | API | Client | 429 / 5xx (reply) |
| 3 | Client | Client | backoff sleep |
| 4 | Client | Token bucket | take est tokens |
| 4 | Token bucket | Client | tokens granted (reply) |
| 5 | Client | API | retry call(p) |
| 5 | API | Client | response (reply) |
Source: This page's text
Vectorised numerics in NumPy and PyTorch
Know broadcasting (dimensions are compared from the right; each pair must match or one must be 1). Use argpartition for top-k in O(n) rather than a full O(n log n) sort; compute softmax as exp(z − max) and log-softmax as z − logsumexp(z); mask with −inf before softmax instead of slicing; keep tensor shapes explicit, e.g. (B, T, H, D), and remember view needs compatible (usually contiguous) memory where reshape copies if needed.
Algorithms to know cold
Hash-map counting in O(n); heaps for top-k in O(n log k); quickselect for the k-th largest in expected O(n) but O(n²) worst case; tries for prefix queries; two pointers and sliding windows; reservoir sampling; and streaming sketches: Misra–Gries with k counters under-counts by at most n/(k+1), Count-Min only over-counts with ε/δ guarantees and merges across shards.
LLM-flavoured implementations
Sampling with temperature, top-k and top-p (keep the token that crosses p and at least one token, then renormalise); BPE training on a word-frequency table with careful handling of overlapping pairs and encoding by merge rank; BM25 plus reciprocal rank fusion (k ≈ 60) for hybrid retrieval; multi-head causal attention with the mask applied before softmax; a streaming parser as a linear-time state machine that handles tags split across chunks.
Testing under time pressure
Write a tiny fake early (a scripted model, a server that injects 429s and latency), seed every random generator, add property-style tests (random chunk boundaries, random inputs compared with a slow reference) and cover edge cases: empty input, Unicode, ties, k larger than n. In staged problems keep level-one code simple and extend it with tests at each level rather than rewriting.
Code review and AI coding tools
Reviewers look at correctness, design, readability, tests and whether complexity is justified. When AI assistants are allowed, interviewers watch how you verify their output: reading every line, running tests, checking edge cases and security-sensitive code. Narrate what you accept, what you change and why. Formats vary by employer and round: some allow an AI assistant, others forbid AI unless a step says otherwise, and some take-homes have been redesigned because frontier models now match strong candidates. Evidence on productivity is mixed (METR found experienced developers took 19% longer with early-2025 tools, and its 2026 follow-up could not pin down the effect), so claim speed-ups only with measurements.
Worked examples
Async LLM client with concurrency cap, token bucket and backoff
Send N = 1,000 prompts of about 1,200 tokens each (input plus expected output) to an API with a limit of 400,000 tokens per minute (TPM). Average latency is 3 s. Implement the client, then work out how long the run takes and how many requests should be in flight.
Capacity first. TPM bound: 400,000 / 1,200 ≈ 333 requests per minute. By Little’s law, in-flight requests = throughput × latency = (333 / 60) × 3 ≈ 17. The run takes 1,000 / 333 ≈ 3 minutes; allowing 32 in flight would not speed it up, it would only trigger 429s.
import asyncio, random, time
class TokenBucket:
def __init__(self, rate_per_s: float, capacity: float):
self.rate, self.capacity = rate_per_s, capacity
self.tokens, self.t = capacity, time.monotonic()
self.lock = asyncio.Lock()
async def take(self, n: float) -> None:
async with self.lock: # FIFO-ish fairness between waiters
while True:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.t) * self.rate)
self.t = now
if self.tokens >= n:
self.tokens -= n
return
await asyncio.sleep((n - self.tokens) / self.rate)
class Retryable(Exception): # raised by `call` on 429 / 5xx
def __init__(self, retry_after: float | None = None):
self.retry_after = retry_after
async def run_all(prompts, call, est_tokens, c=17, tpm=400_000, max_tries=5, timeout_s=60):
sem = asyncio.Semaphore(c)
bucket = TokenBucket(rate_per_s=tpm / 60, capacity=tpm / 10)
async def one(p):
for attempt in range(max_tries):
await bucket.take(est_tokens(p))
try:
async with sem, asyncio.timeout(timeout_s):
return await call(p)
except (Retryable, TimeoutError) as e:
if attempt == max_tries - 1:
return e # isolate the failure, keep going
ra = getattr(e, "retry_after", None)
await asyncio.sleep(ra if ra is not None
else random.uniform(0, min(30.0, 2.0 ** attempt)))
except Exception as e: # 400, auth, schema: do not retry
return e
return await asyncio.gather(*(one(p) for p in prompts)) # input order preserved
Talking points: the backoff sleep happens outside the semaphore so a waiting retry does not hold a
slot; the token estimate should include the max output tokens because providers usually count them;
asyncio.CancelledError is not caught, so cancelling the run works; tests use a fake call that raises
Retryable on a schedule and records timestamps to assert the TPM limit holds.
Flow · 4 stepsAsync LLM client with cap, bucket and backoff
- Take tokens Prompts enter and the token bucket takes the estimated tokens before any call.
- Cap and call In-flight work is capped by the semaphore and the call runs under asyncio.timeout.
- Retry transient failures Transient failures back off with jitter and re-enter the bucket; non-retryable failures return.
- Gather results Successful calls and isolated failures are gathered in input order.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Take tokens | Prompts enter and the token bucket takes the estimated tokens before any call. |
| 2 | Cap and call | In-flight work is capped by the semaphore and the call runs under asyncio.timeout. |
| 3 | Retry transient failures | Transient failures back off with jitter and re-enter the bucket; non-retryable failures return. |
| 4 | Gather results | Successful calls and isolated failures are gathered in input order. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Prompts | Input | N = 1,000 prompts |
| Token bucket | Rate limit | capacity + refill rate |
| Semaphore | Compute | cap in-flight work |
| Async call | Compute | under asyncio.timeout |
| Backoff | Compute | capped exponential with jitter |
| Results | Output | input order preserved |
Source: This page's text
Temperature, top-k and top-p sampling with the boundary done right
For logits [2.0, 1.0, 0.5, −1.0], compute the distribution after temperature 1 and top-p = 0.8, then with temperature 0.5. Implement a seeded sampler.
T = 1. exp values: 7.389, 2.718, 1.649, 0.368; sum 12.124 → p = [0.609, 0.224, 0.136, 0.030]. Sorted cumulative sums: 0.609, 0.834, … The token that crosses 0.8 (the second) is kept, so the nucleus is {0, 1}; renormalised: 0.609 / 0.834 = 0.731 and 0.224 / 0.834 = 0.269.
T = 0.5. Logits become [4, 2, 1, −2]: exp 54.60, 7.39, 2.72, 0.14; sum 64.84 → p = [0.842, 0.114, 0.042, 0.002]. The first token alone already exceeds 0.8, so the nucleus is {0} and sampling is greedy. Lower temperature sharpens the distribution, so the nucleus shrinks.
import numpy as np
def sample(logits, temperature=1.0, top_k=None, top_p=None, rng=None):
rng = rng or np.random.default_rng(0)
if temperature == 0:
return int(np.argmax(logits))
z = np.asarray(logits, dtype=np.float64) / temperature
if top_k is not None and top_k < z.size:
kth = np.partition(z, -top_k)[-top_k] # O(n), ties at kth are kept
z = np.where(z < kth, -np.inf, z)
p = np.exp(z - z.max())
p /= p.sum()
if top_p is not None and top_p < 1.0:
order = np.argsort(-p)
cum = np.cumsum(p[order])
keep = order[: np.searchsorted(cum, top_p) + 1] # include the crossing token
mask = np.zeros(p.size, dtype=bool)
mask[keep] = True
p = np.where(mask, p, 0.0)
p /= p.sum()
return int(rng.choice(p.size, p=p))
For a batch with per-row parameters: divide by a (B, 1) temperature tensor, compute per-row thresholds,
set excluded logits to −inf instead of slicing, and sample with torch.multinomial on the GPU. Test by
drawing 100,000 samples and comparing frequencies with the expected nucleus probabilities.
Heavy hitters in bounded memory with Misra–Gries
A stream has n = 1,000,000 items and you may keep k = 99 counters. Implement Misra–Gries, state its error bound and say which items are guaranteed to be reported.
def misra_gries(stream, k):
counters = {}
for x in stream:
if x in counters:
counters[x] += 1
elif len(counters) < k:
counters[x] = 1
else: # decrement everyone, drop zeros
for key in list(counters):
counters[key] -= 1
if counters[key] == 0:
del counters[key]
return counters
Error bound. Each decrement round removes k + 1 units of count (one from each of the k counters plus the discarded arrival), and at most n units exist, so there are at most n / (k + 1) rounds. Every estimate is therefore an under-count by at most n / (k + 1) = 1,000,000 / 100 = 10,000.
Guarantee. Any item with true frequency above 10,000 (1% of the stream) must still hold a counter. Reported counts can be low by up to 10,000; if the stream can be replayed, a second pass gives exact counts for the at most 99 candidates.
Cost. Each round costs O(k) and there are at most n / (k + 1) rounds, so total time is O(n) and memory is O(k). For distributed streams Misra–Gries summaries (and Count-Min sketches) can be merged. Contrast: an exact dictionary needs memory proportional to the number of distinct items, which breaks the budget.
What changed recently
Python 3.15: lazy imports and a free-threading stable ABI
Python 3.15 added explicit lazy imports (PEP 810), made UTF-8 the default text encoding (PEP 686), shipped a sampling profiler and introduced a stable ABI for free-threaded builds (PEP 803), so extensions can target no-GIL Python without rebuilding for every release. For ML services with heavy import chains and CPU-bound pre-processing, interviewers may ask how you would adopt lazy imports and free-threading safely.
METR's second developer study cannot pin down AI's effect
METR’s follow-up with 57 developers and over 800 tasks estimated that AI cut task time by 18% for returning and 4% for new participants, but both confidence intervals include zero, and 30–50% of developers said they held back tasks they did not want to do without AI, a selection effect that led METR to redesign the study. With its 2025 result (experienced developers 19% slower while believing they were faster), it is the evidence interviewers expect when they ask how you know AI tools help.
Anthropic redesigns its take-home after models beat candidates
Anthropic described how its performance-engineering take-home had to be redesigned repeatedly: given the same time limit, Claude Opus 4 outperformed most applicants, and by the two-hour mark Opus 4.5 matched the best human score, so the current version uses novel puzzles on a tiny, heavily constrained instruction set with no debugging tools supplied. It illustrates a direction in technical assessment: novel rather than familiar problems, and credit for building your own tooling and verifying results.
Python 3.14 makes free-threading officially supported
Python 3.14 (7 October 2025) moved the free-threaded build to supported status (PEP 779) with a single-threaded penalty of roughly 5–10%, and added subinterpreters in the standard library, template strings and asyncio introspection commands (python -m asyncio ps/pstree). Interviewers now ask when threads, asyncio, subinterpreters or processes fit a workload, and what breaks when the GIL no longer hides data races.
Pitfalls
- Calling time.sleep or a synchronous HTTP client inside a coroutine, which blocks the whole event loop.
- Uncapped retry loops, retrying 400s, ignoring Retry-After, or backoff without jitter.
- Sorting everything for a top-k, or writing Python loops where one matrix operation is expected.
- Softmax without subtracting the max, softmax over the wrong axis, or applying the causal mask after softmax.
- Assuming tags or JSON never split across streamed chunks, or re-parsing the whole buffer on every chunk (quadratic time).
- Skipping tests, or over-engineering stage one of a staged problem so later stages run out of time.
How interviewers probe it
- Start simple, then extend: ‘now add concurrency’, ‘now each row has its own top-p’, ‘now the input is a stream’.
- Complexity probes: ‘what does your encode cost?’, ‘what is quickselect’s worst case?’, ‘how does this scale to 10M documents?’
- ‘How would you test this?’ — fakes, seeded randomness, property tests, comparison with a slow reference.
- Code comprehension: read 40 lines of unfamiliar numerical code, predict its output and spot edge cases.
- Debug-style coding rounds: a repository or notebook with failing tests or silent bugs to find while narrating.
- Some companies allow AI assistants in coding rounds and assess how you check their output rather than banning them.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Implement an async client that sends N prompts to an LLM API with at most C requests in flight, a tokens-per-minute limit, exponential backoff with jitter and per-request timeouts, returning results in input order.
Model answer, written in a candidate's voice
- Semaphore(C) bounds in-flight requests; token bucket refilled by elapsed time gates sends; estimate prompt+output tokens before sending and reserve/refund.
- Classify retryable vs non-retryable errors; exponential backoff with jitter and cap; honour Retry-After; max attempts.
- Index every prompt; collect results by index and return in input order; per-request timeout and cancellation; isolate exceptions per request.
- Return structured per-item results instead of raising the first failure; caller cancellation still propagates.
- Test with a fake server injecting 429s, latency, 5xx, malformed responses and slow bodies; assert concurrency, pacing, retries, timeouts, cancellation and order.
Implement an agent loop in Python that takes a goal, a set of tools with JSON-schema arguments and a model client. Handle tool errors, a step limit and a token budget; then let independent tool calls run concurrently.
Model answer, written in a candidate's voice
- Model call -> validate JSON-schema args -> execute -> append results with matching call IDs -> repeat until final answer or limit
- Tool/validation errors become informative tool results; transient API errors retry with exponential backoff and jitter
- Budgets: max steps, token/cost cap, per-tool timeout, output truncation/summarisation
- asyncio.gather for independent calls in one assistant turn, preserving call IDs and isolating failures
- Structured tracing per step and tests using a scripted fake model
Write a small eval harness: load a JSONL dataset, call a model concurrently under a rate limit, apply code-based and judge-based graders, cache results and print a per-slice report.
Model answer, written in a candidate's voice
- Define small interfaces: DatasetItem, ModelClient, Grader, ResultStore, and a RunConfig with model, prompt version, params, and slice
- Run async with a semaphore for concurrency plus a token bucket for the rate limit, per-call timeouts, and exponential backoff with jitter on 429/5xx
- Cache by sha256 of model, prompt version, parameters, and input hash; persist results and resume by skipping cache hits
- Keep deterministic ordering by sorting items by stable id and emitting results sorted by slice and id
- Use exact/regex/schema graders plus a judge grader that records judge model, prompt, and rationale
- Aggregate per slice with n, pass rate, mean score, and confidence intervals such as Wilson for pass rates and bootstrap/t intervals for numeric scores
You have finished this topic.
Reading
- Coroutines and tasks (Python asyncio documentation)TaskGroup, gather, timeouts and cancellation semantics you will use in every async coding round.
- Exponential Backoff and JitterWhy retries need jitter and how the main jitter strategies compare.
- Broadcasting (NumPy user guide)The shape rules behind every vectorised NumPy or PyTorch solution.
- Autograd mechanics (PyTorch notes)Grad modes, no_grad versus inference mode, eval mode and in-place pitfalls that appear in debugging rounds.
- minbpeMinimal, readable byte-level BPE training and encoding, with exercises matching the BPE coding question.
- Google engineering practices: code reviewWhat reviewers check and how to write reviewable changes, useful for code-review style rounds.
- What's new in Python 3.14Free-threaded build support, subinterpreters, template strings, deferred annotations and new asyncio debugging tools in one place.
- Designing AI-resistant technical evaluationsA frontier lab explains how models broke its take-home and what it now looks for, which tells you how to prepare.
Practise this topic
- Implement an async client that sends N prompts to an LLM API with at most C requests in flight, a tokens-per-minute limit, exponential backoff with jitter and per-request timeouts, returning results in input order.
- Implement an agent loop in Python that takes a goal, a set of tools with JSON-schema arguments and a model client. Handle tool errors, a step limit and a token budget; then let independent tool calls run concurrently.
- Write a small eval harness: load a JSONL dataset, call a model concurrently under a rate limit, apply code-based and judge-based graders, cache results and print a per-slice report.
- Given a logits vector, implement sampling with temperature, top-k and top-p and a fixed seed. Then explain how you would vectorise it across a batch where each row has different parameters.
- In about 45 minutes, write a function that learns N BPE merges from a small corpus and an
encode()that applies them to new text. Then discuss complexity and how you would make encoding fast. - Without a vector database, implement top-k retrieval: cosine similarity over an embedding matrix, a simple BM25 scorer, and reciprocal rank fusion of the two lists. Then discuss complexity and scaling.
- Implement multi-head causal self-attention from scratch in PyTorch or JAX, without built-in attention functions. Be explicit about tensor shapes, the mask and the output projection.
- Given an unbounded stream and a small fixed memory budget, report approximately which items are most frequent. Implement your approach and state its error guarantee.
- Build an in-memory key–value store in stages under a time limit: basic get/set/delete, then expiring entries, then nested transactions with rollback, and finally saving and restoring state.
- Find the least frequent value in a list in O(n log n) or better, and the k-th largest element in expected O(n) time. Explain the complexity.
- Python 3.14 made the free-threaded (no-GIL) build officially supported. For an LLM data-processing service that tokenises, parses JSON and calls model APIs, what would you change, what would you keep, and what could break?
- In this coding round you may use an AI assistant. Implement a rate-limited async client that retries failed model calls with exponential backoff and jitter. Talk through how you use the assistant and how you check its output.