Multi-Tenant GPU Cluster Scheduler for ML Workloads

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design a centralized job scheduler for machine learning workloads running on shared GPU cluster hardware. Engineering and research teams submit compute-heavy jobs—such as multi-node model training runs, hyperparameter tuning sweeps, and offline batch scoring—and rely on the scheduler to queue submissions, assign accelerator machines, track execution state end to end, and recover cleanly from hardware or process failures.

Because detailed cluster parameters and policy rules are intentionally left open, establish concrete scope assumptions with the interviewer before diving into the architecture:

  • Workload classes in scope (distributed and single-node training, tuning trials, sharded batch inference, interactive sessions, or recurring pipelines) and whether distributed runs require simultaneous all-or-nothing gang startup across servers.
  • Multi-tenant sharing policies across dozens of teams, including guaranteed per-pool GPU quotas, priority tiers, borrowing idle capacity, graceful preemption, and periodic model checkpointing.
  • Target fleet scale (server and GPU counts, heterogeneous accelerator generations/pools, daily submission volume, burst patterns, and multi-day runtime limits).

Scope & Expectations

  • Contrast distributed multi-GPU training requirements (gang co-allocation, rack/switch network locality, multi-day runtimes, and correlated worker stalls) against stateless request or task scheduling.
  • Define the submission API, separation of durable job state from individual execution attempts, and a control-plane architecture that isolates running GPU containers from scheduler restarts.
  • Design topology-aware gang placement, anti-fragmentation bin packing, dynamic cross-team quota borrowing with low-waste preemption, and backfill reservations that prevent large-job starvation.
  • Cover automated recovery from GPU/node crashes, checkpoint lifecycle tracking, and epoch-fenced scheduler failover.

Step-by-step walkthrough

  1. Clarify scope, scale, and what makes ML jobs different

    Because cluster scale and policy rules are intentionally open-ended, begin by pinning down scope and contrasting distributed ML workloads against stateless web requests or short cron tasks:

    • A web request uses 1 CPU thread for 50 milliseconds and can be retried on any server.
    • A distributed ML training job needs, say, 16 servers with 8 GPUs each (128 GPUs total) at the exact same moment (gang scheduling — allocating every worker of a multi-machine job together or not starting any of them), placed close together on the high-speed network, for days at a time. At the end of every training batch, all 128 GPUs synchronize gradients in an all-reduce step (a collective operation where every GPU exchanges and averages numbers with every other GPU), so if even one machine fails or lags, all 16 machines stall.

    State your concrete scope assumptions out loud so the interviewer can confirm or adjust them:

    • Workloads in scope: Multi-node and single-node model training, hyperparameter sweeps (hundreds of independent 1–8 GPU trials), and sharded batch inference (such as scoring millions of catalog recommendations overnight). Interactive notebooks run in a separate small pool with short idle timeouts, and multi-step recurring pipelines sit in a workflow layer above this scheduler.
    • Gang requirement: Distributed training jobs scale up to 64 nodes (512 GPUs) and require all-or-nothing gang startup.
    • Multi-tenant sharing: Around 40 engineering and research teams share the cluster. Each team gets a guaranteed GPU quota per hardware pool, and any team may temporarily borrow another team's idle GPUs.
    • Preemption and checkpointing: Preemption (stopping a lower-priority or over-quota running job to reclaim its GPUs) is supported. Long training jobs perform checkpointing (periodically saving model weights and optimizer state to shared storage so a stopped run can resume from its last saved step instead of restarting from zero). Batch inference jobs split inputs into small independent shards, so preemption only loses in-progress shards.
    • Heterogeneous hardware: Multiple GPU pools (such as H100, A100, and L4); users specify one required GPU type or an ordered list of acceptable types.

    Core non-functional goals

    1. High GPU utilization: GPUs dominate infrastructure cost, so idle GPUs must be lent out rather than fenced off.
    2. Bounded quota reclamation: An under-quota team reclaims its guaranteed GPUs from borrowers within ~5–20 minutes (a 5-minute checkpoint grace period, plus up to a 15-minute anti-thrashing floor for newly started jobs).
    3. Zero starvation: Large multi-node gangs start in bounded time even under a continuous stream of 1-GPU jobs.
    4. Control-plane isolation: Running training jobs keep executing uninterrupted if the scheduler process restarts.
  2. Back-of-the-envelope numbers

    Put concrete numbers on the board to see what actually needs distributed scale and what fits comfortably on one machine:

    Cluster hardware (assumed)
      1,000 nodes * 8 GPUs/node = 8,000 GPUs total
        - H100 pool: 500 nodes (4,000 GPUs) -> large distributed training
        - A100 pool: 400 nodes (3,200 GPUs) -> medium training & sweeps
        - L4 pool:   100 nodes   (800 GPUs) -> sharded batch inference
      Cost intuition: just 1% idle capacity = 80 GPUs sitting dark continuously
    
    Job arrival rate
      20,000 jobs/day = 20,000 / 86,400 s ~ 0.23 submissions/s average
      Bursts: a hyperparameter sweep submits 1,000 trials in 1 second
      Workload mix: 70% sweep trials & inference shards (1-8 GPUs, minutes to hours)
                    25% single-node training (8 GPUs, hours to days)
                     5% multi-node training (2-64 nodes, days to 2 weeks)
    
    Scheduler memory footprint
      ~50,000 queued + running + recent jobs * ~2 KB/job = ~100 MB RAM
      -> Fits easily in memory inside ONE leader scheduler with a hot standby!
    
    Hardware failure math
      Assume 1 job-killing failure per node every 100 days (MTBF = 2,400 hours)
      Whole cluster (1,000 nodes): 1,000 / 100 = ~10 node failures/day
      Single 64-node training job: 100 days / 64 = 1.5625 days = 37.5 h (135,000 s) between crashes
      Over a 14-day training run:  14 / 1.5625 ~ 9 hardware crashes -> recovery MUST be automatic!
    
    Checkpoint size & optimal interval (7B-parameter mixed-precision Adam run)
      Saved state: 4 B fp32 master weights + 4 B Adam m + 4 B Adam v = 12 bytes/param
                   7B * 12 B = 84 GB per checkpoint (~98 GB if 2 B bf16 weights are also saved)
      Assume pausing training to save takes C = 60 s
      Young's optimal interval: sqrt(2 * C * MTBF) = sqrt(2 * 60 * 135,000) ~ 4,025 s (~67 min)
      Expected lost work per crash: ~half an interval (~34 min) + container restart time
    

    Three architectural takeaways come straight from these numbers:

    • Submission QPS (0.23/s) and state (100 MB) are tiny. Do not waste interview time sharding the scheduler database; focus on gang placement, fair preemption, and automatic crash recovery.
    • Multi-node crashes are routine (~9 per two-week 64-node run). Checkpointing and automatic rescheduling are part of everyday normal operation.
    • A 300-second (5-minute) preemption grace period gives a job plenty of room to finish a 60-second emergency checkpoint before eviction.
  3. API design

    POST /v1/jobs
    {
      "idempotency_key": "recs-ranker-2026-12-01",
      "name": "catalog-ranker-v5",
      "team": "search-ranking",
      "type": "training",                       // "training" | "sweep_trial" | "batch_inference"
      "priority": "normal",                     // "production" | "normal" | "best_effort"
      "preemptible": true,
      "image": "registry.internal/trainer@sha256:4a9b...",
      "command": ["torchrun", "--nnodes=16", "--nproc_per_node=8", "train.py"],
      "resources": {
        "gpu_types": ["H100"],
        "gpus_per_worker": 8,
        "workers": 16,
        "cpu_per_worker": 96,
        "memory_gb_per_worker": 1500
      },
      "gang": true,
      "max_runtime_hours": 72,
      "max_retries": 5,
      "checkpoint_grace_seconds": 300
    }
    -> 202 { "job_id": "job_4920", "state": "QUEUED" }
    
    GET  /v1/jobs/{job_id}
    -> 200 {
         "state": "QUEUED", "attempt": 2, "queue_position": 3,
         "pending_reason": "Waiting for 16 whole H100 nodes; reserved, expected start in ~38 min"
       }
    
    POST /v1/jobs/{job_id}/cancel
    GET  /v1/teams/{team}/usage                 // guaranteed quota, in-use, and borrowed GPUs
    
    // Reported by running workers (via the local node agent) whenever a checkpoint finishes:
    POST /v1/attempts/{attempt_id}/checkpoint
    { "step": 145000, "path": "s3://ml-ckpts/job_4920/att_2/step_145000" }
    

    Four small API details pay off enormously in production:

    • idempotency_key prevents a network timeout on POST /v1/jobs from accidentally launching two identical 128-GPU training runs.
    • pending_reason answers "Why is my job sitting in QUEUED?" directly in the CLI/UI — the #1 daily support question on any shared ML cluster.
    • Container images pinned by @sha256 digest guarantee that an attempt resumed 3 days later after a node failure runs the exact same code and libraries.
    • The /checkpoint callback lets the scheduler track last_checkpoint_at, so when it needs to preempt a job it can pick a victim that checkpointed 2 minutes ago rather than 55 minutes ago.
  4. Data model and job-vs-attempt lifecycle

    Store durable state in a strongly consistent relational database (PostgreSQL with a synchronous standby replica), and mirror active state in the leader scheduler's RAM:

    teams          team_id PK, quota_by_gpu_type JSONB, borrow_limit_by_gpu_type JSONB
    jobs           job_id PK, idempotency_key UNIQUE, team_id, type, priority, preemptible,
                   spec JSONB, state, submitted_at, queue_since,
                   user_retry_count, max_retries, infra_retry_count,
                   last_checkpoint_step, last_checkpoint_path, last_checkpoint_at
    attempts       attempt_id PK, job_id FK, attempt_number, node_ids TEXT[],
                   leader_epoch BIGINT, state, started_at, ended_at,
                   exit_reason ('SUCCEEDED' | 'USER_ERROR' | 'NODE_FAILURE'
                                | 'PREEMPTED' | 'RUNTIME_LIMIT' | 'LAUNCH_TIMEOUT')
    nodes          node_id PK, pool, gpu_type, gpus_total, gpus_free, switch_group,
                   health ('OK' | 'SUSPECT' | 'CORDONED'), last_heartbeat_at
    reservations   job_id PK, node_ids TEXT[], shadow_start_at
    events         event_id PK, created_at, job_id, attempt_id, event_type, details JSONB
    

    Separating one job from many attempts keeps restarts clean: every hardware failure or preemption closes the old attempt row (freeing all nodes of that gang at once) and opens a fresh attempt row on healthy nodes, while the parent job keeps its last_checkpoint_path and its original queue_since timestamp so it resumes at the front of its team's queue rather than starting wait time over.

     submit --> QUEUED --(all gang nodes allocated)--> PLACED --(all workers healthy)--> RUNNING
                  ^                                      |                                |   |
                  |                                      | 10-min launch timeout          |   +--> SUCCEEDED
                  |                                      v                                |   +--> FAILED
                  +--------------------------------------+--------------------------------+
                    requeued with original `queue_since` on:
                      - launch timeout (slow image pull / bad node)
                      - node or GPU crash (uses infra_retry_count, not user max_retries!)
                      - preemption (RUNNING -> PREEMPTING -> saves checkpoint -> QUEUED)
    
  5. High-level architecture

      ML Engineers / CLI / Workflow Engine (Airflow / Dagster)
              |  POST /v1/jobs, GET /v1/jobs/{id}
              v
      +----------------+     reads & writes     +-------------------------------------+
      |   API Server   |----------------------->| Job Store: Postgres (sync replica)  |
      +----------------+                        | jobs, attempts, nodes, reservations |
                                                +-------------------------------------+
                                                           ^                |
                                      persists decisions   |                | loads state on failover
                                                           |                v
                                +-------------------------------+  lease   +---------------------+
                                |   Active Scheduler (Leader)   |<-------->|  Standby Scheduler  |
                                | - Fair-Share Queue Manager    | (epoch)  +---------------------+
                                | - Gang & Topology Placer      |
                                | - EASY Backfill Reservations  |
                                | - Preemption Victim Planner   |
                                +-------------------------------+
                                         |                     ^
                  launch / kill RPCs     |                     | 10 s heartbeats, container exits,
                  (stamped with epoch)   v                     | GPU ECC / NVLink health checks
                                +-------------------------------+
                                |  Node Agents (x 1,000 nodes)  |
                                +-------------------------------+
                                         |
                                [ Worker Containers ] ---> [ Shared Object / Parallel FS Checkpoints ]
    

    Every 1–2 seconds (or on job/node events), the single-threaded scheduling loop runs four phases in memory: 1. Order QUEUED jobs across teams by fair share and priority. 2. Try to place each job (place_gang); if a head-of-line gang cannot fit yet, maintain a node reservation for it. 3. If an under-quota (or production) job still cannot fit, select minimal-cost preemption victims. 4. Commit placement/preemption transitions to Postgres before sending epoch-stamped launch/kill RPCs to node agents.

  6. Deep dive 1: Topology-aware gang placement and anti-fragmentation

    Why must a 16-node training job be placed all-or-nothing? If Job A grabs 10 free nodes and waits for 6 more while Job B grabs the remaining 6 free nodes and waits for 10 more, neither job can ever run its first all-reduce step — 16 nodes (128 GPUs) sit completely deadlocked! Our scheduler assigns all 16 nodes in a single atomic in-memory step, with a 10-minute PLACED -> RUNNING launch timeout (covering large container pulls); if one worker fails to start, all 16 nodes are released together and the slow node is inspected.

    Next, consider network topology and fragmentation: - Inside one 8-GPU server, GPUs communicate over NVLink (ultra-high-bandwidth direct GPU-to-GPU wires, ~900 GB/s). Across servers, traffic crosses leaf switches (top-of-rack switches connecting ~32–64 nodes in one hop) and slower spine switches between racks. Because all-reduce runs at the speed of the slowest network link, a gang runs fastest inside one switch group, or otherwise across the fewest switch groups. - If eight 1-GPU sweep jobs land on 8 separate servers (1 GPU used on each), they block all 8 servers from hosting any whole-node (8-GPU) gang!

    Bad (spread / first-fit):  [1/8] [1/8] [1/8] [1/8]  -> 28 free GPUs, ZERO whole 8-GPU nodes!
    Good (best-fit packing):   [4/8] [0/8] [0/8] [0/8]  -> 28 free GPUs, THREE whole 8-GPU nodes!
    

    We prevent fragmentation with best-fit bin packing at both levels: - Sub-node jobs (1–4 GPUs): Pick the healthy node with the fewest gpus_free that is still >= gpus_needed, packing small jobs onto already-partial nodes first. - Whole-node gangs (workers_needed full 8-GPU nodes): Prefer a single switch group using best fit (the smallest switch group with >= workers_needed empty nodes, preserving huge empty switch groups for 64-node jobs); if no single switch group fits, take largest free switch groups first so the gang spans as few switches as possible.

    def place_gang(workers_needed, free_nodes_by_group):
        """Choose whole 8-GPU nodes for a distributed gang inside one GPU pool.
    
        free_nodes_by_group: list of node_id lists, one list per leaf-switch group,
                             containing only healthy nodes with all 8 GPUs free.
        Returns a list of `workers_needed` node_ids, or None if the gang must wait.
        """
        # Phase 1: Try to fit the entire gang under ONE leaf switch (best-fit: smallest
        # switch group that fits, keeping larger contiguous groups intact for 64-node runs).
        best_single_group = None
        for group in free_nodes_by_group:
            if len(group) >= workers_needed:
                if best_single_group is None or len(group) < len(best_single_group):
                    best_single_group = group
    
        if best_single_group is not None:
            return best_single_group[:workers_needed]
    
        # Phase 2: Check total free whole nodes across all switch groups (all-or-nothing!).
        total_free_nodes = 0
        for group in free_nodes_by_group:
            total_free_nodes += len(group)
        if total_free_nodes < workers_needed:
            return None
    
        # Phase 3: Span across the FEWEST switch groups by draining largest groups first.
        largest_first = sorted(free_nodes_by_group, key=len, reverse=True)
        chosen_nodes = []
        for group in largest_first:
            for node_id in group:
                chosen_nodes.append(node_id)
                if len(chosen_nodes) == workers_needed:
                    return chosen_nodes
        return chosen_nodes
    

    Trace place_gang(workers_needed=4, ...) on three switch groups with [6, 4, 2] free nodes: Phase 1 picks the 4-node group (leaving the 6-node group intact for a future 6-node gang!). If a 7-node gang arrives next against [6, 0, 2], Phase 1 finds no single group >= 7, Phase 2 sees 6 + 2 = 8 >= 7, and Phase 3 picks all 6 from group 1 plus 1 from group 3 (2 switch groups total). At 1,000 nodes, this runs in microseconds.

  7. Deep dive 2: Fair sharing, dynamic borrowing, and low-cost preemption

    Next, address peak resource contention: every GPU in the pool is currently allocated, an urgent job enters the queue, and all active workloads belong to neighboring teams.

    Guaranteed quotas + dynamic borrowing. Every team has a guaranteed GPU count per pool (summing to <= 100% of the pool), and any team may borrow idle GPUs above its guarantee so expensive hardware never sits idle. Critically, over-quota ("borrowed") status is tracked dynamically at the team level (over_quota_gpus = max(0, team_used - team_quota)), not stamped permanently on a job at launch time! Why? Suppose Team A has a 64-GPU guarantee, starts Job 1 (64 GPUs) at 9:00 AM, and borrows 64 extra GPUs for Job 2 at 9:10 AM (128 used). When Job 1 finishes at 10:00 AM, Team A's usage drops back to 64 <= 64 — Job 2 is now within Team A's guarantee and must not be treated as borrowed capacity!

    • Queue ordering: Across teams, pick the next job from the team with the lowest used / quota ratio (or Dominant Resource Fairness (DRF) — ordering by whichever resource ratio, GPU, CPU, or RAM, is highest for that team). Within a team, sort by priority (production > normal > best_effort), then queue_since.
    • Who can preempt whom:
      1. An under-quota job (team_used + job_gpus <= team_quota) may reclaim GPUs from any over-quota team (victim_team_used > victim_team_quota), evicting that team's best_effort and normal jobs until the borrower is no longer over quota.
      2. A production job (e.g., deadline-bound nightly ranking inference) may also preempt best_effort jobs anywhere, or lower-priority jobs inside its own team.
      3. Never preempt another team's in-quota normal or production job. Otherwise "guaranteed quota" is not a guarantee.

    Choosing minimal-pain victims and executing graceful preemption: - Score eligible victims in the target GPU pool by wasted GPU-minutes: victim_cost = victim_gpus * (minutes_lost_after_sigterm + restart_overhead_minutes) Because jobs report /checkpoint timestamps and can save an emergency checkpoint on SIGTERM, a right-sized job or recently checkpointed job has far lower cost than preempting a 64-node job just to free 2 nodes. - Anti-thrashing rules: Skip any attempt running < 15 minutes (it has barely finished container startup) and cap preemptions per job per day (except opportunistic backfill tasks). - Graceful eviction: Mark victim PREEMPTING -> send SIGTERM -> worker writes emergency checkpoint and exits within 300 s (else SIGKILL) -> launch waiting job and return victim to QUEUED with its original queue_since.

  8. Deep dive 3: Preventing starvation of large gangs (EASY backfill)

    With naive "run whatever fits now" scheduling, a 32-node (256-GPU) job at the head of the queue starves forever: every time 1 node frees up, a queued 1-GPU job snaps it up before 32 nodes ever accumulate! We solve this without idling GPUs using EASY backfill (an HPC scheduling technique that reserves a future start time for the head-of-line large job while letting short or preemptible small jobs borrow those nodes in the meantime):

    32-node gang J is head-of-line. Right now 20 nodes are free; 12 more finish by t_shadow (in 45m).
    
    Time --->      now                                        t_shadow (+45 min)
    Nodes 1..20    [ FREE NOW -> Reserved for J; backfill   ] [ Gang J runs on all 32 nodes ... ]
                   [ ONLY jobs ending < t_shadow OR         ]
                   [ preemptible inference shards           ]
    Nodes 21..32   [ Running jobs finishing by <= t_shadow  ] [ Gang J runs on all 32 nodes ... ]
    Nodes 33..500  [ Unreserved -> normal scheduling continues without restriction ............. ]
    

    Four rules make reservations work cleanly in production: 1. Still try opportunistic early start every cycle: If 12 other unreserved nodes finish early at +15 min, place_gang immediately places J on 20 + 12 = 32 free nodes and deletes J's reservation instead of waiting until +45 min. 2. Enforce hard max_runtime_hours: If jobs could run past their declared limit, t_shadow would slip indefinitely. Because engineers often pad max_runtime_hours, estimate expected duration from past runs of the same job name while still enforcing the hard ceiling. 3. Reserve only for the top 1–2 head-of-line gangs per pool and keep each reservation pinned until its job starts, so shifting fair-share ratios do not thrash reservations across jobs. 4. Combine with quota preemption: If J's team is under quota and borrowers are holding nodes for multi-day runs, reclaim borrowed nodes immediately via Deep Dive 2 rather than waiting days for t_shadow.

  9. Failure handling and split-brain fencing

    • Node failure or silent GPU corruption: Node agents send heartbeats every 10 s and run hardware diagnostics checking ECC errors (hardware-detected memory bit flips on a GPU), dropped NVLink lanes, and straggler GPUs.
      • Control-plane vs. data-plane check: If a node misses heartbeats for 60 s (SUSPECT), check whether its gang's sibling nodes still report advancing training steps. If training steps are still advancing, only the node_agent daemon died — restart the agent without killing a healthy 512-GPU job! If steps stalled or peers report a collective timeout, terminate all remaining workers of the attempt, record NODE_FAILURE, cordon the faulty node, and requeue the job using infra_retry_count (never burning the user's small max_retries budget, which is reserved for USER_ERROR crash loops).
      • Optional hot spares: Holding ~1% of H100 nodes (5 nodes) running only instant-evict best_effort tasks lets a 64-node job swap out 1 dead node in minutes instead of waiting in QUEUED for 64 fresh nodes.
    • Scheduler crash and split-brain fencing: Running containers are owned by local node agents, so a scheduler crash interrupts zero running GPUs. When the leader's 15-second lease in Postgres/etcd expires, the standby increments a monotonically increasing leader_epoch (fencing token), reloads state from Postgres, reconciles against live container lists reported by node agents, and resumes scheduling. Every node agent rejects launch/kill RPCs carrying an epoch < highest_seen_epoch, preventing a frozen old scheduler from waking up and double-launching jobs.
    • Network partitions: Node agents never self-kill containers merely because they lost contact with the scheduler (otherwise a brief control-plane blip would wipe all 8,000 GPUs!). A partitioned multi-node worker automatically exits at its next all-reduce once its peers stop; for partitioned single-node jobs, checkpoint metadata updates in Postgres/object storage use compare-and-swap on attempt_id so a stale isolated attempt can never overwrite a newly rescheduled attempt's checkpoints or batch outputs.
  10. Scaling bottlenecks and summary of trade-offs

    At 1,000 nodes and 20,000 jobs/day, a single leader scheduler handles everything in memory. As the platform grows 10x, watch five bottlenecks: - Scheduling loop CPU: Group queued jobs by resource shape (gpu_type, gpus_per_worker, workers). Once one (H100, 8, 16) job fails to place in a cycle, skip remaining identical shapes in O(1). - Millions of tiny inference tasks: Support array jobs where 1 scheduler job launches long-lived worker containers that pull 100,000 micro-shards from an internal queue, keeping container startup and scheduler metadata small. - Container image thundering herd: 64 nodes pulling a 20 GB PyTorch image simultaneously (1.28 TB burst) saturates a central registry. Use NVMe node image caches, peer-to-peer layer distribution, and pre-pulling onto reserved nodes before t_shadow. - Synchronized checkpoint bursts: Copy model weights from GPU HBM to host CPU RAM in < 2 seconds, resume training immediately, and stream the 84 GB checkpoint to object storage asynchronously in the background. - Monitoring: Track allocated GPUs vs. actual GPU compute utilization (catching jobs that reserve 8 GPUs and bottleneck on 1 CPU dataloader), queue wait p50/p95 by team and gang size, and goodput (the fraction of allocated GPU-hours that produce committed training steps rather than work lost to crashes, launches, or preemptions).

    Summary of trade-offs: Lending idle quota maximizes utilization at the cost of occasional graceful preemptions; all-or-nothing gang startup + EASY backfill eliminates deadlocks and starvation while adding runtime-limit enforcement; best-fit switch-group placement trades slightly longer queue waits when "required" for much faster all-reduce throughput; and a single epoch-fenced leader scheduler keeps global fairness and gang placement simple at the cost of a ~15-second failover pause for new launches.

Intuition & how it works

Think of an ML cluster scheduler like the host at a busy banquet restaurant seating both solo diners and 16-table wedding parties, rather than a fast-food counter handing out grab-and-go sandwiches. A distributed training run needs gang scheduling (allocating all machines of a multi-worker job at the exact same moment, or none at all) on tables right next to each other, because at the end of every training step all GPUs pause for an all-reduce synchronization (where every GPU exchanges and averages gradients with every other GPU) — if even one table is missing or one stove breaks, the entire wedding party sits frozen. To keep every table busy without breaking promises to different departments, we give each team a guaranteed quota while letting anyone temporarily borrow idle GPUs, reclaim borrowed GPUs through graceful preemption (stopping an over-quota or low-priority job after letting it save state), protect progress via checkpointing (periodically saving model weights and optimizer state to shared storage so a stopped job resumes from its last saved step), and prevent huge gangs from waiting forever via EASY backfill (reserving a future start window for the front-of-line large gang while letting short or preemptible small jobs fill those GPUs until that window arrives).

Why do the naive approaches fail? Scheduling workers one machine at a time deadlocks the cluster as soon as two 16-node training jobs each grab 8 free nodes and wait forever for the other 8. Running a simple "start whichever queued job fits right now" loop starves large multi-node jobs indefinitely because tiny 1-GPU tasks constantly slip into every freed GPU before 16 whole nodes ever open up together. And enforcing rigid, unshareable per-team walls leaves expensive H100 GPUs sitting idle whenever one team is between experiments, whereas sharing without checkpoints and graceful preemption either breaks team guarantees or throws away days of GPU compute.

Let's trace a tiny concrete cluster of 4 nodes x 8 GPUs = 32 GPUs, shared equally by Team Search (quota 16 GPUs) and Team Vision (quota 16 GPUs):

t = 00:00  Team Search submits Run_S1 (2 nodes = 16 GPUs) and Run_S2 (2 nodes = 16 GPUs).
           Team Vision is idle, so both start! Team Search uses 32 GPUs (16 guaranteed + 16 borrowed).
t = 01:00  Run_S1 and Run_S2 each write a checkpoint to shared storage (step 2,500).
t = 01:05  Team Vision submits Run_V1 (2 nodes = 16 GPUs, gang=true).
           Team Vision uses 0/16 GPUs (under quota!), while Team Search is 16 GPUs over quota (32 > 16).
           Preemption planner picks Run_S2 (16 GPUs, losing only 5 min since its 01:00 checkpoint):
           sends SIGTERM -> Run_S2 writes emergency checkpoint (step 2,710) in 60 s & exits ->
           Run_V1 starts on all 16 GPUs together! Run_S2 returns to QUEUED keeping its timestamp.
t = 02:00  Team Vision submits a 4-node gang Big_V (32 GPUs; borrowing idle capacity once S1 ends):
           Suppose 2 nodes are free now and 2 finish at t = 02:40 (shadow time).
           EASY backfill reserves the 2 free nodes for Big_V at 02:40, lets a 20-minute 8-GPU sweep
           trial run on them from 02:00 to 02:20 (zero wasted GPUs!), and starts Big_V right at 02:40.

Key trade-offs

  • All-or-nothing gang placement vs. instant partial startup. Waiting until all N whole nodes are free prevents partial-allocation deadlocks and wasted idle GPUs waiting at their first all-reduce, at the cost of longer queue wait times for large jobs — which we bound using EASY backfill reservations.
  • Dynamic quota borrowing + preemption vs. strict static partitions. Lending idle GPUs keeps cluster utilization high, while tracking over-quota usage dynamically (max(0, team_used - team_quota)) ensures a team can always reclaim its guaranteed capacity within minutes (5 min checkpoint grace + 15 min anti-thrashing floor). The trade-off is occasional preemption restarts, made cheap by regular and SIGTERM-triggered checkpoints.
  • Topology-aware best-fit packing vs. first-available placement. Packing small 1–4 GPU tasks onto already-partial nodes prevents node fragmentation, and placing whole-node gangs inside a single leaf switch (a rack/pod network switch connecting servers in one hop) maximizes all-reduce speed. Defaulting topology to "preferred" starts jobs faster across multiple switches when the cluster is fragmented, while allowing "required_single_group" for communication-heavy runs.
  • Checkpoint frequency (Young's formula sqrt(2 * C * MTBF)). Checkpointing every few minutes loses almost no work on crashes or preemptions, but stalls GPUs and hammers storage bandwidth; checkpointing once a day wastes up to 24 hours of GPU compute per failure. Around ~60–70 minutes (plus asynchronous host-RAM-to-storage uploads) balances both for large runs.
  • Hot spares (~1% of nodes) vs. full production allocation. Keeping a handful of nodes running only instant-evict best_effort shards lets a 64-node training job swap out one failed machine in minutes rather than returning to the queue to wait for 64 free nodes, trading ~1% peak training capacity for dramatically higher goodput (useful committed training steps per GPU-hour).
  • Single leader scheduler with standby vs. distributed sharded schedulers. Because 50,000 jobs take ~100 MB of RAM and arrive at < 1/s on average, one active leader with a standby gives exact global fair-share accounting and atomic multi-node gang decisions without distributed lock contention, trading off a brief ~15 s pause in new placements during leader failover.

Common mistakes

  • Scheduling multi-GPU training workers one container at a time like stateless web pods, causing partial gangs to sit idle at 0% compute or deadlock against each other.
  • Stamping a static borrowed = True boolean on a job at launch time. When an earlier in-quota job from the same team finishes, that team's total usage drops back inside its guaranteed quota; static job flags wrongly leave the remaining job exposed to preemption by other teams.
  • Spreading 1-GPU sweep trials across empty nodes (round-robin / least-loaded). Putting one 1-GPU job on each of 100 8-GPU servers leaves 700 free GPUs but zero whole 8-GPU servers for distributed training.
  • Using a naive "first job that fits" loop without reservations, which lets continuous 1-GPU tasks starve 32-node gangs forever, or reserving nodes without backfill, which leaves dozens of expensive GPUs idle while waiting for the last node to free up.
  • Counting hardware crashes (NODE_FAILURE) and preemptions against the user's max_retries limit. A healthy 2-week 64-node run expects ~9 hardware failures by probability alone (14 days / 1.56 days MTBF), so conflating hardware faults with USER_ERROR crash loops kills valid flagship runs right before completion.
  • Having node agents kill running containers when they lose network contact with the scheduler, turning a routine 10-second scheduler restart or database blip into a catastrophic cluster-wide wipeout.
  • Omitting fencing tokens (leader_epoch and attempt_id compare-and-swap), allowing a paused old scheduler leader to double-launch jobs or a network-partitioned worker to overwrite a newer attempt's checkpoint pointer.

Follow-up questions

  • How do you prevent a continuous stream of small single-GPU tasks from starving a massive multi-node training job without wasting idle GPUs while nodes drain? Use EASY backfill: when the head-of-line gang cannot fit, compute its shadow time (the earliest timestamp enough whole nodes will finish, based on enforced max_runtime_hours or historical runtime predictions) and reserve those specific nodes. While waiting for that shadow time, allow smaller queued jobs onto the reserved nodes only if their enforced runtime finishes before the shadow time or if they are preemptible tasks (like batch inference shards) that can be evicted immediately when the gang is ready. Keep trying to place the gang on every cycle in case unreserved nodes finish early, reserve only for the top 1–2 head-of-line gangs so the cluster never freezes, and use quota preemption instead of waiting if borrowers are holding the team's guaranteed GPUs.
  • How would you extend the platform to support scheduled multi-stage workflows where model training depends on an upstream feature-preparation step? Keep DAG (Directed Acyclic Graph — a multi-step workflow graph with ordered dependencies and no loops) orchestration in a separate workflow layer (such as Airflow, Dagster, or Flyte) on top of the cluster scheduler rather than baking pipeline logic into the GPU placer. Each scheduled run generates a deterministic idempotency_key like <pipeline_name>:<logical_date>:<step_name> so workflow retries never duplicate GPU jobs, and submits the downstream training job to POST /v1/jobs only after the upstream data-prep job succeeds and validates its output partition. Deadline-critical daily pipelines submit with priority = "production" so they can preempt best_effort and over-quota jobs automatically.
  • How does your scheduling architecture evolve once compute capacity spans multiple distinct clusters or geographic regions? Split scheduling into two levels: a lightweight global router and independent per-pool/per-region schedulers. The global router assigns an incoming job to a single region/pool based on required GPU type, data gravity (where the multi-terabyte training dataset and checkpoints already live, since cross-region egress is slow and expensive), remaining team quota in that pool, and estimated queue wait. Each pool runs its own leader scheduler, Postgres store, and failure domain, and a single gang never spans across regions because wide-area network latency destroys synchronous all-reduce throughput.
  • When should an organization layer custom batch scheduling onto an existing container orchestrator versus adopting or building a dedicated cluster scheduler? Reuse an existing orchestrator for container lifecycle, networking, storage mounts, secrets, and node health agents — rebuilding those from scratch takes years — and customize only the scheduling policy layer. On Kubernetes (whose documented single-cluster limits of ~5,000 nodes and ~150,000 pods comfortably fit a 1,000-node / 8,000-GPU cluster), the default pod-by-pod scheduler lacks gang startup and dynamic quota borrowing, so teams pair Kubernetes with an ML batch add-on like Kueue or Volcano (plus custom plugins for topology-aware best-fit and checkpoint-cost victim selection). In pure research environments, Slurm natively supports whole-node gang allocation, fair-share trees, and EASY backfill out of the box (note that Slurm's own "gang scheduling" config term refers to time-slicing, whereas its standard multi-node job allocation is already all-or-nothing); choose between Kubernetes + Kueue/Volcano vs. Slurm based on your org's existing ops expertise and service ecosystem.

Follow-up questions

Similar questions

More Netflix interview questions

All 97 Netflix questions →