Design a Batching Service for GPU Model Inference
Machine LearningModel answerLast updated
Build an online inference system that groups compatible GPU requests into batches to maximize throughput while meeting latency SLAs.
You're building an online inference service that runs machine learning models on GPUs. Client requests arrive individually through an API, but GPUs achieve much better throughput when processing multiple requests simultaneously—batching amortizes fixed overhead like kernel initialization and weight loading across many inputs. However, every request added to a batch forces earlier requests to wait longer. Your system must create batches large enough to be cost-efficient without violating latency requirements.
Design an inference service that:
- Serves real-time prediction requests through an HTTP/gRPC API
- Groups compatible requests into efficient batches
- Distributes batches across a fleet of GPU workers
- Handles multiple models and versions running simultaneously
- Optimizes for both throughput (cost efficiency) and latency (SLA compliance)
- Manages overload conditions, worker failures, and provides operational visibility
Your design should address the API contract, queue architecture, batch formation logic, worker management, scaling decisions, and key trade-offs.
Assumptions & Scope
Define your own assumptions where unstated, but consider this baseline:
- Latency target: Synchronous API with p95 latency of 200-500ms for single-pass models, or p95 time-to-first-token plus streaming constraints for generative models
- Heterogeneous traffic: Different models, varying input sizes (text token counts, image dimensions), fluctuating request rates with daily patterns and bursts
- Shared infrastructure: Multiple teams use the same GPU pool; prevent any one team from monopolizing resources
- Stateless inference: Predictions don't modify external state, simplifying retry logic
- GPU instances take 30-60 seconds to become available after provisioning
Important Clarifications
Before designing, establish:
- Model type: Single forward-pass (classification, embeddings) or autoregressive generation (text completion with unknown output length)?
- Latency definition: Total request duration, time-to-first-token, or per-token generation speed?
- Scale parameters: Expected requests/second, typical input size distribution, number of active models?
- Tenancy model: Strict isolation with quotas, or best-effort fairness?
- Reliability requirements: Can timed-out requests simply be retried by clients, or must the system guarantee exactly-once processing?
- Response format: Complete responses only, or streaming token-by-token output?
Hints
Hint 1
Think about what makes two requests 'compatible' for batching—which mismatches waste compute versus which cause correctness errors?
Hint 2
The optimal wait time before flushing a batch depends on your latency budget and the current queue depth—derive it rather than guessing.
Hint 3
Autoregressive models generate tokens iteratively with unpredictable completion times; their batching strategy differs fundamentally from single-pass models.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Challenge
The fundamental tension is batch efficiency versus request latency. Larger batches increase GPU utilization and reduce cost-per-inference, but holding requests to accumulate a batch directly increases wait time. The system must dynamically choose batch sizes that maximize throughput without violating latency SLAs.
Total request latency breaks down into:
- Queue wait time (controllable by batching policy)
- Batch preparation overhead (copying data, padding inputs)
- GPU compute time (scales sublinearly with batch size due to parallelism)
- Network and serialization overhead
System Architecture
API Layer
Expose a REST/gRPC endpoint accepting:
POST /v1/predict
{
"model_id": "bert-large-v2",
"input": {...},
"priority": "normal",
"timeout_ms": 500
}
Return either a synchronous response or a streaming connection for generative models. Include request metadata (arrival timestamp, deadline, tenant_id) for scheduling decisions.
Request Router & Queue
Deploy a stateless routing tier that:
- Validates and enriches requests (authentication, rate limiting, deadline calculation)
- Assigns requests to queues based on batch compatibility key:
(model_id, model_version, input_shape_bucket) - Maintains per-model FIFO queues with head-of-line blocking prevention
Use shape bucketing to group similar input sizes: requests with 50, 55, and 60 tokens all map to the 64-token bucket. This trades some padding overhead for better batching opportunities.
Batching Policy
Flush a batch when any condition triggers:
- Size threshold reached: Batch contains N requests (model-specific, e.g., 32 for small models, 8 for large)
- Timeout elapsed: Oldest request has waited T milliseconds (derived from SLO minus expected compute time)
- Queue drained: No new compatible requests arrived in the last few milliseconds
For a 200ms p95 SLO with 80ms expected GPU compute, set timeout to ~100ms to leave buffer for queueing delays upstream and result serialization.
Compatibility rules:
- Must match: model_id, version, output requirements (e.g., temperature, top-k for generation)
- Should match but can pad: input dimensions (pad shorter sequences to batch max)
- Can differ: priority, tenant_id (handle via separate fairness mechanism)
Autoregressive vs. Single-Pass Models
Single-pass models (BERT embeddings, ResNet classification) execute once per request. Use the batching policy above directly.
Autoregressive models (GPT-style generation) produce tokens iteratively:
- Batch formation happens at each decode step, not just initial prompt processing
- Requests complete at different times (varying output lengths)
- Use continuous batching: as requests finish, immediately add waiting requests to the partially-complete batch
- Admission control based on KV-cache memory, not just batch size—a single 4096-token request may consume more memory than 16 short requests
For generation, track time-to-first-token (TTFT) and inter-token latency (ITL) separately. TTFT uses the same batching logic as single-pass. ITL depends on batch size during generation; limit concurrent generation batch size to maintain ITL targets.
Worker Management
Worker Lifecycle
- Provisioning: Start GPU pod, load model weights into VRAM (~10-30 seconds for multi-GB models)
- Warm pool: Keep instance in ready state, registered with router
- Active: Process batches, report health and capacity
- Draining: Stop accepting new batches, finish in-flight work (for version rollout)
- Terminated: Release GPU resource
Use rolling deployments for model updates: spin up new-version workers, mark old-version workers as draining, wait for in-flight batches to complete.
Failure Handling
- Worker crash: Router detects via health check failure; automatically retry in-flight requests on healthy workers
- Request timeout: Client receives timeout error after deadline; idempotent retry is safe
- Partial batch failure: Re-batch failed requests individually to isolate bad inputs
- Network partition: Use circuit breakers to stop routing to unreachable workers
Overload Management
When request rate exceeds capacity:
- Admission control: Reject requests immediately with 503 if queue depth exceeds threshold (fail fast beats slow failure)
- Priority tiers: Process high-priority requests first, shed low-priority load under pressure
- Per-tenant quotas: Prevent single tenant from consuming entire fleet
- Backpressure signals: Return load metrics to clients for client-side throttling
Track queue depth per model as the primary overload signal.
Autoscaling
Scale on metrics that predict SLO violations:
- Queue wait time p95: Leading indicator of insufficient capacity
- GPU utilization AND queue depth: High GPU + empty queue = right-sized; high GPU + deep queue = under-provisioned
- Batch size distribution: Consistently small batches suggest either low traffic (scale down) or high traffic with tight latency (need more workers)
Avoid scaling on raw GPU utilization alone—80% GPU with no queue is healthy; 60% GPU with growing queue is not.
Scale-up: Aggressive, triggered by queue wait time crossing 50% of timeout budget Scale-down: Conservative with 5-10 minute cooldown, triggered by sustained low utilization AND shallow queues
Observability
Instrument:
- Per-model latency breakdown: queue_wait, batch_prep, gpu_compute, serialization
- Batch size distribution: Actual batch sizes achieved (vs. target)
- Queue depth timeseries: Per-model queue length over time
- GPU utilization: Compute, memory, kernel efficiency
- SLO compliance: % requests meeting latency target, by model and tenant
This telemetry distinguishes "slow because waiting for batch" from "slow because model is computationally expensive."
Key Trade-offs
- Batch size vs. latency: Larger batches are more efficient but increase wait time
- Shape bucketing granularity: More buckets reduce padding waste but fragment batches
- Multi-tenancy fairness vs. efficiency: Strict per-tenant queues prevent interference but reduce batching opportunities
- Warm pool size vs. cost: Keeping spare capacity reduces cold-start latency but wastes GPU hours
Minimal Viable Design
Start with:
- Single model support with fixed batch size and timeout
- FIFO queue per shape bucket
- Simple autoscaling on queue depth
- Basic retry on worker failure
Add complexity incrementally:
- Multi-model support via separate queues
- Dynamic batch sizing based on observed latency
- Continuous batching for autoregressive models
- Sophisticated fairness and priority mechanisms