Design a GPU Job Scheduler for Text-to-Video Generation
System DesignModel answerLast updated
Design an asynchronous GPU scheduling service for single-GPU text-to-video jobs, featuring weighted fair queueing, fault tolerance, and lease-based worker management.
Architect the backend infrastructure and scheduling engine for an AI text-to-video generation platform. Users submit textual prompts to generate short video clips, with each request dispatched to a dedicated GPU within a compute cluster.
Key Constraints & Requirements
- Single-GPU Execution: Each generation job runs exclusively on one GPU; distributed multi-GPU training/inference is out of scope for a single task. Tasks cannot be preempted or checkpointed mid-generation.
- Fair Resource Allocation: Multiple tenants (free, pro, enterprise users) share the compute fleet. The system must implement fair queueing based on consumed GPU compute time rather than task count to prevent resource monopolization.
- Resilience & Fault Tolerance: System components (workers, individual GPUs, state stores, and the scheduler instance) can crash at any point. The platform must guarantee eventual completion or terminal failure reporting without leaking resources or executing duplicated side effects.
Discussion Areas
- System Architecture & Data Model: API endpoints, persistent job state management, worker execution flows, and output distribution.
- Fair Queueing & Scheduling Logic: Algorithms for weighted fair sharing, handling idle user credits, managing per-tenant concurrency limits, and admission control under heavy traffic load.
- Failure Modes & Edge Cases: Lease mechanisms, heartbeat strategies, handling poison-pill prompts, GPU hardware faults, split-brain mitigation, and scheduler recovery.
Hints
Hint 1
Base fairness on accumulated GPU execution time (e.g., Weighted Fair Queueing or Dominant Resource Fairness principles) rather than a simple round-robin or raw task count.
Hint 2
Decouple the durable job persistence layer (e.g., PostgreSQL/DynamoDB) from the fast in-memory scheduling queue (e.g., Redis/custom engine) to simplify state recovery.
Hint 3
Use short-lived, auto-renewing leases with fencing tokens so the system safely reassigns tasks when workers or GPUs crash.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Overview & Scale Estimation
Text-to-video inference is compute-intensive. Assume:
- Fleet Size: 1,000 GPUs (e.g., NVIDIA H100s).
- Execution Profile: Average generation time = 60 seconds per video (varies between 30s and 120s based on resolution/frames).
- Fleet Throughput: 1,000 GPUs / 60s = ~16.6 jobs/sec (or ~1.44M videos/day max capacity).
- Peak Request Rate: 50 submissions/sec (3x maximum steady-state fleet throughput during peak hours).
Because peak input rate exceeds maximum generation capacity, requests must queue asynchronously, and admission control must shed excessive load.
Part 1 — Architecture & Data Flow
[ Client ] ---> [ API Gateway / Web Tier ] ---> [ Job Store (DB) ]
| ^
v |
[ Scheduler Engine ] <--------------------+
|
(Lease / Assign)
v
[ GPU Worker Fleet ] ---> [ Object Storage (S3/GCS) ]
Core Components
- API Gateway / Web Tier: Auth, validation, rate limiting, and job submission.
- Job Store (Relational/Key-Value DB): The persistent source of truth holding job lifecycle states.
- Scheduler Engine: An in-memory, highly available service that maintains per-tenant queues and assigns jobs to idle workers.
- GPU Worker Fleet: Statelss worker nodes attached to dedicated GPUs that pull/lease jobs, run inference pipelines (e.g., Stable Video Diffusion), upload outputs, and renew heartbeats.
- Blob Store & CDN: Stores final MP4 artifacts served directly to users via pre-signed URLs.
Job Schema & Lifecycle
CREATE TABLE generation_jobs (
job_id UUID PRIMARY KEY,
user_id UUID NOT NULL,
tenant_tier VARCHAR(20) NOT NULL, -- 'free', 'pro', 'enterprise'
status VARCHAR(20) NOT NULL, -- 'QUEUED', 'RUNNING', 'COMPLETED', 'FAILED', 'CANCELLED'
prompt TEXT NOT NULL,
model_params JSONB NOT NULL,
output_url TEXT,
allocated_worker_id VARCHAR(64),
lease_token UUID,
lease_expires_at TIMESTAMP WITH TIME ZONE,
execution_duration_ms INT DEFAULT 0,
retry_count INT DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_user_status ON generation_jobs(user_id, status);
CREATE INDEX idx_status_lease ON generation_jobs(status, lease_expires_at);
End-to-End Execution Flow
- Submission: User calls
POST /v1/videos/generate. The Web Tier writes a job record (status='QUEUED') to the DB and pushes a lightweight notification event to the Scheduler Engine. - Scheduling: When a GPU worker becomes available, it sends a heartbeat/poll request (
POST /v1/workers/poll). The Scheduler selects the next job using the Fair Queueing algorithm and returns the job assignment with a 30-secondlease_token. - Execution: The worker updates the DB state to
RUNNINGvia a conditional CAS (Compare-And-Swap) write, downloads model weights (if not cached locally), and streams generation progress. - Heartbeat: Every 10 seconds, the worker sends a heartbeat to extend
lease_expires_at. - Completion: The worker writes the output file to Object Storage, marks the job
COMPLETEDin the DB, records total GPU duration, and notifies the user via Webhook/WebSocket.
Part 2 — Fair Queueing Strategy
Fairness cannot be defined by simple task count because a 120-second 4K generation consumes 4x the compute of a 30-second 720p task. We measure resource usage in GPU-seconds.
Weighted Virtual Time Fair Queueing (WFQ)
We adapt Virtual Clock / Weighted Fair Queueing for discrete batch jobs:
- Track Virtual Time ($V_u$): Each tenant $u$ maintains a virtual start time tracker ($V_u$).
- Cost Calculation: When job $j$ for user $u$ completes or is scheduled, we calculate its virtual cost:
$$\text{Virtual Cost} = \frac{\text{Estimated Execution Time}}{\text{Tier Weight } W_u}$$
- Tier Weights:
Free = 1,Pro = 4,Enterprise = 20.
- Tier Weights:
- Scheduling Priority:
- The Scheduler maintains a priority queue of active users ordered by their current Virtual Time ($V_u$).
- The user with the lowest $V_u$ gets their head-of-line job scheduled next.
- Upon scheduling job $j$, update $V_u \leftarrow \max(V_u, V_{\text{global}}) + \text{Virtual Cost}$.
Handling Edge Cases in Fairness
- Idle User Catch-Up (Unearned Credits): If an Enterprise user submits no jobs for a week, their $V_u$ remains small. If they suddenly submit 1,000 jobs, they would starve all other users.
- Fix: When an idle user submits a new job, set $V_u = \max(V_u, V_{\text{global}})$, resetting unearned starvation credits.
- Per-Tenant Concurrency Caps: Absolute hard caps prevent single tenants from filling all 1,000 GPUs simultaneously even if their tier weight is high (e.g., Free: max 2 parallel jobs; Pro: max 10; Enterprise: max 50).
- Admission Control & Queue Limits: If a tenant's queue exceeds 500 pending requests or global backpressure triggers, incoming
POST /v1/videos/generaterequests receive HTTP 429 (Too Many Requests).
Part 3 — Fault Tolerance & Resiliency
1. Worker & GPU Failures (Lease-Based Health Checks)
- Worker Loss: If a worker node crashes or loses network connectivity, its heartbeat stops.
- Detection & Recovery: A background sweeper process in the Scheduler scans for jobs where
status = 'RUNNING'ANDlease_expires_at < NOW(). - Fencing Tokens: Every lease renewal increments a monotonic counter (
lease_token). If a stalled worker revives and attempts to write completion, its stale token is rejected by the DB conditional update:UPDATE generation_jobs SET status = 'COMPLETED', output_url = :url WHERE job_id = :job_id AND lease_token = :current_token;
2. Poison-Pill Tasks & Bad Prompts
- Problem: Certain prompts or parameters cause CUDA Out-Of-Memory (OOM) errors or kernel panics, causing infinite re-execution loops.
- Handling:
- Limit retries per job (
MAX_RETRIES = 2). - Distinguish between transient infrastructure errors (node died $\rightarrow$ retry on another node) and fatal runtime errors (CUDA OOM $\rightarrow$ mark job
FAILEDimmediately without retry).
- Limit retries per job (
3. Scheduler Node Failures (State Recovery)
- The Scheduler Engine maintains active queues in memory for sub-millisecond scheduling latency.
- Replicas & Leader Election: Use a consensus protocol (e.g., Raft via etcd or Zookeeper) to elect an Active Leader Scheduler while standby instances remain passive.
- Rebuilding State: If the active scheduler crashes and a standby takes over, the new leader queries the DB for all jobs in
QUEUEDandRUNNINGstatus to reconstruct its in-memory virtual time priority queues within seconds.
Trade-Off Summary
| Architectural Decision | Chosen Approach | Alternative Considered | Trade-Off Rationale |
|---|---|---|---|
| Fairness Metric | GPU-seconds (WFQ) | Job Count Round-Robin | Simple job counting penalizes users running short jobs and rewards heavy compute hogs. |
| Queue Architecture | Hybrid (DB + In-Memory) | Pure Message Queue (RabbitMQ) | RabbitMQ/Kafka makes it difficult to dynamically re-order pending jobs based on changing virtual times and tier weights. |
| Worker Interaction | Worker-driven Polling + Leases | Central Push Execution | Polling simplifies NAT/firewall traversal across dynamic GPU cloud providers and ensures workers only take jobs when capacity is ready. |