Architecture

From Nightly Batch to In-Session: Rebuilding Ranking Around a 120 ms Budget

A batch recommender is a model of who you were yesterday. Here is the architecture that moved ranking into the session, what it cost, and the three places latency actually hides.

A nightly batch recommender answers a specific question: given everything this person did up to midnight, what should we show them?

That is a perfectly good question. It is also not the question a browsing session is asking. Someone who has spent the last four minutes looking exclusively at winter jackets is telling you something right now, and a model trained on yesterday's snapshot cannot hear it. You can have the best batch recommender in the world and it will still show a jacket shopper the sandals they bought in April.

This is a write-up of moving from the first architecture to the second, and the parts that were harder than I expected.

#What "real-time" actually has to mean

The phrase is used loosely enough to be meaningless, so it is worth being precise about which clock you are racing.

There are three distinct latencies in a recommender and they are frequently confused:

  1. Serving latency. How long a ranking request takes. Measured in milliseconds.
  2. Feature freshness. How old the inputs to that request are. Measured in anything from milliseconds to a day.
  3. Model freshness. How old the trained weights are. Usually days.

A batch system has fast serving (it's a key lookup) and terrible feature freshness. Everyone notices the first number and ignores the second. The thing users actually perceive as "this site gets me" is almost entirely feature freshness. You can serve a stale recommendation in 8 ms and it will still feel stupid.

So the target was not "faster responses". It was: an event that happens at t must be able to influence ranking by t + 2s, and the ranking call itself must finish inside 120 ms at p95.

#The shape of the system

The batch version was three boxes: a nightly Spark-ish job, a table of precomputed recommendations keyed by user, and an API that read from it.

The in-session version is five.

code
 browser ──event──▶ collector ──▶ stream ──▶ feature writer ──▶ online store
                                                                     │
 browser ──request──▶ ranking API ──▶ candidate gen ──▶ scorer ◀─────┘
                                            │
                                      item index (ANN)

The key change is that the online store is now written to continuously and read from on every request, rather than being populated once a night.

Collector. A single endpoint that accepts batched client events, validates them and drops them on a stream. Deliberately dumb, no enrichment, no joins. Its only job is to never be the thing that falls over.

Feature writer. Consumes the stream and maintains a small, bounded per-session state in Redis: the last N viewed items, a rolling category histogram, dwell buckets, and the session's entry context. Bounded is the important word. The temptation is to maintain rich per-user state; the discipline is to maintain the smallest state that changes the ranking.

Candidate generation. Approximate nearest neighbours over item embeddings, seeded by the session's recent items. This is where the in-session signal enters. A user who has viewed three jackets gets a candidate pool built from jacket neighbours, not from their all-time profile.

Scorer. The ranking model. Takes the candidate pool plus session features plus long-term user features (which can be a day stale, that is fine) and orders them.

#Where the 120 ms actually went

My first working version ran at about 340 ms p95, which is not a recommendation system, it is a loading spinner. Here is where the time was, in the order I found it.

Feature fetch was N round trips. The scorer was fetching features per candidate. Two hundred candidates, two hundred Redis calls. Obvious in hindsight, invisible while writing it because each call is sub-millisecond and the damage is entirely in the round trips. Pipelining the whole batch into one call took it from ~150 ms to ~9 ms.

Candidate generation was too generous. I was retrieving 500 candidates and scoring all of them, on the theory that more candidates means better recall. Measured against the actual positions users click, almost entirely the first twelve, the marginal value past about 150 candidates was indistinguishable from noise. Cutting the pool cut scoring time proportionally.

The model was fine; serialisation was not. Python object construction for every candidate was costing more than the forward pass. Moving to a single pre-allocated numpy array, filled in place, removed a surprising amount of time. This is a boring optimisation and it bought more than any clever modelling change.

Final shape: p50 around 38 ms, p95 around 110 ms, with candidate generation and scoring roughly even.

#The three things I underestimated

Event ordering. Streams give you at-least-once delivery, not order. A "removed from cart" arriving before the "added to cart" it refers to will corrupt session state in a way that is almost impossible to reproduce. Every event carries a client timestamp, and the feature writer ignores anything older than the state it already holds. Cheap, and it ends an entire category of ghost bugs.

Backfill on cold Redis. The first time the online store restarted, every session lost its state at once and the whole site fell through to the contextual fallback. Fine, but silent. The fix was not persistence. It was alerting on the ratio of requests served by each layer, so a mass fallback is loud.

Training/serving skew got worse, not better. With a batch system, the features in training and the features at serving came from the same table, so they matched by construction. With a streaming system, training features are reconstructed from historical logs and serving features are computed live, and they drift apart in a dozen small ways. Timezones. Null handling. Whether a dwell event that never got a "page hidden" counts.

The only thing that reliably caught this was logging the exact feature vector used for a sample of live requests and comparing its distribution to the training distribution, feature by feature, on a schedule. Three real bugs came out of that comparison, and none would have shown up in any accuracy metric, they just quietly made the model slightly worse than it was in the notebook.

The hard part of a real-time recommender is not the real-time part. It is keeping two codepaths that compute the same features from agreeing to disagree.

#What stays batch, and why that matters

The mistake available at this point is to decide that if real-time is good, everything should be real-time. It should not, and the discipline of deciding what stays batch is most of what keeps the system affordable.

Three things stayed firmly offline.

Item embeddings. Computed nightly from the catalogue. A product's description does not change between 2 pm and 2:05 pm, and recomputing embeddings continuously would burn compute to produce identical vectors. New items get embedded on write, which is the only real-time path that is justified.

Long-term user profiles. Lifetime category affinity, price sensitivity, typical basket size. These are genuinely slow-moving. A day of staleness is invisible to the user and the batch job is an order of magnitude cheaper than maintaining them in a stream.

Model training. Weekly. A continuously-trained ranker sounds appealing and introduces an unpleasant property: when quality drops you cannot tell whether it was the data, the code, or the particular hour the model happened to be trained in. Discrete, versioned, rollback-able training runs are worth more than freshness here.

So the system is a hybrid, and the dividing line is a question I now ask of every feature: does this change within a session? Session state does. Item content does not. Lifetime behaviour does not. Only the first group earns the streaming path.

Getting this wrong in the generous direction is expensive in a way that is easy to miss, because nothing breaks. You just spend several times more on infrastructure than the problem requires, and your on-call surface grows for no gain.

#The caching layer I did not plan for

One more thing emerged from load testing rather than design.

Candidate generation was the most expensive step, and a large fraction of requests were asking for neighbours of the same small set of popular items. Approximate nearest-neighbour lookups for the twenty most-viewed products were being recomputed thousands of times an hour, returning identical results each time.

Caching neighbour lists per item, with a TTL tied to the nightly embedding rebuild, removed a large share of ANN calls. The cache key is the item, not the user, which is what makes the hit rate high. Personalisation happens at the scoring step, after retrieval, so the retrieval step is far more cacheable than it first appears.

The general shape: find the part of your pipeline that does not depend on the user, and cache it hard. In most ranking systems that is candidate generation and feature lookup for item-side features, and together they are usually the majority of your latency budget.

#Was it worth it?

For a catalogue where intent shifts within a session, fashion, travel, food, most marketplaces, yes, clearly. The in-session signal is the strongest single input you have, and a batch system throws it away by construction.

For a catalogue where preferences are stable over weeks, insurance, enterprise software, most B2B. The honest answer is probably not. You will spend three months building streaming infrastructure to capture a signal that barely moves. A nightly job and a good fallback chain would serve you better, and you can spend the three months on something that matters more.

The useful question is not "is real-time better". It is "how fast does intent change in my domain, and am I currently throwing that change away?" If the answer is "within a session", you have a latency problem. If it is "within a quarter", you have a batch job and a lot of free time.