Python for AI Engineers · Part B · Lesson 18 of 26
Python performance: the GIL, threads, processes and asyncio for AI apps
Make Python AI code fast, explained for Java and JavaScript developers: the GIL, I/O-bound vs CPU-bound work, thread pools, process pools, asyncio for many LLM calls, a decision table, batching, caching LLM replies, profiling with cProfile, and NumPy before parallelism.
⏱ 45 min3 exercises that check your codeRuns in your browser
By the end you can
- Tell I/O-bound from CPU-bound work, and explain what the GIL does (and does not) stop, compared with Java threads
- Run blocking calls on a
ThreadPoolExecutorand CPU-heavy work on aProcessPoolExecutor, with the__main__guard processes need - Send many LLM calls at once with
asyncio, and pick between async, threads, processes and NumPy with a decision table - Cut calls and cost with batching,
functools.lru_cacheand a small TTL cache for model replies - Find the slow function with
time.perf_counterandcProfilebefore optimising anything
1Two kinds of slow: waiting and working
Before making code faster, ask why it is slow. There are two very different answers.
I/O-bound code spends its time waiting: for an LLM API, a database, a file, a web page. The CPU sits idle. Almost everything an AI app does over the network is I/O-bound. CPU-bound code spends its time computing: parsing a 300-page PDF, tokenising a million chunks, scoring vectors in a Python loop, running a model on your own machine. The CPU is at 100%.
The fix for each is different, so measure first. time.perf_counter() is a precise clock in seconds (like System.nanoTime() in Java or performance.now() in JavaScript): read it before and after, and subtract. The box below times one fake model call (time.sleep waits without using the CPU) and one CPU-heavy function that counts prime numbers in pure Python.
import time
def fake_llm_call(prompt):
time.sleep(0.3) # waiting: the CPU is idle, like a network call
return f"answer to {prompt!r}"
def count_primes(limit):
count = 0
for n in range(2, limit): # pure Python arithmetic: the CPU is busy
if all(n % d for d in range(2, int(n ** 0.5) + 1)):
count += 1
return count
def timed(label, fn, arg):
start = time.perf_counter() # a precise clock, in seconds
result = fn(arg)
seconds = time.perf_counter() - start
print(f"{label}: {result} ({seconds:.1f} s)")
timed("I/O-bound", fake_llm_call, "summarize")
timed("CPU-bound", count_primes, 100_000)
Expected output
I/O-bound: answer to 'summarize' (0.3 s) CPU-bound: 9592 (0.2 s)
The results are exact; the times depend on your machine (Python in the browser is slower than on your laptop). Both lines take a fraction of a second, but for opposite reasons, and wall-clock time alone cannot tell you which.
Run it in a normal Python on your machine (the browser version cannot measure CPU time reliably) and compare the wall clock with time.process_time(), which counts only the time your process spent on the CPU. If CPU time is close to wall time, the code is CPU-bound; if CPU time is near zero, it is waiting:
wall, cpu = time.perf_counter(), time.process_time()
result = work()
print(f"wall {time.perf_counter() - wall:.1f} s, cpu {time.process_time() - cpu:.1f} s")
# a model call: wall 0.3 s, cpu 0.0 s counting primes: wall 0.3 s, cpu 0.3 s
Tip Use perf_counter, not time.time(), to measure durations. time.time() is the wall clock and can jump when the system clock is adjusted.
2The GIL, explained for Java developers
In Java, eight threads on an eight-core machine really run at the same time, one per core. In standard Python (called CPython) they do not. CPython has a Global Interpreter Lock, the GIL: a single lock that a thread must hold to run Python code. So inside one Python process, only one thread runs Python code at any moment, however many cores you have.
Two details make threads still useful. A thread releases the GIL while it waits for I/O: time.sleep, reading a socket, an HTTP call, a file read. And a running thread is asked to hand the GIL over every few milliseconds (the switch interval), so threads take turns. Result: threads are great for waiting on many things at once, and useless for making pure Python arithmetic faster.
Many C libraries also release the GIL while they work: NumPy, for example, during big matrix operations. That is why NumPy code can use several cores even though your Python code cannot.
import sys
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
print("switch interval:", sys.getswitchinterval(), "seconds")
# sys._is_gil_enabled() exists from Python 3.13; older versions always have the GIL
gil_check = getattr(sys, "_is_gil_enabled", None)
print("GIL enabled:", gil_check() if gil_check else True)
Expected output
Python 3.12 switch interval: 0.005 seconds GIL enabled: True
// 4 threads, 4 cores: all 4 compute at the same time
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<Integer>> fs = limits.stream()
.map(n -> pool.submit(() -> countPrimes(n)))
.toList();
// about 4x faster than one thread # 4 threads, 4 cores: they take turns holding the GIL
with ThreadPoolExecutor(max_workers=4) as pool:
counts = list(pool.map(count_primes, limits))
# no faster than one thread for pure Python work The first line shows whatever Python you run (the browser box is 3.12). The switch interval is 5 milliseconds by default.
Free-threaded Python (optional). Python 3.13 added a separate, optional build without the GIL (PEP 703), installed as python3.13t; in 3.14 it became officially supported, but it is still not the default. With it, threads can run Python code on all cores like Java threads. For now treat it as an experiment: some libraries with C code do not support it yet, and a single thread runs a little slower. If you want to try it, uv python install 3.14t installs it; sys._is_gil_enabled() then prints False. Everything in this lesson assumes the normal build with the GIL.
Watch out The GIL does not make your code thread-safe. A switch can happen between reading and writing a shared value, so counter += 1 from several threads can still lose updates. Protect shared state with threading.Lock() (with lock: counter += 1), exactly as you would use synchronized in Java.
3Threads for blocking I/O: ThreadPoolExecutor
concurrent.futures.ThreadPoolExecutor is Python's ExecutorService: a pool of worker threads that runs functions for you. pool.map(fn, items) calls fn on every item using the pool and returns the results in input order. The with block shuts the pool down and waits for all work to finish when it ends.
Use threads when the code you need to speed up is blocking (synchronous) and mostly waits: the requests library, the synchronous OpenAI client, a database driver without async support, reading many files. This file runs four fake 0.5-second downloads one by one, then on four threads, and then does the same with the CPU-heavy count_primes to show the GIL at work.
Threads do not work in the browser boxes on this page (the browser version of Python cannot start them), so save this as threads_demo.py and run it with uv run python threads_demo.py or python3 threads_demo.py.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(url):
time.sleep(0.5) # blocking I/O, like requests.get or the sync OpenAI client
return f"page {url}"
def count_primes(limit):
count = 0
for n in range(2, limit):
if all(n % d for d in range(2, int(n ** 0.5) + 1)):
count += 1
return count
def timed(label, work):
start = time.perf_counter()
result = work()
print(f"{label:<18} {time.perf_counter() - start:.1f} s {result}")
def main():
urls = ["a", "b", "c", "d"]
limits = [150_000] * 4
timed("I/O, one by one:", lambda: [fetch(u) for u in urls])
with ThreadPoolExecutor(max_workers=4) as pool:
timed("I/O, 4 threads:", lambda: list(pool.map(fetch, urls)))
timed("CPU, one by one:", lambda: [count_primes(n) for n in limits])
with ThreadPoolExecutor(max_workers=4) as pool:
timed("CPU, 4 threads:", lambda: list(pool.map(count_primes, limits)))
if __name__ == "__main__":
main() concurrent.futuresis in the standard library. It has a thread pool and a process pool with the same interface.line 2time.sleepreleases the GIL while it waits, exactly like a real network read. Other threads run in the meantime.line 6workis a function with no arguments; thelambda: ...on the calling lines makes one on the spot, like() -> ...in Java.line 18{label:<18}pads the label to 18 characters, left-aligned, so the columns line up.line 21- Four worker threads. Without
max_workersPython picksmin(32, CPU count + 4).line 29 pool.maprunsfetchon the threads and returns the results in the order ofurls, not the order they finish.line 30- The same pool with CPU work: the threads take turns holding the GIL, so there is no gain.line 34
- True only when you run this file directly. Threads do not need it, but it is the normal way to start a script (lesson 9 explains it).line 37
I/O, one by one: 2.0 s ['page a', 'page b', 'page c', 'page d'] I/O, 4 threads: 0.5 s ['page a', 'page b', 'page c', 'page d'] CPU, one by one: 1.0 s [13848, 13848, 13848, 13848] CPU, 4 threads: 1.3 s [13848, 13848, 13848, 13848]
The I/O part is four times faster with four threads, because the four waits overlap. The CPU part is not faster, and often a little slower, because the threads take turns and switching costs time. Your times will differ a little; that pattern will not.
When you want each result as soon as it is ready (to show progress, or to handle errors one by one), use submit and as_completed instead of map. submit returns a Future, and future.result() gives its value or re-raises its exception, like Future.get() in Java:
from concurrent.futures import ThreadPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=8) as pool:
futures = {pool.submit(fetch, url): url for url in urls} # Future -> url
for future in as_completed(futures): # in finish order
print(futures[future], future.result())
Tip Inside async code you do not need your own pool for one blocking call: await asyncio.to_thread(fetch, url) (lesson 9) runs it on a shared thread pool without freezing the event loop.
4Processes for CPU work: ProcessPoolExecutor
To use several cores for pure Python work, use several processes. Each process is a separate Python with its own memory and its own GIL, so four processes really compute at the same time. ProcessPoolExecutor has the same interface as the thread pool: swap the class name and keep map.
The price: the function and its arguments are sent to the worker processes, and the results sent back, by pickling them (Python's built-in serialisation, like Java serialisation). That means the function must be defined at the top level of a module (not a lambda or an inner function), arguments and results must be picklable, and sending big objects costs time. Starting the workers also takes a moment. So processes pay off for chunks of work that take at least tens of milliseconds each, not for millions of tiny calls.
Processes do not work in the browser either. Save this as processes_demo.py and run it with uv run python processes_demo.py.
import os
import time
from concurrent.futures import ProcessPoolExecutor
def count_primes(limit): # top level: worker processes must be able to import it
count = 0
for n in range(2, limit):
if all(n % d for d in range(2, int(n ** 0.5) + 1)):
count += 1
return count
def main():
limits = [150_000] * 4
print("CPU cores:", os.cpu_count())
start = time.perf_counter()
print([count_primes(n) for n in limits])
print(f"one by one: {time.perf_counter() - start:.1f} s")
start = time.perf_counter()
with ProcessPoolExecutor(max_workers=4) as pool:
print(list(pool.map(count_primes, limits)))
print(f"4 processes: {time.perf_counter() - start:.1f} s")
if __name__ == "__main__": # required: worker processes import this file again
main() - Each worker finds this function by importing your module, so it must live at the top level. A
lambdahere fails with a pickling error.line 6 os.cpu_count()is the number of logical cores. Withoutmax_workers, the pool starts that many processes.line 16- Four separate Python processes, each with its own GIL. The
withblock waits for them and shuts them down.line 23 - Each number in
limitsis pickled, sent to a worker, and the count is sent back. Results keep the input order.line 24 - On macOS and Windows (and on Linux from Python 3.14) each worker starts a fresh Python that **imports this file**. Without the guard, every worker would run
main()again and try to start its own pool: the workers crash with aRuntimeErrorand your program getsBrokenProcessPoolinstead of results.line 28
CPU cores: 8 [13848, 13848, 13848, 13848] one by one: 1.0 s [13848, 13848, 13848, 13848] 4 processes: 0.3 s
The output above is from a laptop with 8 cores and nothing else busy; the counts are exact and the times are approximate. The speed-up is at most the number of free cores, minus the cost of starting workers and pickling. On a busy or 2-core machine you will see less.
In AI work, typical process-pool jobs are parsing many PDFs, cleaning and chunking a large corpus, or computing features for training data. Running a neural network is different: PyTorch and NumPy already run their heavy maths in C on several cores, so do not wrap them in a process pool.
Watch out The if __name__ == "__main__": guard is not optional for process pools. In a Jupyter notebook, a process pool cannot find functions defined in the notebook either: put them in a .py file and import them.
5asyncio for many concurrent LLM calls
For many network calls, such as grading 500 answers with a model or embedding a corpus through an API, asyncio (lesson 9) beats threads. One thread and one event loop can wait on hundreds of requests at once, each waiting request costs a few kilobytes instead of a whole thread, and there are no locks to think about because switches only happen at await.
The pattern for a batch job: one shared AsyncOpenAI client, one shared asyncio.Semaphore to cap how many requests are in flight, and asyncio.gather to run them all. It is Python's version of Java 21 virtual threads, or of Promise.all with a concurrency limit in Node.
This needs a model server, so it is a file, not a browser box. Start Ollama with llama3.2:3b as in the first lab. In a uv project (lesson 1), install the SDK and run the script with the two commands right here; you should see output like the lines under them. The file many_calls.py follows.
uv add openai==3.60.0
uv run python many_calls.py 20 answers, 0 errors, 9.8 s The number 1 is the only positive integer that is neither prime nor composite.
import asyncio
import time
import openai
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="http://localhost:11434/v1", # Ollama; any OpenAI-compatible server works
api_key="ollama", # Ollama ignores the key, but the SDK needs one
timeout=30.0, # seconds per request
max_retries=2, # the SDK retries 429, 5xx and connection errors
)
limit = asyncio.Semaphore(8) # at most 8 requests in flight at once
async def ask(prompt: str) -> str:
async with limit:
try:
reply = await client.chat.completions.create(
model="llama3.2:3b",
messages=[{"role": "user", "content": prompt}],
max_tokens=60,
)
return reply.choices[0].message.content
except openai.APITimeoutError: # check first: it is a subclass of APIConnectionError
return "ERROR: timed out"
except openai.APIConnectionError:
return "ERROR: cannot reach the server"
async def main() -> None:
prompts = [f"Give one fact about the number {n}." for n in range(1, 21)]
start = time.perf_counter()
answers = await asyncio.gather(*(ask(p) for p in prompts))
errors = sum(a.startswith("ERROR") for a in answers)
print(f"{len(answers)} answers, {errors} errors, {time.perf_counter() - start:.1f} s")
print(answers[0])
if __name__ == "__main__":
asyncio.run(main()) AsyncOpenAIis the async twin of theOpenAIclient: the same methods, but youawaitthem.line 5- One client for the whole program. It keeps a pool of HTTP connections, so reusing it is much faster than creating one per call.line 7
- One semaphore shared by every call: the 9th request waits until one of the first 8 finishes.line 13
- Catch the timeout before the connection error:
APITimeoutErroris a subclass ofAPIConnectionError, so the other order would never reach it.line 25 - Builds 20 coroutines and runs them all;
gatherreturns the answers in the order ofprompts.line 34 a.startswith("ERROR")isTrueorFalse, andTruecounts as 1 in a sum, so this counts the error strings.line 35- Starts the event loop (lesson 9). In FastAPI you would just
await ask(...)inside anasync defendpoint.line 41
The time and the fact depend on your machine and the model. A local Ollama server works on only a few requests at a time (its OLLAMA_NUM_PARALLEL setting), so the gain is smaller there than against a hosted API, where 8 or 16 requests in flight can make a batch job close to 8 or 16 times faster. If Ollama is not running you get 20 answers, 20 errors and ERROR: cannot reach the server after the SDK's retries.
Tip Size the semaphore from your provider's rate limits, not from your CPU: async concurrency is about how many requests the server accepts at once, not about cores.
6Profile first, then vectorise with NumPy
Guessing which line is slow is usually wrong. cProfile, in the standard library, counts every function call and how long each took. From the command line, python -m cProfile -s tottime app.py runs a whole script and prints a table sorted by tottime, the time spent inside each function itself (not in the functions it calls); cumtime includes those.
Below, a hand-written vector search (cosine similarity in a pure Python loop, like a naive RAG retriever) is profiled in code with cProfile.Profile(), and pstats reads the numbers back. The box prints how often each function ran and which one used the most time. Then the same search is written with NumPy (lesson 15): one matrix product instead of a million Python additions.
import cProfile
import math
import pstats
import time
import numpy as np
rng = np.random.default_rng(seed=0) # fixed seed: the same "embeddings" every run
doc_matrix = rng.standard_normal((1000, 256)) # 1000 documents, 256 numbers each
query_vec = rng.standard_normal(256)
docs, query = doc_matrix.tolist(), query_vec.tolist() # the same numbers as plain Python lists
def dot(a, b):
total = 0.0
for x, y in zip(a, b):
total += x * y
return total
def norm(a):
return math.sqrt(dot(a, a))
def cosine(a, b):
return dot(a, b) / (norm(a) * norm(b))
def search_loop(query, docs, k=3):
scores = [cosine(query, d) for d in docs]
return sorted(range(len(docs)), key=lambda i: scores[i], reverse=True)[:k]
profiler = cProfile.Profile()
profiler.enable() # start counting calls
top_loop = search_loop(query, docs)
profiler.disable() # stop counting
stats = pstats.Stats(profiler).stats # {(file, line, name): (calls, ..., own time, total time, ...)}
mine = {key[2]: row for key, row in stats.items() if key[2] in {"dot", "norm", "cosine", "search_loop"}}
for name, row in sorted(mine.items(), key=lambda kv: kv[1][1], reverse=True):
print(f"{name:<12} called {row[1]:>5} times")
print("most own time:", max(mine, key=lambda name: mine[name][2]))
def search_numpy(query_vec, doc_matrix, k=3):
scores = doc_matrix @ query_vec / (np.linalg.norm(doc_matrix, axis=1) * np.linalg.norm(query_vec))
return np.argsort(scores)[::-1][:k].tolist()
def best_time(fn, *args, runs=5):
"""Fastest of a few runs: the one least disturbed by whatever else the machine is doing."""
times = []
for _ in range(runs):
start = time.perf_counter()
fn(*args)
times.append(time.perf_counter() - start)
return min(times)
top_numpy = search_numpy(query_vec, doc_matrix)
speedup = best_time(search_loop, query, docs) / best_time(search_numpy, query_vec, doc_matrix)
print("same top 3:", top_loop == top_numpy, top_numpy)
print("NumPy at least 10x faster:", speedup >= 10)
Expected output
dot called 3000 times norm called 2000 times cosine called 1000 times search_loop called 1 times most own time: dot same top 3: True [367, 849, 248] NumPy at least 10x faster: True
Read the profile like a detective. dot does nearly all the work, and it runs 3000 times for 1000 documents. norm runs 2000 times because cosine recomputes the length of the same query for every document: a free win just by computing it once. In a real profile you then look at the slowest function and ask "can this run fewer times, or in C?".
Each row of pstats data is a tuple; row[1] is the total number of calls and row[2] the own time (tottime) in seconds. In your own projects you rarely read it by hand: pstats.Stats(profiler).sort_stats("tottime").print_stats(5) prints the five most expensive functions as a table, and the python -m cProfile command does the same for a whole script.
search_numpy does the whole search in three NumPy operations: doc_matrix @ query_vec computes all 1000 dot products at once, np.linalg.norm(..., axis=1) computes every row's length, and np.argsort sorts the scores (ascending, so [::-1] reverses it and [:k] keeps the best three). It returns the same documents and is typically 50 to 100 times faster on a laptop, on one core. That is why the rule for CPU-bound number crunching is: vectorise first, parallelise only if it is still too slow.
Tip best_time takes the fastest of several runs because a single timing is easily disturbed by other programs. For quick experiments, the standard library's timeit module does the same, and in Jupyter %timeit is one line.
7Choosing: a decision table
Start from the question in section 1: is the slow part waiting or computing? Then pick the row that fits.
| Your slow part | Example in an AI app | Use | Java equivalent |
|---|---|---|---|
| Many network calls, async library available | 500 LLM calls, embeddings over HTTP, agent tool calls | asyncio + gather + Semaphore |
virtual threads, CompletableFuture |
| Blocking (sync) calls you cannot make async | requests, a sync DB driver, the sync OpenAI client |
ThreadPoolExecutor or asyncio.to_thread |
ExecutorService with a thread pool |
| Number crunching on arrays | cosine similarity, normalising vectors, scoring | NumPy first (vectorise) | a tuned library instead of loops |
| Pure Python CPU work in big chunks | parsing PDFs, chunking a corpus, custom tokenising | ProcessPoolExecutor |
a thread pool (Java has no GIL) |
| The same request again and again | repeated questions, re-embedding unchanged text | a cache (section 9) | Spring @Cacheable, Caffeine |
| Lots of tiny calls to one API | embedding 10,000 chunks one by one | batching (section 8) | batch endpoints |
| A whole model running locally | PyTorch inference or training | the library's own parallelism (GPU, its threads) | DJL, ONNX Runtime |
The rows combine. A RAG indexer typically parses PDFs in a process pool, batches the chunks 100 at a time, sends the batches concurrently with asyncio and a semaphore, and caches embeddings of chunks it has seen before. And from async code you can reach a process pool for one CPU-heavy step with await loop.run_in_executor(pool, fn, arg), where loop = asyncio.get_running_loop().
Watch out Do not reach for processes to speed up network calls. They work, but each process costs tens of megabytes and a slow start; asyncio or threads do the same job almost for free.
8Batching: fewer, bigger requests
Every HTTP request has a fixed cost: the round trip, authentication, queuing at the provider. If each text is sent on its own, that overhead is paid thousands of times. Most AI APIs accept a list: the embeddings endpoint takes many texts in one input (OpenAI allows up to 2048 per request), and a local embedding model processes a batch on the GPU or CPU much faster than one text at a time.
itertools.batched(items, n) (new in Python 3.12) cuts any list into tuples of up to n items. The fake API below does not really wait: it adds up the time each request would take, 200 ms per request plus 2 ms per text, so the result is the same on every run.
from itertools import batched # Python 3.12+
class FakeEmbeddingsAPI:
"""Counts requests and adds up how long they would take (nothing really waits)."""
def __init__(self):
self.requests = 0
self.seconds = 0.0
def embed(self, texts):
self.requests += 1
self.seconds += 0.200 + 0.002 * len(texts) # 200 ms per request + 2 ms per text
return [[float(len(t))] for t in texts] # one tiny "vector" per text
texts = [f"chunk {i}" for i in range(1000)]
one_by_one = FakeEmbeddingsAPI()
vectors = []
for t in texts:
vectors.extend(one_by_one.embed([t]))
print(f"one by one: {one_by_one.requests} requests, {one_by_one.seconds:.0f} s, {len(vectors)} vectors")
in_batches = FakeEmbeddingsAPI()
vectors = []
for batch in batched(texts, 100): # tuples of up to 100 texts
vectors.extend(in_batches.embed(list(batch)))
print(f"batches of 100: {in_batches.requests} requests, {in_batches.seconds:.0f} s, {len(vectors)} vectors")
Expected output
one by one: 1000 requests, 202 s, 1000 vectors batches of 100: 10 requests, 4 s, 1000 vectors
vectors.extend(...) appends every item of a list (like addAll in Java). The API returns the vectors in the same order as the texts, so vectors[i] belongs to texts[i]. With the real client, one batch is one call: client.embeddings.create(model="nomic-embed-text", input=list(batch)), and [d.embedding for d in reply.data] gives the vectors in order.
For chat models you cannot put many prompts into one request, but two things still help: run requests concurrently (section 5), and for big offline jobs use the provider's Batch API where there is one. OpenAI's, for example, takes a file of requests, returns results within 24 hours, and costs about half the normal price.
Tip Keep batches to a size the server accepts and the network carries comfortably: 64 to 256 texts is a common choice. Then combine: send several batches concurrently under a semaphore.
9Caching: never pay for the same answer twice
The fastest and cheapest LLM call is the one you do not make. @functools.lru_cache(maxsize=N) is a decorator (lesson 4) that remembers the results of a function by its arguments, keeping the N most recently used. Calling it again with the same arguments returns the stored result without running the function. functools.cache is the same with no size limit.
Two limits: the arguments must be hashable (strings, numbers, tuples; not lists or dicts), and entries never expire. Model answers and anything read from outside should expire, so for those write a small TTL cache (time to live): store each value with the time it expires. The cache below takes its clock as a parameter, so the example can move time forward by hand instead of waiting a minute.
import functools
import json
import time
@functools.lru_cache(maxsize=1024) # remembers the last 1024 different arguments
def count_tokens(text: str) -> int:
print(f" counting {text!r}") # only printed when the function really runs
return len(text.split())
print(count_tokens("what is dns"), count_tokens("what is dns"), count_tokens("hi there"))
print(count_tokens.cache_info())
class TTLCache:
"""Keeps each value for ttl seconds. `clock` is a parameter so tests can fake time."""
def __init__(self, ttl, clock=time.monotonic):
self.ttl, self.clock, self.data = ttl, clock, {}
def get(self, key):
hit = self.data.get(key)
if hit is None:
return None
value, expires = hit
if self.clock() >= expires: # too old: forget it
del self.data[key]
return None
return value
def put(self, key, value):
self.data[key] = (value, self.clock() + self.ttl)
def cache_key(model, messages, **options):
# dicts and lists are not hashable: turn the whole request into one stable string
return json.dumps({"model": model, "messages": messages, **options}, sort_keys=True)
now = [0.0] # a fake clock we can move forward by hand
cache = TTLCache(ttl=60, clock=lambda: now[0])
calls = {"n": 0}
def ask(question):
messages = [{"role": "user", "content": question}]
key = cache_key("llama3.2:3b", messages, temperature=0)
answer = cache.get(key)
if answer is None:
calls["n"] += 1 # here a real app calls the model
answer = f"answer #{calls['n']} to {question!r}"
cache.put(key, answer)
return answer
print(ask("What is DNS?"))
now[0] = 30
print(ask("What is DNS?")) # 30 s later: from the cache
now[0] = 61
print(ask("What is DNS?")) # 61 s later: expired, asked again
print("model calls:", calls["n"])
Expected output
counting 'what is dns' counting 'hi there' 3 3 2 CacheInfo(hits=1, misses=2, maxsize=1024, currsize=2) answer #1 to 'What is DNS?' answer #1 to 'What is DNS?' answer #2 to 'What is DNS?' model calls: 2
The two "counting" lines print before 3 3 2 because Python evaluates all three calls before print runs, and only the first "what is dns" and "hi there" really run the function. cache_info() confirms it: one hit, two misses.
TTLCache stores (value, expires) pairs in a dict. time.monotonic is a clock that never goes backwards, the right choice for expiry. ask uses a fake clock, lambda: now[0], that reads a number we change by hand: the answer from time 0 is still fresh at 30 seconds and expired at 61. cache_key turns the model, the messages and the options into one string with json.dumps(..., sort_keys=True), so the same request always gives the same key, whatever order the options were written in.
In production you would put this behind an async lock if many tasks share it, cap its size, or use Redis so all your servers share one cache. Libraries such as cachetools (its TTLCache) give you a ready-made, size-limited version.
Watch out Only cache what should repeat. A reply with temperature above 0 is meant to vary, and an answer built from one user's private documents must never be served to another user: put the user or tenant id into the key, or do not cache it.
Common mistakes
- Using threads to speed up pure Python number crunching. The GIL lets one thread run Python at a time, so it is no faster. Vectorise with NumPy, or use processes.
- Forgetting the
if __name__ == "__main__":guard around aProcessPoolExecutor, or passing it a lambda or an inner function. Workers must be able to import the function. - Sending thousands of tiny requests one at a time instead of batching them, and paying the round-trip cost for every one.
- Running hundreds of LLM calls at once without a shared semaphore, then being rate limited with
429errors. - Caching model replies forever, or under a key that ignores the model, the options or the user, so stale or private answers leak.
- Optimising without measuring. Profile with
cProfileand time withperf_counterfirst; the slow part is rarely where you guessed.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Make the TTL cache expire
TTLCache.get below never forgets anything. Fix it so a value is returned only before it expires: at or after put time + ttl it must return None and remove the entry. The clock is passed in, so the tests can move time by hand.
import time
class TTLCache:
def __init__(self, ttl, clock=time.monotonic):
self.ttl, self.clock, self.data = ttl, clock, {}
def put(self, key, value):
self.data[key] = (value, self.clock() + self.ttl)
def get(self, key):
hit = self.data.get(key)
if hit is None:
return None
value, expires = hit
return value # never expires: fix this
Hint
Before returning, compare `self.clock()` with `expires`. If it is `>=`, delete `self.data[key]` and return `None`.
2Embed in batches
Write embed_all(texts, embed, size). embed is a function that takes a list of texts and returns a list of vectors, one per text, in order. Call it once per batch of at most size texts and return all the vectors in the same order as texts. Do not call embed with an empty list.
def embed_all(texts, embed, size):
vectors = []
for t in texts:
vectors.extend(embed([t])) # one request per text: too many calls
return vectors
Hint
`for i in range(0, len(texts), size):` gives the start of each batch; `texts[i:i + size]` is the batch. (`itertools.batched` also works, but it gives tuples, so wrap each batch in `list(...)`.)
3Vectorise the search
Write top_k(query, docs, k) with NumPy and no Python loop. query is a 1-D array, docs a 2-D array with one document per row. Return a list of the row numbers of the k documents with the highest cosine similarity to query, best first.
import numpy as np
def top_k(query, docs, k):
# your code here: use docs @ query and np.linalg.norm
return []
Hint
`scores = docs @ query / (np.linalg.norm(docs, axis=1) * np.linalg.norm(query))`, then `np.argsort(scores)[::-1][:k].tolist()`.
Interview questions
Q1What is the GIL, and how does it affect a Python program compared with Java?
The Global Interpreter Lock is a lock in CPython that a thread must hold to run Python bytecode, so only one thread runs Python code at a time in a process. Threads still help with I/O, because they release the GIL while waiting, but pure Python CPU work does not get faster with more threads, unlike Java. Python 3.13+ also has an optional free-threaded build without the GIL.
Q2When would you use threads, processes or asyncio in Python?
asyncio for many concurrent network calls when async libraries exist (LLM APIs, HTTP, databases). Threads for blocking libraries that mostly wait, or asyncio.to_thread from async code. Processes for CPU-heavy pure Python work in sizeable chunks, since each process has its own GIL. For numeric work, vectorise with NumPy before any of these.
Q3Why does a ProcessPoolExecutor need the if __name__ == "__main__" guard?
With the spawn and forkserver start methods (default on macOS and Windows, and on Linux from 3.14), each worker starts a fresh interpreter that imports your main module. Without the guard, that import would run the code that creates the pool again. Functions sent to workers must also be importable top-level functions and their arguments picklable.
Q4How would you speed up embedding a million text chunks through an API?
Batch the texts (for example 100 per request), send several batches concurrently with asyncio and a semaphore sized to the rate limit, retry transient errors with backoff, cache embeddings by a hash of the text and model so unchanged chunks are never re-embedded, and write results incrementally so a failure does not lose the job.
Q5How do you find out why a Python program is slow?
Measure before changing anything: time.perf_counter around suspect steps, comparing wall time with time.process_time to see if it is waiting or computing, and python -m cProfile -s tottime (or cProfile.Profile in code) to see which functions are called most and use the most time. Then fix the hot spot: call it less, cache it, vectorise it, or parallelise it.
Q6What should you watch out for when caching LLM responses?
Build the key from everything that changes the answer (model, full messages, temperature and other options, and the user or tenant for private data), give entries a TTL, cap the size, and do not cache non-deterministic replies you want to vary. For several servers use a shared store such as Redis.