← All Google Cloud AI guidesSection 4 · 4.1, 4.2

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 inferenceBatch inference
LatencyMilliseconds per requestMinutes to hours per job
InfrastructureAn endpoint with replicas running all the time (minimum one replica on Agent Platform endpoints)Resources only while the job runs; no endpoint needed
Input / outputJSON request, JSON responseBigQuery table or Cloud Storage files (JSONL, CSV, TFRecord) in; BigQuery or Cloud Storage out
UseCheckout fraud scoring, chat, personalization per page viewNightly churn scores, weekly forecasts, bulk document processing

Where to serve

TargetChoose when
Agent Platform endpointsManaged autoscaling, traffic splitting, Model Monitoring, explanations, request-response logging; least ops
Model Garden one-click deployOpen models (Gemma, Llama) on optimized serving containers (for example vLLM) with chosen GPUs or TPUs
Cloud RunLightweight models or pre/post-processing services, scale to zero, GPUs available for small models
GKEExisting Kubernetes platform, custom serving stacks, many models sharing hardware, GKE Inference Gateway
BigQuery MLBatch 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:

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

Rollout strategies

StrategyHow on an endpointUse
CanaryDeploy the new model to the same endpoint with a small traffic split (for example 5–10%), watch metrics, then increaseReduce risk of a bad release
A/B testSplit traffic between versions and compare a business metric with enough samples for significanceDecide which model performs better for users
Shadow (mirroring)Send copies of requests to the new model without returning its answersCompare outputs with zero user impact (implemented in your app or gateway)
Blue/greenDeploy to a new endpoint, switch clients over, keep the old one for rollbackClean cutover
RollbackSet traffic back to 100% on the previous deployed modelFast 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"
Training-serving skew often comes from preprocessing done differently at serving (in app code) than in training (in a notebook). Put preprocessing in the model graph, the BQML 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 typeUse
Public (shared) endpointDefault; reachable over the internet with IAM authentication
Dedicated public endpointIsolated, 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

Making models faster and cheaper to serve

TechniqueEffect
Quantization (float16, int8, int4)Smaller, faster models; small accuracy cost to verify
DistillationA small student model mimics a large teacher
Pruning, smaller architecturesFewer operations
Optimized runtimes (TensorRT, vLLM, optimized TensorFlow runtime)Better kernels and batching on the same hardware
Server-side batchingHigher throughput for a little latency
Caching predictions or featuresSkip 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.

Joining BigQuery at request time for features is too slow for low-latency serving. Precompute into the online store.

3. Serving open LLMs efficiently

TechniqueEffect
Optimized runtimes (vLLM, TensorRT-LLM, JetStream on TPU)Much higher throughput per accelerator than naive serving
Continuous batchingAdds new requests to in-flight batches; keeps accelerators busy
Paged / managed KV cacheMore concurrent sequences in the same memory
Quantization (int8, int4, FP8)Smaller memory, faster; small quality loss to evaluate
Tensor parallelismSplits one model across several GPUs when it doesn't fit on one
Speculative decodingA small draft model proposes tokens the large model verifies; lower latency
StreamingBetter time to first token for chat
Smaller or distilled modelOften the biggest saving if quality holds
Two latency numbers matter for LLMs: time to first token (prompt processing, queueing) and time per output token (decoding). Long prompts hurt the first; long answers hurt the second. If no custom weights or VPC control are needed, Gemini or a MaaS model avoids running this stack at all.

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

  1. Using version 1 from the training lab (or any registered model), create an endpoint and deploy with min 1, max 2 replicas.
  2. Load-test with increasing request rates; note the rate one replica handles at your latency target and use it in the capacity calculator.
  3. 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.
  4. Roll back: set version 1 to 100%, then undeploy version 2.
  5. 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.

Pick one above.

7. Sample outputs

What the tools return. Expand an item to see a typical result and what to read in it.

Illustrative output, not captured from a real project. IDs, numbers and some field names are invented or simplified, and formats change between releases. Learn the shape and the fields called out under each one.
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': 10

What 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

ItemMeaning

10. Flashcards (click to flip)

11. Common gotchas in one list

  1. Batch when results can wait: endpoints bill every replica hour.
  2. Canary on one endpoint with a traffic split; roll back by moving traffic.
  3. Shadow tests behaviour; A/B tests business impact.
  4. Custom containers must serve on AIP_HTTP_PORT with health and predict routes.
  5. CPR avoids writing a web server for custom pre- and post-processing.
  6. Autoscaling lags sudden peaks: raise min replicas or pre-scale.
  7. Private Service Connect for private prediction traffic.
  8. Quantize and use optimized runtimes before buying more GPUs.
  9. Same preprocessing in batch and online paths, or predictions diverge.
  10. Fetch online features from Feature Store, not BigQuery per request.
  11. Time to first token and time per token are different problems.

12. Practice quiz (19 questions)

Score: 0 / 0
← Training, tuning and hardwareNext: Pipelines and MLOps →