
Module 15 Exercises: Engineering for Scale
Practical exercises to challenge your understanding of async concurrency, caching, and load testing.
Module 15 Exercises: Engineering for Scale
Performance is a feature. These exercises will help you transform your API from a "Prototype" into a "Platform."
Exercise 1: The Event Loop Audit
Identify the mistake in the following code. How would it affect other users of the API?
@app.get("/calculate")
async def calculate_heavy_pi():
# A massive calculation that takes 2 seconds
result = sum(i * i for i in range(10_000_000))
return {"result": result}
Exercise 2: Designing a Cache Key
You are building a Global News API. You want to cache the "Top 10 Headlines" per Country.
If you use Redis, what would your cache key look like? (e.g., news:US, news:UK).
Exercise 3: Scaling Strategy
Your API is running on a single server. You are hitting the limits of your CPU. Draw a simple diagram (or describe in words) how you would use a Load Balancer and Three FastAPI Servers to handle triple the traffic.
Self-Correction / Discussion
Exercise 1 Answer:
The calculation is Synchronous and CPU-heavy. Because it's inside an async def function, it will block the entire event loop. No other requests can be handled until the calculation is finished.
Fix: Change to def calculate_heavy_pi() so FastAPI runs it in a separate thread.
Exercise 2 Answer:
news:headlines:{country_code} is a good pattern. It's descriptive and allows for easy expansion if you want to add categories later (e.g., news:headlines:US:technology).
Exercise 3 Answer:
Users hit the Load Balancer (Nginx/AWS). The Load Balancer looks at your 3 servers and picks the one with the least traffic. It forwards the request, and the server returns the data. This is called Round Robin or Least Connections load balancing.
Summary of Module 15
You have learned to think like a "Systems Architect."
- Concurrency: You know how to keep the event loop moving.
- Caching: You know how to avoid redundant work.
- Stress Testing: You know how to find the limits before your users do.
In Module 16: Security Best Practices, we will look at how to protect your high-performance API from malicious actors.