Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 13 of 13
Serving Open Models: Continuous Batching, vLLM and Cold Starts
Why continuous batching cuts the wait (a simulation: 26.6 s mean wait down to 4.2 s), a real vLLM run on a laptop GPU (27 tokens/s one at a time, 429 all at once, a 96-second cold start), and the scale-to-zero vs warm-pool trade.
What you will learn
- Explain why continuous batching beats static batching for language models
- Run an open model behind vLLM's OpenAI-style HTTP API
- Weigh scale to zero against a warm pool
- Measure a cold start on your own server
Before you start
- Loading a Language Model and Running Inference
- Latency Math: p50, p95, p99
Think of a bus. A tour bus waits for its whole group, and nobody gets off until the tour ends, so one long trip holds up every seat. A city bus works differently. People get on at any stop and get off as soon as they reach theirs. A seat that empties is filled at the next stop.
That city bus is continuous batching, and the seats are requests being answered by a language model. In this article we look at serving an open model to many people at once: batching, then vLLM, a server that does it for you, then cold starts, the wait when a machine has to wake up.
What's measured and what's simulated. The batching and cold-start numbers come from a small Python simulation with times I assumed: no model, no GPU. Trust the direction, not the exact sizes. The vLLM numbers were really measured, with a small open model on a laptop RTX 4070 (8 GB).
Why batching matters for a language model
A language model writes one word (token) per step, and it can do that step for everyone in the batch at once. That's why a GPU can serve many people: one step for 16 requests costs far less than 16 separate steps (the simulation below assumes 104 ms against 16 x 44 ms). The question is who gets a seat and when. For batching a classic model's requests, see Making ML Inference Fast; here we look at answers that are written word by word.
- Static batching (tour bus). A batch starts together and ends when its longest answer ends. A short answer finishes early and its seat sits empty. New requests stand outside in the queue.
- Continuous batching (city bus). Every step is a chance to let someone in. No seat sits empty while people wait.
Continuous batching in code
Here's the idea in batching.py. It's a simulated server: the step times are assumptions written at the top of the file.
"""SIMULATED server. No model, no GPU, times assumed."""
import random
STEP_MS = 40 # assumed: one step, one word each
PER_REQ_MS = 4 # assumed: extra per request in a step
MAX_BATCH = 16 # assumed: seats in one batch
def step_ms(size):
return STEP_MS + PER_REQ_MS * size
def continuous_batching(reqs):
"""Join at any step, leave as soon as you finish."""
done, seats, i, clock = [], [], 0, 0.0
while i < len(reqs) or seats:
if not seats:
clock = max(clock, reqs[i][0])
while (i < len(reqs) and reqs[i][0] <= clock
and len(seats) < MAX_BATCH):
seats.append([reqs[i][0], reqs[i][1]])
i += 1
clock += step_ms(len(seats))
for seat in seats:
seat[1] -= 1
ended = [s for s in seats if s[1] == 0]
done += [(s[0], clock) for s in ended]
seats = [s for s in seats if s[1] > 0]
return done
Read the loop one step at a time:
- Requests that have arrived take any free seat, up to 16.
- One step runs and the clock moves on.
step_msgrows with the number of seats, so a fuller batch makes each step a bit slower. It isn't free. - Every seat gets one word closer to done (
seat[1] -= 1). - Anyone finished gets off, and their finish time is noted. Back to the top.
The static_batching function in the same file fills a batch, then adds longest * step_ms(len(batch)) to the clock before anyone can leave or join.
The simulated result
Each request asks for between 10 and 100 words, and requests arrive on average 600 ms apart. Both functions get exactly the same 300 arrivals:
SIMULATED: 300 requests, same arrivals for both
static mean 26.6 s p95 44.2 s 83.7 words/s
continuous mean 4.2 s p95 8.1 s 101.2 words/s
simulate.py. Continuous batching cuts the mean wait from 26.6 s to 4.2 s and the p95 from 44.2 s to 8.1 s.The average wait drops from 26.6 seconds to 4.2. 95% of requests finish within 8.1 seconds instead of 44.2 (if p95 is new to you, see Latency Math: p50, p95, p99). Now look at total output: 83.7 words a second against 101.2. The wait drops far more than the output rises. Continuous batching is mostly about people not waiting behind someone else's long answer.
vLLM does this for you
You wouldn't write that loop yourself. vLLM is a server for open models that does continuous batching for you. Here's how it was started for this lesson, in Docker on a laptop GPU, with a small open model from Hugging Face, Qwen2.5-0.5B-Instruct:
docker run -d --name cap-vllm --gpus all -p 8000:8000 \
-v <your-hf-cache>:/root/.cache/huggingface --ipc=host \
vllm/vllm-openai:latest --model Qwen/Qwen2.5-0.5B-Instruct \
--gpu-memory-utilization 0.45 --max-model-len 1024 \
--max-num-seqs 16 --enforce-eager
--modelpoints at a model on Hugging Face. vLLM downloads and loads it.--max-num-seqs 16sets how many requests share a batch. That's our 16 seats.--gpu-memory-utilization 0.45and--max-model-len 1024keep it inside an 8 GB card.-vmounts a folder for the downloaded model, so the next start doesn't download it again. Use your own cache path.
vLLM answers over HTTP in the same style as the OpenAI API, so any app can call it like any other service. The test script posted this body to /v1/chat/completions:
body = json.dumps({"model": MODEL, "messages": [{"role": "user", "content": PROMPT}],
"max_tokens": MAXTOK, "temperature": 0, "min_tokens": MAXTOK}).encode()
r = urllib.request.Request(URL + "/v1/chat/completions", body, {"Content-Type": "application/json"})
with the prompt "Explain in two sentences why batching helps a GPU serve many users." and 64 tokens per answer.
What we measured
| Measurement | Result |
|---|---|
| First start, including the model download | 154.3 s |
| Cold starts with the model already downloaded (3 runs) | 91.6 s, 95.8 s, 106.2 s (median 95.8 s) |
| 16 requests sent one at a time | 1,024 tokens in 37.89 s = 27.0 tokens/s |
| 16 requests sent all at once | 1,024 tokens in 2.39 s = 429.3 tokens/s |
| GPU memory used | 1,414 MiB before, 5,488 MiB during, of 8,188 MiB |
Same model, same 1,024 tokens. Sent all at once they finished about 15.9 times faster, because vLLM put them in the same batch. And before the server answered anything, it took about 96 seconds to start: that's a cold start. vLLM itself took about 4 GB of the card's 8.
So the whole setup is your FastAPI app in front, vLLM behind it, and the GPU doing the work. For the FastAPI side, see A Production FastAPI for an ML Model.
Engine off or engine on: cold starts
A GPU machine costs money while it sits idle, so you might shut it down when nobody is asking. That's scale to zero. But the next request finds a bus with its engine off: a machine has to start and the model has to load into memory. That wait is a cold start.
The other choice is a warm pool: at least one machine always on, model loaded. No wait, and you pay for it around the clock.
Putting numbers on it (simulated)
LOAD_S = 45 # assumed: load model on a new machine
IDLE_MIN = 5 # assumed: idle minutes before zero
REPLY_S = 2 # assumed: one normal reply
# Requests in minutes: a busy morning, then a quiet gap
times = [0, 1, 2, 3, 4, 30, 31, 90, 200, 201]
cold, last = 0, None
for t in times:
if last is None or t - last > IDLE_MIN:
cold += 1
last = t
A request is a cold start when the machine has been idle for more than 5 minutes (or has never started).
SIMULATED: 10 requests, 201 minutes
cold starts with scale to zero: 4
worst wait, scale to zero: 47 s
worst wait, one warm machine: 2 s
machine minutes, scale to zero: 26
machine minutes, one warm machine: 206
Ten requests across 201 minutes give four cold starts: at minutes 0, 30, 90 and 200. Those four people wait 47 seconds instead of 2. But the machine runs for 26 minutes instead of 206. Scale to zero saves machine time and makes some people wait. A warm pool saves people's time and costs machine time.
Measure your own cold start
On your own server it's simple. Send a request to a sleeping machine, then send another straight after. The difference is your cold start. In the simulation that's 47 minus 2, so 45 seconds. On the real vLLM run above, the server start alone took about 96 seconds, longer than the 45 seconds the simulation assumed. For how many machines to keep warm under load, see Sizing and Autoscaling an Inference Service.
Common mistakes
- Judging batching by throughput alone. In the simulation output rose by about a fifth, but the mean wait fell from 26.6 s to 4.2 s. Watch the wait and the p95.
- Treating simulated numbers as benchmarks. They follow from assumed times. The direction holds, the sizes don't.
- Testing a server one request at a time. Here that showed 27 tokens/s. The same server gave 429 tokens/s when requests overlapped.
- Forgetting the cold start when you scale to zero. The first user after a quiet spell pays for the model load.
- Not sizing the server to the card. Set
--gpu-memory-utilizationand--max-model-lento fit the GPU, as in the run above. See Model Size and Memory for the arithmetic.
Quick recap
| Idea | What to remember | Number here |
|---|---|---|
| Static batching | The batch ends with its longest answer | Mean wait 26.6 s (simulated) |
| Continuous batching | Join and leave at every step | Mean wait 4.2 s (simulated) |
| vLLM | Continuous batching plus an OpenAI-style API | 27 vs 429 tokens/s (measured) |
| Cold start | Start the machine and load the model | About 96 s for vLLM (measured) |
| Scale to zero vs warm pool | Machine time vs people's wait | 26 vs 206 machine minutes (simulated) |
Try it yourself
In simulate.py, change IDLE_MIN from 5 to 60 and run it again. How many cold starts are left, and how many machine minutes does scale to zero use now?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.