Batch LLM Inference with Heterogeneous Hardware Routing

Medium · ML System Design · Member of Technical Staff, ML Systems · Onsite

Prompt

Architect an asynchronous batch LLM inference system that schedules work across heterogeneous accelerator clusters—including older-generation GPUs whose memory-bandwidth-per-dollar makes them attractive for autoregressive token decoding.

Your design must operate under four real-world constraints: - Batch submissions are non-interactive, yet carry explicit completion deadlines and per-tenant priority tiers. - Accelerator pools vary substantially in device RAM, memory bandwidth, compute throughput, supported numeric precisions, and node failure rates. - Shipping intermediate attention state (KV cache) between disaggregated stages consumes substantial datacenter network bandwidth. - Giant batch submissions from a single customer must never starve competing tenants, and routing must adapt to live empirical hardware performance rather than static datasheet numbers.

Clarify your assumptions around target model architectures, prompt and output token lengths, numeric formats, whether prefill and decode split selectively or always, and how deadline adherence, cost per token, fleet utilization, and numerical fidelity are ranked.

Scope & Expectations

  • Job intake, sharding, & fairness: Structure admission control, shard sizing, prefix/length-aware batching, deadline slack scheduling, and multi-tenant fair-share enforcement.
  • Disaggregated execution & placement: Coordinate model weight residency and optional prefill-to-decode KV-cache streaming across heterogeneous GPU pools under network and memory budgets.
  • Empirical hardware-aware routing: Continuously fit and validate runtime performance and failure profiles from live execution telemetry to guide placement without relying on static specs.
  • Resilience & capacity planning: Handle worker crashes, partial-progress recovery, retry idempotency, and sudden capacity drops while protecting accepted deadlines.

Step-by-step walkthrough

  1. Clarify requirements, LLM phases, and hardware pools

    Large language model (LLM) generation runs in two distinct phases with opposite hardware needs:

    • Prefill reads the entire input prompt in parallel to compute the model's initial attention memory—called the KV cache (Key-Value cache), the per-layer key and value vectors saved for every token so earlier tokens never have to be recomputed. Prefill does huge matrix-matrix multiplications and is compute-bound (limited by math operations per second, FLOPs).
    • Decode generates output tokens one token at a time, reading all model weights plus the growing KV cache from GPU memory on every single step. Decode is memory-bandwidth-bound (limited by how fast gigabytes can stream out of GPU High-Bandwidth Memory, HBM).

    Pin down explicit production assumptions before sizing the cluster:

    • Supported models, lengths, and formats: dense decoder-only transformers (8B to 70B parameters) using grouped-query attention (GQA)—an attention layout where multiple query heads share fewer KV heads to shrink the KV cache. Prompts reach 32k tokens (median 2,000), outputs reach 4k tokens (median 400). Weight formats are BF16, FP8, FP16, and INT4 weight-only (FP16 lets older V100 GPUs, which lack BF16 and FP8 hardware, run 8B models). The tenant chooses the format per job; the router never silently quantizes a job, because changing precision alters output quality.
    • Disaggregation policy: prefill and decode are optionally separated per shard of requests. Colocated execution on one replica is the safe default; splitting across pools happens only when decode cost savings beat network transfer overhead.
    • Optimization goals (in priority order): (1) meet >= 99% of accepted job completion deadlines, (2) minimize total dollars per generated token, (3) keep every hardware pool well utilized without letting one giant batch starve other tenants, and (4) preserve numerical reproducibility when requested.
    Pool  Accelerator       HBM RAM  HBM Bandwidth  Peak BF16/FP16  Supported Formats  Assumed $/GPU-hr
    ----  ----------------  -------  -------------  --------------  -----------------  ----------------
    H     H100-class SXM    80 GB    3.35 TB/s      ~989 TFLOPS     BF16, FP8, FP16    $2.50
    A     A100-class SXM    80 GB    2.04 TB/s      ~312 TFLOPS     BF16, FP16         $1.20
    V     V100-class SXM    32 GB    0.90 TB/s      ~125 TFLOPS     FP16, INT4 only    $0.35
    
  2. Back-of-the-envelope: why prefill, decode, and KV transfer pull apart

    Run the numbers on a concrete 70B GQA model (80 layers, 8 KV heads of dimension 128, BF16 weights = 70B * 2 B = 140 GB):

    1. Per-token fundamentals
       Prefill math      ~2 * 70e9 = 1.4e11 FLOPs/prompt token (+ ~2% causal attention at 2k, ~30% at 32k)
       KV cache size     2 (K,V) * 80 layers * 8 heads * 128 dims * 2 B = 327,680 B = 320 KiB / token
    
    2. Prefill cost (compute-bound; assume 40% achieved FLOP utilization)
       H100:  989e12 * 0.40 / 1.4e11 = ~2,830 prompt tok/s/GPU  -> $2.50 / (2,830 * 3,600) = $0.25 / 1M tok
       A100:  312e12 * 0.40 / 1.4e11 =   ~890 prompt tok/s/GPU  -> $1.20 / (  890 * 3,600) = $0.37 / 1M tok
    
    3. Decode cost (bandwidth-bound; 8-GPU replica, batch = 256, context = 2,500, 70% HBM bandwidth)
       Bytes read/step = 140 GB weights + (256 * 2,500 * 320 KiB = 210 GB KV) = 350 GB total
       8x A100 (8 * 2.04 = 16.3 TB/s): 350 GB / (16.3 TB/s * 0.70) = 31 ms/step -> ~8,400 tok/s roofline
       8x H100 (8 * 3.35 = 26.8 TB/s): 350 GB / (26.8 TB/s * 0.70) = 19 ms/step -> ~13,700 tok/s roofline
       Budgeting conservatively at 50% of roofline (~4,200 tok/s on 8x A100 @ $9.60/hr; ~6,900 on 8x H100 @ $20/hr):
         Pool A decode = $0.64 / 1M output tok     vs.     Pool H decode = $0.81 / 1M output tok
    
    4. Daily workload (assumed: 10B prompt tokens/day = 115,700 tok/s; 2B output tokens/day = 23,100 tok/s)
       Fleet size (+25% headroom):  Pool H = 52 H100s (13 replicas of TP=4);  Pool A = 56 A100s (7 replicas of TP=8)
       KV network load if 100% split: 115,700 prompt tok/s * 320 KiB = 37.9 GB/s = ~303 Gb/s!
    

    Four design lessons jump right out of this math:

    1. Comparative advantage is real but bounded: Pool H is ~1.5x cheaper on prefill ($0.25 vs. $0.37/M), while Pool A is ~1.25x cheaper on decode ($0.64 vs. $0.81/M, saving $0.17/M output tokens). Across 2,000M output tokens/day, splitting saves 2,000 * $0.17 = ~$340/day (~8.5% off $4,070/day colocated on H down to $3,730/day).
    2. Inter-pool KV bandwidth is the bottleneck: moving 320 KiB/token (655 MB for a 2,000-token prompt; 2.62 GB for 8,000 tokens) for every prompt would consume ~303 Gb/s—nearly saturating a 400 Gb/s inter-pool link. The router must split selectively.
    3. Why TP = 4 for prefill and TP = 8 for decode: tensor parallelism (TP) splits each layer's weight matrices across N GPUs connected over fast NVLink. On prefill, 4 H100s (320 GB HBM) easily hold 140 GB of weights (35 GB/GPU) with minimal cross-GPU sync; on decode, 8 A100s (640 GB HBM) leave ~430 GB free for KV cache so hundreds of sequences batch together and amortize the 140 GB weight read.
    4. Pool V (32 GB V100s) serves 8B FP16 models (16 GB weights + ~13 GB KV cache on a single GPU, no cross-card 70B conversion headaches).
  3. API contracts, reproducibility, and job lifecycle

    Expose an asynchronous batch API that checks deadline feasibility before accepting a job:

    POST /v1/jobs
      { "model": "dense-70b", "weight_format": "bf16",
        "input_uri": "s3://tenant-a/prompts.jsonl",     # one JSON line per custom_id
        "sampling": { "temperature": 0.0, "max_tokens": 1024, "seed": 7 },
        "deadline": "2026-11-28T06:00:00Z", "priority": "standard",
        "placement": { "pin_hardware": null, "allow_split": true } }
      -> 202 Accepted { "job_id": "job_8f2", "state": "validating" }
      -> 409 Conflict { "error": "deadline_infeasible", "earliest_feasible": "2026-11-28T11:30:00Z" }
    
    GET  /v1/jobs/{id}          -> progress counts, predicted finish timestamp, slack status
    POST /v1/jobs/{id}/cancel   -> halts queued shards; keeps completed shard outputs intact
    GET  /v1/jobs/{id}/results  -> manifest of output JSONL files (exactly one record per custom_id)
    

    Internal control-plane and data-plane RPCs:

    Scheduler -> Worker   Assign    { shard_id, attempt, plan: Colocate(pool) | Split(p_pool, d_pool), lease_s: 60 }
    Worker -> Scheduler   Heartbeat { shard_id, attempt, reqs_done, tokens_done }           (every 10 s)
    Worker -> Scheduler   Done      { shard_id, attempt, output_uri, batch_timings[] }
    Prefill -> Decode     KVStream  { request_id, layer_idx, kv_pages }                     (RDMA per layer)
    
    • Why pin_hardware exists: floating-point addition is not associative, so H100 vs. A100 tensor cores—or even different batch sizes on the same GPU—produce tiny rounding differences that occasionally flip greedy token choices. Tenants needing bit-identical reruns set pin_hardware and enable batch-size-invariant reduction kernels, trading slightly lower throughput for determinism.
    • Zero-overhead profiling: every Done RPC piggybacks measured (batch_shape, elapsed_ms) tuples from live production work.
  4. Data model: shards, manifests, partial checkpoints, and versioned profiles

    Break huge jobs into shards of ~512 requests (~1.2M tokens, taking a few minutes on one replica) grouped by shared system-prompt prefix hash and prompt-length bucket:

    jobs       job_id PK, tenant_id, model, weight_format, sampling, deadline, priority, state,
               est_prompt_tokens, est_output_tokens, submitted_at
    
    shards     shard_id PK, job_id, req_range, prefix_hash, length_bucket, est_gpu_seconds,
               state: queued | leased | done | failed, attempt INT, lease_owner, lease_expires_at
    
    manifest   (job_id, shard_id) PK -> winning_attempt INT, output_uri   # written atomically once
    partials   request_id PK -> generated_token_ids[]                     # checkpointed every 256 tokens
    
    profiles   key = (pool, gpu_sku, driver_ver, runtime_ver, model, weight_fmt, kv_fmt, tp_degree, phase)
               coeffs: { a0, a1, a2 } | { b0, b1, b2 }, sample_count, p50_err, p90_err,
               state: fresh | suspect | expired, updated_at
    
    pools      pool_id PK, total_gpus, healthy_gpus, cost_per_gpu_hr, failures_per_gpu_hr, link_gbps_map
    tenants    tenant_id PK, fair_share_weight, reserved_gpu_s_rate, max_pool_fraction
    
    • Why group shards by prefix and length: grouping requests that share a 1,500-token system prompt computes and transfers that prefix KV once per shard; bucketing similar prompt lengths eliminates wasted padding and makes batch duration tightly predictable.
    • Why commit via manifest: retried shards write to .../shard_12_attempt_2.jsonl; atomic insertion into manifest selects exactly one winning attempt so retries never duplicate results.
  5. Draw the high-level platform architecture

      Tenants --(POST /v1/jobs)--> Job API --> CPU Ingestion Pool (tokenize, hash prefixes, cut ~512-req shards)
                                                       |
                                                       v
                    +---------------------------------------------------------------------+
                    | Hardware-Aware Scheduler & Router                                   |
                    |  - Admission control (sells <= 80% of measured pool capacity)       |
                    |  - Least-slack-first queue + GPU-second deficit round robin         |
                    |  - Per-shard planner: Colocate vs Split under inter-pool link cap   |
                    +----------------------------------+----------------------------------+
                         | Assign (60 s lease)         |                    ^
                         v                             v                    | live timings + errors
            +-------------------------+   RDMA KV   +-------------------------+   +-------------------+
            | Pool H (H100, TP=4/8)   |==400 Gb/s==> | Pool A (A100, TP=8)    |   | Profile Service   |
            | Prefill + Colocated Dec |  streaming  | Dedicated Decode        |   | (roofline fits,   |
            +-------------------------+             +-------------------------+   |  drift & probing) |
                                                               |                  +-------------------+
            +-------------------------+                        |
            | Pool V (V100, TP=1)     |   Placement Controller (rebalances model replicas every 5 min)
            | 8B FP16 Colocated       |                        |
            +-------------------------+------------------------+
                                                               v
                     Regional Object Storage (inputs, attempt JSONLs, manifests, 256-tok partials, weights)
    

    For a shard planned as Split(H, A):

    1. The scheduler leases the shard on a Pool H prefill replica and simultaneously reserves decode KV slots on a Pool A replica before prefill begins, so 655 MB+ of KV never stalls in expensive H100 memory waiting for downstream room.
    2. Pool H runs chunked prefill and streams each transformer layer's KV pages directly into Pool A's GPU memory via RDMA (Remote Direct Memory Access)—network hardware that copies memory card-to-card without CPU copies—overlapping Layer i network transfer with Layer i+1 compute.
    3. Pool A folds the arrived sequences into its continuous decode batch, checkpoints long outputs every 256 tokens, writes the attempt output file, commits the manifest row, and releases both reservations.
  6. Deep dive 1: hardware-aware routing from live roofline profiles

    Datasheet FLOPs lie in production: kernel regressions after a runtime update, rack thermal throttling, or degraded NVLink lanes can slow a pool by 30%. Frame performance prediction as an online ML regression service:

    • Prediction target and labels: predict batch wall-clock time (ms) for a prefill chunk or single decode step, plus pool failures_per_gpu_hr from expired leases. Every Done message supplies ground-truth batch timings (millions of labeled batches/day).
    • Physics-informed roofline model (one lightweight linear model per profiles.key, fit via exponentially decayed weighted least squares over a 24-hour window, seeded by a 20-minute micro-benchmark sweep whenever a new software/hardware key appears):
    prefill_chunk_ms = a0 + a1 * new_tokens + a2 * causal_attention_token_pairs
    decode_step_ms   = b0 + b1 * active_batch_size + b2 * total_kv_tokens_read
    

    Unlike an opaque deep neural net, a roofline-shaped linear model extrapolates safely to unseen batch sizes, and its slopes have physical meaning (b2 equals bytes_per_kv_token / achieved_hbm_bandwidth, making bad fits trivial to sanity-check). Evaluate offline on p90 shard runtime error (target < 15%), 95% confidence-interval calibration, and replay simulations of week-long production traces.

    Scoring candidate plans and preventing stale-profile collapse:

    plan_cost(shard, plan) = E[gpu_seconds] * pool_price + failure_rate * E[lost_gpu_s] + link_shadow_cost
    predicted_finish       = replica_queue_wait_s + E[shard_run_s]
    

    Four guardrails stop feedback loops where one optimistic or stale profile breaks routing:

    1. Continuous residual check: if actual vs. predicted median error exceeds 20% over 10 minutes, flip the profile to suspect, widen its time buffer, and cap new assignments to that pool until refit.
    2. Software-versioned keys: bumping CUDA, driver, or vLLM/TensorRT-LLM version creates a fresh key requiring a benchmark sweep before taking full traffic.
    3. Epsilon exploration (~3%): keep ~3% of eligible shards flowing to under-routed pools so a pool that suffered temporary thermal throttling keeps generating fresh timing samples and recovers automatically once healthy.
    4. Queue-aware damping: include live replica queue wait in predicted_finish and cap pool share shifts to <= 20% per 5 minutes so the router never stampedes 100% of work onto one pool.
  7. Deep dive 2: prefill/decode disaggregation under a network budget

    In online chat serving, disaggregation protects interactive typing smoothness; in offline batch processing, nobody watches tokens stream, so disaggregation must pay for its KV network transfer in pure dollars saved.

    Notice the asymmetry: decode savings scale with output tokens (~$0.17 saved per 1M output tokens on Pool A vs. Pool H), whereas network transfer scales with prompt tokens (320 KiB moved per prompt token):

    Workload shape                        KV moved     Output saved   Output tokens saved per MB moved
    ------------------------------------  -----------  ------------   --------------------------------
    Balanced generation (1,000 in/1,000)   328 MB       1,000 tok      3.05 output tokens / MB
    Long-doc extraction (8,000 in / 50)   2,621 MB         50 tok      0.019 output tokens / MB (160x worse!)
    
    • Greedy knapsack routing: estimate output length from historical runs of that tenant's job template—or run a 1% pilot slice first to measure empirical output lengths. Every 30 seconds, sort queued shards by predicted_output_tokens / kv_megabytes_moved and assign top shards to Split(H, A) until predicted inter-pool traffic hits 70% of link capacity (280 Gb/s on a 400 Gb/s link) or Pool A fills up; route remaining shards to Colocate(H). (Ranking by value-per-weight solves the fractional knapsack problem—maximizing total dollars saved subject to a fixed bandwidth cap.)
    • Cutting bytes and latency per transfer:
      • Layer-wise RDMA overlap: streaming each of the 80 layers as soon as it finishes hides 52 ms of 100 Gb/s transfer inside 180 ms of H100 prefill.
      • Prefix deduplication: for shards sharing a 1,500-token system prompt, Pool A caches that prefix KV once so only the 500-token user suffix (164 MB instead of 655 MB) crosses the wire.
      • Zero-reshuffle head mapping: Pool H uses TP = 4 (2 KV heads/GPU) and Pool A uses TP = 8 (1 KV head/GPU); each H100 streams Head 0 to one A100 and Head 1 to a second A100 with zero tensor slicing, keeping BF16 KV intact since A100 lacks native FP8 tensor cores.
    • When the router colocates anyway: long-prompt/short-output tasks, congested inter-pool links, full or degraded Pool A, tight deadline slack (splitting adds a second queue and failure domain), unsupported precision, or off-peak hours when Pool H GPUs would otherwise sit idle.
  8. Deep dive 3: admission control, deadlines, fair share, and batching

    Balance strict deadlines, multi-tenant fairness, and large GPU batches across three layers:

    1. Admission control (<= 80% sold capacity): after tokenizing an uploaded job, compute est_gpu_seconds and required_rate = est_gpu_seconds / (deadline - now - safety_margin) (with safety_margin = max(30 min, 10% of window)). Accept the job only if cumulative required_rate across admitted jobs stays <= 80% of measured pool throughput; otherwise return 409 with earliest_feasible. Keeping 20% unsold absorbs output-length variance and hardware hiccups.
    2. Urgency + GPU-second fairness: define each job's slack—the spare time left before we must run flat-out to make its deadline (slack = deadline - now - remaining_work / allocated_rate).
      • Jobs with slack < 2 hours enter an at-risk priority lane scheduled in least-slack-first order.
      • Normal jobs share capacity via deficit round robin—a weighted fair queuing loop where each tenant accumulates a credit counter measured in GPU-seconds (never raw request count, so 32k-token prompts pay their true compute cost!). Enforce a 40% per-tenant cap whenever other tenants have queued shards, while remaining work-conserving: if the cluster is quiet, one tenant's huge batch may borrow 100% of idle GPUs and hand borrowed slots back at shard boundaries (~2-4 minutes) as soon as peers arrive.
      • Distant-deadline low-priority "filler" shards soak up leftover 20% headroom so fleet utilization stays near 95%+.
    3. Hardware-friendly batching: prefill uses chunked prefill (16k-token fixed chunks from one length bucket for predictable step times); decode uses continuous batching—swapping new sequences into finished batch slots after any single token step so short answers never wait for 4,000-token essays. On 8x A100 (640 GB HBM minus 140 GB weights minus ~70 GB activation/CUDA/NCCL buffers = ~430 GB KV space), one replica holds 430 GB / (2,500 * 320 KiB) ~= 525 concurrent sequences.
  9. Model placement, retries, pool loss, and switchback testing

    Amortizing model swaps. Streaming 140 GB of weights from local NVMe (~5 GB/s) stalls an 8-GPU replica for ~30 seconds (minutes from object storage). A placement controller adjusts replica counts every 5 minutes with hysteresis: switch a replica's loaded model only when queue imbalance persists >= 10 minutes and pays back the 30 s reload cost within 30 minutes.

    Leases, checkpoints, and surviving a full pool outage:

    • 60-second leases + manifest fencing: if a worker dies, its 60 s heartbeat lease expires and the shard re-queues as attempt + 1. Even if a zombie worker wakes up later, atomic manifest fencing rejects stale attempts, ensuring at-least-once execution with exactly-once output. Seeding token sampling from hash(job_seed, custom_id, token_idx) keeps random draws reproducible across retries.
    • 256-token partial checkpoints & poison isolation: long 4,000-token decodes flush token IDs to partials every 256 tokens; after a crash, another replica re-prefills prompt + partial_tokens, losing at most ~8 seconds of decode work. Requests crashing workers twice are quarantined as per-item errors so one malformed input never kills a whole job.
    • When an entire pool disappears mid-job: within 60 s, expired leases return in-flight shards to the scheduler while completed shards remain safe in object storage. If Pool A vanishes completely, its 23,100 output tok/s workload requires 23,100 / (6,900 / 8) ~= 27 H100 GPUs running colocated—more than Pool H's 11 spare GPUs (52 total minus 41 busy). The scheduler immediately pauses low-priority filler work, dedicates Pool H to high-priority and least-slack jobs, resumes interrupted long decodes from partials, and pushes updated finish-time alerts to affected standard-tier jobs.

    Evaluating router upgrades via switchback tests. You cannot A/B test two cluster schedulers by splitting jobs 50/50 simultaneously because both policies compete for the same GPU queues and RDMA links! Validate first in a week-long trace-replay simulator, then run a production switchback test—alternating the entire cluster between Router v1 and Router v2 in randomized 2-hour time blocks over two weeks (discarding the first 20 minutes of each block while carry-over shards drain), comparing $/million tokens under strict deadline-hit-rate and fairness guardrails.

  10. Summarize the design trade-offs

    • Selective disaggregation vs. universal splitting. Splitting prefill (H100) and decode (A100) saves ~$0.17/M output tokens (~8.5% fleet cost) but moves 320 KiB/prompt token; ranking shards by output-tokens-per-MB under a 70% RDMA link cap captures nearly all the savings without saturating the network.
    • Live roofline models vs. static datasheets. Regression models trained on live Done timings adapt to driver changes and throttling, while versioned keys, 20%-error circuit caps, 3% exploration, and damped shifts prevent feedback collapse.
    • 80% admission cap + filler work vs. 100% booking. Leaving 20% capacity unpromised protects 99% deadline guarantees against variance and node failures, while low-priority filler shards recover high GPU utilization.
    • GPU-second fair share vs. giant single-tenant batches. Deficit round robin on GPU-seconds with work-conserving 40% pool caps stops 32k-prompt whales from monopolizing the cluster while still letting idle GPUs run full batches.

Intuition & how it works

Picture an overnight commercial bakery with two kinds of machines: brand-new industrial flash ovens (Pool H, H100 GPUs) that bake whole trays of dough in parallel at blazing speed, and older, much cheaper packaging lines (Pool A, A100 GPUs, plus Pool V, V100 GPUs for small items) that box baked cookies one by one. LLM inference splits into the exact same two jobs: prefill processes all input prompt tokens in parallel (heavy math, where H100s are 1.5x cheaper per token), while decode generates output tokens one step at a time, bottlenecked by reading memory (memory-bandwidth-bound, where A100s are 1.25x cheaper per output token). The catch is the conveyor belt between rooms: handing a request from Pool H to Pool A means shipping its KV cache (the per-layer attention memory built from the prompt—320 KiB per prompt token for a 70B model, or 655 MB for a 2,000-token prompt) across the datacenter network.

A naive platform either runs everything on expensive H100s, blindly ships every prompt's KV cache across the network (instantly clogging a 400 Gb/s link and losing money on long-prompt/short-answer jobs), or routes using static datasheet specs that go wrong after a single GPU driver update or thermal throttle. It also lets one customer upload a 10-million-prompt batch and freeze everyone else's deadlines for a day.

Watch how our router handles two 512-request shards (bite-sized chunks of a batch job) arriving together:

  1. Shard 1 (1,000 prompt tokens -> ~1,000 output tokens, essay generation): Moving 328 MB of KV saves 1,000 expensive H100 decode tokens (3.05 tokens saved per MB moved). Because the 400 Gb/s RDMA (direct GPU-to-GPU network) link is below its 70% budget and Pool A has room, the scheduler reserves decode slots on Pool A first, prefills on 4x H100, streams KV layer-by-layer while computing, and decodes cheaply on 8x A100.
  2. Shard 2 (8,000 prompt tokens -> ~50 output tokens, document classification): Moving 2.62 GB of KV would save only 50 output tokens (0.019 tokens/MB—160x worse payoff!). The router keeps Shard 2 colocated on Pool H, skipping network transfer completely.
  3. Fairness and live feedback: Both tenants pay from GPU-second fair-share budgets so long 8,000-token prompts cannot hog the cluster, and when both shards finish, their Done messages report exact batch runtimes back to the Profile Service to keep our hardware speed models honest.

Key trade-offs

  • Selective disaggregation vs. colocated execution in offline workloads. Unlike live chat—where splitting prefill and decode protects interactive typing speed—offline batch jobs care only about deadlines and total dollars. Because 70B BF16 decode saves ~$0.17 per million output tokens on Pool A while KV transfer costs 320 KiB per prompt token, greedily splitting only high output_tokens / kv_MB shards up to a 70% link cap captures most of the ~8.5% (~$340/day) cost savings without saturating inter-pool networking.
  • Physics-based roofline regression vs. static specs or black-box ML. Static datasheet numbers miss driver regressions and thermal throttling, whereas black-box neural nets extrapolate poorly to unseen batch sizes. Fitting a linear roofline model (predicting batch time from new tokens, causal attention pairs, batch size, and KV bytes read) per software-versioned hardware key adapts in real time while staying physically interpretable—at the cost of maintaining residual alerts, ~3% exploration probes, and rate-limited traffic shifts.
  • 80% admission control + filler queues vs. 100% capacity booking. Promising 100% of cluster throughput guarantees missed deadlines whenever output lengths run long or nodes fail. Capping deadline-committed admissions at 80% protects our >= 99% deadline SLA, while filling idle cycles with distant-deadline low-priority "filler" shards wins back high GPU utilization.
  • GPU-second fair share vs. maximum single-job batching. Enforcing deficit round robin (weighted fair queuing) on GPU-seconds with a 40% per-tenant cap slightly fragments one whale tenant's uniform batches when the cluster is busy, but prevents starvation; making the cap work-conserving lets large jobs borrow 100% of idle GPUs during quiet periods and yield at shard boundaries (~2-4 minutes).
  • Shard granularity (~512 requests) and 256-token checkpoints. Tiny shards add scheduling chatter and weaken system-prompt prefix sharing; giant shards waste hours on retries and react sluggishly to fairness changes. Multi-minute shards paired with 256-token partial decode checkpoints bound lost work on crashes to seconds.
  • Model-swap hysteresis vs. instant queue rebalancing. Reloading 140 GB of 70B weights takes ~30 seconds even from local NVMe SSDs (~5 GB/s). Requiring a 10-minute sustained imbalance and a 30-minute payback window avoids thrashing GPUs on brief traffic blips.
  • Hardware pinning vs. routing flexibility. Cross-GPU floating-point differences and dynamic continuous batching shapes can alter greedy token choices. Offering pin_hardware plus batch-invariant kernels satisfies strict reproducibility tenants at the price of narrower pool choices and slightly lower kernel throughput.

Common mistakes

  • Assuming "older GPUs for decode" is unconditionally cheaper. Decode is HBM-bandwidth- and KV-capacity-bound, so older cards win only when measured (tokens/sec per dollar) minus failure retry waste beats newer cards—and 32 GB V100s lack BF16/FP8 support and cannot hold 140 GB 70B weights without awkward 8-way splitting, making them suited to 8B FP16 jobs instead.
  • Ignoring KV cache network volume. Forgetting that 115,700 prompt tok/s * 320 KiB/tok generates ~303 Gb/s of continuous cross-pool traffic, which easily chokes datacenter links if long-prompt classification jobs are split blindly.
  • Running prefill before reserving downstream decode KV memory, trapping gigabytes of finished KV cache inside scarce H100 HBM while Pool A is full.
  • Mismatched tensor-parallel KV head layouts or unsupported KV formats, such as choosing tensor parallelism (TP) degrees that do not evenly divide the 8 GQA KV heads (forcing expensive network reshuffles) or streaming FP8 KV tensors to A100s without accounting for software dequantization overhead.
  • Silently quantizing weights (BF16 -> INT4/FP16) inside the router to squeeze a job onto older hardware; precision changes alter model accuracy and must be explicitly chosen by the tenant.
  • Metering fairness by request count instead of GPU-seconds, letting a tenant sending 32k-token prompts consume 30x more cluster compute than a tenant sending 1k-token prompts.
  • Evaluating two routing policies with a simultaneous 50/50 job split, ignoring shared-queue interference where Policy B's pool congestion slows Policy A's jobs, instead of running time-alternating switchback tests.

Follow-up questions

  • Under what workload or cluster conditions should the scheduler keep prefill and decode on the same replica even if disaggregated pools would improve per-chip utilization? Colocate whenever KV transfer costs or operational risk outweigh the decode price gap: first, on long-prompt, short-output shards (such as 8,000 tokens in and 50 tokens out, yielding just 0.019 saved decode tokens per MB moved vs. 3.05 on balanced generation). Second, colocate when the inter-pool RDMA link approaches its 70% bandwidth cap, when the decode pool is full, draining, or showing elevated failure rates, or when a job's slack (spare time before missing its deadline) is tight enough that adding a second queue and network hop risks a miss. Finally, colocate when the job's model or precision (FP8) is unsupported on older pools, or during off-peak hours when Pool H H100s would otherwise sit idle anyway.
  • What safeguards stop outdated or miscalibrated hardware speed models from triggering herd stampedes or starving a throttled pool of fresh measurements? Key every profile by (hardware SKU, driver, runtime, model, precision, TP degree) so software upgrades automatically expire old coefficients and trigger a short benchmark sweep before taking full load. Continuously compare live Done batch durations against predictions: if median error exceeds 20% for 10 minutes, mark the profile suspect, widen its uncertainty penalty, and cap new shard assignments to that pool until refit. Finally, include live replica queue wait in routing scores, rate-limit pool allocation shifts to at most 20% per 5 minutes to prevent herd stampedes onto one "fast-looking" pool, and maintain ~3% exploration traffic across all eligible pools so temporarily throttled hardware keeps getting measured and recovers smoothly.
  • Walk through how in-flight shards, partial token generation, and deadline commitments recover if an entire accelerator pool goes offline mid-run. Within ~60 seconds, missed heartbeats expire active shard leases on the lost pool and return those shards to the scheduler, while already-completed shards stay safe in object storage behind the atomic manifest (preserving exactly-once output) and interrupted long decodes resume elsewhere by re-prefilling prompt + 256-token partials. The scheduler immediately recomputes every job's slack against the smaller fleet: our 20% unsold admission buffer absorbs single-node or rack losses seamlessly, whereas losing all of Pool A shifts 23,100 output tok/s (~27 H100s of colocated decode work) onto Pool H, which has only ~11 spare H100s. Consequently, the scheduler pauses low-priority filler work, prioritizes high-priority and least-slack jobs, and sends early revised completion estimates to at-risk standard jobs; once Pool A returns, it runs a verification benchmark and ramps traffic back gradually under the 20%-per-5-minute rate limit.

Follow-up questions

Similar questions

More Gimlet Labs interview questions

All 4 Gimlet Labs questions →