Foundations to Frontier
Tests

Model Serving: REST, gRPC and Batch Inference

Serving turns a trained model into a service: requests arrive over the network, are decoded, queue up, run through the model, and the answer goes back, all within a latency target. The main choices are the protocol (REST with JSON, or gRPC with binary protobuf), whether to batch requests together, and whether to predict online at all or precompute predictions in a batch job. The exercises model a server as a queue with realistic decoding and model costs, check the simulation against the Pollaczek-Khinchine formula, and measure how many requests one worker can serve within a p99 latency target for a cheap CPU model and an expensive GPU model under four serving modes. Practice problems cover Little's law and variable service times, load balancing across replicas, batch precomputation, retry storms, and tail latency when requests fan out.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A kitchen with a ticket queue

A restaurant kitchen takes orders, reads each ticket, cooks, and sends plates out. If orders arrive faster than the kitchen cooks, tickets pile up and every diner waits longer. Cooking several identical dishes in one pan is much faster per plate, but the first order waits for the others. And some dishes can be prepared in the morning and simply served, as long as nobody minds that they are not fresh. Model serving faces exactly these choices: how requests are written and read, whether they are batched, and whether predictions are made in advance.

🎮 MLOps lab
REST + JSON, one at a time
136 per s within the SLO (saturation 228) · 3074 bytes · 4.91 / 17.39 ms at 100 per s
gRPC, one at a time
141 per s within the SLO (saturation 234) · 1067 bytes · 4.79 / 16.58 ms at 100 per s
gRPC, batching up to 2 ms
2100 per s within the SLO (saturation 2463) · 1067 bytes · 6.79 / 9.2 ms at 100 per s
gRPC, batching up to 10 ms
2080 per s within the SLO (saturation 2463) · 1067 bytes · 14.79 / 15.91 ms at 100 per s

Blue: highest rate one worker sustains with p99 latency within 25 ms; red mark: saturation. Latencies are median / p99 at 100 requests per second.

N3-1, seed 0. For the cheap model decoding the request is most of the work, so binary gRPC serves 2.5 times as many requests as JSON; for the GPU model the protocol barely matters and dynamic batching serves 15 times as many, at the cost of the batching wait.

Why engineers care

In Exercise 2, switching from JSON to binary gRPC served 2.5 times as many requests for a cheap model but only 4% more for an expensive one, while batching served 15 times as many for the expensive model.

📝 Quick check (Level 0)
0/3 answered
  1. 1. If requests arrive faster than the server can handle them…
  2. 2. Batching requests helps most when…
  3. 3. Precomputing predictions in a nightly batch is suitable when…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • REST: HTTP requests with text payloads, usually JSON; simple, universal, and costly to parse.
  • gRPC: remote procedure calls over HTTP/2 with binary protobuf messages and generated client code; compact and fast to decode.
  • Batch inference: scoring a whole dataset offline (for example nightly) and storing predictions for lookup.
  • Dynamic batching: the server collects requests for a short time (or until a maximum batch) and runs them in one model call; offered by TensorFlow Serving, Triton and TorchServe.
  • Latency percentiles: p50 is the median, p99 the time 99% of requests beat; service level objectives (SLOs) are usually stated on p99.
  • Utilization ρ: arrival rate times mean service time; queues explode as ρ approaches 1.
  • Little’s law: mean number in the system = arrival rate × mean time in the system.
  • Tail at scale: a request that waits for many servers is as slow as the slowest of them.
📝 Quick check (Level 1)
0/3 answered
  1. 1. gRPC messages are encoded as…
  2. 2. p99 latency is…
  3. 3. Utilization ρ equals…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

A server as a queue

Exercise 1.

  • Request: 256 features; JSON text (about 3,000 bytes with headers) or packed float32 protobuf (1,067 bytes).
  • Decoding cost per request: REST 0.1 ms plus 10 ns per byte; gRPC 0.03 ms plus 1 ns per byte; network: 0.5 ms round trip plus 8 ns per byte.
  • Models: small (CPU trees) 0.03 ms per call plus 0.004 ms per example; large (GPU network) 4 ms per call plus 0.25 ms per example.
  • One worker, first come first served: finish times by a running maximum, or dynamic batching with a maximum wait and batch size.

Practice.

  • Measure p99, not the mean, and keep utilization well below 1 to meet it.
  • Use a binary protocol when decoding dominates (cheap models, large payloads); otherwise choose for convenience.
  • Batch on accelerators, with a maximum wait that fits the latency budget.
  • Precompute what does not need to be fresh, and serve the rest online.
  • Route to lightly loaded replicas, cap retries, and hedge fan-out requests.
def serve_batched(arr, decode, model, max_wait, Bmax):
    fin, free, i = np.empty(len(arr)), 0.0, 0
    while i < len(arr):
        t0 = max(free, arr[i]); launch = max(t0, arr[i] + max_wait)
        if i + Bmax - 1 < len(arr):
            launch = min(launch, max(t0, arr[i + Bmax - 1]))
        j = min(np.searchsorted(arr, launch, side="right"), i + Bmax)
        free = launch + (j - i) * decode + model_ms(model, j - i)
        fin[i:j] = free; i = j
    return fin
🐍 Exercise 1: a queueing model of a model server
Compute request sizes and costs, simulate one worker with and without dynamic batching, and check the mean wait against the Pollaczek-Khinchine formula.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Dynamic batching adds latency because…
  2. 2. Switching to binary gRPC helps most when…
  3. 3. A latency SLO on p99 limits…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

One worker. With arrival times a and service times S, the n-th request finishes at f_n = max(f_(n−1), a_n) + S_n. Writing C_n for the cumulative service time, f_n = C_n + max over k ≤ n of (a_k − C_(k−1)): a running maximum, which is how the simulation runs 20,000 requests in a few array operations.

Poisson arrivals. For arrivals at rate λ and service times with mean E[S] and second moment E[S²], the Pollaczek-Khinchine formula gives the mean queueing delay W_q = λE[S²]/(2(1 − ρ)) with ρ = λE[S]. Fixed service gives ρS/(2(1 − ρ)); exponential service doubles it. The 1/(1 − ρ) factor is why a latency target caps utilization: at ρ = 0.6 the large model’s p99 was already 24 ms.

Little’s law. L = λW holds for any stable system: the time-average number of requests inside equals the arrival rate times the mean time each spends there. It turns a measured latency into the concurrency a server must hold.

Batching. A batch of B requests costs B·d + a + bB, so one worker saturates at B/(Bd + a + bB) requests per unit time, which increases with B when the per-call cost a is large. For the GPU model, B = 32 raises saturation from 234 to 2,463 per second; for the CPU model, decoding d dominates and batching gains less than a factor of 2.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The Pollaczek-Khinchine mean wait grows like…
  2. 2. Little's law states…
  3. 3. Batching raises saturation most when…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How many requests can one worker serve within a 25 ms p99 target, and what decides it: the protocol, batching, or the model?

History.

  • A. K. Erlang (1909) founded queueing theory on telephone exchanges; F. Pollaczek (1930) and A. Khinchine (1932) derived the mean wait of the M/G/1 queue; J. Little (1961) proved L = λW.
  • R. Fielding (2000) defined REST in his dissertation; Google released gRPC in 2015, based on its internal Stubby RPC system and protobuf.
  • TensorFlow Serving (C. Olston and colleagues, 2017), Clipper (D. Crankshaw and colleagues, 2017) and NVIDIA Triton made dynamic batching standard; J. Dean and L. Barroso’s “The tail at scale” (2013) described hedged requests.

Exercise 2.

  • Four modes: REST + JSON and gRPC, one request per model call; gRPC with dynamic batching (at most 32) waiting up to 2 ms or 10 ms.
  • 20,000 Poisson arrivals with common random numbers; capacity is the highest rate whose p99 latency is at most 25 ms, found by bisection and capped at the saturation rate.

Seed 0:

model mode request bytes saturation (per s) capacity within SLO (per s) p50 / p99 at 100 per s (ms)
small REST + JSON 3,074 6,070 6,000 0.69 / 0.76
small gRPC 1,067 15,369 15,300 0.57 / 0.57
small gRPC, batching up to 2 ms 1,067 27,774 27,700 2.57 / 2.64
small gRPC, batching up to 10 ms 1,067 27,774 27,700 10.57 / 10.69
large REST + JSON 3,074 228 136 4.91 / 17.39
large gRPC 1,067 234 141 4.79 / 16.58
large gRPC, batching up to 2 ms 1,067 2,463 2,100 6.79 / 9.20
large gRPC, batching up to 10 ms 1,067 2,463 2,080 14.79 / 15.91

Seeds 1 and 2: small model 6,060 and 6,000 (REST), 15,300 (gRPC), 27,700 (batching); large model 135 and 134 (REST), 140 and 139 (gRPC), 2,110 and 2,030 (batching, 2 ms), 2,080 and 1,980 (10 ms).

Findings.

  • For the cheap model the protocol decided capacity: gRPC served 2.5 times as many requests as JSON in every seed, because decoding was most of the work; batching added another factor of 1.8.
  • For the GPU model the protocol changed capacity by 3 to 4%, and batching by a factor of 15 (14.6 to 15.1 across seeds); the SLO, not saturation, set the limit: one request per call reached only 60% utilization.
  • Batching costs latency at low load: the median rose by the batching wait (from 4.8 ms to 6.8 or 14.8 ms at 100 requests per second), so the wait must fit the latency budget.
🐍 Exercise 2 (research): how many requests can one worker serve within a 25 ms p99 target, and what decides it: the protocol, batching, or the model?
Measure one worker's capacity within a p99 target for two models and four serving modes.

Model serving in practice

  • Serving systems: TensorFlow Serving, TorchServe, NVIDIA Triton, KServe and Ray Serve provide REST and gRPC endpoints, dynamic batching, model versioning and metrics; managed platforms (topic N3-3) wrap them.
  • Large language models use continuous batching (adding requests to a running batch token by token) because generation lengths vary.
  • Batch scoring in Spark or a warehouse is common for recommendations, risk scores and email targeting, where yesterday’s prediction is good enough.
  • Spacecraft and edge devices cannot call a server at all: the model runs on board (topic M4-5), and only results are downlinked.

References

  1. F. Pollaczek (1930). “Über eine Aufgabe der Wahrscheinlichkeitstheorie.” Mathematische Zeitschrift; A. Khinchine (1932), Matematicheskii Sbornik.
  2. J. D. C. Little (1961). “A proof for the queuing formula L = λW.” Operations Research.
  3. R. T. Fielding (2000). “Architectural styles and the design of network-based software architectures.” PhD thesis, UC Irvine.
  4. J. Dean and L. A. Barroso (2013). “The tail at scale.” Communications of the ACM.
  5. C. Olston and colleagues (2017). “TensorFlow-Serving: flexible, high-performance ML serving.” NeurIPS workshop on ML Systems.
  6. D. Crankshaw and colleagues (2017). “Clipper: a low-latency online prediction serving system.” NSDI.
  7. M. Mitzenmacher (2001). “The power of two choices in randomized load balancing.” IEEE Transactions on Parallel and Distributed Systems.