Serving and scaling models
Section 4: online vs batch inference, where to serve (Agent Platform endpoints, Model Garden, Cloud Run, GKE), prebuilt and custom containers, custom prediction routines, Model Registry, canary and A/B rollouts, public, dedicated and private endpoints, autoscaling, serving hardware and model optimization. Includes a serving capacity calculator and a rollout lab.
1. Serving models
Online vs batch
| Online inference | Batch inference | |
|---|---|---|
| Latency | Milliseconds per request | Minutes to hours per job |
| Infrastructure | An endpoint with replicas running all the time (minimum one replica on Agent Platform endpoints) | Resources only while the job runs; no endpoint needed |
| Input / output | JSON request, JSON response | BigQuery table or Cloud Storage files (JSONL, CSV, TFRecord) in; BigQuery or Cloud Storage out |
| Use | Checkout fraud scoring, chat, personalization per page view | Nightly churn scores, weekly forecasts, bulk document processing |
Where to serve
| Target | Choose when |
|---|---|
| Agent Platform endpoints | Managed autoscaling, traffic splitting, Model Monitoring, explanations, request-response logging; least ops |
| Model Garden one-click deploy | Open models (Gemma, Llama) on optimized serving containers (for example vLLM) with chosen GPUs or TPUs |
| Cloud Run | Lightweight models or pre/post-processing services, scale to zero, GPUs available for small models |
| GKE | Existing Kubernetes platform, custom serving stacks, many models sharing hardware, GKE Inference Gateway |
| BigQuery ML | Batch scoring inside the warehouse |
Containers
Prebuilt prediction containers serve TensorFlow SavedModel, PyTorch, scikit-learn and XGBoost artifacts from Cloud Storage with no server code. A custom container is needed for other frameworks or custom logic. It must:
- Run an HTTP server on the port in
AIP_HTTP_PORT(default 8080). - Answer health checks on
AIP_HEALTH_ROUTEand predictions onAIP_PREDICT_ROUTE. - Accept
{"instances": [...]}and return{"predictions": [...]}. - Load model files from
AIP_STORAGE_URI, and live in Artifact Registry.
Custom prediction routines (CPR) let you add preprocessing and postprocessing in Python (a Predictor class with preprocess, predict, postprocess) and build the container for you, so you don't write a web server.
Model Registry and versions
- Each upload is a model version under one model; aliases (
default,champion,challenger) point to versions. - Register models from custom training, AutoML and BigQuery ML (
model_registry='VERTEX_AI'); attach evaluations; deploy any version to an endpoint.
Rollout strategies
| Strategy | How on an endpoint | Use |
|---|---|---|
| Canary | Deploy the new model to the same endpoint with a small traffic split (for example 5–10%), watch metrics, then increase | Reduce risk of a bad release |
| A/B test | Split traffic between versions and compare a business metric with enough samples for significance | Decide which model performs better for users |
| Shadow (mirroring) | Send copies of requests to the new model without returning its answers | Compare outputs with zero user impact (implemented in your app or gateway) |
| Blue/green | Deploy to a new endpoint, switch clients over, keep the old one for rollback | Clean cutover |
| Rollback | Set traffic back to 100% on the previous deployed model | Fast recovery: keep the old model deployed during the canary |
# Deploy version 2 alongside version 1, sending it 10% of traffic
gcloud ai endpoints deploy-model ENDPOINT_ID --region=us-central1 \
--model=MODEL_ID@2 --display-name=churn-v2 --machine-type=n1-standard-4 \
--min-replica-count=1 --max-replica-count=5 \
--traffic-split=0=10,DEPLOYED_MODEL_ID_V1=90 # 0 means "the model being deployed"
TRANSFORM clause, TensorFlow Transform, a CPR predictor, or Feature Store features so both paths share one implementation.2. Scaling online serving
Endpoints and networking
| Endpoint type | Use |
|---|---|
| Public (shared) endpoint | Default; reachable over the internet with IAM authentication |
| Dedicated public endpoint | Isolated, lower-latency serving, larger payloads and longer timeouts; recommended for production and gen AI models |
| Private endpoint with Private Service Connect (or VPC peering, older) | Traffic stays on private IPs inside your VPC; meets "no public internet" requirements; lowest network latency from your services |
Autoscaling and hardware
min_replica_countkeeps capacity warm (latency on spikes, but you pay for it).max_replica_countcaps cost.- Autoscaling follows CPU or accelerator duty cycle against a target (default about 60%), or request metrics on newer options. Scale-out takes minutes, so set the minimum for your baseline and expected surges.
- Some endpoint configurations can scale to zero; check current support. Otherwise the minimum replica bills continuously.
- GPUs for large deep models and LLMs; CPUs for trees and small models (cheaper per prediction at low volume); TPUs for high-throughput LLM serving.
- Several models can share one machine with deployment resource pools (co-hosting) to cut cost for low-traffic models.
Making models faster and cheaper to serve
| Technique | Effect |
|---|---|
| Quantization (float16, int8, int4) | Smaller, faster models; small accuracy cost to verify |
| Distillation | A small student model mimics a large teacher |
| Pruning, smaller architectures | Fewer operations |
| Optimized runtimes (TensorRT, vLLM, optimized TensorFlow runtime) | Better kernels and batching on the same hardware |
| Server-side batching | Higher throughput for a little latency |
| Caching predictions or features | Skip repeated work; precompute embeddings |
Serving features
Online models need the same features they were trained with, fresh enough, in milliseconds. Fetch them from Feature Store online serving by entity ID (keyed on user, product, device), or compute request-time features in the request itself. Streaming features flow through Pub/Sub and Dataflow into the store.
3. Serving open LLMs efficiently
| Technique | Effect |
|---|---|
| Optimized runtimes (vLLM, TensorRT-LLM, JetStream on TPU) | Much higher throughput per accelerator than naive serving |
| Continuous batching | Adds new requests to in-flight batches; keeps accelerators busy |
| Paged / managed KV cache | More concurrent sequences in the same memory |
| Quantization (int8, int4, FP8) | Smaller memory, faster; small quality loss to evaluate |
| Tensor parallelism | Splits one model across several GPUs when it doesn't fit on one |
| Speculative decoding | A small draft model proposes tokens the large model verifies; lower latency |
| Streaming | Better time to first token for chat |
| Smaller or distilled model | Often the biggest saving if quality holds |
4. Serving capacity calculator
Estimate replicas for an online endpoint from peak traffic and what one replica can handle at your latency target (measure that with a load test). The calculator applies the autoscaling target so replicas aren't planned at 100%.
5. Lab: endpoint, canary rollout and rollback
- Using version 1 from the training lab (or any registered model), create an endpoint and deploy with min 1, max 2 replicas.
- Load-test with increasing request rates; note the rate one replica handles at your latency target and use it in the capacity calculator.
- Train version 2, deploy it to the same endpoint with a 10% traffic split, and send 200 requests. Check the split in the endpoint metrics.
- Roll back: set version 1 to 100%, then undeploy version 2.
- Run batch inference for the same model over a BigQuery table and compare cost and effort with the endpoint.
Clean up: undeploy all models and delete the endpoint (gcloud ai endpoints undeploy-model, gcloud ai endpoints delete). Endpoints bill for every hour a replica is deployed, even with no traffic.
6. "Which serving option?" chooser
Pick an item to see what it means, why, and the tempting wrong choice.
7. Sample outputs
What the tools return. Expand an item to see a typical result and what to read in it.
gcloud ai endpoints describe ENDPOINT_ID --region=us-central1Endpoint with a canary traffic split
deployedModels:
- id: '1111111111111111111'
displayName: churn-v1
model: projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID@1
dedicatedResources:
machineSpec: {machineType: n1-standard-4}
minReplicaCount: 1
maxReplicaCount: 5
- id: '2222222222222222222'
displayName: churn-v2
model: projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID@2
dedicatedResources:
machineSpec: {machineType: n1-standard-4}
minReplicaCount: 1
maxReplicaCount: 5
trafficSplit:
'1111111111111111111': 90
'2222222222222222222': 10What to look at: Two versions of one registered model share the endpoint, with 10% of traffic on v2: a canary. Rollback is a traffic-split change, with no redeploy. Each deployed model has its own minimum replica, so the canary costs a full replica even at 10% traffic.
8. Scenarios
Exam-style situations: how to diagnose each one, the likely cause and the fix.
9. Searchable reference
| Item | Meaning |
|---|
10. Flashcards (click to flip)
11. Common gotchas in one list
- Batch when results can wait: endpoints bill every replica hour.
- Canary on one endpoint with a traffic split; roll back by moving traffic.
- Shadow tests behaviour; A/B tests business impact.
- Custom containers must serve on AIP_HTTP_PORT with health and predict routes.
- CPR avoids writing a web server for custom pre- and post-processing.
- Autoscaling lags sudden peaks: raise min replicas or pre-scale.
- Private Service Connect for private prediction traffic.
- Quantize and use optimized runtimes before buying more GPUs.
- Same preprocessing in batch and online paths, or predictions diverge.
- Fetch online features from Feature Store, not BigQuery per request.
- Time to first token and time per token are different problems.