Design a Multi-Tenant Cluster Scheduler for GPU Training

Easy · System Design · Software Engineer · Onsite

Prompt

ML engineering groups across your company launch ad-hoc model training and fine-tuning workloads requiring diverse accelerator classes (including NVIDIA H100, A100 40GB/80GB, and L40S GPUs). Design a centralized, multi-tenant GPU training platform that validates and queues submitted workloads, enforces team-level resource entitlements, prevents starvation across competing job sizes, and orchestrates distributed runs reliably across a fixed hardware fleet.

Functional requirements:

  • Workload specification: Accept job manifests declaring the container image, launch command, accelerator model and GPU count (both single-GPU and multi-GPU gangs), hard runtime ceiling, and checkpoint storage URI.
  • Decoupled admission and placement: Validate tenant entitlements at submission time, enqueue accepted workloads, and bind queued jobs onto concrete hosts that satisfy hardware interconnect topology.
  • Topology-aware gang allocation: Co-locate multi-GPU workloads on fast interconnects—placing up to 8-GPU single-server runs over intra-node NVLink and keeping multi-node gangs within a single InfiniBand leaf/rail domain—allocated atomically as a gang.
  • Multi-tenant fairness and anti-starvation: Apply fair-sharing policies (such as Dominant Resource Fairness or weighted fair queuing) across teams so short, single-GPU experiments are never starved by multi-day gangs, and large gangs are never starved by small-job fragmentation.
  • Graceful preemption and fault recovery: Signal lower-priority or over-quota workloads to flush a checkpoint before termination (SIGKILL), and reschedule interrupted gangs automatically when hosts fail.
  • Cluster visibility: Surface live accelerator utilization, queue wait metrics, and per-team quota consumption.

Non-functional requirements & scale:

  • Control-plane durability: Scheduler restarts or failovers must never drop queued submissions or disrupt actively running training containers.
  • Fast binding: Bind waiting workloads within 1–2 seconds once matching GPU capacity becomes available.
  • Idempotent state reconciliation: Delayed heartbeats or reconnecting node daemons must never cause duplicate GPU assignments.
  • Target scale: 5,000 GPUs distributed across 750 physical hosts, shared by 50 teams submitting up to 500 jobs/hour at peak, with execution lengths spanning 15 minutes (hyperparameter sweeps) to 48 hours (multi-node fine-tuning).

Scope & Expectations

  • Control-plane and host architecture: Define the submission API, durable state store, admission gate, topology-aware gang scheduler, and on-box node agents, keeping active training runs autonomous during control-plane restarts.
  • Core schema and allocation invariants: Model jobs, GPU claims, physical hosts/accelerators, and tenant entitlements so physical GPUs can never be double-booked.
  • Fair-share queuing and topological gang binding: Separate tenant priority/entitlement ordering from all-or-nothing NVLink and InfiniBand placement while preventing starvation in both directions.
  • Preemption, hardware faults, and telemetry: Detail checkpoint-preserving eviction, host heartbeat and GPU hardware error (Xid / ECC) handling, and operator/researcher observability.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Scheduling GPU training jobs is fundamentally harder than scheduling stateless web containers for one physical reason: distributed training runs synchronous collective operations (such as AllReduce, where every GPU averages its gradients with every other GPU after every training step). That creates three interlocking constraints: 1. All-or-nothing gang scheduling: A 32-GPU job needs all 32 GPUs running at the exact same moment; 31 GPUs accomplish zero work. 2. Hardware topology locality: Those 32 GPUs cannot sit on random racks — inside an 8-GPU server they must talk over NVLink (a ~900 GB/s direct GPU-to-GPU interconnect on H100), and across servers they must sit inside one InfiniBand pod (a group of servers sharing the same high-speed leaf switches). 3. Two-way fairness without starvation: Across 50 teams submitting 15-minute 1-GPU sweeps alongside 48-hour 32-GPU runs, neither small jobs nor large multi-node jobs may starve.

    Clarified assumptions and rules

    • Two-level team quotas per GPU type: Each team has a guaranteed GPU count (inside which its jobs can never be preempted by another team) and a maximum GPU count (allowing it to borrow idle GPUs from quiet teams, with borrowed GPUs reclaimable via preemption).
    • Priority classes: prod (urgent deadlines), standard (default), and preemptible (opportunistic sweeps).
    • Valid job shapes: 1..8 GPUs co-located on a single node; > 8 GPUs requested in whole-node multiples of 8 inside a single InfiniBand pod (L40S PCIe/Ethernet nodes accept single-node jobs up to 4 GPUs only).
    • Enforced max_runtime and checkpoint contract: Jobs are terminated when max_runtime expires (making runtimes trustworthy for scheduling), and multi-hour jobs save periodic checkpoints to shared storage so preempted or failed runs resume automatically.
    • Data-plane autonomy: Control-plane restarts must never drop queued jobs or interrupt actively training containers.
  2. Back-of-the-envelope numbers

    Let's break down the 5,000 GPUs across 750 physical nodes and model a realistic daily workload using Little's Law (average concurrent jobs = arrival rate * average duration):

    Physical Fleet (750 nodes, 5,000 GPUs total)
      H100 80GB SXM (8 GPUs/node, NVLink + InfiniBand)   250 nodes = 2,000 GPUs (8 pods of <= 32 nodes)
      A100 80GB SXM (8 GPUs/node, NVLink + InfiniBand)   150 nodes = 1,200 GPUs (5 pods of <= 32 nodes)
      A100 40GB SXM (8 GPUs/node, NVLink + InfiniBand)   100 nodes =   800 GPUs (4 pods of <= 32 nodes)
      L40S 48GB PCIe (4 GPUs/node, Ethernet only)        250 nodes = 1,000 GPUs (single-node pool)
    
    Daily Workload (~5,000 submissions/day; peak 500/hour = 1 job every ~7.2 seconds)
      1-GPU sweeps    (80%)   4,000/day x  1 GPU  x  1 h =  4,000 GPU-h/day  (mostly L40S)
      8-GPU 1-node    (17%)     850/day x  8 GPUs x  5 h = 34,000 GPU-h/day  (NVLink pools)
      32-GPU 4-node    (3%)     150/day x 32 GPUs x 11 h = 52,800 GPU-h/day  (NVLink pools)
      NVLink supply vs. demand: 86,800 / (4,000 GPUs x 24 h = 96,000) = ~90.4% avg (>100% daytime!)
    
    Active Concurrent Jobs (Little's Law)
      Sweeps: ~167    Single-node: ~177    Multi-node: ~69 (holding 69 x 32 = ~2,208 GPUs!)
      Total active jobs across the entire cluster: ~413 jobs
    
    Control Plane, Telemetry, and Checkpoints
      Job submissions     ~0.14 req/s peak; metadata ~25 MB/day -> 1 PostgreSQL HA pair is plenty
      Node heartbeats     750 nodes / 5 s = 150 req/s
      GPU telemetry       5,000 GPUs x 20 metrics / 10 s = 10,000 samples/s -> TSDB (Prometheus), NOT DB!
      Checkpoint size     Mixed-precision Adam stores ~12-14 bytes/param (4B FP32 master weights +
                          4B first moment + 4B second moment + optional 2B BF16 weights):
                          7B model -> ~100 GB (~10 s at 10 GB/s); 70B model -> ~1 TB (~100 s at 10 GB/s)
                          -> 5-minute default preemption grace period (configurable up to 15 min)
    

    Three crucial takeaways guide our architecture: 1. Control-plane volume is tiny (~413 active jobs, 750 nodes): One active leader scheduler holding the entire cluster graph in RAM can compute fair-share and gang placement in milliseconds, easily beating the 1–2 second scheduling target. 2. Multi-node jobs consume > 50% of NVLink GPU-hours: Anti-fragmentation and checkpoint-aware preemption matter enormously because restarting a 32-GPU job idles 4 whole servers during reload. 3. Separate control-plane state from GPU telemetry: Keep PostgreSQL strictly for job/allocation state (~25 MB/day) and route 10,000 samples/sec of GPU metrics to a time-series store.

  3. Job contract API and node agent protocol

    Users submit jobs with an Idempotency-Key header and a digest-pinned container image (@sha256:...) so restarts after preemption or hardware failure execute the exact same code. Node agents maintain a persistent mTLS gRPC stream receiving declarative desired state ("these allocation_ids should be running on your GPUs") rather than one-off imperative "start" RPCs — making delayed heartbeats and agent reconnects naturally idempotent.

    User & Admin REST API
      POST /v1/jobs                         Idempotency-Key: <uuid>
        {
          "name": "qwen2-72b-instruct-ft",
          "team": "reasoning-lab",
          "image": "registry.internal/ml/trainer@sha256:9a2e7d...",
          "command": ["torchrun", "finetune.py", "--cfg", "instruct.yaml"],
          "resources": { "gpu_type": "H100-80GB", "gpu_count": 32 },
          "max_runtime": "24h",
          "checkpoint": { "path": "s3://ml-artifacts/ckpt-409/", "interval": "30m", "grace_period": "5m" },
          "priority_class": "standard",     -- prod | standard | preemptible
          "elastic": null                   -- or { "min_gpus": 16, "max_gpus": 64 }
        }
        -> 201 { "job_id": "job_3d9c", "state": "QUEUED", "pending_reason": "Resources", "estimate": {...} }
        -> 403 QUOTA_EXCEEDED (gpu_count > team max_gpus) | 422 INVALID_TOPOLOGY (e.g., 12 GPUs)
    
      GET  /v1/jobs/{job_id}                (state, allocated nodes/ranks, pending_reason, wait estimate)
      POST /v1/jobs/{job_id}:cancel         GET /v1/jobs/{job_id}/logs?rank=0&follow=true
      GET  /v1/teams/{team}/usage           GET /v1/pools
      POST /v1/nodes/{node_id}:cordon | :drain | :uncordon
    
    Internal Node Agent gRPC Stream (mTLS)
      Register { node_id, boot_id, gpus: [...], running_allocations: [...] }
      Watch    -> server streams desired allocations (START, PREEMPT_WITH_DEADLINE, KILL)
      Report   <- agent streams { allocation_id, rank, state, exit_code, last_ckpt_at, dcgm_health }
    
  4. Data model and job lifecycle

    PostgreSQL (primary + synchronous cross-AZ standby) acts as our single source of truth. Look closely at gpu_claims: its primary key is (node_id, gpu_index). Even if a software bug or split-brain leader ever attempted to double-book a physical GPU, PostgreSQL aborts the transaction immediately!

    quotas            PK (team_id, gpu_type)       guaranteed_gpus, max_gpus
    jobs              PK job_id                    UNIQUE (team_id, idempotency_key)
                      team_id, image, command, gpu_type, gpu_count, max_runtime_s,
                      checkpoint_path, checkpoint_interval_s, grace_period_s, priority_class,
                      state, queued_since, restart_count, last_checkpoint_at,
                      pending_reason, version
    allocations       PK allocation_id
                      job_id, attempt, scheduler_epoch, state, borrowed (BOOL),
                      slice_ends_at, started_at, ended_at, end_reason
    gpu_claims        PK (node_id, gpu_index)      allocation_id, rank  -- 1 row per live allocated GPU!
    nodes             PK node_id
                      gpu_type, pod_id, gpu_count, state ('READY' | 'SUSPECT' | 'DEGRADED' |
                      'CORDONED' | 'LOST'), agent_boot_id, last_heartbeat_at
    gpus              PK (node_id, gpu_index)      uuid, health_state, ecc_errors, last_xid
    reservations      PK reservation_id            job_id, gpu_type, node_ids, expected_start
    scheduler_lease   single row                   epoch, leader_id, lease_until
    usage_ledger      PK (team_id, gpu_type, hour) total_gpu_seconds, borrowed_gpu_seconds
    
      SUBMITTED --admission--> QUEUED --atomic gang bind--> BINDING --> STARTING --> RUNNING
                                  ^                                         |           |
                                  |     keeps original queued_since!        |           |
                                  +----------- PREEMPTING / RECOVERING <----+-----------+
                                                                                        v
                                                                 [ SUCCEEDED | FAILED | TIMED_OUT ]
    
  5. High-level two-tier scheduling architecture

    We split scheduling into two decoupled stages—Tier 1 (Admission Control) and Tier 2 (Topological Gang Placement):

     Researchers / CI Pipelines
                 | HTTPS
                 v
      [ Stateless API Service ] ---------------- write jobs + idempotency ------------+
                 |                                                                    v
      [ Tier 1: Admission Controller ] --- validate shape & team max quota ---> [ PostgreSQL HA ]
                 (stateless; sets state = QUEUED, reserves 0 GPUs)              [ Primary + Sync ]
                                                                                      ^
      [ Tier 2: Leader Scheduler (+ Hot Standby) ]                                    |
         In-memory cluster snapshot per GPU pool:                                     |
         1. Fair-share + deficit + aging queue order                                  |
         2. EASY backfill reservations for multi-node gangs                           |
         3. NVLink / InfiniBand best-fit gang placement                               |
         4. Epoch-fenced single-transaction bind (gpu_claims) ------------------------+
                 | gRPC Watch (desired state per node)
                 v
      [ 750 Node Agents (containerd + NVIDIA DCGM + Xid watcher) ]
            | checkpoints                        | logs + 10k/s GPU metrics
            v                                    v
      [ Shared Object / Parallel FS ]     [ Prometheus + Log Store -> Wait Estimator & UI ]
    

    Why decouple Admission from Placement? 1. Admission needs zero knowledge of live node fragmentation: it checks static invariants (gpu_count <= team.max_gpus, valid topology multiple, per-team cap of 500 pending jobs so a runaway loop cannot flood the queue) and immediately stamps queued_since. 2. Placement wakes up via event notifications within milliseconds whenever an allocation finishes, a node recovers, or a job enters QUEUED. Because the entire 750-node graph sits in memory, computing fair-share ordering + gang placement + committing the single bind transaction completes in ~50–200 ms (well inside the 1–2 second SLA).

  6. Deep dive 1: Fair sharing, deficits, and anti-starvation

    1. Provable quota entitlements via a 90% guarantee ceiling In each GPU pool, we keep sum(guaranteed_gpus across teams) <= 90% of physical pool capacity (reserving 10% headroom for spare/broken nodes). That simple rule gives a mathematical guarantee: whenever Team A is below its guaranteed_gpus, other teams must currently be borrowing at least as many GPUs as Team A is owed, so Team A can always reclaim its entitled GPU count by preempting borrowers!

    2. Two-tier fair-share ordering (DRF / Weighted Fair Queuing) Because CPU and system RAM are allocated proportionally per GPU on training nodes, Dominant Resource Fairness (DRF) (an algorithm that equalizes each tenant's share of their most-heavily-used resource) simplifies cleanly to per-GPU-pool weighted max-min fairness (if custom CPU-heavy jobs are added later, replace gpu_share with max(gpu_share, cpu_share, mem_share)).

    Look closely at how we rank teams so a zero-guarantee borrower (guaranteed_gpus = 0) never jumps ahead of an entitled team and never causes division by zero: - Tier 0 (Entitled: used < guaranteed): Ranked by used / guaranteed (strictly < 1.0). - Tier 1 (Borrowing: used >= guaranteed): Ranked by excess (used - guaranteed) / max(1, guaranteed).

    To also account for history (for instance, a team that waited behind a large unpreemptible gang for 3 hours), we blend in a dynamic share deficit (decaying 24-hour exponential moving average of guaranteed_gpu_hours - used_gpu_hours) as a tie-breaker discount within each tier, and rank jobs inside each team by priority class + aging:

    CLASS_SCORE = {"preemptible": 0.0, "standard": 100.0, "prod": 200.0}
    AGING_PER_HOUR = 10.0
    MAX_AGING_BONUS = 100.0
    
    
    def effective_job_priority(job, now_s: float) -> float:
        """Priority aging: a standard job waiting 10h rises to match a fresh prod job."""
        waited_hours = max(0.0, (now_s - job.queued_since) / 3600.0)
        aging_bonus = min(MAX_AGING_BONUS, AGING_PER_HOUR * waited_hours)
        return CLASS_SCORE[job.priority_class] + aging_bonus
    
    
    def team_fairness_key(used_gpus: int, guaranteed_gpus: int, deficit_gpu_h: float) -> tuple:
        """Entitled teams (tier 0) strictly beat borrowers (tier 1); larger deficit wins ties."""
        if used_gpus < guaranteed_gpus:
            # Guaranteed > 0 is always true when used_gpus < guaranteed_gpus
            return (0, used_gpus / guaranteed_gpus, -deficit_gpu_h)
        weight = max(1, guaranteed_gpus)
        borrowed_ratio = (used_gpus - guaranteed_gpus) / weight
        return (1, borrowed_ratio, -deficit_gpu_h)
    
    
    def fair_share_schedule_order(teams, gpu_type: str, now_s: float, max_picks: int) -> list:
        """Progressively pick next job from the most under-served team in this GPU pool."""
        simulated_used = {t.team_id: t.gpus_in_use(gpu_type) for t in teams}
        team_queues = {t.team_id: t.sorted_queued_jobs(gpu_type, now_s) for t in teams}
        ordered_jobs = []
    
        while len(ordered_jobs) < max_picks:
            best_team = None
            best_key = None
            for team in teams:
                if not team_queues[team.team_id]:
                    continue
                key = team_fairness_key(
                    simulated_used[team.team_id],
                    team.guaranteed_gpus(gpu_type),
                    team.deficit_gpu_hours(gpu_type),
                )
                if best_key is None or key < best_key:
                    best_team = team
                    best_key = key
    
            if best_team is None:
                break
    
            candidate = team_queues[best_team.team_id].pop(0)
            if simulated_used[best_team.team_id] + candidate.gpu_count > best_team.max_gpus(gpu_type):
                candidate.pending_reason = "TeamMaxQuota"
                continue
    
            ordered_jobs.append(candidate)
            simulated_used[best_team.team_id] += candidate.gpu_count
    
        return ordered_jobs
    

    3. Preventing starvation in BOTH directions - Protecting large multi-node jobs from 1-GPU fragmentation: When an entitled (or > 1h aged) multi-node job reaches the head of the queue and cannot find k empty nodes in one pod, the scheduler creates a node reservation on the k nodes in one pod whose running jobs finish earliest (expected_start = max(started_at + max_runtime_s)), capped at at most 2 active reservations per pool so reservations never freeze the whole cluster. To avoid wasting idle GPUs while waiting for the slowest node in the reservation to drain, we apply EASY backfilling: smaller waiting jobs may still run on the reserved nodes if and only if their enforced now + max_runtime_s <= reservation.expected_start (or if they are preemptible, marked borrowed so they are killed when the reservation starts). - Protecting small jobs and waiting borrowers from 48-hour hogs: 1. Checkpoint-aligned time-sliced preemption: Every borrowed allocation receives a 4-hour time slice (slice_ends_at). Once its slice expires and a team with a lower share is waiting, the scheduler waits for the running job's next reported checkpoint (up to 1 checkpoint_interval), then gracefully preempts it — rotating borrowed capacity with almost zero wasted compute! 2. Priority aging + dynamic deficits: Waiting jobs gain +10 priority per hour, and teams blocked behind a large reservation accumulate deficit_gpu_hours so their pending small jobs jump to the front as soon as GPUs free up. 3. Short-job fast lane: Dedicating ~2–3% of nodes to max_runtime <= 2h jobs ensures debugging runs start within minutes even at peak daytime load.

  7. Deep dive 2: Topological gang placement and atomic binding

             [ Cross-Pod Spine Switch (oversubscribed — avoid spanning pods!) ]
                       /                                           \
        [ Pod 1 InfiniBand Leaf Switches ]           [ Pod 2 InfiniBand Leaf Switches ]
          /            |              \                /            |              \
      [Node 1]      [Node 2]  ...  [Node 32]       [Node 33]     [Node 34]  ...  [Node 64]
     (8x H100      (8x H100       (8x H100        (8x H100      (8x H100        (8x H100
      NVSwitch)     NVSwitch)      NVSwitch)       NVSwitch)     NVSwitch)       NVSwitch)
    

    To keep whole nodes and whole pods free for large gangs, we use best-fit bin packing at two levels: - Sub-node (1..7 GPUs): Pick the READY node with the fewest free GPUs (>= gpu_count). That packs four 2-GPU jobs onto one 8-GPU server instead of ruining four empty 8-GPU servers! (On PCIe L40S nodes, prefer GPUs sharing the same CPU root complex / PCIe switch.) - Single-node (8 GPUs) & Multi-node (16..256 GPUs, k = gpu_count // 8 nodes): Pick the InfiniBand pod with the fewest completely empty nodes that still has >= k empty nodes, preserving emptier pods for larger 64- or 128-GPU runs.

    def may_use_node(node, job, pool, now_s: float) -> bool:
        if node.gpu_type != job.gpu_type or node.state != "READY":
            return False
        res = pool.reservation_on(node.node_id)
        if res is None or res.job_id == job.job_id:
            return True
        # EASY backfill: allow short jobs finishing before reservation starts, or preemptible jobs
        if job.priority_class == "preemptible":
            return True
        return (now_s + job.max_runtime_s) <= res.expected_start
    
    
    def place_multi_node_gang(job, pool, now_s: float):
        """All-or-nothing topological placement: k whole 8-GPU nodes inside ONE InfiniBand pod."""
        needed_nodes = job.gpu_count // 8
        best_pod_nodes = None
        for pod in pool.pods:
            empty_usable = [
                n for n in pod.nodes if may_use_node(n, job, pool, now_s) and n.free_gpus() == 8
            ]
            if len(empty_usable) >= needed_nodes:
                # Pod-level best fit: choose the tightest fitting pod to avoid fragmenting big pods
                if best_pod_nodes is None or len(empty_usable) < len(best_pod_nodes):
                    best_pod_nodes = empty_usable
        if best_pod_nodes is None:
            return None
        return best_pod_nodes[:needed_nodes]
    
    
    def bind_gang_atomically(db, job, gpu_slots: list, my_epoch: int):
        """Commit all gpu_claims in ONE epoch-fenced transaction (all GPUs or zero GPUs)."""
        with db.transaction() as tx:
            live_epoch = tx.query_scalar("SELECT epoch FROM scheduler_lease FOR SHARE")
            if live_epoch != my_epoch:
                raise RuntimeError("Fenced: newer scheduler leader took over")
    
            updated = tx.execute(
                "UPDATE jobs SET state = 'BINDING', version = version + 1 "
                "WHERE job_id = :jid AND state = 'QUEUED'",
                {"jid": job.job_id},
            )
            if updated == 0:
                return None  # Job was cancelled concurrently
    
            if tx.count_unready_nodes([node_id for node_id, _, _ in gpu_slots]) > 0:
                raise RuntimeError("Node cordoned since snapshot; rollback and retry next cycle")
    
            alloc_id = new_allocation_id()
            tx.execute(
                """
                INSERT INTO allocations (allocation_id, job_id, attempt, scheduler_epoch, state)
                VALUES (:aid, :jid, :attempt, :epoch, 'STARTING')
                """,
                {"aid": alloc_id, "jid": job.job_id, "attempt": job.restart_count + 1, "epoch": my_epoch},
            )
            for node_id, gpu_idx, rank in gpu_slots:
                # PK (node_id, gpu_index) guarantees zero double-allocation across the cluster
                tx.execute(
                    "INSERT INTO gpu_claims (node_id, gpu_index, allocation_id, rank) "
                    "VALUES (:nid, :gidx, :aid, :rank)",
                    {"nid": node_id, "gidx": gpu_idx, "aid": alloc_id, "rank": rank},
                )
            return alloc_id
    

    Gang startup barrier: Node agents launch containers with MASTER_ADDR, WORLD_SIZE, NODE_RANK, and RDMA/NCCL rendezvous keyed to allocation_id. Only when all ranks report ready does the job move to RUNNING; if any node hangs (e.g., stuck image pull) past 10 minutes, the entire gang aborts cleanly, releases all gpu_claims, cordons the faulty node, and requeues the job at the front with its original queued_since. Reserved nodes pre-pull the container image while draining!

  8. Deep dive 3: Graceful preemption, GPU Xid faults, and idempotency

    Graceful preemption flow: 1. Victim selection: An entitled team never has its in-guarantee jobs preempted by another team. Among borrowed allocations on target nodes, pick victims with the least work since their last checkpoint, lowest priority class, and fewest distinct jobs — skipping any job running for < 30 minutes so jobs always make forward progress. 2. Signal -> checkpoint -> exit: Scheduler sets PREEMPTING (deadline = now + grace_period, default 5m). Agents send SIGTERM and write deadline to /run/platform/preempt. The training loop finishes its current step, writes <checkpoint_path>/attempt-k/step-N/, writes manifest.json last (atomic commit marker), and exits 0 (with SIGKILL enforced at deadline). 3. Why checkpoint alignment saves huge GPU-hours: On a 32-GPU job with 30-minute checkpoints and 10-minute startup/reload, killing randomly wastes (15m lost + 10m reload) * 32 = ~13.3 GPU-hours, whereas preempting right after a checkpoint costs only 10m * 32 = ~5.3 GPU-hours.

    Hardware fault handling (Heartbeats + NVIDIA DCGM / Xid events): - Silent node (30s -> SUSPECT, 90s -> LOST): Because NCCL collectives block indefinitely when even 1 rank vanishes, the entire multi-node gang transitions to RECOVERING, restarts from its latest checkpoint using the pod's warm spare node (1 spare node per 32-node pod = ~3% of H100 capacity, lent only to preemptible 1-node sweeps during normal health!), and does not decrement user error retries. - GPU Xid & DCGM fault classification (Xid codes are hardware/driver error events emitted by the NVIDIA kernel module; ECC is Error-Correcting Code memory protection): - Fatal hardware faults (Xid 48 double-bit ECC, Xid 79 fallen off PCIe bus, Xid 95 uncontained memory error): Cordon node immediately, stop entire gang, restart from last clean checkpoint on spare node, trigger automated DCGM diagnostics. - Degraded hardware (Xid 63/64 row-remapping, Xid 74 NVLink error, severe thermal throttling): Mark DEGRADED (block new placements); trigger an on-demand checkpoint and migrate onto a spare node if remaining runtime cost exceeds restart cost. - Application faults (Xid 13 graphics exception, Xid 31 illegal GPU memory access / OOM): Fail the user job (not the physical node!), draining the node only if distinct teams hit faults on it repeatedly.

    Strict idempotency against delayed heartbeats and zombie nodes: - Database claims own capacity: Free GPUs equal physical GPUs minus gpu_claims rows — a reconnecting agent claiming "I am idle" never creates phantom capacity. - Cordoned fenced cleanup: When a silent node is marked LOST, its gpu_claims are cleared only after either out-of-band BMC/IPMI power-off succeeds OR the node reconnects and confirms old containers are dead (and even while partitioned, old attempts write to <checkpoint_path>/attempt-1/ so they can never overwrite attempt-2/'s checkpoints!).

  9. Control-plane HA, scaling, and real-time observability

    Control-plane high availability: - Scheduler leader + standby: Coordinated via scheduler_lease (epoch incremented on every takeover). On leader crash (~15s lease expiry), the hot standby reloads all ~750 nodes and ~413 active allocations from PostgreSQL into RAM in < 1 second, and any stale bind from the old leader fails SELECT epoch ... FOR SHARE. - Control-plane outage isolation: Node agents keep running active training jobs autonomously if API/scheduler pods go down, buffering status updates locally until reconnection. If shared checkpoint storage degrades, voluntary time-slice preemptions pause automatically so running jobs are never killed when unable to save checkpoints. - 10x cluster scaling: Because each gpu_type pool schedules independently, scaling to 50,000 GPUs simply shards the in-memory scheduler into 1 process per gpu_type pool and moves raw 5-second heartbeats to an in-memory lease service.

    Real-time observability dashboards: - Allocated vs. True Compute Utilization: Show both % GPUs claimed and actual DCGM SM / Tensor Core utilization + NVLink bandwidth — immediately exposing jobs holding 32 H100s at 4% GPU activity due to CPU data-loader bottlenecks! - Capacity waterfall per pool: Healthy allocated, EASY-backfilled, idle-reserved, preempting, fragmented-free, and cordoned/repair GPUs. - Queue transparency: Live p50/p90 wait times by (gpu_type, size_bucket, priority_class), explicit per-job pending_reason (TeamMaxQuota, WaitingForFairShare, TopologyReservation), and per-team guaranteed vs. borrowed GPU-hours.

  10. Summary of key trade-offs

    • Two-tier Admission vs. Placement: Fast, stateless submission checks decoupled from live cluster topology, paired with transparent pending_reason and wait-time estimates.
    • 90% guaranteed quotas + elastic borrowing vs. static partitions: Drives ~90%+ cluster utilization while guaranteeing under-quota teams reclaim their GPUs within one checkpoint grace window.
    • Single-leader in-memory scheduler + epoch-fenced DB binds: Sub-second globally optimal gang placement without distributed lock deadlocks, easily handling 750 nodes and 500 jobs/hour.
    • EASY backfilling + checkpoint-aligned time-slicing + dynamic deficits: Prevents both small-job fragmentation from starving 32-GPU gangs and 48-hour borrowers from starving short jobs.
    • 1 warm spare node per 32-node InfiniBand pod (~3% capacity, lent to preemptible sweeps): Enables immediate in-pod gang recovery on hardware Xid failures without cross-pod spine bottlenecks.

Intuition & how it works

Picture managing a busy research banquet hall with 750 eight-person tables where a party of 32 ML researchers must sit at four whole tables wired together under the same intercom switch so everyone can exchange results after every single step. If the host seats solo guests one chair at a time across random tables, four empty connected tables will never open up at once; and if two 32-person parties each grab two tables and refuse to budge, both sit deadlocked forever.

Simple schedulers break down on shared GPU fleets for three reasons. Allocating GPUs one by one causes deadlocks for multi-GPU training jobs, while scattering ranks across distant network racks bottlenecks gradient synchronization on the slowest network hop. Giving each of the 50 teams a rigid, isolated hardware slice wastes expensive GPUs whenever a team is idle, yet a single greedy FIFO queue lets endless 1-GPU sweeps fragment nodes (starving 32-GPU runs) or lets 48-hour borrowed runs block urgent short jobs.

Walk through four concrete steps to see how our two-tier platform balances utilization, topology, and fairness: 1. Tier 1 Admission: Team Reasoning submits a 32-GPU H100-80GB fine-tuning job (max_runtime = 24h, checkpoint interval 30m). A stateless Admission Controller verifies the shape is a valid multiple of 8 within Team Reasoning's max quota and marks it QUEUED immediately without locking any physical GPUs. 2. Fair-share ordering and reservation: Holding all 750 nodes in memory, the Leader Scheduler sees Team Reasoning is using only 32 / 128 (25%) of its guaranteed H100 quota (entitled tier), reserves 4 nodes inside InfiniBand Pod 3 where active jobs finish earliest, and backfills (temporarily schedules smaller waiting jobs onto reserved nodes) 1-hour sweeps only if their enforced max_runtime ends before the reservation starts. 3. Checkpoint-aligned preemption: Because Team Multimodal is currently borrowing 2 of those reserved nodes above its guarantee and just finished saving a checkpoint, the scheduler sends SIGTERM with a 5-minute grace deadline so Team Multimodal exits cleanly with near-zero lost training work. 4. Atomic gang bind: Within ~1 second of all 32 GPUs becoming free, the scheduler commits the allocation and all 32 gpu_claims(node_id, gpu_index) rows in one epoch-fenced PostgreSQL transaction (gang scheduling — allocating all required GPUs simultaneously or none at all) and streams desired state to the 4 node agents.

Key trade-offs

  • Guaranteed quotas (<= 90% of pool) + borrowing vs. static per-team partitions: Static partitions never preempt, but leave GPUs idle whenever a team pauses experiments; guarantees + borrowing keep the cluster > 90% utilized while ensuring any under-quota team can reclaim its entitled GPUs within a 5–15 minute checkpoint grace period.
  • Reservations with EASY backfilling vs. pure greedy placement: Greedy placement maximizes short-term fill rate but starves 32-GPU gangs behind constant 1-GPU arrivals; capping each pool at 2 active reservations with enforced-runtime backfilling guarantees bounded start times for large gangs with minimal idle waste.
  • Checkpoint-aligned preemption + 4h borrow slices vs. waiting for completion: Waiting up to 48 hours avoids restarts altogether, whereas preempting borrowers right after a checkpoint rotates surplus capacity fairly at a modest ~5.3 GPU-hour reload cost on a 32-GPU job (vs. ~13.3 GPU-hours for an unaligned hard kill).
  • Single-leader in-memory scheduler vs. distributed multi-scheduler architectures: At 750 nodes and ~500 submissions/hour (~1 every 7s), one in-memory leader computes globally optimal multi-node topology placements in milliseconds without optimistic-concurrency collisions across gangs, trading limitless control-plane throughput for simplicity and < 15s standby failover.
  • Best-fit bin packing vs. least-loaded spreading: Packing small jobs onto already partially filled nodes preserves whole 8-GPU NVLink (intra-node high-speed GPU bus) servers and InfiniBand (low-latency cross-node RDMA fabric) pods for large gangs, at the cost of concentrating more small jobs onto each shared host if that host fails.
  • Warm spare node per 32-node pod (~3% capacity) vs. 100% non-preemptible booking: Keeping 1 node per pod free of non-preemptible work (while lending it to preemptible 1-GPU sweeps) lets a multi-node gang swap out a failed node inside the same leaf-switch pod immediately instead of waiting hours for 4 new nodes.
  • Per-attempt checkpoint isolation + cordoned claim release vs. instant timeout release: Waiting for agent reconciliation or out-of-band power-off before deleting gpu_claims — and writing checkpoints under <checkpoint_path>/attempt-k/ — prevents a network-partitioned zombie container from double-using GPUs or corrupting checkpoints.

Common mistakes

  • Allocating multi-GPU jobs incrementally instead of atomically: Holding 16 GPUs while waiting for 16 more lets two 32-GPU jobs deadlock each other indefinitely.
  • Ignoring network topology across multi-node gangs: Placing an 8-GPU job across two 4-GPU slices on different hosts, or splitting a 32-GPU job across spine-connected InfiniBand pods, throttles AllReduce collective throughput by 5–10x.
  • Computing fair share without a tier split for zero-guarantee borrowers: Writing used / max(1, guaranteed) gives a team with 0 guarantee and 0 usage a share of 0.0, letting pure borrowers jump ahead of paying/entitled teams; ranking (is_borrowing, ratio) keeps all under-guarantee teams strictly first.
  • Implementing fair share without anti-fragmentation reservations: Even if Team A ranks #1 in every scheduling cycle, its 32-GPU job will starve forever if 1-GPU jobs keep grabbing single freed GPUs first.
  • Treating max_runtime as an unenforced hint: Without strictly stopping jobs at max_runtime, EASY backfilling and queue wait-time bounds become impossible because backfilled jobs can overrun reservations.
  • Killing preempted training runs immediately with SIGKILL: Aborting a 70B-parameter run mid-step without SIGTERM + a 5–15 minute grace window to flush ~1 TB of optimizer state destroys tens of GPU-hours of training progress.
  • Attempting to restart only the single dead container of a synchronous multi-node gang: Remaining NCCL ranks hang on collective barriers and may hold stale state; the entire gang must wind down and resume cleanly from its last verified checkpoint.
  • Deriving free GPU counts from node heartbeat messages: If a delayed heartbeat or reconnecting agent marks GPUs free while old containers still occupy GPU memory, new jobs crash on launch; PostgreSQL gpu_claims must be the sole authority on free capacity.
  • Monitoring only allocated GPUs instead of active GPU compute (DCGM): A job stalling on slow S3 data loading appears 100% allocated while burning 95% idle H100 cycles.

Follow-up questions

  • When a host participating in a multi-node training gang develops hardware issues—such as double-bit ECC memory faults or severe thermal throttling—how should the platform respond? Fatal ECC (Error-Correcting Code memory) faults like NVIDIA Xid 48 or Xid 95 mean GPU memory is corrupted and bad gradients may already have propagated via AllReduce, so we immediately cordon the faulty node, stop the entire gang, and restart cleanly from the latest checkpoint written before the fault using the pod's warm spare node (without charging the user's retry budget). Soft degradation like thermal throttling slows down the single hot node, which drags every synchronous rank down to that slowest rank's step time. The scheduler marks the node DEGRADED and compares GPU-hour math: if a 64-GPU run has 20 hours left at a 15% slowdown (~192 GPU-hours wasted) versus ~15 minutes to trigger an on-demand checkpoint and swap in a spare node (~16 GPU-hours), it proactively checkpoints and migrates; if only 1 hour remains at a 3% dip, it lets the run finish before draining the node.
  • How would you adapt your design for elastic training frameworks that can expand or shrink their active GPU world size mid-run without aborting? Jobs opt in by specifying elastic: {min_gpus: 16, max_gpus: 64} in whole-node increments alongside an elastic launcher like torchrun --nnodes=2:8. Admission and initial gang placement guarantee min_gpus inside the team's quota; whenever whole idle nodes open inside the same InfiniBand pod, the scheduler expands the allocation up toward max_gpus by marking the added nodes borrowed. When another entitled team needs capacity back, those elastic borrowed nodes are the very first preemption candidates: the platform signals the gang to save a checkpoint, detaches only the extra nodes, and re-runs torchrun rendezvous across the remaining nodes without requeuing the job. Because every membership change still pauses training for rendezvous and checkpoint reload (and requires the script to scale learning rate or gradient accumulation to keep global batch math consistent), we rate-limit elastic resizes to at most once every 10–15 minutes.
  • Which queue signals and forecasting methods would you surface so researchers get trustworthy start-time estimates before their run launches? First, surface an explicit pending_reason (TeamMaxQuota, WaitingForFairShare, TopologyReservation) alongside queue position metrics: total GPUs ahead in the same hardware pool, the team's current in_use / guaranteed GPUs, and its dynamic deficit balance. Second, compute a simulated start-time window (like Slurm's squeue --start) by replaying our fair-share and reservation rules forward against running jobs' started_at + max_runtime upper bounds — presented as an [optimistic, worst-case] range because jobs frequently finish early while higher-entitlement arrivals can overtake borrowers. Third, pair that forward simulation with empirical historical percentiles (p50 and p90 wait times) over the past 7 days bucketed by (gpu_type, node_count_bucket, priority_class, entitled_vs_borrowing) and track calibration accuracy so researchers know how much confidence to place in the estimate.

Follow-up questions

Similar questions

More Fluidstack interview questions

All 2 Fluidstack questions →