The interview problem

Practice prompt

Design product recommendations for visitors without long-lived user profiles. A session contains only a few clicks, and intent can change abruptly. Serve recommendations within a 100 ms server-side budget at 20,000 requests/second while handling duplicate and delayed events. Explain training, evaluation and fallback behavior.

Original ML-design practice, not a reported company interview. Workload and examples are hypothetical. Primary research retrieved September 27, 2026; interview date not applicable.

1. Define what a session means

Use a short-lived opaque session token scoped to this application, with an explicit inactivity expiry. Do not quietly turn it into a persistent identity by joining devices or recovering past browsing histories. The session may still contain sensitive behavioral information; anonymous here means no long-lived profile, not that every event is nonpersonal.

Start with eligible product discovery as the objective. Measure useful engagement and completed purchases where available, alongside availability, diversity and latency. A next-click prediction is a training proxy, not proof that the recommendation caused value. Define whether already-viewed products should remain eligible: comparison shopping may benefit from revisits.

Separate one session from one person. Multiple tabs, shared devices and token resets can fragment or mix behavior. Prefer an explicit new-session action and a bounded retention policy over an unsupported claim that the system understands identity.

2. Keep the serving path bounded

click event → validation/dedup → ordered session state
                                      ↓
request + current item → candidate retrieval → rank → eligibility filter
                                      ↓
                       response + impression/version log

historical event snapshots → prefix examples → temporal evaluation → model release

Keep the most recent bounded event sequence and derived state in a partitioned store keyed by session token. Retrieve candidates from item-to-item neighbors, session embeddings and a contextual popularity fallback. Rank using recent actions, item metadata, recency and availability. Apply authoritative eligibility checks before returning products; an embedding index is not a stock or permission authority.

A simple starting baseline combines last-item neighbors with time-decayed category preferences. Compare a recurrent or attention-based sequence model only after the event and evaluation pipeline is trustworthy. Hidasi and colleagues studied recurrent models for short session recommendation; that motivates a model family, not a claim that it is best for this workload.

Reserve illustrative stage budgets of 10 ms state lookup, 25 ms candidate retrieval, 35 ms ranking and 10 ms filtering, leaving 20 ms for overhead within 100 ms. These are allocated deadlines, not independently measured p99 values that can simply be added into an end-to-end p99 guarantee. Measure the whole request path and stop optional stages before the deadline.

3. Make ordering and retry behavior explicit

Give each event an idempotency key, event timestamp and ingestion timestamp. For one client stream, a monotonic sequence number helps order retries; separate tabs need distinct stream identifiers, since their local counters are not globally ordered. Partitioned serialization or compare-and-swap prevents two writers from losing each other's updates.

Maintain a bounded event-id deduplication window. Its retention must cover the supported retry horizon; beyond that horizon, reject stale replays or accept that deduplication is no longer guaranteed. A duplicated click must not update a recurrent hidden state twice. Commit the event-id marker and state mutation atomically, or a crash between separate writes can lose an event or apply it twice.

A delayed earlier click cannot safely be appended as though it happened last. Either rebuild the bounded sequence in the defined order or exclude the late event from online state under a documented lateness policy while retaining it for audit. Resolve timestamp ties deterministically, and limit trust in client clocks. Offline feature replay must reproduce the information actually available at recommendation time.

Version sequence features and hidden state with the model that produced them. A new encoder must rebuild state from retained events or start fresh; interpreting an old hidden vector under new weights silently corrupts the input. If the model represents exactly the last twenty events, recompute from that window or use a model with an explicit eviction mechanism; a recurrent hidden state carried forward indefinitely still contains older history after raw events are dropped. When state is missing, serve a contextual fallback rather than extending the response deadline indefinitely.

4. Trace a rapid change of intent

Suppose a visitor clicks three running shoes and then a coffee grinder. A uniform category count favors shoes 3:1. With a per-event decay factor of 0.5, weights from oldest to newest are 0.125, 0.25, 0.5 and 1. Shoes total 0.875 while coffee totals 1, so coffee's normalized share is 1/1.875≈53.33%.

A last-click-only policy assigns all preference to coffee. The decayed policy adapts while retaining some earlier evidence. Neither is universally correct: the grinder could be an accidental click or a genuine new shopping task. Combine actions such as dwell or cart additions only when they are already observed, and evaluate explicit topic-switch slices. Future dwell duration cannot be used for a request sent immediately after the click.

Event-count decay is different from elapsed-time decay. Four clicks in ten seconds and four clicks across an hour receive identical weights in this example. A time-based alternative uses exp(−λΔt), with λ selected on training/validation data under the declared session policy. Do not call the numerical example a learned optimal decay rate.

5. Train on prefixes available at decision time

Create examples mapping a session prefix to the next eligible action. For sequence A,B,C, one example uses A to predict B, and another uses A,B to predict C. Never encode the full A,B,C sequence and then use that vector to predict B. Causal masks are necessary for some architectures but do not prevent leakage through precomputed aggregates containing future events.

Use chronological dataset boundaries and prevent related prefixes from leaking across splits. For sessions crossing a boundary, use a documented policy such as excluding boundary-crossing sessions from that comparison. Build popularity tables and item features only from information available at the relevant cutoff. A catalog entry introduced after an event cannot be a historical candidate merely because it exists today.

Unclicked items are not necessarily disliked; they may never have been exposed. Record impressions, candidate eligibility and recommendation policy versions. Negative sampling changes the learning problem, and sampled evaluation can overstate ranking quality relative to the full eligible catalog. Report the candidate universe and sampling policy. Define how next actions on ineligible products are counted or excluded before evaluation, and report their frequency so eligibility filtering cannot quietly remove difficult targets.

6. Evaluate state, ranking and outcomes separately

For five requests with one relevant next item each, suppose ranks are 1, 2, 10, 11 and absent. Recall@10 is 3/5=0.6. MRR@10 is (1+1/2+1/10+0+0)/5=0.32. Rank 11 contributes zero under the stated cutoff. These are request-level metrics; long sessions with many requests can dominate them, so also report a session-balanced view.

Slice by prefix length, new items, topic switches, region and state availability. Log whether failures come from missing candidates, poor ranking or eligibility removal. A sequence model cannot rank an item that retrieval omitted. Measure end-to-end freshness and latency as well as offline relevance.

For a controlled launch, keep assignment stable for the session and evaluate uncertainty at the randomization unit. Do not interpret session counts as unique people. Track conversion, repeat exposure, failures and latency against the baseline. Shared inventory or repeated visits can complicate independence; declare the experiment's limits rather than assuming all requests are independent.

7. Size the state and failure paths

Assume two million active sessions, each storing twenty events at 32 bytes and a 128-dimensional float32 hidden vector. Raw payload per session is 640+512=1,152 bytes; total is 2.304 GB decimal. Three copies require 6.912 GB before keys, timestamps, dedup metadata, indexes and allocator overhead. Those omitted costs can be substantial.

At 20,000 recommendation requests/second and mean 50 ms in-system time, Little's law gives about 1,000 requests in flight in a stable system. This is not a worker-thread count or a peak-capacity guarantee. Apply admission limits and test bursts. Model state writes depend on event rate, which must be estimated separately from recommendation request rate.

If the session store fails, use current-item or contextual recommendations and expose a degraded-state metric. Avoid replay storms on recovery through bounded queues and jitter. If the catalog or eligibility check fails, return a safe restricted fallback or no recommendations according to the product contract; do not blindly reuse stale sellability decisions.

8. Trade-offs and self-review

Last-click methods are fast and responsive but discard context. Sequence models represent more history but increase state complexity and sensitivity to ordering. Longer sessions provide more signal while raising retention and intent-mixing concerns. Aggressive decay adapts rapidly but overreacts to noise.

Follow-ups: What if a model deployment changes hidden-state dimensions? Rebuild or reset with explicit versioning. What if a click arrives twice? Deduplicate before state mutation. Does high next-click recall prove causal lift? No. Can final-session aggregates train an online prefix predictor? Only if restricted to information available at the prediction time.

Score 0–2 each for session scope, state ordering, intent-switch reasoning, leakage-free evaluation and capacity/fallback design.

Sources and next steps

Architecture, arithmetic and scenarios are original practice. Review data leakage for broader evaluation pitfalls.

Continue your preparation

Choose a connected learning path or browse more ML system design questions. Read our editorial method and attribution policy.