Batch vs real-time inference

In one sentence

Batch precomputes predictions on a schedule (cheap, stale); online computes them per request (fresh, latency-bound); streaming keeps features fresh from events. Choose by how fresh the decision must be, and usually mix them.

Analogy: A bakery bakes bread at 5 a.m. (batch), makes sandwiches to order (online), and a runner tells the counter when the oven tray just came out (streaming).

The hybrid most teams end up with: batch precomputes the expensive part, streaming keeps features fresh, the online model decides per request.

How it works

  • Batch is cheapest per prediction and validated before use, but scores users who never show up.
  • Online handles inputs you can't enumerate, like a search query, but you pay for peak capacity.
  • Online latency is tight: a page gets ~100–200 ms end to end, and the model only a slice.
  • Streaming through Kafka and Flink updates features within seconds, making 'the user just clicked X' usable.
  • Typical hybrid: precompute candidates or embeddings in batch, then rank in real time with fresh features.

Check yourself

Answer to mark it learned; your answers aren't scored.

An e-commerce site recomputes 'recommended for you' nightly for 20M users. A shopper who just bought a tent keeps seeing tents all morning. What's the best fix?

Go deeper

Full explanation

Three ways to serve predictions:

  • Batch: a scheduled job scores everything (e.g. all users, nightly) and writes results to a table or key-value store; the app just looks them up. Cheapest per prediction, easy to validate before anyone sees it, but stale by up to one cycle, and it wastes compute on users who never show up.
  • Online (real-time): the model runs per request behind an API. Fresh, and it handles inputs you can't enumerate (a search query, a chat message), but every millisecond counts against a latency budget and you pay for peak capacity.
  • Streaming: events flow through Kafka into Flink or Spark Streaming, which update features within seconds for the online model. This is what makes 'the user just clicked X' usable.

Choose by freshness need × cost. Most real systems are hybrid: precompute candidates or embeddings in batch, then rank in real time with fresh features.

For LLMs, nightly enrichment (tagging, summaries, embeddings) goes through Batch inference APIs at about half price; live chat is online and streamed.

Code Hybrid serving: batch candidates, real-time ranking
pythonHybrid serving: batch candidates, real-time ranking
import redis
from fastapi import FastAPI

app = FastAPI()
kv = redis.Redis(decode_responses=True)

@app.get("/recs/{user_id}")
def recs(user_id: str, k: int = 10):
    # Batch: ~500 candidates precomputed nightly (cheap, up to a day old)
    cands = kv.lrange(f"cands:{user_id}", 0, 499) or popular_fallback()
    # Streaming: session features updated by Flink seconds after each click
    fresh = online_features(user_id, ["last_5_clicks", "session_len"])
    try:
        # Online: rank only the candidates, inside the latency budget
        scores = rank_with_timeout(user_id, cands, fresh, timeout_ms=40)
    except TimeoutError:
        return cands[:k]  # degrade to the batch order, never to an error
    ranked = sorted(zip(scores, cands), reverse=True)
    return [item for _, item in ranked[:k]]
Real example

An e-commerce site recomputes 'recommended for you' nightly for 20M users in a two-hour Spark job. But a shopper who just bought a tent still sees tents all morning. The fix is hybrid, not a rewrite: keep nightly candidate generation (500 items per user), stream clicks and purchases through Kafka into an online feature store, and re-rank the 500 per request in ~30 ms using session features. Serving cost stays close to batch, because only active users trigger the ranker.

Trade-offs +3 · −3

+ You gain

  • Batch: cheapest per prediction, easy to backfill and validate before users see it.
  • Online: fresh, handles unbounded inputs (queries, chat) and reacts to the current session.
  • Hybrid gets most of the freshness at close to batch cost.

− You pay

  • Batch: stale by a full cycle, and wastes compute on inactive users.
  • Online: a latency budget, peak-capacity cost and a 24/7 service to operate.
  • Streaming adds Kafka/Flink operations and is a classic source of training-serving skew.

Use it when

Batch when inputs are enumerable and hours-old answers are fine (churn scores, nightly embeddings). Online when inputs are open-ended or the session changes the answer. Streaming when seconds-fresh features measurably move the metric.

Avoid it when

Don't go real-time or streaming by default: if replaying logs shows fresher predictions barely move the metric, the extra system isn't worth operating.

Numbers to know 3
  • OpenAI Batch API and Anthropic Message Batches: 50% cheaper than synchronous calls, results within 24 h.
  • Rule of thumb: an interactive page has ~100–200 ms end to end; the model gets only a slice of it.
  • Kafka's default retention is 7 days (log.retention.hours=168): your window to replay events into a backfill.
Common pitfalls 4
  • Computing a feature one way in the batch pipeline and another way online: skew.
  • Going real-time 'because it's better' without measuring the uplift of fresher predictions.
  • No fallback when the online model times out: serve the batch result or a popularity list.
  • Batch-scoring every user nightly when only 5% are active: score the active set or go on demand.
Interview questions 2

Answer out loud first, then reveal.

How do you decide between batch and real-time for a new model?Show answer

Two questions: can I enumerate the inputs, and how fast does the right answer change? If inputs are known, like every customer or product, and a day-old answer is fine, batch wins on cost and simplicity. If the input is a free-text query or the session changes the answer, it must be online. Then I measure: replay logs to estimate what fresher predictions would gain. Often the answer is hybrid, batch candidates plus online re-ranking, and I keep the batch result as the fallback.

Where do LLM calls fit: batch or online?Show answer

Both, split deliberately. Anything not user-facing in the moment, such as tagging a catalog, summarizing tickets, generating embeddings or running evals, goes through batch APIs at half price with relaxed latency and easy retries. Live chat and agents are online and streamed, where I optimize time to first token. A strong pattern is precomputing LLM outputs like product summaries nightly, so the online path only does retrieval and a short generation.