Sign in

Online

Online inference (real-time model serving)

A real-time model server in one process: a bounded request queue, dynamic micro-batching, load shedding, timeouts, a cache and latency statistics.

Overview

A model is usually much faster per input when it handles many inputs in one call. Online requests arrive one at a time, though, and each caller is waiting. A model server bridges the two. It lets requests collect for a few milliseconds, runs them through the model as one small batch, and hands each caller its own answer. It also protects itself: when more requests arrive than it can serve, it refuses the extra ones at once, because a late answer is of no use to a caller who has stopped waiting.

A short history

Online model serving borrows from the engineering of web services, with no single inventor: bounded queues, timeouts and load shedding are long standing ways to keep a service responsive under overload. Serving systems for machine learning added batching across requests. Google released TensorFlow Serving in 2016, and the Clipper system by Crankshaw and colleagues in 2017 showed how adaptive batching and caching raise throughput while holding a latency target.

How it works

  1. A caller calls predict(x) with one input. The request is placed in a queue of at most queue_size and the caller waits.
  2. If the queue is full, the request is rejected immediately with ServerOverloaded. This is called load shedding.
  3. A worker thread takes the first waiting request, then gathers more for at most max_wait_ms or until it has max_batch_size.
  4. It stacks the inputs, makes one model call, and gives each caller the row that belongs to it.
  5. A caller who has waited longer than timeout_s gets a TimeoutError, and the worker skips requests whose caller gave up before they started.
  6. With cache_size above zero, repeated inputs are answered from a least-recently-used cache. stats() reports counts, batch sizes and latency percentiles.

Watch out for

  • A long max_wait_ms adds that delay to requests at quiet times, when there is nobody to batch with. Keep it small next to the model's own time.
  • A queue that is too long lets requests wait past their timeout, so the server does work for callers who have already left. Size the queue so it can drain inside the timeout.
  • If requests arrive faster than the server's capacity for long, no setting helps: the queue fills and requests are rejected. That needs a faster model or more servers.
  • A model error fails every request in that batch, so one bad input takes its batch neighbours down with it.
  • This template shows the mechanism only, in one process with one worker thread. It has no HTTP layer and no network.

Use cases

When to use it

When predictions are needed while a user or another service waits. Raise max_wait_ms and max_batch_size to trade a little latency for throughput when the model is much faster per row on a batch.

In industry

Payments
A card payment must be approved or declined in a fraction of a second, so the fraud model is served online with a strict timeout and a fallback rule.
Search and advertising
Ranking models score candidates for each page view. Micro-batching groups requests that arrive within a few milliseconds into one model call.
Conversational products
A text classifier that screens messages for abuse runs behind a bounded queue, and sheds load during spikes instead of slowing every user.

Choosing it: what must hold

  • A caller waiting for each answer, with a latency target measured in milliseconds or seconds.
  • Inputs that only exist at request time.
  • A model fast enough for that target, ideally faster per row when given a batch.
  • A defined behaviour when the server is overloaded or a request times out.

When to choose something else

IfUse instead
All inputs are known in advance and results can be storedThe batch inference lesson, with results served from a lookup table
Traffic needs many machines, rolling updates or several model versionsA dedicated serving system such as TensorFlow Serving, TorchServe or NVIDIA Triton
The model is too slow for the latency targetA smaller or simpler model, for example Logistic Regression or LightGBM

Math foundations

  1. Capacity with batching

    μ=BT(B)\mu = \frac{B}{T(B)}

    The most requests per second one worker can serve when every model call carries a full batch. Batching pays when T(B)T(B) grows more slowly than BB.

  2. Stability condition

    λ<μ\lambda < \mu

    The arrival rate must stay below the capacity. Otherwise the queue grows until it is full and the server starts rejecting requests.

  3. Latency of one request

    L=Wqueue+Wbatch+T(k),0≤Wbatch≤wL = W_{\text{queue}} + W_{\text{batch}} + T(k), \qquad 0 \le W_{\text{batch}} \le w

    A request waits in the queue, then waits for its batch to fill for at most ww, then waits for the model call on a batch of kk. The reported p50 and p95 are percentiles of LL.

  4. Time to drain a full queue

    Wmax⁡≈QB  T(B)W_{\max} \approx \frac{Q}{B}\; T(B)

    A request that joins a full queue has about Q/BQ / B batches ahead of it. Keep this below the timeout, or queued requests expire before they are served.

Symbols

BB
max_batch_size
T(k)T(k)
time of one model call on a batch of k inputs
μ\mu
capacity in requests per second
λ\lambda
arrival rate in requests per second
LL
latency of one request, from submit to answer
Wqueue, WbatchW_{\text{queue}},\, W_{\text{batch}}
time spent queued and time spent waiting for the batch to fill
ww
max_wait_ms, the longest wait for more requests
QQ
queue_size, the most requests waiting at once

Worked by hand

A model takes 5 ms for one input and 8 ms for a batch of 16. The server uses B=16B = 16 and Q=1024Q = 1024.

μno batching=10.005 s=200 requests per second\mu_{\text{no batching}} = \frac{1}{0.005\ \text{s}} = 200 \text{ requests per second}
μbatching=160.008 s=2000 requests per second\mu_{\text{batching}} = \frac{16}{0.008\ \text{s}} = 2000 \text{ requests per second}
Wmax⁡≈102416×0.008 s=64×0.008 s=0.512 sW_{\max} \approx \frac{1024}{16} \times 0.008\ \text{s} = 64 \times 0.008\ \text{s} = 0.512\ \text{s}

Batching raises capacity tenfold. A full queue takes about half a second to drain, which fits inside the default 5 second timeout with room to spare.

Visual example

Loading the example.

Try this

  • Raise the arrival rate past the capacity shown in the readout and watch the queue fill and requests get rejected.
  • Set max_batch_size to 1: the capacity drops to what one call at a time can serve.
  • At a low arrival rate, raise max_wait_ms and see every request pay that wait for a batch that never fills.

Code sample

import numpy as np
from concurrent.futures import ThreadPoolExecutor
from impl import ModelServer
from config import OnlineInferenceConfig

weights = np.array([0.5, -1.0, 2.0])
model = lambda batch: batch @ weights                 # batch (b, 3) -> (b,)

with ModelServer(model, OnlineInferenceConfig(max_batch_size=8, max_wait_ms=5)) as server:
    print(server.predict(np.array([1.0, 2.0, 3.0])))  # 4.5
    inputs = np.random.default_rng(0).normal(size=(50, 3))
    with ThreadPoolExecutor(16) as clients:           # 16 callers at once
        answers = list(clients.map(server.predict, inputs))
    print(np.allclose(answers, inputs @ weights), server.stats()["mean_batch_size"])
Read the implementation (173 lines)
"""Online serving in one process: a request queue, a worker thread, dynamic micro-batching, a bounded queue
that sheds load, per-request timeouts, an LRU cache and latency statistics.

Standard library and NumPy only, no network. Callers hand in ONE input and get ONE answer; the server
merges requests that arrive close together into a single model call, because one call on a batch is much
cheaper than many calls on single rows. A web framework would sit in front of `predict` and is not part
of this template.
"""
from __future__ import annotations

import queue
import threading
import time
from collections import OrderedDict, deque
from concurrent.futures import Future
from concurrent.futures import TimeoutError as FutureTimeout
from typing import Callable

import numpy as np

try:
    from .config import OnlineInferenceConfig
except ImportError:  # run from the template's own folder
    from config import OnlineInferenceConfig


class ServerOverloaded(RuntimeError):
    """The request queue is full. The caller should back off or answer 'try again later'."""


class ModelServer:
    """Serve single predictions from a batch model.

    predict_fn: function(batch) -> outputs, where batch has shape (b, ...) and outputs has b as its first
                dimension. Row i of the output answers row i of the batch.

    Use as a context manager, or call `start` and `stop`.
    """

    def __init__(self, predict_fn: Callable, config: OnlineInferenceConfig | None = None) -> None:
        self.predict_fn = predict_fn
        self.config = config or OnlineInferenceConfig()
        self._queue: queue.Queue = queue.Queue(maxsize=self.config.queue_size)
        self._stop = threading.Event()
        self._worker: threading.Thread | None = None
        self._lock = threading.Lock()                      # guards the cache and the counters
        self._cache: OrderedDict = OrderedDict()
        self._latencies: deque = deque(maxlen=10000)       # seconds, most recent requests
        self._batch_sizes: list[int] = []
        self._counts = {"requests": 0, "cache_hits": 0, "rejected": 0, "errors": 0}

    # ---------------------------------------------------------------------------------------- lifecycle
    def start(self) -> "ModelServer":
        """Start the worker thread."""
        if self._worker is not None:
            raise RuntimeError("the server is already running")
        self._stop.clear()
        self._worker = threading.Thread(target=self._run, name="model-server", daemon=True)
        self._worker.start()
        return self

    def stop(self) -> None:
        """Finish the requests already queued, then stop the worker."""
        if self._worker is None:
            return
        self._stop.set()
        self._worker.join()
        self._worker = None

    def __enter__(self) -> "ModelServer":
        return self.start()

    def __exit__(self, *exc) -> None:
        self.stop()

    # ------------------------------------------------------------------------------------------- client
    @staticmethod
    def _key(x: np.ndarray) -> tuple:
        return (x.shape, x.dtype.str, x.tobytes())

    def submit(self, x) -> Future:
        """Queue one input (shape (...), without a batch dimension) and return a Future for its answer."""
        if self._worker is None:
            raise RuntimeError("the server is not running, call start() first")
        x = np.asarray(x)
        future: Future = Future()
        started = time.perf_counter()
        with self._lock:
            self._counts["requests"] += 1
            if self.config.cache_size:
                key = self._key(x)
                if key in self._cache:
                    self._cache.move_to_end(key)           # mark as most recently used
                    self._counts["cache_hits"] += 1
                    self._latencies.append(time.perf_counter() - started)
                    future.set_result(self._cache[key])
                    return future
        try:
            self._queue.put_nowait((x, future, started))
        except queue.Full:
            with self._lock:
                self._counts["rejected"] += 1
            raise ServerOverloaded(f"{self.config.queue_size} requests are already waiting") from None
        return future

    def predict(self, x):
        """Answer for one input. Blocks until the answer is ready or timeout_s has passed (TimeoutError)."""
        future = self.submit(x)
        try:
            return future.result(timeout=self.config.timeout_s)
        except FutureTimeout:  # before Python 3.11 this is not the built-in TimeoutError, so translate it
            future.cancel()  # if it has not started yet the worker will skip it
            raise TimeoutError(f"no answer within {self.config.timeout_s} s") from None

    # ------------------------------------------------------------------------------------------- worker
    def _collect(self) -> list:
        """Wait for one request, then gather more until the batch is full or max_wait_ms has passed."""
        cfg = self.config
        try:
            batch = [self._queue.get(timeout=0.02)]
        except queue.Empty:
            return []
        deadline = time.perf_counter() + cfg.max_wait_ms / 1000.0
        while len(batch) < cfg.max_batch_size:
            remaining = deadline - time.perf_counter()
            try:
                batch.append(self._queue.get_nowait() if remaining <= 0 else self._queue.get(timeout=remaining))
            except queue.Empty:
                break
        return batch

    def _run(self) -> None:
        while not (self._stop.is_set() and self._queue.empty()):
            # set_running_or_notify_cancel is False for a request whose caller gave up: skip those
            batch = [item for item in self._collect() if item[1].set_running_or_notify_cancel()]
            if not batch:
                continue
            inputs = [item[0] for item in batch]
            try:
                outputs = np.asarray(self.predict_fn(np.stack(inputs)))
                if outputs.shape[:1] != (len(batch),):
                    raise ValueError(f"the model returned shape {outputs.shape} for a batch of {len(batch)}")
            except Exception as error:  # the whole batch fails, the server keeps running
                with self._lock:
                    self._counts["errors"] += len(batch)
                for _, future, _ in batch:
                    future.set_exception(error)
                continue
            now = time.perf_counter()
            with self._lock:
                self._batch_sizes.append(len(batch))
                for (x, _, started), output in zip(batch, outputs):
                    self._latencies.append(now - started)
                    if self.config.cache_size:
                        self._cache[self._key(x)] = output
                        while len(self._cache) > self.config.cache_size:
                            self._cache.popitem(last=False)  # drop the least recently used entry
            for (_, future, _), output in zip(batch, outputs):
                future.set_result(output)

    # -------------------------------------------------------------------------------------------- stats
    def stats(self) -> dict:
        """Counters and latency percentiles (milliseconds) since the server was created."""
        with self._lock:
            latencies = np.array(self._latencies) * 1000.0
            sizes = list(self._batch_sizes)
            out = dict(self._counts)
        out["batches"] = len(sizes)
        out["mean_batch_size"] = float(np.mean(sizes)) if sizes else 0.0
        out["max_batch_size"] = max(sizes) if sizes else 0
        for name, q in (("latency_p50_ms", 50), ("latency_p95_ms", 95), ("latency_max_ms", 100)):
            out[name] = float(np.percentile(latencies, q)) if latencies.size else 0.0
        return out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Start ModelServer(model, OnlineInferenceConfig(max_batch_size=8, max_wait_ms=5)) in a with block and send 200 inputs to predict from a thread pool of 16 callers. Print stats() and note mean_batch_size and latency_p95_ms. Repeat with max_wait_ms=0 and explain both changes.

Check on learning

  1. At 3 in the morning one request arrives per second and max_wait_ms is 50. What latency does each request see, and what does batching buy at that hour?
    A way to think about it

    Follow one lone request through the worker: it waits for companions that never come. Compare that wait with the model time.

  2. Why is it better to reject a request at once when the queue is full than to accept it and answer late?
    A way to think about it

    Think about the caller's timeout, and about the work the server spends on a request whose caller has already given up.

  3. Your p50 latency is 6 ms and your p95 is 80 ms. What could explain such a gap, and why is the mean a poor summary here?
    A way to think about it

    A few requests are far slower than most. Look for causes that hit only some requests: joining a queue behind a full batch, or a cache miss.

  4. The model takes 5 ms for 1 input and 40 ms for 16. A colleague proposes a batch size of 64. How would you decide whether that helps?
    A way to think about it

    Compute requests per second from B/T(B)B / T(B) for each size you can measure, and weigh it against the time added to every request in the batch.

  5. A cache answers repeated inputs without a model call. For which kinds of model inputs is this nearly useless, and when could it return a wrong answer?
    A way to think about it

    Ask how often two requests are identical when inputs are real-valued measurements. Then consider what happens to cached answers when the model is replaced.