Hardware-Aware Routing for Multi-Phase LLM Inference
Machine LearningModel answerLast updated
Build a system that dynamically assigns prefill and decode stages of large language model inference to heterogeneous hardware pools based on profiled capabilities.
You are building an inference service that processes batch jobs using large language models. The service has access to multiple hardware pools with varying characteristics: some have high memory and throughput, others are older units better suited for less compute-intensive work.
Your system should support phase-aware execution: the initial prefill stage (processing the input prompt and generating the KV cache) can run on different hardware than the decode stage (autoregressively generating output tokens). Jobs arrive with deadlines and belong to tenants with different priority levels.
Design the end-to-end system covering:
- Job lifecycle: How jobs are submitted, admitted, scheduled, and tracked through completion
- Hardware profiling and placement: How you measure and model each hardware pool's performance for different phases, models, and batch configurations
- Routing logic: How you decide which hardware executes prefill vs. decode for each job, considering queues, batching opportunities, transfer overhead, and deadline pressure
- Coordination and reliability: How prefill and decode phases communicate, how you handle failures and retries, and how you prevent stragglers from missing deadlines
- Resource fairness: How you prevent any single tenant from monopolizing capacity while respecting priorities
- Observability: What metrics and dashboards you expose, and how you validate that routing decisions improve utilization and meet deadlines
Assume you support multiple model families (7B to 70B parameters), quantization formats (FP16, INT8, INT4), and sequence lengths up to 8K tokens. Transferring KV cache state between hardware pools has measurable latency and bandwidth cost.
Walk through your architecture, key algorithms, and the trade-offs in your design. Discuss how your approach adapts to shifting workloads and hardware characteristics over time.
Hints
Hint 1
Consider how batch size affects throughput differently for prefill (compute-bound, benefits from larger batches) versus decode (memory-bound, constrained by KV cache size).
Hint 2
Profile each hardware pool offline with representative workloads, then use these profiles at runtime to estimate queue delay and execution time for placement decisions.
Hint 3
Think about when it makes sense to keep prefill and decode colocated on the same hardware versus splitting them—transfer cost and queueing dynamics both matter.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
The system consists of four major layers:
Job Control Plane: A durable job store (PostgreSQL or similar) tracks each request with its model, input/output token estimates, deadline, tenant ID, and priority. An admission controller enforces per-tenant quotas and rejects jobs that cannot feasibly meet their deadline given current queue depth.
Hardware Registry: Each pool (GPU type, count, memory, interconnect) is profiled offline with microbenchmarks across model sizes, quantization levels, and batch configurations. Profiles capture prefill throughput (tokens/sec), decode throughput (tokens/sec), memory capacity (max batch × sequence length), mean time between failures, and inter-pool transfer bandwidth. The registry exposes APIs to query "can this pool run model X at batch size B?" and "estimated runtime for phase Y."
Scheduler and Router: A central scheduler polls admitted jobs, evaluates candidate placements using the hardware profiles, and assigns prefill and decode phases to specific pools. The router optimizes a weighted objective: minimize deadline misses, maximize hardware utilization, minimize KV-cache transfer cost, and enforce fairness via tenant shares.
Execution Layer: Workers in each pool run a batching inference engine (vLLM, TensorRT-LLM, or similar). Workers accept phase assignments, execute them, optionally serialize KV cache to shared storage (S3 or a low-latency blob store), and report completion or failure back to the scheduler.
Hardware Profiling and Cost Model
Before deployment, profile each pool with:
- Prefill benchmarks: Measure throughput across batch sizes [1, 2, 4, 8, 16, 32] and sequence lengths [512, 1K, 2K, 4K, 8K].
- Decode benchmarks: Measure per-token latency and memory usage (KV cache grows linearly with batch size and sequence length).
- Transfer tests: Measure latency and bandwidth for moving KV cache between pools via the blob store.
Store these as lookup tables or fit simple regression models (e.g., prefill_time = a + b × batch_size + c × seq_len). At runtime, the scheduler queries these models to estimate:
- Queue delay: current queue depth × average job duration in that pool.
- Execution time: prefill_time(model, batch_size, input_len) + decode_time(model, batch_size, output_len).
- Transfer overhead: if prefill and decode are split, add serialize_time + transfer_latency + deserialize_time.
Routing and Placement Logic
The scheduler runs every few seconds (or on job arrival). For each unassigned job:
-
Generate candidate plans:
- Colocated: both prefill and decode on the same pool.
- Split: prefill on a high-throughput pool, decode on a pool optimized for memory-bound workloads (e.g., older GPUs with less compute but sufficient memory).
-
Estimate cost for each plan:
- Completion time: queue_delay + exec_time + transfer_time (if split).
- Deadline slack: deadline - estimated_completion_time.
- Resource cost: GPU-seconds consumed, weighted by pool expense.
- Fairness penalty: if tenant is above their fair share, reduce priority.
-
Score and rank: Use a weighted sum or multi-objective optimization. Prioritize jobs close to their deadline. Prefer colocation unless the decode queue is much shorter or the transfer cost is low.
-
Batch formation: If multiple jobs target the same model and pool, batch them together up to memory limits. Cap batch size per tenant to prevent monopolization (e.g., no more than 30% of a batch from one tenant).
-
Assign: Reserve capacity in the chosen pool(s), write phase records to the job store, and enqueue work to the execution layer.
Coordination Between Prefill and Decode
Colocated path: The worker completes prefill, holds the KV cache in GPU memory, and immediately begins decode. No serialization needed.
Split path:
- Prefill worker finishes, serializes the KV cache (compressed if possible), uploads to blob storage, and marks the prefill phase complete with a cache pointer.
- Scheduler assigns decode phase to a (possibly different) pool.
- Decode worker downloads the cache, loads it into GPU memory, and runs autoregressive generation.
Use idempotent phase identifiers (job_id + phase_name) so retries don't create duplicates. Store phase state transitions (pending → running → complete/failed) in the job store with timestamps.
Retries and Failure Handling
- Transient failures (OOM, GPU crash): Retry the phase on the same or a different pool. Update the cost model if a particular pool shows elevated failure rates.
- Stragglers: If a phase runs longer than 1.5× the estimated time, preemptively launch a duplicate on another pool (speculative execution). Cancel the slower one once the first completes.
- Deadline misses: If estimated completion time exceeds the deadline mid-execution, either abort and return partial results or continue with degraded priority. Log the miss for capacity planning.
Fairness and Quota Enforcement
Implement weighted fair queueing by tenant:
- Each tenant has a configured share (percentage of total capacity).
- Track recent GPU-seconds consumed per tenant over a sliding window (e.g., last hour).
- When forming batches or assigning work, deprioritize tenants above their share and boost those below.
- Hard quotas at admission prevent any tenant from queuing unlimited work.
Metrics and Validation
Operational metrics:
- Jobs completed, deadline miss rate (overall and per tenant).
- Per-pool utilization (GPU-seconds busy / total).
- Prefill and decode throughput (tokens/sec).
- KV-cache transfer volume and latency (95th percentile).
- Queue depth and wait time per pool.
Experiments:
- A/B test routing policies (always colocate vs. always split vs. adaptive).
- Measure impact of batching caps on fairness and utilization.
- Validate that profiled cost models match observed runtimes; re-profile pools periodically.
Quality checks:
- Compare output quality (perplexity, BLEU) across pools and quantization levels to detect drift.
- Alert if a pool's error rate or latency degrades beyond historical baselines.
Trade-Offs and Extensions
Colocation vs. splitting: Colocation is simpler and avoids transfer cost, but splitting can unlock better utilization if decode queues are shorter or older hardware is underutilized. The router should adapt based on observed queue depths.
Batching granularity: Larger batches improve prefill throughput but increase latency for individual jobs and make fairness harder. Use dynamic batch timeouts: wait up to T seconds to form a batch, then launch even if not full.
Model caching: Preload popular models on multiple pools to reduce cold-start latency. Use LRU eviction when memory is scarce.
Autoscaling: If queue depths grow, spin up additional workers or request more capacity. If utilization is low, scale down to save cost.
This design balances deadline adherence, hardware efficiency, and tenant fairness while leveraging empirical profiles to make smarter placement decisions than static heuristics would allow.