Multi-Cloud GPU Scheduler for Machine Learning Workloads
System DesignModel answerLast updated
Build a resource manager that schedules ML training jobs across on-premises and public cloud GPU clusters with fairness, cost optimization, and reliability.
Problem Statement
You need to architect a platform that manages GPU compute resources for machine learning training across both private datacenters and public cloud providers. The system must intelligently allocate resources, handle long-running workloads, and balance cost against availability.
What the System Must Do
Resource Management Across Environments
- Decide whether to place each job in your own datacenter or rent cloud GPUs
- Consider availability, cost, data location requirements, and user preferences when choosing
Job Submission Interface
- Accept training workloads with their container images or code repositories
- Understand resource requests: GPU model, quantity, CPU, memory
- Support optional constraints like geographic restrictions, budget limits, urgency level
Workload Lifecycle
- Track jobs through their lifecycle: waiting, executing, finished, failed, stopped
- Surface progress through logs and metrics
- Implement retry logic for transient failures
What to Consider
Multi-Tenancy: How do you share limited GPUs fairly across many teams while preventing one team from monopolizing resources?
Fault Tolerance: Training jobs run for hours or days. What happens when a machine dies or a cloud API becomes unavailable?
Data and Code Security: How do you isolate workloads? How do you handle authentication and prevent teams from accessing each other's data?
Scale: The system serves hundreds of teams submitting dozens of jobs per minute with thousands of jobs in various states.
What to Produce
- Component architecture showing how pieces interact
- API contracts for submitting, monitoring, and canceling work
- Scheduling algorithm that decides placement and order
- Storage strategy for code, training data, and artifacts
- Approach to monitoring, debugging, and operating the system
Make explicit assumptions about scale, workload characteristics, and SLOs. Discuss trade-offs in your design choices.
Hints
Hint 1
Start by clarifying scale: how many GPUs, how many teams, typical job sizes, and what availability target you're designing for.
Hint 2
The scheduling problem has two levels: choosing which cluster (on-prem vs cloud), then allocating specific machines within that cluster.
Hint 3
Multi-GPU jobs need all their resources simultaneously—partial allocation creates deadlock. Think about atomic reservations.
Hint 4
Consider the cost model: owned hardware has fixed costs while cloud charges by the hour. How does this affect placement decisions?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Multi-Cloud GPU Scheduler
1. Scope and Scale Assumptions
I'll establish concrete parameters to ground the design:
Capacity:
- Private datacenter: 1,500 GPUs (mix of A100 and H100) across two facilities
- Cloud capacity: elastic up to 4,000 GPUs across AWS and GCP, constrained by quotas
- Target: 300 teams, 3,000 active users, 8,000 concurrent jobs (including queued)
Workload Profile:
- Small jobs: 1-8 GPUs for minutes to hours
- Large jobs: 64-256 GPUs for days or weeks
- Submission rate: 40 jobs/minute at peak
- Multi-node jobs require synchronized startup across all workers
Availability and Cost:
- Control plane: 99.9% uptime (jobs continue running during control plane degradation)
- Datacenter GPUs cost ~$0 marginal; cloud costs $2-4/GPU-hour
- Prefer datacenter placement; burst to cloud when wait times exceed 20 minutes or users opt in
Constraints:
- Some datasets cannot leave the datacenter due to compliance
- Each team has quota limits and cloud spending budgets
Out of Scope: automated hyperparameter tuning, inference serving, interactive notebooks
2. API Design
POST /v1/jobs
{
"name": "finetune-llama-7b",
"container": "registry.company.com/ml/trainer@sha256:abc...",
"entrypoint": ["python", "train.py"],
"code": { "type": "git", "repo": "[email protected]:...", "commit": "a1b2c3" },
"datasets": [
{ "source": "s3://data/imagenet", "mount": "/data", "readonly": true }
],
"compute": {
"gpu_model": "A100-40GB",
"gpus_per_node": 8,
"node_count": 2,
"vcpus": 64,
"memory_gb": 256
},
"placement": {
"prefer": "datacenter", // or "cloud" or "any"
"regions": ["us-east", "us-west"],
"compliance": "datacenter-only"
},
"priority": "normal", // low/normal/high
"cost_limit_usd": 500,
"allow_preemption": false,
"retry_policy": { "max_attempts": 3, "on_failures": ["node_crash", "oom"] },
"checkpoint_path": "s3://checkpoints/job-123/"
}
Returns: 202 { "job_id": "...", "state": "PENDING" }
GET /v1/jobs/{job_id}
Returns: job details, current state, placement info, cost-to-date, timestamps
GET /v1/jobs?team_id=X&state=RUNNING&limit=50&cursor=...
Returns: paginated job list
POST /v1/jobs/{job_id}/cancel
Returns: 202 (asynchronous cancellation)
GET /v1/jobs/{job_id}/logs?node=0&follow=true
Returns: streaming logs
GET /v1/jobs/{job_id}/metrics
Returns: GPU utilization, throughput, loss curves
Key Design Choices:
- Immutable container references (digest, not tag) ensure retry consistency
- Async semantics (202 responses) allow the system to queue decisions
- Idempotency headers prevent duplicate submissions from client retries
- Placement preferences guide but don't mandate scheduling
3. Architecture
┌─────────────┐
│ Clients │
└──────┬──────┘
│
▼
┌─────────────────────────────────────┐
│ API Gateway (Auth, Rate Limiting) │
└──────────────┬──────────────────────┘
│
▼
┌───────────────────────────────────────┐ ┌──────────────┐
│ Job Management Service │─────▶│ PostgreSQL │
│ (validation, quota check, persistence)│ │ (jobs, quota)│
└───────────────┬───────────────────────┘ └──────────────┘
│ publishes events
▼
┌──────────────┐
│ Event Queue │ (Kafka)
└───────┬──────┘
│
▼
┌────────────────────────────────────────┐
│ Global Scheduling Service │
│ (placement decisions, fairness logic) │
│ (leader-elected, stateless) │
└────┬──────────────────────────┬────────┘
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ Datacenter Agent│ │ Cloud Provisioner│
│ (local scheduler)│ │ + Cluster Agent │
└────────┬────────┘ └─────────┬─────────┘
│ │
┌────┴─────┐ ┌──────┴──────┐
│ GPU Node │ │ Cloud Pods │
│ Agents │ │ (K8s/VMs) │
└──────────┘ └─────────────┘
Components:
- Job Management Service: validates requests, enforces admission quotas, persists jobs, emits state-change events via transactional outbox
- Global Scheduler: consumes new job events, scores placement options, assigns jobs to clusters without knowing node-level topology
- Cluster Agents: run in each environment (datacenter and cloud), perform local bin-packing, report capacity snapshots, reconcile desired vs actual state
- Cloud Provisioner: wraps provider APIs, manages node pools, handles rate limits and retries
- State Reconciler: processes status updates from agents, advances job state machines with optimistic locking
4. Data Model
Jobs Table:
id, team_id, user_id, spec_json, priority, state, version, created_at, updated_at- State: PENDING → SCHEDULING → RUNNING → COMPLETED/FAILED/CANCELED
- Version field enables optimistic concurrency
Job Attempts Table:
job_id, attempt_number, cluster_id, node_ids[], state, started_at, finished_at, exit_code, error_message- Retries create new attempts, preserving audit history
Cluster Inventory:
cluster_id, environment_type, region, gpu_types[], available_count, cost_per_gpu_hour, health_status, last_heartbeat
Allocations Table:
allocation_id, job_id, attempt_number, node_id, gpu_slots[], created_at- Unique constraint on (node_id, gpu_slot) prevents double-booking
Team Quotas:
team_id, gpu_type, guaranteed_slots, burst_limit, current_usage, cloud_budget_remaining
Storage: PostgreSQL for transactional consistency (or CockroachDB for geo-distribution). Object storage (S3) for artifacts. Prometheus for metrics. Elasticsearch for logs.
5. Scheduling Algorithm
Step 1: Admission Control
- Check team quota: block if usage exceeds burst limit
- Below guaranteed quota: always admit
- Above guarantee but within burst: admit but mark as preemptible
Step 2: Priority Queue
- Order pending jobs by: priority class, then fair-share ratio (teams using less than their share go first), then submission age
- Prevents starvation through aging
Step 3: Placement Scoring For each eligible cluster, compute:
score = (capacity_match * 0.4) + (data_locality * 0.3)
- (hourly_cost * 0.2) - (expected_wait_minutes * 0.1)
- Datacenter gets cost advantage (marginal cost ≈ 0)
- Cloud considered only if: wait > threshold OR user requested OR datacenter insufficient
- Respect hard constraints (compliance, regions)
Step 4: Gang Scheduling
- Multi-node jobs need all GPUs available simultaneously
- Reserve all slots atomically in one database transaction or wait
- Without this, partial allocations cause deadlock
Step 5: Backfilling
- Large job reservations may wait for resources
- Small jobs with known runtime can use reserved slots if they finish before the large job needs them
- Maximizes utilization without starving large workloads
Step 6: Preemption
- Higher priority or in-quota jobs can evict preemptible workloads
- Send graceful termination signal (60s grace period for checkpointing)
- Requeue preempted jobs without counting against retry budget
6. Data and Code Handling
Container Images:
- Store in private registry with namespace isolation per team
- Reference by digest (sha256) to ensure reproducibility
- Deploy pull-through caches in each cluster to reduce registry load
Training Data:
- Large datasets live in object storage (S3-compatible on-prem, native cloud buckets)
- Pre-stage datasets in target region before job starts (or accept longer startup)
- Use read-only mounts to prevent accidental corruption
Checkpoints and Outputs:
- Jobs write checkpoints to persistent storage on a schedule
- On failure/preemption, retry resumes from last checkpoint
- Final artifacts saved to user-specified output path
7. Reliability Patterns
Node Failures: agent heartbeats detect dead nodes within 30s; jobs automatically retry on new nodes
Network Partitions: agents use exponential backoff and reconcile state when connectivity returns; running jobs continue executing
Cloud API Failures: provisioner implements retries with jitter, circuit breakers, and fallback to alternative regions
Control Plane Outage: agents cache recent decisions and continue managing running jobs autonomously; new submissions queue until recovery
Data Consistency: use optimistic locking (version field) to prevent concurrent state updates; allocation uses unique constraints to prevent double-booking
8. Operational Concerns
Observability:
- Metrics: queue depth per priority, utilization per cluster, cost burn rate, P95 wait time
- Distributed tracing across components
- Alert on: quota exhaustion, abnormal failure rate, cloud spend rate
Common Pitfalls:
- Fragmentation: small jobs scatter, leaving unusable gaps. Mitigation: bin-packing with topology awareness
- Starvation: large jobs wait forever. Mitigation: priority aging and reserved capacity windows
- Cascading failures: cloud provider outage takes down scheduler. Mitigation: graceful degradation, multi-cloud
- Cost runaway: jobs run longer than estimated. Mitigation: budget alerts, automatic termination at cost limit
Security:
- Network isolation between team workloads (VPC per team or network policies)
- Image scanning before execution
- IAM roles scoped to team resources
- Audit logs for all job submissions and data access
This architecture balances cost efficiency (prioritize owned hardware), fairness (quota and priority), and reliability (retries, preemption, graceful degradation) while scaling to thousands of concurrent workloads across heterogeneous infrastructure.