Online inference

Also known as: real-time inference

On this page 7

Online inference, also called real-time inference, is the practice of running a trained machine learning model on demand for individual requests and returning predictions within a strict latency budget, typically from a few milliseconds to a few seconds. In AI infrastructure it is the serving mode behind search ranking, fraud scoring, recommendations and conversational assistants, where a user or another service waits for the answer.

Online inference contrasts with batch inference, which scores large datasets on a schedule when nobody is waiting. The defining constraint is that the system must meet tail latency targets under unpredictable traffic while keeping hardware costs acceptable, which shapes every design choice from model size to autoscaling.

How online inference serves a request

Online inference follows a request-response path that starts when a client calls an inference endpoint and ends when the prediction returns. Each stage adds latency, so engineers measure and budget every hop rather than only the model’s compute time.

A typical request passes through a load balancer or AI gateway, then an inference server that deserializes inputs, fetches features, runs the model on a CPU or GPU and post-processes the output. The table below shows where time is usually spent.

StageWork performedTypical latency share
Network and gatewayRouting, authentication, rate limitsLow, a few milliseconds
Feature retrievalLookups in an online feature storeModerate for tabular models
Queueing and batchingWaiting for a free worker or batch slotGrows sharply under load
Model executionForward pass on CPU, GPU or acceleratorDominant for large models
Post-processingThresholds, formatting, loggingUsually small
Stages of an online inference request

For large language models, model execution splits into a prefill phase that processes the prompt and a decode phase that generates tokens one by one. Many LLM services therefore use streaming responses, so the user sees the first tokens long before the full answer is complete.

Latency, throughput and cost metrics

Online inference is judged by tail latency, throughput and cost per request together, because improving one usually worsens another. Averages hide the problem: a service with a fast mean but a slow 99th percentile still frustrates many users at scale.

MetricDefinitionTypical target range
p50 and p99 latencyMedian and tail response time10-200 ms for ranking models
Time to first tokenDelay before the first LLM tokenRoughly 0.2-2 s for chat
Time per output tokenGap between generated tokensOften 20-100 ms
ThroughputRequests or tokens served per secondSet by traffic forecasts
GoodputThroughput that meets latency targetsAs close to throughput as possible
Cost per requestHardware cost divided by served loadDepends on model and utilization
Key metrics for online inference

These ranges vary widely with model size, hardware and product expectations, so teams define service level objectives for their own workload rather than copying generic numbers. Goodput is especially useful because it counts only requests that actually met the objective.

Online inference compared with other serving modes

Online inference is one of several serving modes, and choosing the right one depends on whether someone waits for the result. Many production systems combine modes, for example precomputing candidate lists in batch and re-ranking them online.

ModeWhen predictions are madeBest suited for
Online inferenceSynchronously, per requestInteractive apps, fraud checks, chat
Batch inferenceOn a schedule over large datasetsReports, nightly scoring, embeddings
Streaming inferenceContinuously on event streamsSensor data, log analysis
Serverless inferenceOn demand with scale to zeroSpiky or low traffic
On-device AILocally on phones or edge hardwarePrivacy, offline use, low latency
Comparison of inference serving modes

The key trade-off is freshness versus efficiency. Online inference uses the latest inputs, such as the current shopping cart, but it pays for idle capacity and small batches, while batch inference achieves much higher hardware utilization with stale results.

Techniques that make online inference fast

Engineers reduce online inference latency by shrinking the work per request and by keeping hardware busy without long queues. The most effective techniques depend on whether the model is a compact classifier or a large generative model.

  • Dynamic batching groups requests arriving within a few milliseconds to raise GPU efficiency.
  • Continuous batching lets LLM servers add and remove sequences at every decode step.
  • Model compression through quantization, pruning or distillation lowers compute per request.
  • KV cache reuse and prompt caching avoid recomputing shared prompt prefixes.
  • Speculative decoding uses a small draft model to propose several tokens at once.
  • Inference autoscaling adds replicas ahead of traffic peaks to prevent queue buildup.

Each technique has limits. Larger batches improve throughput but increase waiting time, and aggressive quantization can reduce accuracy on rare inputs, so every optimization should be validated against both quality and latency targets.

Common failure modes and how to avoid them

Most online inference incidents come from capacity, dependency and consistency problems rather than from the model itself. The table pairs frequent symptoms with their usual causes and fixes.

SymptomLikely causeTypical fix
p99 latency spikesQueue buildup during traffic burstsAutoscaling and admission control
Slow first requestsModel cold start on new replicasWarm pools and preloaded weights
Accuracy lower than offline testsTraining-serving skew in featuresShared feature definitions
Timeouts during outagesSlow feature store or downstream APITimeouts, caching, model fallback
High cost at low trafficIdle GPUs reserved for peaksScale to zero or shared GPU partitioning
Online inference problems and remedies

Reliable services also define a fallback behavior, such as a simpler model or a cached default, and they track model drift through monitoring so that degraded predictions are noticed before users report them.

Put simply

Online inference means asking an AI model a question and getting the answer right away. It is like ordering at a coffee counter. You wait at the counter, so speed matters a great deal.

Batch inference is more like a bakery that prepares bread overnight for the morning. Online inference is made to order, while batch inference is made in advance. Made to order is fresher. It also needs staff ready even when few customers arrive, which costs more.

In practice

A payment processor scores every card transaction for fraud before approving it. The checkout flow allows the fraud service about 50 milliseconds, so the team deploys a gradient-boosted model on CPU servers behind a load balancer. Each request fetches recent spending features from an online feature store, runs the model and returns a risk score.

During a holiday sale, traffic rises roughly fivefold within an hour. Because the team configured autoscaling on queue depth and kept warm replicas ready, p99 latency stays near 40 milliseconds. When the feature store slows briefly, a timeout triggers a fallback rule set, so payments continue with slightly weaker scoring instead of failing. Fraud checks stay within budget for the whole peak, and engineers later review the fallback periods in their monitoring dashboards.