Profile and Speed Up a Slow Customers Also Bought Scoring Loop
Last updated: November 29, 2026
Quick Overview
A recommendation function that scores catalog items against a customer's recent purchases takes seconds per call. Find the hot spots and rewrite it to produce identical results orders of magnitude faster.
Amazon
November 29, 20260
0
0 solved
A recommendation function that scores catalog items against a customer's recent purchases takes seconds per call. Find the hot spots and rewrite it to produce identical results orders of magnitude faster.
Amazon recommendation widgets have tight latency budgets on the detail page, and this question checks practical performance work: profiling before guessing, picking data structures that change complexity, and preserving output exactly while optimizing.
What the Interviewer Expects
- Profiles first, for example with cProfile, and names the hot loop
- Recognizes the triple nested loop as O(C times H times P)
- Precomputes a neighbor index offline instead of scanning pairs
- Uses a set for membership and partial selection for top k
- Verifies identical output before and after
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you move the index build into an offline job and ship it to hosts?
- When would you reach for NumPy or sparse matrices instead?
- How would you cap latency for customers with huge histories?
- How would you cache results per customer, and what invalidates them?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
- Score of candidate = sum of co-purchase weights over history items .
- Exclude items already purchased.
- Return the top by score, ties broken by id, identical to the current ou...
High-Level Design
Profiling shows nearly all time in the inner for a, b, w in pairs scan, called for every candidate and history item pair, plus repeated c in history on a list. The fix flips the loop: build a neig...