Hybrid-Cloud GPU Cluster Scheduling Service
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a multi-tenant orchestration platform that schedules and supervises GPU-accelerated machine learning training jobs across a hybrid-cloud fleet combining company-owned on-premises GPU clusters with elastic public-cloud capacity.
Engineers submit batch or distributed training runs—for example, project vision-models launching a 64-GPU training job (vit-xl-run-09) over a 6 TB dataset (ds://vision/imagenet-xl) stored on-premises with an optional cloud-burst budget (max_cost_usd: 6000), while another team (foundation-pretrain) holds guaranteed on-premises GPU quota that may reclaim borrowed capacity. Your system must support three core capabilities:
- Policy- and capacity-aware hybrid placement: Decide whether each workload runs on an on-premises cluster or bursts to a public cloud based on live GPU availability, queue delay, data locality/residency rules, and budget policy.
- Declarative job submission: Allow users to specify or upload container/program artifacts, training datasets, hardware footprints (GPU model and count, vCPUs, host RAM), and optional scheduling rules (allowed regions, spend cap, priority class).
- Lifecycle tracking & fault recovery: Transition long-running jobs cleanly across
queued,running,completed,failed, andcanceledstates while exposing live logs, hardware/training telemetry, and automated retry semantics.
State explicit engineering assumptions and address multi-tenant quota fairness, resilience to worker hardware crashes and cloud-provider API failures, strict tenant isolation and IAM security for code and datasets, and horizontal scalability across thousands of simultaneous users and jobs.
Scope & Expectations
- Control-plane & data-plane architecture: Present the end-to-end component topology spanning global scheduling, cluster-local execution, and cross-environment networking without making running jobs brittle to control-plane restarts.
- APIs & persistent state: Define idempotent endpoints for submitting, inspecting, listing, and canceling jobs alongside the relational schema and deterministic job-state machine.
- Hybrid scheduling & fairness: Detail how gang scheduling, on-premises vs. cloud cost/wait scoring, quotas, borrowing, and preemption avoid cluster fragmentation and starvation.
- Artifact staging, security & operations: Explain how container images, multi-terabyte datasets, and checkpoints reach GPU nodes securely, how split-brain retries and leaked cloud VMs are prevented, and what SLIs operators monitor.
Step-by-step walkthrough
Clarify requirements and scope
Machine learning (ML) training jobs behave very differently from ordinary web requests. A web request takes milliseconds on one CPU core; a training job can lock up 1 to 1,024 GPUs for hours or weeks. Worse, in distributed training all GPUs compute each step and exchange gradients together, so if 1 node out of 64 is missing or slow, the other 63 sit idle. Our service accepts training jobs from many teams, decides whether each job runs on the company's own on-premises (on-prem) GPUs or in a public cloud, stages the code and data, monitors execution, and recovers automatically from hardware crashes.
Functional requirements
- Submit a job: users provide a container image (plus an optional lightweight code archive), input datasets, resource requirements (GPU model and count, CPU, RAM, local scratch disk), and optional constraints (allowed regions, data residency, cost ceiling, priority, maximum runtime).
- Hybrid placement: choose an on-prem cluster or a cloud cluster automatically based on GPU availability, queue wait time, policy, data location, and dollar cost.
- Lifecycle tracking and telemetry: move every job cleanly through
QUEUED,RUNNING,COMPLETED,FAILED, andCANCELED, streaming live logs, GPU metrics, training progress, and human-readable reasons for every state change. - Automatic retries: restart automatically from the latest saved checkpoint (a periodic snapshot of model weights and optimizer state written to storage) when hardware fails or capacity is reclaimed; retry bugs in user code only if explicitly requested.
- Management APIs: get job details, list/filter jobs, cancel a job, and inspect per-project quota and cloud spend.
Non-functional requirements
- Multi-tenant fairness: every team receives its guaranteed GPU share quickly when needed, while idle GPUs can be temporarily lent to other teams instead of sitting dark.
- Reliability and decoupling: a crashed node or flaky cloud API never loses a job silently, and a control-plane outage must never kill jobs that are already running on GPU nodes.
- Security and isolation: one team cannot read another team's code, datasets, checkpoints, or logs; jobs receive short-lived credentials scoped strictly to their declared inputs and outputs.
- Scale: support thousands of concurrent users and jobs ranging from 1-GPU experiments to 1,024-GPU foundation-model runs.
Assumptions to confirm with the interviewer
- Gang scheduling required: distributed jobs require gang scheduling (starting all worker nodes of a job at the exact same time on one high-speed network fabric, or starting none at all). A single job never spans across on-prem and cloud because wide-area links are orders of magnitude slower than cluster interconnects.
- Checkpointing contract: long jobs save checkpoints periodically and handle a graceful stop signal (
SIGTERM) by flushing a checkpoint before exiting. Jobs that opt out of checkpointing cannot use interruptible capacity. - Batch training focus: interactive Jupyter notebooks are out of scope; we focus on non-interactive batch and distributed training.
Back-of-the-envelope numbers
Before sketching boxes, we estimate traffic, storage, failure rates, and network transfer times so we know where the real bottlenecks live.
Fleet size (assumed baseline) On-prem 256 nodes x 8 H100 = 2,048 H100 GPUs (fabric A) + 128 nodes x 8 A100 = 1,024 A100 GPUs (fabric B) = 3,072 GPUs across 384 nodes Public cloud 2 providers x 2 regions = 4 cloud clusters: 64 reserved nodes x 8 H100 = 512 reserved H100 GPUs + up to 250 burst nodes x 8 H100 = 2,000 on-demand / spot H100 GPUs = up to 314 cloud nodes (~2,512 cloud GPUs) Workload & control-plane QPS Users & projects 2,000 engineers across 100 projects Submissions 20,000 jobs/day / 86,400 s = ~0.23 submits/s average (hyperparameter sweeps can burst 1,000 jobs in one call) Active jobs ~3,000 running + up to 10,000 queued at peak Status polling 400 active users / 15 s (~27 QPS) + CI/CLI (~100 QPS) = ~130 QPS Node heartbeats ~700 total nodes / 10 s = ~70 heartbeats/s Telemetry ~5,500 GPUs x 30 metrics / 15 s = ~11,000 metric samples/s 3,000 running jobs x 500 B/s logs = 1.5 MB/s = ~130 GB/day (~3.9 TB/month) Checkpoints & failure math (example: 70B-parameter mixed-precision run on 128 nodes = 1,024 GPUs) Bytes per param 4 B (FP32 master weights) + 4 B (Adam momentum) + 4 B (Adam variance) = 12 B Checkpoint size 70B x 12 B = 840 GB (~900 GB including RNG and dataloader state) Write time (C) 900 GB / 20 GB/s aggregate cluster storage bandwidth = 45 s Job failure rate If 1 node has an MTBF of 180 days, a 128-node gang loses a node every: 180 days / 128 nodes = 1.406 days = 121,500 s (~34 hours) Optimal interval sqrt(2 x C x MTBF_job) = sqrt(2 x 45 s x 121,500 s) = ~3,307 s (~55 min) -> checkpoint roughly once per hour (~1.25% write overhead if blocking) Cross-site data transfer & cloud economics (illustrative rates) Hybrid interconnect 2 x 100 Gbps = 25 GB/s line rate -> ~15 GB/s usable (60% utilization) 6 TB dataset = 6,000 GB / 15 GB/s = 400 s (~6.7 min) 100 TB dataset = 100,000 GB / 15 GB/s = 6,667 s (~1.85 hours) Cloud egress fee ~$0.05/GB leaving cloud -> copying one 900 GB final checkpoint home = ~$45 GPU hourly rates on-prem internal chargeback $1.50/GPU-h; cloud on-demand $6.00/GPU-h; spot $2.50/GPU-h Orphaned VM risk 1 idle 8-GPU cloud node = 8 x $6 = $48/h; 10 leaked nodes over a 60 h weekend = $28,800Here MTBF (Mean Time Between Failures) is the average time a single machine runs before a hardware or OS crash, spot instances are discounted spare cloud VMs that the provider can reclaim on short notice, and egress is data transferred out of a cloud provider's network (whereas copying data into a cloud is typically free).
Four design lessons jump straight out of this math:
- Control-plane QPS is tiny (
0.23 writes/s,130 reads/s). One PostgreSQL primary with read replicas easily handles metadata. The hard problems are gang placement, fairness, data gravity, and fault recovery. - Hardware failures are routine at scale. A two-week 128-node run (
14 days / 1.4 days ≈ 10 crashes) will fail around 10 times. Automatic checkpoint-and-resume is a core path, not an edge case. - Data has gravity. Copying 100 TB takes nearly two hours, so we must stage datasets before renting cloud GPUs and prefer clusters that already cache the dataset.
- Leaked cloud VMs burn real money. Every cloud API call must be idempotent and backed by a background reconciler that terminates orphaned instances.
- Control-plane QPS is tiny (
API design
To prevent duplicate GPU launches when a client retries after a network timeout, mutating endpoints require an
Idempotency-Key(a unique client-generated UUID stored by the server so repeating the exact same request returns the original job instead of creating a second one). Container images are pinned by immutablesha256digest (a cryptographic hash of exact image contents) rather than mutable tags like:latestso Attempt 2 always runs the exact code Attempt 1 ran.POST /v1/jobs Headers: Authorization: Bearer <oidc-jwt>, Idempotency-Key: 4c1f-99a2-... { "name": "vit-xl-run-09", "project": "vision-models", "image": "registry.internal/vision/train@sha256:9ab3...", "code_overlay": "artifacts://vision/snap-91ab.tar.gz", "command": ["torchrun", "--nnodes=$NNODES", "--nproc-per-node=8", "train.py"], "inputs": [ {"dataset": "ds://vision/imagenet-xl", "version": "2026-11-01", "mount": "/data", "mode": "ro"} ], "outputs": {"checkpoints": "ckpt://vision/vit-xl-run-09/"}, "resources": { "gpu_type": "H100-80GB", "nodes": 8, "gpus_per_node": 8, "cpu_per_gpu": 12, "memory_gb_per_gpu": 200, "local_nvme_gb": 3000 }, "placement": { "allowed_sites": ["onprem", "cloud"], "residency": "us", "spot_allowed": true, "max_cost_usd": 6000 }, "priority": "normal", "max_runtime": "24h", "retry": {"max_user_failures": 1}, "checkpoint": {"resume_flag": "--resume-from", "signal": "SIGTERM", "grace_s": 120} } -> 202 Accepted { "job_id": "j_7f3a", "state": "QUEUED", "sub_state": "waiting_capacity", "estimated_start": "2026-11-29T16:10:00Z" } GET /v1/jobs/{job_id} -> state, sub_state, reason, attempts[], cluster, cost_usd GET /v1/jobs?project=vision-models&state=RUNNING&limit=100&page_token=... POST /v1/jobs/{job_id}:cancel -> 202 Accepted (idempotent; triggers graceful stop -> CANCELED) POST /v1/jobs:batchCreate -> submit up to 1,000 sweep jobs atomically GET /v1/jobs/{job_id}/logs?attempt=2&rank=0&follow=true GET /v1/jobs/{job_id}/metrics?names=gpu_util,sm_active,loss,step&from=...&to=... POST /v1/datasets -> register immutable dataset manifest; returns presigned upload URLs GET /v1/projects/{project_id}/quota -> guaranteed GPUs, borrowed GPUs, monthly cloud budget & spendNotice how we separate coarse public states (
QUEUED,RUNNING,COMPLETED,FAILED,CANCELED) from detailedsub_stateandreasonstrings (such as"QUEUED / staging_data: copying 6 TB to cloud-us-east (42%)"). Automation scripts match cleanly on the 5 stable states, while engineers immediately see why their job is waiting without filing support tickets.Data model and job lifecycle
All authoritative metadata lives in PostgreSQL. To stop stale worker callbacks from overwriting newer job states, updates use optimistic locking (storing an integer
row_versionon each row and updating onlyWHERE row_version = expected_version, incrementing it atomically). Side effects (notifications, billing, UI streams) are published via a transactional outbox (writing the event into anoutboxtable inside the exact same SQL transaction as the job update, then relaying rows to an event bus so no event is ever lost or emitted without a committed state change).projects project_id PK, org_id, fair_share_weight, residency, allowed_clouds[], monthly_cloud_budget_usd quotas (project_id, gpu_type) PK, guaranteed_gpus, max_borrow_gpus jobs job_id PK, project_id, user_id, spec_json (immutable), idempotency_key, state, sub_state, reason, priority, current_attempt, cancel_requested, row_version, submitted_at UNIQUE (project_id, idempotency_key) attempts attempt_id PK, job_id FK, attempt_num, cluster_id, node_ids[], state, exit_code, failure_class (user | infra | preempted | timeout), checkpoint_uri_used, fencing_token, started_at, ended_at allocations allocation_id PK, attempt_id FK, cluster_id, node_id, gpu_ids[], lease_expires_at clusters cluster_id PK, kind (onprem | cloud), provider, region, gpu_type, price_per_gpu_h, free_gpus, largest_schedulable_gang, updated_at provision_requests request_token PK, job_id, cluster_id, node_count, state (REQUESTED | PARTIAL | READY | FAILED | RELEASED), cloud_vm_ids[] datasets (dataset_id, version) PK, manifest_uri, size_bytes, sensitivity (public | internal | restricted), residency, replicas_json usage_ledger (project_id, gpu_type, site, hour_bucket) PK, gpu_seconds, cost_usd job_events (job_id, event_ts, seq) PK, event_type, payload_json [partitioned by month]Every job moves through a deterministic state machine:
QUEUED (waiting_quota | waiting_capacity | staging_data | provisioning_cloud) | | all dataset shards staged AND full GPU gang reserved v RUNNING (pulling_image | running | checkpointing) |-- exit code 0 -----------------------------------------------> COMPLETED |-- infra crash / spot reclaim / preemption -------------------> QUEUED (new attempt, auto-resume | from latest checkpoint) |-- non-zero user exit, user retries remaining ----------------> QUEUED (new attempt after backoff) |-- non-zero user exit (0 retries left) / max_runtime / cap ---> FAILED | (from QUEUED or RUNNING) -- cancel requested --> sub_state: canceling (SIGTERM -> wait grace_s -> SIGKILL -> free GPUs) --> CANCELEDHigh-level architecture
Scheduling 5,500+ GPUs across on-prem datacenters and multiple clouds works cleanest with two-level scheduling:
- A global scheduler (one active leader elected via a database lease) owns multi-tenant quotas, hybrid cost/wait-time trade-offs, and dataset locality. It assigns a job to a cluster, not individual PCIe cards.
- Each cluster runs a local scheduler (such as Kubernetes with Kueue/Volcano or Slurm) that knows live rack switch topology and GPU health, binding the job's gang onto specific physical nodes.
Why shouldn't the global scheduler just read
free_gpusper cluster? Because fragmentation hides inside totals: 64 free GPUs scattered 1-per-node across 64 machines cannot run an 8-node × 8-GPU gang! Each cluster agent therefore reports bothfree_gpusandlargest_schedulable_gang(for each whole-node gang size) every 5 seconds.Engineers / CI / SDK | HTTPS (OIDC token) v [ API Gateway ] ---> [ Stateless Job API ] ---> [ PostgreSQL Primary + Read Replicas ] | (outbox relay) v [ Event Bus (Kafka) ] -> Billing, Audit, Alerts | +---------------------------------------------+ v [ Global Scheduler (1 active leader w/ epoch lease + warm standby) ] reads: pending jobs, quotas & decayed usage, cluster snapshots, dataset replicas writes: job -> cluster placement + cloud provision requests | +---> [ On-Prem Cluster A (H100) ] & [ On-Prem Cluster B (A100) ] | Cluster Agent -> Local Gang/Topology Scheduler -> Node Agents | +---> [ Cloud Provisioner ] --(idempotent ClientToken)--> AWS / GCP Capacity APIs | '--> [ Cloud Clusters (4 regional clusters, same Cluster Agent + Node Agents) ] | '---> [ Reconciler (every 60 s) ] compares Postgres desired state vs actual cluster allocations & cloud VMs; terminates orphaned VMs and re-queues stranded attempts Per-Site Data Plane (independent of control plane once a job starts): [ Pull-Through Image Mirror ] [ Object Store + NVMe Dataset Cache ] [ Checkpoint Store ] [ Node Agent (10 s heartbeat, DCGM GPU health, SIGTERM handler, log/metric shipper) ]Crucially, running jobs never depend on the global control plane. If PostgreSQL or the global scheduler restarts for maintenance, node agents keep running containers and writing checkpoints to their local site object store; only new job placements pause briefly.
Deep dive 1: Hybrid placement, cost scoring, and gang backfill
When a job reaches the global scheduler, placement runs in four clear stages:
Stage 1 — Hard eligibility filters. A cluster is kept only if: 1. It has the requested
gpu_typeand its network fabric can hold the entire gang (one job never splits across sites because all-reduce—the collective operation summing gradients across all GPUs after every training batch—needs hundreds of GB/s inside one InfiniBand/RoCE fabric, not a shared 15 GB/s WAN link). 2. Project policy (allowed_sites) and dataset governance (residency,sensitivity) allow that site (for example,restrictedcustomer datasets never leave on-prem). 3. Estimated run cost fitsmax_cost_usdand the project's remaining monthly cloud budget (enforced dynamically during execution too: hittingmax_cost_usdtriggers a checkpoint and stops the job cleanly). 4. Spot capacity is considered only whenspot_allowed = trueand checkpointing is enabled.Stage 2 — Cost-plus-time scoring. Fixed rules like "spill to cloud if on-prem wait > 4 hours" ignore job size, data transfer time, and urgency. Instead, each project configures a
value_of_time(in dollars per hour of earlier completion), and we pick the candidate cluster minimizing:completion_h = queue_wait_h + cloud_provision_h + data_staging_h + runtime_h dollar_cost = (gpus x runtime_h x gpu_price) + egress_cost + expected_spot_rework_cost total_score = dollar_cost + (value_of_time x completion_h)Let's trace this on our sample 64-H100 job (
vit-xl-run-09) running for 12 hours whose 6 TB dataset currently lives only on-prem (and will copy one ~1 TB final checkpoint home at$50egress if run in the cloud):Candidate Wait Setup (provision + stage) Runtime Completion Dollar Cost ----------------- ----- ---------------------------- ------- ---------- ------------------------------- On-prem H100 6.0 h 0 h 12.0 h 18.00 h 64 x 12 x $1.50 = $1,152 Cloud on-demand 0.0 h 15 min VM + 9 min copy (0.40h) 12.0 h 12.40 h 64 x 12 x $6.00 + $50 = $4,658 Case A — Urgent launch team (value_of_time = $1,000/h): On-prem score = $1,152 + ($1,000 x 18.00) = $19,152 Cloud score = $4,658 + ($1,000 x 12.40) = $17,058 --> Burst to cloud (saves 5.60 hours for $3,506 extra) Case B — Routine research sweep (value_of_time = $300/h): On-prem score = $1,152 + ($300 x 18.00) = $6,552 Cloud score = $4,658 + ($300 x 12.40) = $8,378 --> Wait on-prem (saving $3,506 outweighs 5.60 h wait)Queue wait on-prem is estimated by fast forward-simulation of the queue using historical runtime distributions per project (capped by
max_runtime). We log predicted vs. actual wait times continuously so bad estimates are caught immediately.Stage 3 — Handling unreliable cloud capacity. Public clouds frequently run out of contiguous 8×H100 blocks or return only 5 of 8 requested nodes. - We prioritize 512 pre-paid reserved cloud H100s first (their marginal hourly cost is
$0, just like on-prem). - For burst nodes, the job staysQUEUED (provisioning_cloud)until all 8 nodes pass health checks. If only 5 nodes arrive, we hold them for at most 15 minutes while retrying the remaining 3; after 15 minutes (5 × $48/h × 0.25 h = $60bounded cost), we release all 5 and fall back to the next region/provider or the on-prem queue.Stage 4 — Preventing head-of-line blocking inside a cluster. Suppose a 64-node (512-GPU) job reaches the front of the queue when 40 nodes are free and the remaining 24 nodes will free up in 2 hours. Pure FIFO causes head-of-line blocking: those 40 free nodes (320 H100s!) sit completely idle for 2 hours waiting for the other 24. We solve this with reservation + backfill:
Nodes 64 +---------------------------------------+========================+ | 24 nodes busy (finish by t = 2h) | | 40 +--------------------+------------------+ 512-GPU Gang Reserved | | Backfill Job X | Backfill Job Y | (starts at t = 2h) | | (32 nodes, max 1h) | (16 nodes, max 1h| | 0 +--------------------+------------------+------------------------+--> Time t = 0 t = 1h t = 2h t = 14hThe local scheduler locks in a
t = 2hstart reservation for the 64-node gang, then allows smaller queued jobs (Job X,Job Y) to leapfrog onto the 40 idle nodes only if their enforcedmax_runtimefinishes beforet = 2h. That is whymax_runtimeis mandatory on every job. For network locality, gangs are placed under as few top-of-rack leaf switches as possible, while 1–4 GPU jobs are packed best-fit onto partially filled nodes so whole 8-GPU nodes stay intact for distributed gangs.Deep dive 2: Multi-tenant fairness, quotas, and safe preemption
Static cluster partitions keep teams isolated but waste GPUs whenever one team is between training runs. Pure first-come-first-served keeps utilization high but lets a single 1,000-job sweep starve everyone else. We get both utilization and guarantees with guaranteed + borrowable quotas across our guaranteed H100 pool (
2,048 on-prem + 512 reserved cloud = 2,560 H100s):Project Guaranteed H100s Max Borrow Effective Behavior -------------------- ---------------- ---------- -------------------------------------------------- foundation-pretrain 1,280 +512 Always gets 1,280 within minutes; can burst to 1,792 vision-models 640 +640 Guaranteed 640; can double to 1,280 when pool is quiet applied-ml 384 +256 Guaranteed 384; can grow to 640 shared-dev 256 +256 1-8 GPU exploratory runs across smaller teams -------------------- ---------------- Sum 2,560 (= exact physical + reserved capacity; guarantees are never oversold)Queue ordering. Pending jobs are ordered by: 1. Priority tier (
critical > high > normal > low), 2. Fair-share ratio (decayed_gpu_hours_used / guaranteed_gpus), where past usage decays exponentially with a 24-hour half-life so a team that monopolized idle GPUs yesterday yields today to a team that was quiet, 3. Submit timestamp with aging (gradually boosting wait score so low-priority jobs never starve forever).Inside each project, the exact same decayed fair-share rule runs per user so one engineer's 1,000-job sweep interleaves fairly with teammates' single jobs. And to close the loophole where a job asks for 1 GPU alongside 100% of a node's RAM (effectively stranding the other 7 GPUs!), usage is charged by Dominant Resource Fairness (DRF):
max(gpu_fraction, cpu_fraction, ram_fraction)of the node.Safe preemption rules. Reclaiming GPUs is never free—even a well-checkpointed 1,024-GPU job loses ~30 minutes of work since its last checkpoint plus ~10 minutes of startup. We minimize wasted work with four strict invariants: - Guarantees are sacred: a job running inside its project's
guaranteed_gpuscan never be preempted by another project—only jobs running on borrowed GPUs (or lower-priority jobs within the same project) are eligible victims. - Least-work-lost victim selection: among eligible borrowed jobs, pick those with the smallestgpus × minutes_since_last_checkpointthat free enough contiguous nodes. - Graceful stop: sendSIGTERM, waitgrace_s(default 120 s) so the training loop flushes an emergency checkpoint, then sendSIGKILLand return the job to the front of its queue. - Anti-thrashing: a job cannot be preempted during its first 15 minutes of runtime or more than 3 times in 24 hours.To prevent two scheduler instances from ever handing the same GPUs to two projects during a failover, only one global scheduler holds an active lease (a time-bounded lock row in PostgreSQL renewed every 5 s) carrying a monotonically increasing
epochinteger. Every placement transaction checksWHERE scheduler_epoch = $my_epoch, immediately rejecting stale writes from a deposed leader.Deep dive 3: Staging code, datasets, and checkpoints
Fast code delivery without registry meltdowns. If 128 nodes simultaneously pull a 15 GB PyTorch container image at job start, the registry gets slammed with
128 × 15 GB = 1.92 TBof traffic at once. We avoid this in three ways: 1. Every on-prem datacenter and cloud region runs a local pull-through registry mirror, so cloud nodes never pull across the hybrid WAN link. 2. Base images are pre-warmed on GPU nodes and distributed across cluster nodes via peer-to-peer layer sharing (such as Dragonfly/Kraken) or lazy chunked image loading. 3. Engineers iterating on Python scripts upload a< 100 MBcontent-addressedcode_overlaytarball unpacked onto a cached base image at container start—cutting iteration startup from 10 minutes of Docker builds to seconds.Dataset staging before GPU allocation. Datasets are immutable versioned manifests (
ds://vision/imagenet-xl@2026-11-01) listing object keys, SHA-256 checksums,sensitivity, andresidency. - Never hold GPUs during cross-site copies: if a cloud cluster lacks a 6 TB dataset, the job entersQUEUED (staging_data)while a background data-mover copies objects bucket-to-bucket over the hybrid link (~7–9 minfor 6 TB). Only after the replica is markedpresentindatasets.replicas_jsondo we provision cloud VMs—saving$384/h(64 × $6/h) in idle GPU rent. - Locality caching: staged cloud dataset replicas are kept in regional cloud object storage and evicted LRU (Least Recently Used) once no queued or running job references them, so follow-up runs in that region start with zero transfer time and cost. Hot shards are cached on each GPU node's local 3 TB NVMe SSDs during training epochs.Asynchronous checkpointing. Blocking 1,024 H100s for 45 seconds every hour wastes compute. Training frameworks use asynchronous checkpointing: workers copy model/optimizer tensors from GPU HBM memory into pinned host CPU RAM in ~1–2 seconds, immediately resume the next training batch on GPUs, and let background CPU threads stream the 900 GB snapshot to the cluster's local object store under
ckpt://project/job/attempt-N/step-K/. Once all ranks finish uploading stepK, rank 0 atomically updates alatest.jsonpointer, and a background replicator copies the final or periodic milestone checkpoints back to the project's home store so artifacts survive cloud cluster teardown.Failure handling, split-brain fencing, and cloud reconciliation
Detecting silent hangs as well as hard crashes. - Node & GPU crashes: node agents send heartbeats every 10 s (marked
NODE_LOSTafter 60 s of silence) and run DCGM (NVIDIA Data Center GPU Manager) checks. Uncorrectable GPU memory (ECC) errors or fatal driver (XID) faults automatically cordon/drain the bad node and re-queue the attempt on healthy hardware. - Collective deadlocks: in distributed PyTorch (NCCL), a degraded network cable can freeze all 128 nodes forever with 100% power draw and zero crashes. Workers emit a lightweightstep_completedheartbeat; if step count stalls for 30 minutes (configurable), the platform classifies the attempt as a hunginfrafailure, captures stack traces, and restarts it on fresh nodes.Preventing split-brain checkpoint corruption. Suppose a network partition isolates Node 7 from the control plane while Attempt 1 is still running on it, and the scheduler launches Attempt 2 on replacement nodes. Without protection, split brain occurs: Attempt 1 and Attempt 2 run simultaneously and overwrite each other's checkpoints! We prevent this with two independent shields:
Attempt 1 starts on Nodes 1..8 ---> issued fencing_token = 101, cluster-local lease = 60 s | | Node 7 loses link to Cluster Agent -> cannot renew 60 s lease -> Node Agent self-kills containers! | (Notice: lease is renewed with the LOCAL Cluster Agent, NOT global Postgres, so a global | control-plane outage never expires leases or kills healthy jobs!) v Scheduler waits > 60 s lease expiry, then launches Attempt 2 ---> issued fencing_token = 102 | '--> Even if a zombie process from Attempt 1 tries to update latest.json with token 101, the Checkpoint Store rejects 101 < 102 via atomic Compare-And-Set!Retry rules by failure class.
Failure Class Examples Platform Action Counts Against User? -------------- ---------------------------------------- ----------------------------------- -------------------- infra Node crash, ECC/XID GPU fault, NCCL hang Auto-retry from latest checkpoint No (pages ops after 5 registry outage, lost cloud VM attempts w/ 0 new steps) preempted Borrowed quota reclaim, cloud spot notice Auto-retry; preserves queue front No user Python exception, CUDA OOM, bad args Retry up to max_user_failures w/ Yes (aborts early if backoff (1m, 5m, 25m) same step crashes 2x) timeout / cap max_runtime or max_cost_usd reached Graceful checkpoint, then FAILED -Notice why we cap consecutive infra attempts with zero step progress (5) rather than total infra retries: our earlier math showed a healthy two-week 128-node job averages ~10 hardware interruptions, so a naive lifetime cap of 10 retries would kill ~42% of healthy runs right before completion!
Cloud API resilience and orphan cleanup. Before calling
RunInstances, the provisioner writes aprovision_requestsrow with a UUIDrequest_tokenpassed as the cloud provider's idempotency token (ClientTokenon AWS,requestIdon GCP) and tags every VM withjob_idandattempt_id.429/5xxcloud errors trigger exponential backoff and a regional circuit breaker (temporarily excluding a failing cloud region from placement for 5 minutes). Every 60 seconds, the reconciler diffs cloud provider VM lists against activeallocationsin Postgres; any VM with no live allocation for > 10 minutes is terminated and alerted, guaranteeing zero$28,800weekend leaks.Security, scaling, and observability
Defense-in-depth multi-tenant security. - Identity & scoped short-lived credentials: engineers authenticate via OIDC SSO; RBAC (Role-Based Access Control) enforces
viewer,submitter, andadminroles per project. Dataset permissions are verified at submission and re-verified at container start (in case access was revoked while queued). Each attempt receives short-lived (1-hour auto-rotated) workload credentials—via Vault on-prem or cloud Workload Identity—scoped strictly to read its declaredinputsand write its ownoutputsprefix. Secrets are never baked into specs or images. - Compute, storage & network isolation: multi-node jobs always receive exclusive whole nodes, and between tenants the node agent zeroes local NVMe scratch disks and runsnvidia-smi --gpu-reset. Hardware slicing via MIG (Multi-Instance GPU)—partitioning one H100 into isolated smaller GPU slices—is restricted to 1-GPU dev jobs within the same project, and untrusted workloads use micro-VM runtimes (Kata Containers). Network policies block all pod-to-pod traffic outside a job's own gang and restrict egress to storage/registry endpoints. Data is encrypted in transit (mTLS) and at rest using per-project keys in a KMS (Key Management Service).Scaling and operational visibility. - Scaling metadata & scheduling:
job_events(~1M rows/day) is partitioned monthly and archived to object storage after 90 days. Evaluating 10,000 queued jobs across 6 clusters is 60,000 fast in-memory checks (< 100 ms in Go/Rust), triggered incrementally on state changes and every 5 seconds; if pending jobs ever grow 10×, we shard scheduler loops cleanly bygpu_typesince H100 and A100 queues never share hardware. - User & operator dashboards: users see live per-rank logs, GPU utilization/VRAM/step-time charts, cost accrued, and queue wait reasons. Operators track SLOs (99.9% API availability, < 5 min start time for jobs within guaranteed on-prem quota, < 2 min crash detection-to-requeue) alongside fleet health metrics:Operator Metric What It Catches Early ------------------------------------------ ------------------------------------------------------- Queue wait p50 / p95 within guaranteed cap Broken fairness weights or cluster fragmentation Allocated GPUs with SM activity < 10% Jobs bottlenecked on dataloader CPU/I/O wasting GPUs Largest schedulable gang vs total free GPUs Severe node fragmentation blocking multi-node gangs Predicted vs actual queue wait error Stale runtime estimates causing bad cloud burst choices Node infra failure rate (XID / NCCL hangs) "Lemon" nodes killing multiple jobs -> auto-cordon Orphaned cloud VMs caught by reconciler Provisioner bugs (target = 0; any hit pages on-call)Before rolling out quota weight or backfill rule changes to production, operators replay the past 7 days of real job traces through the scheduler simulator offline to verify wait-time and cloud-spend impact.
Intuition & how it works
Think of a hybrid-cloud GPU allocation service like running a logistics company that owns a fixed fleet of freight trains (on-prem GPU clusters) and can also rent expensive express trains from external railways (public cloud GPUs) during rush periods. Unlike small parcel couriers, a distributed ML job is an 8-car train that must depart with all 8 cars coupled on the exact same high-speed track at the exact same moment—this all-or-nothing rule is called gang scheduling. On top of that, loading 100 TB of cargo (training datasets) from the home warehouse to an external railway takes nearly two hours, and on a two-week cross-country trip a wheel bearing will inevitably fail every day or two, so the train must save progress markers (checkpoints) at stations along the way rather than restarting from mile zero.
A naive design—putting all jobs into a single first-in, first-out queue and renting cloud GPUs whenever the total count of free on-prem GPUs drops below a job's request—fails in three painful ways. First, seeing "64 free GPUs" scattered 1-per-machine across 64 machines cannot launch an 8-machine gang that needs 8 GPUs per machine on one fast network switch. Second, renting 64 cloud GPUs before copying a 100 TB dataset burns nearly $700 while expensive GPUs sit completely idle waiting on network I/O. Third, without checkpoints and split-brain protection, a single dead machine or network hiccup on day 10 of a 1,024-GPU run either wipes out 240,000 GPU-hours of work or lets two attempts overwrite each other's saved weights.
Walk through our sample 3-job timeline to see how all pieces fit together:
Job A(low-urgency 64-H100vision-modelssweep) arrives whenfoundation-pretrainhas idle GPUs.vision-modelsalready uses its 640 guaranteed H100s, so the global scheduler letsJob Aborrow 64 idle H100s on-prem, requiringJob Ato save checkpoints hourly.Job B(vit-xl-run-09, urgent 64-H100 launch run, 12 h runtime, 6 TB dataset on-prem,value_of_time = $1,000/h) arrives when on-prem now has a 6-hour wait. The scheduler scores on-prem ($1,152compute +$18,000time cost =$19,152) against cloud on-demand ($4,658compute/egress +$12,400time cost =$17,058) and picks the cloud. Crucially,Job BstaysQUEUED (staging_data)for ~9 minutes while its 6 TB dataset copies to the cloud bucket before any cloud VMs are booted, then launches all 8 cloud nodes together once all 8 are healthy.Job C(foundation-pretrainowner reclaiming its guaranteed H100s) arrives on-prem. BecauseJob Ais running on borrowed quota, the scheduler selectsJob Aas the victim with the least work lost, sendsSIGTERM, waits 120 seconds whileJob Aflushes an asynchronous checkpoint, re-queuesJob Aat the front of the line, and hands those 8 whole nodes cleanly toJob C.
Key trade-offs
- Two-level scheduling vs. a single monolithic scheduler. Having one global scheduler pick the cluster (owning quotas, hybrid cost scoring, and dataset locality) while each cluster's local scheduler picks the physical nodes keeps high-frequency node/GPU state inside each cluster and lets on-prem Slurm/Kubernetes and cloud clusters share one control plane. The trade-off is that the global scheduler reads a 5-second-old capacity snapshot; publishing
largest_schedulable_gangper cluster and allowing a local scheduler to hand back an unschedulable job prevents stale-snapshot deadlocks. - Explicit
cost + value_of_time × completionscoring vs. static burst rules. A rule like "burst to cloud if wait > 4 hours" treats a cheap 1-GPU sweep and a blocking 64-GPU launch job identically. Pricing time explicitly per project adapts automatically to job size, egress fees, and dataset staging latency, at the cost of maintaining a queue-wait simulator whose prediction error must be monitored. - Guaranteed quotas with borrowing vs. hard static partitions. Letting teams borrow idle GPUs raises cluster utilization toward 90%+, at the price of preempting borrowed jobs when the quota owner returns. That trade-off works cleanly only because guaranteed GPUs are never preempted across projects, preemption sends a graceful
SIGTERMwindow, and jobs resume automatically from checkpoints. - Reservation + backfill vs. strict FIFO. Reserving a future start timestamp for a large waiting gang and backfilling short jobs onto idle nodes eliminates head-of-line blocking (where hundreds of GPUs sit idle waiting for one giant gang to assemble), in exchange for requiring every user to declare an enforced
max_runtime. - Stage datasets before provisioning vs. streaming over the WAN. Copying large datasets bucket-to-bucket while the job is still
QUEUEDadds minutes or hours before container start, but guarantees fast local training I/O and zero idle GPU rental during data transfer. Direct WAN streaming is viable only for small datasets (< 100 GB). - Cluster-local leases + fencing tokens vs. control-plane heartbeats. Renewing allocation leases (time-bounded ownership locks) against the cluster-local agent ensures a global PostgreSQL outage never kills running training jobs, while monotonic fencing tokens (increasing attempt numbers verified via compare-and-set on checkpoint writes) guarantee an isolated zombie node can never overwrite a newer attempt's checkpoint.
Common mistakes
- Assuming public cloud GPU capacity is infinite and instant. Requesting 8 or 64 H100 nodes on-demand frequently fails with
InsufficientInstanceCapacityor returns only 5 of 8 nodes; without a bounded partial-hold timeout (e.g., 15 minutes) and region fallback, partial nodes sit idle burning$48/heach forever. - Scheduling multi-node jobs one node at a time or across sites. Allocating nodes incrementally lets two 8-node jobs grab 4 nodes each and deadlock forever, and splitting one training gang across on-prem and cloud turns microsecond InfiniBand gradient syncs into wide-area network bottlenecks.
- Looking only at total
free_gpusinstead oflargest_schedulable_gang. Sixty-four free GPUs scattered 1-per-node across 64 fragmented machines cannot run an 8-node × 8-GPU gang. - Allocating cloud GPUs first and copying multi-terabyte datasets second. Leaving 64 cloud GPUs idle during a 2-hour 100 TB transfer wastes over
$750per job before step 1 even starts. - Treating hardware crashes and user bugs identically—or setting a fixed lifetime infra retry cap. Retrying a deterministic Python syntax error wastes GPUs, while capping total infra retries at 10 kills ~42% of healthy two-week 1,024-GPU runs that naturally suffer ~10 node failures; cap consecutive attempts with zero checkpoint progress instead.
- Calling cloud VM APIs without idempotency tokens or a background reconciler. A single network timeout during
RunInstanceswithout aClientTokenplus periodic orphan sweeping silently leaks$48/hGPU instances. - Baking long-lived cloud keys into containers or using mutable
:latestimage tags. Credentials must be short-lived and scoped per attempt to the job's declared buckets, and images must be pinned bysha256digest so retries run identical code.
Follow-up questions
- How would your scheduler support elastic distributed training so losing a single worker node does not force a full-gang restart? Allow jobs using elastic frameworks (such as
torchrun --nnodes=6:8) to specifymin_nodesandmax_nodesalongside areplica_group_size(for instance, 2 nodes per model replica when tensor/pipeline parallelism spans 2 nodes). When one node dies, the local scheduler first checks a small pool of warm spare nodes on the same fabric; if none is free, the surviving workers rendezvous at6nodes (dropping one whole 2-node data-parallel replica), reload the latest checkpoint, and adjust gradient accumulation steps so the mathematical global batch size stays unchanged. When a replacement pair of nodes frees up later, the job scales back from 6 to 8 nodes at the next checkpoint boundary. - How should the platform handle a strict-deadline production training job when on-premises clusters are full and cloud regions lack spare GPUs? Admission first runs a feasibility check (
now + stage_time + runtime <= deadline) so impossible deadlines fail fast with a clear earliest-completion estimate instead of silently missing the deadline in the queue. If feasible, a dedicated, tightly auditedcriticalpriority class (capped at a small org-wide quota, e.g., 512 GPUs) can gracefully preempt on-prem jobs in strict order: borrowed-quota jobs first, thenlow, thennormal, picking victims with the smallestgpus × time_since_checkpointon a single fabric. For planned recurring deadlines (like weekly production model refreshes), teams book cloud capacity blocks in advance rather than relying on emergency preemption. - When on-premises GPUs become idle mid-run, under what conditions would you repatriate a running cloud job back to the datacenter? Only at a checkpoint boundary, and only when the net savings clearly exceed migration overhead and those freed on-prem GPUs would otherwise sit completely idle (if another queued job is waiting on-prem, repatriating the cloud job just forces the queued job to wait or burst instead). For a 64-H100 job with 8 hours remaining, staying in the cloud costs
64 × 8 × ($6.00 - $1.50) = $2,304extra, whereas migrating costs ~$50 in 1 TB checkpoint egress plus ~15 minutes of restart overlap (~$96), netting over$2,100saved. When profitable, the scheduler reserves the on-prem gang first, signals the cloud attempt to flush a checkpoint, copies that checkpoint on-prem, launches the new attempt with a higher fencing token, and tears down the cloud VMs only after the on-prem attempt is running.
Follow-up questions
- How would your scheduler support elastic distributed training so losing a single worker node does not force a full-gang restart?
- How should the platform handle a strict-deadline production training job when on-premises clusters are full and cloud regions lack spare GPUs?
- When on-premises GPUs become idle mid-run, under what conditions would you repatriate a running cloud job back to the datacenter?
Similar questions
- Fix Priority Preemption in GPU Leasing
- Safe Transition Path to Disarm State
- Lower Flat Programs to Triad IR
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform