Sub topic 12
Cold start and warmup
This chapter assumes you have read the earlier chapters on dynamic batching, queue-based scaling signals, and horizontal autoscaling. It also assumes you can read a Kubernetes Deployment manifest. It covers what happens between "the autoscaler asked for a replica" and "that replica serves its first fast request", and how that delay changes your scaling settings.
What a cold start is
A cold start is the time a new replica needs before it can serve traffic at normal speed. The autoscaler's decision is not the same as capacity. A replica adds capacity only after it is scheduled, started, loaded, and warmed up.
For model services this delay is long. A web server may start in a second. A model server has to pull a large image, read gigabytes of weights, and prepare the accelerator.
The delay is the autoscaler's lead time. Every scale-up decision pays for load that is already queued while the new replica starts. A slow cold start therefore pushes you toward more headroom and earlier triggers.
Where the time goes
The phases below are typical for a GPU-backed replica. The numbers are an example. Measure your own.
| Phase | What happens | Example duration |
|---|---|---|
| Scheduling | The scheduler finds a node. If none has a free GPU, the cluster autoscaler adds a node. | 5 s (minutes with a new node) |
| Image pull | The container image is downloaded. Images with CUDA libraries are often several GB. | 40 s |
| Weight load | Model files are read from disk or object storage into host memory, then copied to the GPU. | 30 s |
| Runtime init | The framework sets up CUDA contexts, allocates memory pools, and may compile or build engines. | 15 s |
| Warmup | The first requests trigger lazy initialization and kernel selection. | 5 to 20 s |
The total is about 95 to 110 s. Image pull and weight load usually dominate. The following diagram shows the sequence and the gate that ends it.
Why the first requests are slow
Even after the weights are on the GPU, the first requests are often much slower than later ones. Common causes:
- Lazy initialization. Libraries create CUDA contexts, cuDNN handles, and memory pools on first use.
- Per-shape work. Some runtimes compile kernels or select algorithms for each input shape. A TensorRT engine, a
torch.compilegraph, or an XLA program may be built the first time a given batch size appears. - Cold caches. Weights read from network storage may be in the page cache of the node only after the first read.
The per-shape cause interacts with dynamic batching. The batcher produces batch sizes from 1 up to the maximum, depending on load. If each size pays a one-time cost, then the first time traffic forms a batch of 13, one unlucky group of requests absorbs that cost and blows your p99. Warmup should therefore exercise every batch size the batcher can produce, or the preferred sizes if you pad to them.
Warming up on purpose
Warmup means sending synthetic requests through the real serving path before the replica is allowed to take traffic. The sketch below runs each batch size twice. The first call pays the one-time cost, and the second call shows the warm latency.
import time
class FakeModel:
"""Stand-in model: each new batch size pays a one-time setup cost."""
def __init__(self):
self.seen_sizes = set()
def __call__(self, batch):
if len(batch) not in self.seen_sizes:
time.sleep(0.2) # simulated compile or kernel selection
self.seen_sizes.add(len(batch))
time.sleep(0.005) # simulated steady-state compute
return [x * 2 for x in batch]
def warmup(model_fn, batch_sizes, make_input, rounds=2):
"""Run each batch size `rounds` times; return the last (warm) latency per size."""
warm_latency = {}
for size in batch_sizes:
for _ in range(rounds):
start = time.perf_counter()
model_fn([make_input() for _ in range(size)])
warm_latency[size] = time.perf_counter() - start
return warm_latency
if __name__ == "__main__":
model = FakeModel()
start = time.perf_counter()
result = warmup(model, [1, 2, 4, 8, 16], make_input=lambda: 1.0)
print(f"warmup took {time.perf_counter() - start:.2f}s")
for size, seconds in result.items():
print(f"batch {size}: {seconds * 1000:.1f} ms warm")Some servers do this for you. Triton can run warmup requests when a model loads, and it holds the model back from "ready" until they finish:
model_warmup [
{
name: "batch8"
batch_size: 8
inputs {
key: "INPUT0"
value: { data_type: TYPE_FP32 dims: [ 16 ] zero_data: true }
}
}
]Use realistic data if you can. Zero-filled inputs can skip data-dependent code paths, such as variable-length text. For variable-length inputs, warm up with a few representative lengths.
Gating traffic with probes
Warmup only helps if Kubernetes waits for it. A replica that is "running" but not warmed receives traffic as soon as it appears in the Service endpoints. Two probes control this:
- A startup probe gives a slow-starting container time to finish loading. While it runs, Kubernetes does not apply liveness checks, so a long weight load is not mistaken for a hang.
- A readiness probe decides whether the pod receives traffic. It must return success only after warmup is done.
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-server
spec:
replicas: 2
selector:
matchLabels:
app: model-server
template:
metadata:
labels:
app: model-server
spec:
terminationGracePeriodSeconds: 60
containers:
- name: server
image: registry.example.com/model-server:1.4.0
ports:
- containerPort: 8000
startupProbe:
httpGet:
path: /health/ready
port: 8000
periodSeconds: 5
failureThreshold: 60 # allows up to 300 s to start
readinessProbe:
httpGet:
path: /health/ready
port: 8000
periodSeconds: 5
failureThreshold: 2
livenessProbe:
httpGet:
path: /health/live
port: 8000
periodSeconds: 10
failureThreshold: 3Keep /health/live and /health/ready as separate endpoints. Liveness should say only that the process is not wedged. If liveness also depended on warmup, a slow start would cause restarts, and the restarted pod would start from zero again.
Shortening the cold start
Warmup hides slowness from users. These measures reduce the slowness itself:
- Smaller images. Keep build tools and unused libraries out of the runtime image.
- Cached images. Pre-pull images on GPU nodes, or use a node image that already contains them. This removes most of the pull time on nodes you have used before.
- Faster weight loading. Store weights in a format that loads without conversion, such as safetensors. Place them on a fast local disk or a shared volume instead of fetching them from object storage on every start. Avoid baking multi-GB weights into the image if many versions share them.
- Pre-built engines. Build compiled artifacts (such as TensorRT engines) at release time, not at startup.
- Warm node capacity. New nodes add minutes. Keeping a small pool of spare GPU nodes removes that step.
Cold start and your scaling settings
Cold start changes how you configure the autoscaler from the earlier chapters.
- Trigger earlier. Scale on a queue depth target that fires before the queue hurts latency. A target that fires at the edge of your SLO will always be late by one cold start.
- Hold headroom. If new replicas take about 100 s to become useful, run below your maximum utilization so that demand growth during those 100 s fits in existing capacity.
- Do not undo scale-ups quickly. Replicas are expensive to recreate. A long scale-down stabilization window, such as the 300 s in the earlier HPA example, means a brief dip in traffic does not delete replicas you will need again a minute later.
- Raise the minimum. A
minReplicasabove 1 means a traffic spike always meets at least some warm capacity. - Treat not-ready pods carefully. Pods that are still starting count toward the replica total but add no capacity. Check that your metric is averaged over ready pods, or you may see the autoscaler stop adding replicas too early.
Scale to zero is the extreme case. It removes the warm floor, so the first request after idle waits for the full cold start. A later chapter covers when that trade-off is acceptable.
Common errors
- Readiness before warmup. The pod looks healthy but serves slow first requests.
- Warming only batch size 1. Larger batches that form under load then hit per-shape costs.
- Startup window too short. The pod is killed or restarted during weight load, so it never becomes ready. This is called a crash loop and makes scale-ups fail exactly when load is high.
- Warmup that differs from the real path. Calling the model directly skips the server's batcher, tokenizer, or preprocessing. Send warmup requests through the same entry point real traffic uses where possible.
- Counting cold start as zero. Capacity plans that assume a new replica helps immediately will underestimate the headroom you need.
Exercise
A service runs 5 replicas. Each replica handles at most 40 requests per second. Current traffic is 140 requests per second. Traffic can grow to 280 requests per second within 60 seconds, and a new replica needs 90 seconds from scale-up decision to ready. Can autoscaling alone prevent overload, and what utilization would let the service survive the spike with no scale-up at all?
Show answer
No. Five replicas handle at most 200 requests per second, so demand exceeds capacity after about 43 seconds of the climb. Replicas requested at that point are not ready for another 90 seconds, so the service is overloaded for that whole period. To absorb 280 requests per second without new replicas, you need 280 / 40 = 7 replicas, which means running at 140 / (7 x 40) = 50% utilization against current traffic. In practice you would combine more headroom (a lower utilization target or a higher minReplicas) with an earlier scaling trigger, and shorten the cold start where possible.