09 / 16 · Serving
Serving models
How a trained model answers requests: batch, online and streaming inference, the model as a service with its API and timeouts, the batching trade-off between latency and throughput computed, CPUs against GPUs, model servers, prediction caches and fallbacks.
On this page 9
Suppose a preview-quality scorer takes six milliseconds to process one request. Six requests arriving close together still do not all finish in six milliseconds: they compete for the same worker. Serving begins with that queue and with the action taken when a request can no longer meet its deadline.
Separate the artifact from the request handler#
Load a known scoring artifact when a worker starts, validate its schema, and expose readiness only after initialization succeeds. Loading weights for every request adds repeated work and makes latency depend on storage availability. The request handler validates input, assigns a deadline and invokes the initialized scorer. A valid HTTP response still needs an explicit success or failure meaning for the caller.
Keep prediction identity in the response or its trace: request ID, model version and feature version. If a deployment label moves between two requests, these identifiers let an operator distinguish the outputs. MLflow’s registry describes versioned models and aliases; pinning the resolved version avoids treating a movable alias as immutable evidence (MLflow).
Choose how results become available#
A batch job computes a finite collection, such as last night’s previews, and stores outputs for later reading. An online request waits for one answer before its deadline. A stream processes events as they arrive and must define ordering, duplicates and late events. These are interface and scheduling choices; the same scoring function can appear in all three.
For a slow preview repair, returning an accepted job ID can be preferable to keeping a connection open. That changes the contract: the client must be able to inspect completion, and a repeated submission with the same idempotency key should not create duplicate paid work. It does not make the computation itself faster.
Bound accepted work#
The service contract specifies types, units, maximum payload size, output schema, error states and deadline semantics. Apply admission control before an unbounded queue forms. A queue limit means some requests receive an explicit overload response; without a limit they may wait until they all time out after consuming resources.
For an arrival rate and average time in the system , Little’s law gives average work in the system under a stable flow with consistent boundaries. It describes averages, not a tail-latency guarantee. When long-term arrivals exceed service capacity, a stationary finite backlog assumption no longer holds.
Batch overhead is shared; waiting is individual#
Consider an original deterministic simulation. Request arrival times are ms. A batch of requests takes ms, and only one batch can execute at once. The four milliseconds represent a stipulated shared overhead, not a measured device cost.
A deadline for forming a batch#
Compare single-request execution with a maximum batch of three and a three-millisecond batching wait from the oldest queued arrival. Dispatch early when the batch fills. If the worker was busy past that deadline, dispatch the available batch as soon as it becomes free. This dispatch target does not bound total queue time: a busy worker can force dispatch after the deadline.
| Request | Arrival, ms | Single finish, ms | Batched finish, ms |
|---|---|---|---|
| A | 0 | 6 | 13 |
| B | 2 | 12 | 13 |
| C | 3 | 18 | 13 |
| D | 9 | 24 | 21 |
| E | 10 | 30 | 21 |
| F | 17 | 36 | 27 |
The first batch starts at 3 ms with A, B and C, then finishes at 13. D and E are already waiting; their batching deadline has expired, so their batch runs from 13 to 21. F runs from 21 to 27. Subtract arrival from finish for each latency. The average falls from 14.167 to 11.167 ms, while A becomes slower: 13 rather than 6 ms. A lower average does not mean every caller benefits.
The entire burst finishes at 27 rather than 36 ms. Six completions divided by those durations give about 222.22 and 166.67 requests/second within this finite trace. Neither number establishes sustained hardware capacity. Different arrival spacing or a different service-time function can reverse the trade-off. Triton’s dynamic batcher exposes queue-delay and batch controls for this kind of mechanism, but our scheduler is independently authored and is not an implementation test of Triton (NVIDIA).
The scheduler keeps arrivals ordered. now is the worker’s next free time; the earliest pending arrival sets the batching deadline. If enough requests have already arrived, dispatch immediately. Otherwise jump to the earlier of that deadline and the arrival that would fill the batch. Selecting only arrived requests is essential: looking at future arrivals to schedule a wake-up does not make their work available early.
import math
def serve(arrivals, max_batch, wait, fixed, per_item):
pending = list(enumerate(arrivals))
now = 0
finish = {}
batches = []
while pending:
now = max(now, pending[0][1])
deadline = pending[0][1] + wait
count = sum(at <= now for _, at in pending)
if count < max_batch and now < deadline:
full_at = pending[max_batch - 1][1] if len(pending) >= max_batch else math.inf
now = max(now, min(deadline, full_at))
selected = [item for item in pending if item[1] <= now][:max_batch]
start = now
now += fixed + per_item * len(selected)
for index, _ in selected:
finish[index] = now
pending = pending[len(selected):]
batches.append({"start_ms": start, "finish_ms": now,
"requests": [index for index, _ in selected]})
latencies = [finish[i] - at for i, at in enumerate(arrivals)]
return {"batches": batches, "latencies_ms": latencies,
"mean_latency_ms": sum(latencies) / len(latencies),
"burst_finish_ms": now, "completed_per_second_in_burst": 1000 * len(arrivals) / now}
arrivals = [0, 2, 3, 9, 10, 17]
for size, wait in [(1, 0), (3, 3)]:
result = serve(arrivals, size, wait, fixed=4, per_item=2)
ids = [i for batch in result["batches"] for i in batch["requests"]]
assert ids == list(range(len(arrivals)))
assert all(batch["start_ms"] >= arrivals[i]
for batch in result["batches"] for i in batch["requests"])
print(size, result["latencies_ms"], result["burst_finish_ms"])
The executed output is:
1 [6, 10, 15, 15, 20, 19] 36
3 [13, 11, 10, 12, 11, 10] 27
Two assertions check conservation and causality: every ID is executed exactly once in order, and no request starts before arrival. The worker’s advancing clock also prevents overlapping batches. These checks make a scheduling mistake observable before using its average to argue for a configuration.
There is a useful counterexample at low load. Keep the same service rule, but let one request arrive after the previous batch has finished and leave the worker otherwise idle. Immediate execution takes 6 ms; waiting the full 3 ms for partners that never arrive takes 9 ms. Extra waiting buys no shared overhead. At high load, several requests may already be queued when a worker becomes free, so the batch can form without that additional wait. This is why a batch-size choice needs an arrival process as well as a model benchmark.
Admission adds another boundary. Suppose a caller allows 12 ms end to end. The scheduler must account for age already spent in the queue, predicted compute and response work before admitting another wait. A batching-delay setting is not an end-to-end timeout. If a request expires, removing it from the queue and reporting the cancellation prevents stale work from increasing everyone else’s delay. Our small simulation deliberately has no cancellation policy; adding one requires counting expired requests separately from successful completions.
Hardware changes the service-time function#
A CPU may avoid transfer and launch overhead for a small model. A GPU may benefit when enough parallel work is available. Memory bandwidth, model size, input shape and the execution engine all affect the result. Measure the complete path, including serialization and transfers. A utilization percentage alone cannot tell whether the machine is doing useful work or whether the workload meets a deadline.
What a model server contributes#
A model server can own loading, scheduling, version selection and metrics. The application still owns authorization, permitted inputs and the meaning of a score. State must also be explicit: a stateless classifier can combine independent requests, while a recurrent session needs its state kept with the correct sequence. Triton’s documentation distinguishes dynamic batching of stateless models from sequence batching; do not switch schedulers without checking the model contract.
Cache only a well-defined computation#
A prediction cache key needs every input that can change the result: normalized content identity, feature definition, model artifact and relevant options. Include access boundaries where reuse could otherwise expose another user’s result. A response cached before a threshold change may contain a stale action even if its score remains valid. Choose whether the cache stores a score or the final decision, and invalidate accordingly.
Avoid caching a transient failure as a durable prediction. If the model samples outputs, repeating a cached result also changes the distribution the caller experiences. A cache hit rate is useful only alongside correctness and eviction behaviour.
Recover without inventing a successful prediction#
When the scorer is unavailable, the preview service can preserve the upload and defer review. A fallback may use a simpler versioned rule if the product explicitly accepts its behaviour. Tag which path answered. A timeout must propagate cancellation where possible; otherwise an abandoned request may keep consuming the capacity needed by current callers.
What changed#
The serving decision now includes queue time, accepted load and recovery. Batching improves the stipulated burst as a whole while delaying its earliest request. The release and cache contracts make an otherwise invisible artifact change observable.
Limits#
The simulation has no network, variable compute time, failures or memory limit. It demonstrates scheduling arithmetic. Real load tests should vary concurrency and request shape, record failed requests, and compare latency distributions at a stated arrival process. Do not extrapolate the six-request trace into a production capacity claim.
What to retain#
Load and identify the artifact once per worker lifecycle. Bound queued work. Measure complete-request latency. Batch only compatible requests. Key caches by the full computation. Make overload and fallback outcomes explicit.
Reproduce the trace#
Functions serve and serving in Python source implement the discrete-event trace with the standard library. The saved result includes every batch start/finish, every latency and the finite-trace rates. Change arrivals or the service-time formula to examine a different assumption; no real model or accelerator is exercised.
Next#
A language model retains a sequence across many decoding steps. LLM inference systems uses a separate original scheduling trace to explain why completed sequences should release their slots immediately.
References#
- NVIDIA Triton contributors. Batchers, checked 13 November 2026: dynamic batching, queue delay and sequence scheduling. No configuration or benchmark copied.
- MLflow contributors. Model Registry Workflows, checked 13 November 2026: version and alias semantics.
- John D. C. Little. A Proof for the Queuing Formula: L = λW. Operations Research 9(3), 383–387, 1961. The queueing identity; the numerical trace above is independently specified.