Chapter 21 — Production Inference: Nx.Serving
Nx.Serving provides batched, concurrent inference — and it is a plain OTP
process tree, so everything you know about supervision applies. This chapter
covers the API, then assembles a complete production blueprint — an MNIST
serving Phoenix app — module by module.
21.1 Why Batching Matters
flowchart TD
R1["Request 1"] --> W["batching window<br/>wait up to batch_timeout ms<br/>OR until batch_size reached"]
R2["Request 2"] --> W
R3["Request 3"] --> W
RN["…Request N"] --> W
W --> STACK["stack into one batch tensor<br/>{N, C, H, W}"]
STACK --> PASS["single forward pass<br/>on the accelerator"]
PASS --> SPLIT["split results<br/>each caller gets its answer"]
On GPU this is routinely 10–100x higher throughput than sequential calls.
Work one concrete example — assume a forward pass costs ~20ms whether the batch holds 1 or 32 items (true until the accelerator saturates):
| Config | Added worst-case latency | Throughput ceiling |
|---|---|---|
| size 1, timeout 0ms | none | 50 req/s — one pass per request |
| size 32, timeout 5ms | ~5ms wait | 1,600 req/s |
| size 64, timeout 20ms | ~20ms wait | 3,200 req/s |
batch_timeout bounds only the wait for the first arrival: under load,
batches fill instantly and the timeout never binds; idle systems pay the
full window per request. Practical calibration — timeout at a fraction of
your latency budget, size near observed concurrency, raise size only while
telemetry (§21.2) shows batches filling early. And batching is not always
a win: rare, latency-bound calls (a nightly cron job) gain nothing from
waiting for company.
21.2 The API
Wrap any function as a serving:
{init_fn, predict_fn} = Axon.build(mnist_model)
# Keep captured params on the binary backend so Nx can inline them into JIT
params =
init_fn.(Nx.template({32, 784}, :f32), Axon.ModelState.empty())
|> Nx.backend_copy(Nx.BinaryBackend)
serving = Nx.Serving.jit(fn batch -> predict_fn.(params, batch) end)
Start it supervised:
{:ok, _pid} =
Nx.Serving.start_link(
name: :mnist_classifier,
serving: serving,
batch_size: 32, # max requests per batch
batch_timeout: 5 # max ms to wait filling a batch
)
Call it:
# simple (executes inline in the calling process — wrap input in a batch):
Nx.Serving.run(serving, Nx.Batch.concatenate([image]))
# through the named, batching process (joins other concurrent callers):
Nx.Serving.batched_run(:mnist_classifier, Nx.Batch.concatenate([image]))
Client-side streaming decouples submitting work from consuming results —
wrap a serving and run/2 returns a lazy stream of {:batch, output, metadata} events. (Hook messages, when enabled, appear as
{hook_name, payload} in the same stream, so match those separately.)
streaming = Nx.Serving.streaming(serving)
stream = Nx.Serving.run(streaming, Nx.Batch.concatenate([image]))
for {:batch, output, _metadata} <- stream do
send(self(), {:chunk, output})
end
The stream is consumed in the calling process — nothing polls in the
background. If you hand it to a Task and drop the reply, nothing renders
the output.
Built for token-by-token LLM output (Ch 20’s stream: true) and any
generation long enough that partial results keep callers alive.
| Option | Meaning |
|---|---|
name | registered name for batched_run/2 |
serving | %Nx.Serving{} from jit/2 or Bumblebee |
batch_size / batch_timeout | batching window knobs |
Lifecycle is pure OTP. The supervised serving process receives batched_run/2
calls synchronously: while it executes a batch, later callers wait in its
mailbox. There is no hidden worker pool to tune; scale by adding named
servings (per model variant or tenant) and let routing spread load. Shutdown
honors supervisor semantics — give the child a sensible shutdown value so
in-flight batches drain on deploy.
An unbounded mailbox is buffering, not admission control. Callers queue,
they are not rejected; under a burst the queue grows until the BEAM runs out
of memory, and GenServer.call’s timeout becomes your only backpressure —
which surfaces to users as a 500, not a 503. Bound concurrency at the
caller, where you can still do something about it:
# in the controller — batched_run/3 has no timeout option; bound the wait here
task = Task.async(fn -> Nx.Serving.batched_run(:mnist_classifier, batch) end)
case Task.yield(task, 2_000) || Task.shutdown(task, :brutal_kill) do
{:ok, results} -> json(conn, %{prediction: results})
nil -> conn |> put_status(:service_unavailable) |> json(%{error: "busy"})
end
A semaphore in front of the serving (Ch 26’s pattern) bounds the in-flight count; the caller-side timeout above plus a 503 is the honest alternative. Pick one deliberately — the queue depth is not a policy.
Telemetry: [:nx, :serving, :execute], [:nx, :serving, :preprocessing],
[:nx, :serving, :postprocessing] — span events with :start/:stop
variants carrying duration (in native units). Attach to the :stop
events:
:telemetry.attach_many(
"mnist-serving",
[
[:nx, :serving, :execute, :stop],
[:nx, :serving, :preprocessing, :stop],
[:nx, :serving, :postprocessing, :stop]
],
fn event, measurements, _metadata, _config ->
ms = System.convert_time_unit(measurements.duration, :native, :microsecond)
Logger.info("#{inspect(event)} #{ms}µs")
end,
nil
)
There is no [:nx, :serving, :latency] event — if you want a latency chart,
derive one from :execute, :stop with a Telemetry.Metrics.summary.
Two scaling options this section has not covered yet, both relevant on real fleets:
partitions: truespreads a serving across multiple devices, andNx.Serving.batched_run/3can route to whichever node in the cluster holds the serving — every node must run the same Nx version.- Scale horizontally behind a load balancer: one serving per node, sticky or hash-routed, with weights pinned per node (Ch 09 §9.6 covers rolling weights out).
21.3 Case Study: A Production MNIST Serving App
The blueprint: a Phoenix app that trains an Axon MLP via a mix task,
persists weights, and serves predictions through a supervised Nx.Serving.
Assemble it from parts you already know:
mix phx.new mnist_phoenix --live
cd mnist_phoenix
# add deps: {:axon, "~> 0.8"}, {:exla, "~> 0.13"}, {:scidata, "~> 0.1"}
Four ML modules carry the entire design — ML.Model is Ch 19 in module
form; the other three apply §21.2 to real lifecycle concerns. Once running,
the interfaces look like this:
mix mnist.train --epochs 10 # trains + saves weights to priv/models/
# mix mnist.retrain --epochs 5 # continue from the saved model
mix phx.server # http://localhost:4000 → draw a digit
curl -X POST http://localhost:4000/api/predict \
-H 'content-type: application/json' \
-d '{"image":"<base64-encoded-784-byte-image>"}'
The supervision tree
def start(_type, _args) do
children = [
MnistPhoenixWeb.Telemetry,
{DNSCluster, query: ...},
{Phoenix.PubSub, name: MnistPhoenix.PubSub},
MnistPhoenix.ML.ServingManager, # ← ML lifecycle as a GenServer
MnistPhoenixWeb.Endpoint # web last, as usual
]
Supervisor.start_link(children, strategy: :one_for_one, name: MnistPhoenix.Supervisor)
end
The ML stack is just more children in the tree you already understand:
flowchart TD
SUP["MnistPhoenix.Supervisor"] --> TEL["Telemetry"]
SUP --> DNS["DNSCluster"]
SUP --> PS["PubSub"]
SUP --> SM["ML.ServingManager<br/>GenServer — model lifecycle"]
SM --> SERVE[":mnist_classifier<br/>Nx.Serving — batched inference"]
SUP --> EP["Web.Endpoint<br/>HTTP last, as usual"]
Layer by layer
ML.Model — pure model definition & data prep (Axon.input → dense → dropout → dense → softmax; MNIST download/normalize/one-hot; train,
evaluate, build_predict_fn). Same content as Ch 19, in module form.
ML.Persistence — saves Axon.ModelState to priv/models/ via
:erlang.term_to_binary, with explicit encode/decode for tensors:
defp encode_term(%Nx.Tensor{} = tensor),
do: {:tensor, Nx.type(tensor), Nx.shape(tensor), Nx.to_binary(tensor)}
defp decode_term({:tensor, type, shape, binary}),
do: binary |> Nx.from_binary(type) |> Nx.reshape(shape)
Plus JSON metadata (saved_at) alongside.
ML.ServingManager — GenServer owning the lifecycle:
# config/runtime.exs — the backend is selected ONCE, for the whole node
config :nx, :default_backend, EXLA.Backend
# lib/mnist_phoenix/ml/serving_manager.ex
def init(_opts) do
# NO Nx.default_backend/1 here. It is process-local: setting it in this
# GenServer's init does NOT reach the Nx.Serving partition workers, which
# are separate processes doing the actual tensor work. Ch 18 §18.3 has the
# four setters and their scopes.
case load_model_and_start_serving() do
{:ok, model, params} -> {:ok, %{model: model, params: params, serving_started: true}}
{:error, _reason} -> {:ok, %{model: nil, serving_started: false}} # degrade, don't crash boot
end
end
(“Degrade, don’t crash boot” is the right call here and wrong for most supervisors. Serving is the app’s reason to exist, so you may prefer a failed start — decide per app, and be deliberate either way.)
Also handles :status calls and {:retrain, opts} — retraining can happen
live without restarting the endpoint.
ML.Serving — starts the batched serving, decodes the wire format, and
exposes typed entry points. The curl above posts base64; nothing decodes it
yet, and that glue is the part you always end up writing:
@serving_name :mnist_classifier
@batch_size 32
@batch_timeout 5
# The controller hands a base64 string; tensors must never come from JSON.
defp decode_image!(%{"image" => b64}) when is_binary(b64) do
b64
|> Base.decode64!()
|> Nx.from_binary(:u8)
|> Nx.reshape({1, 784})
|> Nx.as_type(:f32)
|> Nx.divide(255)
end
# ...and the response goes back out as labels + confidence, never raw logits.
defp encode_prediction(logits) do
%{label: Nx.to_number(Nx.argmax(logits, axis: 1)),
confidence: logits |> Nx.exp() |> Nx.sum(axis: 1) |> Nx.to_flat_list()}
end
Then the serving itself:
def start_serving(model, params) do
predict_fn = Model.build_predict_fn(model)
serving_params = Nx.backend_copy(params, Nx.BinaryBackend)
# Nx.Serving.jit/2 IS `new/1` with the jit wrapper already applied —
# do not call new/1 on its result.
{:ok, _} =
Nx.Serving.jit(fn batch -> predict_fn.(serving_params, batch) end)
|> Nx.Serving.process_options(batch_size: @batch_size, batch_timeout: @batch_timeout)
|> then(&Nx.Serving.start_link(name: @serving_name, serving: &1))
{:ok, params}
end
The callback passed to Nx.Serving.jit/1 takes one argument — the
%Nx.Batch{} — and jit/2 is literally new(fn opts -> Nx.Defn.jit(fun, opts) end).
Do not re-wrap its result with new/1; that expects a function, not an
%Nx.Serving{}.
The batch-keyed form Nx.Serving.new(fn key, opts -> ... end) is only worth
the extra indirection once you actually produce keys with Nx.Batch.key/2
and declare batch_keys: in process_options (see Nx.Serving’s docs for
the two-key example). Without a key producer, the batch key is dead
complexity — and Bumblebee does pass keys, which is why its path hits that
EMLX incompatibility in Ch 18.
Serving input is a %Nx.Batch{}, not a tensor. That is why every caller
goes through Nx.Batch.concatenate/1 — it adds the batch axis and marks the
structure as batched:
def predict_single(image) do
image
|> ensure_batch_dim() # {784} → {1, 784}
|> then(&Nx.Batch.concatenate([&1]))
|> Nx.Serving.batched_run(@serving_name)
|> Nx.argmax(axis: 1)
|> Nx.to_number()
end
def predict_batch(images) do
images
|> ensure_batch_dim()
|> then(&Nx.Batch.concatenate([&1]))
|> Nx.Serving.batched_run(@serving_name)
|> Nx.argmax(axis: 1)
|> Nx.to_flat_list()
end
# Shape validation lives at the boundary — and it is only useful if the
# helper actually exists. Here it is:
defp ensure_batch_dim(t) when is_struct(t, Nx.Tensor) do
case Nx.rank(t) do
1 -> Nx.new_axis(t, 0) # {784} → {1, 784}
2 -> t # already {B, 784}
r -> raise ArgumentError, "expected {784} or {B, 784}, rank #{r}"
end
end
Without that guard a single image arrives as {784}, the model’s first
Nx.dot broadcasts against a weight matrix expecting a batch dim, and you
get a shape error 200ms downstream instead of a clear message at the edge.
Mix.Tasks.Mnist.Train / Mnist.Retrain — ops tasks wrapping the same
modules:
mix mnist.train --epochs 20 --batch-size 128
Tasks call Trainer.train_and_save/1 → prepare data → train → evaluate →
persist.
Telemetry Wiring and Warmup
Attach handlers once at boot — the events carry batch sizes and latencies, ready for LiveDashboard or any metrics backend:
:telemetry.attach_many(
"serving-metrics",
[
[:nx, :serving, :execute, :stop],
[:nx, :serving, :preprocessing, :stop],
[:nx, :serving, :postprocessing, :stop]
],
fn event, measurements, _meta, _cfg ->
Logger.info("#{inspect(event)}: #{inspect(measurements)}")
end,
nil
)
One operational subtlety: compilation is per-boot and per-shape-signature. The first real request after a deploy pays it — so health checks should send a synthetic prediction (a zeros tensor works) before marking the node ready. Kubernetes users know this as a readiness probe; here it doubles as JIT warmup.
Lessons to steal
- Model lifecycle is a process: load-on-boot, health via
:status, hot retrain via messages. - Params are immutable data: copy to BinaryBackend once; capture in the JIT closure.
- Persistence is explicit: serialize tensors with type+shape so loads are backend-agnostic.
- Degrade gracefully: missing model file ≠ crashed app; the page renders and reports serving status.
- Batching knobs live next to the serving, not scattered across callers.
Deployment notes specific to EXLA-based releases:
- Bake dependencies (and the downloaded XLA runtime archive) into the release image; nodes must not fetch runtimes at boot.
- Pre-populate the model directory (
priv/models/) in the image or mount it — first-boot downloads are an outage waiting to happen. - Container memory must cover weights + activations + BEAM heap; watch RSS under load, not just at idle.
- Keep backend selection in one place —
config/runtime.exs, orNx.global_default_backend/1for a notebook. Not a GenServerinit/1:Nx.default_backend/1is process-local and would not reach the serving workers (Ch 18 §18.3).
21.4 A Reviewer’s Checklist for Inference Services
Before shipping any Nx.Serving-based service, walk this list — each row
maps back to material above:
| Concern | Question | Reference |
|---|---|---|
| Supervision | Serving a supervised child with sane shutdown? | §21.2 |
| Degradation | Missing/corrupt model file degrades, not crashes? | §21.3 |
| Shapes | Input validated at the boundary (rank, dtype, size)? | §21.3 |
| Batching | Size/timeout match measured traffic, not guesses? | §21.1 |
| Observability | batch_size/latency telemetry attached? | §21.3 |
| Warmup | Readiness gating absorbs first-call compilation? | §21.3 |
| Artifacts | Weights versioned and pinned beside the release? | §21.3 |
| Backend | Platform selection centralized and reviewable? | Ch 18 |
The meta-point for Erlang practitioners: none of this is novel machinery.
It is gen_server etiquette, supervisor hygiene, and telemetry discipline —
applied to tensors. Once the model is just another supervised process with
an API, production AI stops feeling special.
Explore More
- Nx.Serving docs — streaming servings, process options, and the full telemetry event list
Nx.Batch— concatenate vs pad, per-batch compilation keys- Build the §21.3 blueprint yourself, then break one piece on purpose (delete a model file) to watch graceful degradation work
- Telemetry guide — wire
[:nx, :serving, :execute, :stop]into a LiveDashboard chart - Exercise idea: add a probabilities endpoint to your blueprint app — return all ten logits after softmax instead of only the argmax digit
- Practice Labs: Lab 4 — Fashion-MNIST CNN and Lab 6 — Semantic Search — train-then-serve discipline and multi-model serving on all-new examples
Checkpoint
- Difference between
Nx.Serving.run/2andbatched_run/2? - Where does the app change backends per platform?
- How would you add a second model to the same app?
Answers
run/2executes inline (own single batch);batched_run/2goes through the registered serving process and joins other concurrent callers’ batches.config/runtime.exs(config :nx, :default_backend, EXLA.Backend).- Define its serving under a new name in
ML.Serving, add it to the supervision children (or ServingManager), callbatched_run(OtherName, ...).
Next: Chapter 28 — LLM Integration & Agents — skipping Part V (Ch 22–27) because the AI track goes straight to agents. If you want the OTP mechanics under the hood before that, detour to Chapter 22 — Processes through Chapter 27 — Debugging & Tracing.