Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 8 of 16
Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
A recommendations endpoint that always has an answer: precomputed candidates, a 60-second cache that hits 0.819 of 2,000 simulated requests, and a popular list for model errors, new users and candidates older than an hour, each answer tagged with its source.
What you will learn
- Serve precomputed candidates so a request is only a lookup
- Add a cache keyed on user and k that stores only model answers
- Build a fallback ladder for model errors, new users and stale candidates, with a source field on every answer
- Test time-based behaviour with an injected clock
Before you start
- Recommendations, Part 1: Two Stages, Candidates Then Ranking
- FastAPI Hello World: Routes, Uvicorn and Swagger
Over the last three parts we built a recommender offline. Today we put one behind a FastAPI endpoint that always has an answer. The candidates are ready before anybody asks, a cache handles repeat questions, and a popular list steps in when the model is down or the user is new.
This is a smaller project with its own synthetic data: 400 users, 120 items, 3,766 rows in the event log, 30 candidates per user. A batch job builds the candidates ahead of time with an SVD (dim 6). A ranker would order them, but to keep the project small, we store the batch job's order. You already know how to write a FastAPI route (see FastAPI Hello World), so we'll focus on what's behind it.
A good waiter
Today's specials were prepared this morning, so when a regular sits down, the plate is ready. That's the precomputed candidates. The regular asks again a moment later, and the waiter still has it on the tray. That's the cache. A first-timer sits down. The waiter doesn't know them, so they get the safe suggestion, what most people like. And if the kitchen is closed, same thing. Nobody goes without a plate, and each plate has a slip saying how it got there.
Four questions
The app is two routes. One returns recommendations, the other lets an admin mark the model as down:
from fastapi import FastAPI
from data import make_data
from model import train
from service import Recs
app = FastAPI()
recs = Recs(train(make_data()))
@app.get("/recs/{user_id}")
def get_recs(user_id: int, k: int = 5):
return recs.get(user_id, k)
@app.post("/admin/model_ok/{flag}")
def set_model(flag: bool):
recs.model_ok = flag
return {"model_ok": recs.model_ok}
ask.py sends four questions through FastAPI's TestClient: user 3, user 3 again, user 99999, and then user 5 after switching the model off:
known user {"source": "model", "items": [79, 54, 28, 33, 119], "candidate_age_s": 0, "cached": false}
same user again {"source": "model", "items": [79, 54, 28, 33, 119], "candidate_age_s": 0, "cached": true}
new user {"source": "popular_new_user", "items": [108, 61, 18, 34, 54], "candidate_age_s": 0, "cached": false}
model down {"source": "popular_error", "items": [108, 61, 18, 34, 54], "candidate_age_s": 0, "cached": false}
Four answers, all with one shape. User 99999 doesn't exist, and there's no error: they get the most-bought list. When the model is off, user 5 gets the same popular list. The caller never sees a failure, and the source field says which path ran.
The ladder
The cache in code
The top of the ladder is get, in service.py:
import time
class Recs:
def __init__(self, bundle, ttl=60, max_age=3600,
clock=time.time):
self.b = bundle
self.ttl, self.max_age = ttl, max_age
self.clock = clock
self.cache = {}
self.model_ok = True
def get(self, user_id, k=5):
now = self.clock()
hit = self.cache.get((user_id, k))
if hit and now - hit[0] < self.ttl:
return {**hit[1], "cached": True}
out = self._compute(user_id, k, now)
if out["source"] == "model":
self.cache[(user_id, k)] = (now, out)
return {**out, "cached": False}
- The key is a pair,
(user_id, k), because five items and six items are different answers. - An entry younger than the TTL, 60 seconds here, goes back with
cachedset to true. An older one is recomputed. - Only answers with
source == "model"are stored. If we cached the popular list during an outage, a user could be stuck on it for a minute after the model came back.
The checks in code
def _compute(self, user_id, k, now):
age = int(now - self.b["built_at"])
pop = self.b["popular"][:k]
if not self.model_ok:
return self._out("popular_error", pop, age)
if user_id not in self.b["cands"]:
return self._out("popular_new_user", pop, age)
if age > self.max_age:
return self._out("popular_stale", pop, age)
top = self.b["cands"][user_id][:k]
return self._out("model", top, age)
@staticmethod
def _out(source, items, age):
return {"source": source, "items": items,
"candidate_age_s": age}
We work out the age of the batch and cut the popular list down to k. Then three checks: is the model okay, is the user in the candidates dictionary, is the batch older than max_age (3,600 seconds). Past all that, it's a dictionary lookup, one slice. No model runs while the user waits, and that's what precomputed means. The training happens in the batch job, and if the batch breaks, the service keeps answering. (Batch versus online scoring is compared in Online, Batch and Streaming Serving.)
Two clocks
There are two clocks, and they're easy to mix up. The TTL says how long one answer lasts. Max age says how long the whole batch lasts. With a fake clock passed in, the run showed:
| Time | Source | Cached | Why |
|---|---|---|---|
| first call | model | false | cache empty |
| 10 s later | model | true | inside the 60 s TTL |
| 110 s later | model | false | answer expired, batch still fine |
| batch age 4,110 s (k = 6) | popular_stale | false | batch older than 3,600 s |
That stale popular list came from the same batch, so it's just as old. The idea is that a bestseller goes off more slowly than one person's taste, and we haven't measured that.
Nobody waited an hour. The clock is passed in, so a test can move it forward:
def test_stale_candidates_fall_back():
t = [appmod.recs.b["built_at"]]
s = fresh(clock=lambda: t[0], max_age=100)
assert s.get(3)["source"] == "model"
t[0] += 500
assert s.get(3, k=6)["source"] == "popular_stale"
..... [100%]
5 passed in 0.72s
The five tests cover the known user, the cached second call, the new user, the model being down and the stale batch. Testing FastAPI apps this way is covered in Testing FastAPI with pytest.
What the cache bought, and an honest number
We sent 2,000 simulated requests, where some users ask more often than others. The cache hit rate came to 0.819, so about eight in ten requests never reached _compute. A first call took 0.0015 ms and a cached one 0.0006 ms. Faster, but nobody would feel it, because _compute here is only a few dictionary lookups. A cache earns its place when something slow sits behind it. It isn't free either: 400 users leave 400 entries, and nothing removes them. These timings come from one CPU run.
Then the quality check in measure.py, which holds out one random item per user and asks if it's in the top 5:
hit@5 popular 0.35
hit@5 model 0.307
In this small project, the popular list actually beats the stored model list. So a fast service can still give weak answers. Serving doesn't fix quality, so keep measuring it, offline as in Part 3 and online with an A/B test.
Common mistakes
- Caching fallback answers. Users stay on the popular list after the model recovers. Cache only model answers.
- Keying the cache on user alone. k = 5 and k = 6 are different answers.
- Returning an error for unknown users. Return the popular list and say so in
source. - Mixing up TTL and max age. One is per answer, the other is for the whole batch.
- Testing time with
sleep. Pass the clock in and move it forward. - Letting the cache grow forever. 400 users, 400 entries, and nothing removes them.
Recap
| Piece | What it does here |
|---|---|
| Precomputed candidates | 30 per user from a batch job; a request is a lookup |
| Cache | key (user_id, k), TTL 60 s, model answers only; hit rate 0.819 |
| Fallback ladder | popular_error, popular_new_user, popular_stale (batch over 3,600 s) |
| Source field | every answer says which path ran |
| Quality | hit@5: popular 0.35, model 0.307, so keep measuring |
Try it yourself: in service.py, set the TTL to 0, run ask.py again, and watch the cached flag on the second call. The project files are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
Next →Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.