Design a GPU-Backed Video Generation Service with Fair Scheduling
System DesignModel answerLast updated
Design the backend for a text-to-video service where each job occupies exactly one GPU, covering task lifecycle, fair multi-user queueing, and cancellation at every stage.
Background
Your team is building the backend for a text-to-video product. A user submits a text prompt along with generation parameters (resolution, clip length, style), the system converts it into a long-running job that executes on a single GPU, and when the job finishes the user retrieves the resulting video.
One constraint simplifies scheduling considerably: a job always runs on exactly one GPU from start to finish. You never need to coordinate multiple GPUs for a single job.
GPU capacity is finite and shared. At peak times, more jobs are submitted than there are available GPUs, so jobs wait. Many users with different usage patterns compete for the same fleet.
What to Design
Part 1 — End-to-End Architecture and Job Lifecycle
Describe the full system: the client-facing API, the complete set of states a job can be in, how the queue hands jobs to GPU workers, and where everything is stored.
Your answer should address:
- A state machine covering all job states from submission through completion (or failure/cancellation), including which states a cancellation can legally interrupt.
- How the dispatch layer moves jobs from the queue to workers, and how a worker crash mid-job is detected and recovered from.
- Why task metadata and video output should live in separate stores, and how a finished video is delivered to the user.
Part 2 — Fair Sharing Across Users
Some users submit many more jobs than others. Jobs vary widely in how long they actually run on a GPU. Propose at least two distinct approaches to sharing the GPU fleet fairly across users, compare them honestly, and pick one.
Your answer should address:
- At least two fairness strategies with a concrete weakness for each.
- How each strategy handles jobs of variable cost, bursty submission patterns, and users who return after a long idle period.
- Where the scheduling policy lives and what happens to its state when the scheduler process restarts.
Two useful clarifying questions to consider: when only one user has pending jobs, should that user be allowed to use the whole fleet? Should a user who has been idle for a while receive a priority boost when they return?
Part 3 — Cancellation
A user can cancel a job while it is waiting in the queue, while it is in the middle of being dispatched to a GPU, or while it is actively running. Design how cancellation works in each case.
One specific proposal to evaluate: because each job holds at most one GPU and cancellations are rare compared with submissions, the cancel API could simply make a direct RPC or HTTP call to whichever worker is running the job. Assess when this is sufficient and where it breaks down.
Your answer should address:
- Correct cancellation behavior for each job state, including the race between a cancel request and a job that just finished.
- The direct-RPC approach weighed against at least one alternative, using the one-GPU-per-task constraint and low cancel volume to drive the comparison.
- Delivery guarantees: idempotent cancel handling, what happens when a worker is unreachable, and exactly when the GPU is returned to the available pool.
Constraints and Assumptions
- One job uses exactly one GPU for its entire duration.
- Demand routinely exceeds GPU capacity; queueing is expected, not exceptional.
- Cancellations are infrequent relative to submissions.
- No specific fleet size, latency target, or throughput number is given — state the assumptions your design depends on.
Hints
Hint 1
Start with the state machine before anything else. Every interesting design question — dispatch, cancellation, recovery — reduces to "what state is this job in and who owns it right now." Draw it out explicitly: QUEUED → DISPATCHING → RUNNING → DONE/CANCELLED/FAILED.
Hint 2
For fair queueing, think about what the unit of fairness actually is (user, org, subscription tier) and whether fairness means equal GPU-seconds consumed or equal jobs completed. Weighted fair queueing and token buckets answer different questions — be precise about which problem each one solves.
Hint 3
The direct-RPC cancellation proposal is reasonable under the given constraints but has one specific failure mode worth calling out: the worker address has to come from somewhere reliable, and if that record is stale (worker restarted, job just finished), the RPC either fails or hits the wrong target. Walk through what happens in each case and how you make cancel idempotent regardless.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Architecture and Job Lifecycle
Assumptions
A GPU fleet in the hundreds is a reasonable baseline. Jobs run anywhere from 30 seconds to several minutes. Users poll for status or receive a webhook; both are supported. Storage costs for video output are separated from compute costs because their scaling axes differ.
Client API
POST /jobs → { job_id, status: "queued" }
GET /jobs/{id} → { job_id, status, created_at, eta_seconds, video_url? }
DELETE /jobs/{id} → 204 (cancel request accepted)
Video retrieval is a pre-signed object store URL returned once status reaches done. Separating the video URL from the status endpoint means the metadata store never holds large blobs, and the object store (S3 or equivalent) handles bandwidth independently.
State Machine
QUEUED → DISPATCHING → RUNNING → DONE
↘ FAILED
↘ CANCELLED (from QUEUED or DISPATCHING or RUNNING)
- QUEUED: job is in the queue, waiting for a free GPU.
- DISPATCHING: the scheduler has popped the job from the queue and is in the process of assigning it to a specific worker. This is a brief but real state that cancellation must handle.
- RUNNING: the worker has acknowledged the job and is generating.
- DONE / FAILED / CANCELLED: terminal states. Once a job reaches any of these, further transitions are rejected.
The canonical state lives in a relational store (Postgres works well). It is the single source of truth; the queue and the workers defer to it on conflicts.
Dispatch and Worker Failure Recovery
The scheduler runs a polling loop (or reacts to queue events) and, when a GPU worker reports itself idle, pops the highest-priority job, writes status = DISPATCHING, worker_id = W, dispatched_at = now() to the DB, then pushes the job payload to that worker.
Worker crash detection: every RUNNING job has a heartbeat column updated by the worker every 15–30 seconds. A watchdog process queries for jobs where status = RUNNING AND last_heartbeat < now() - 2 minutes. Those jobs are reset to QUEUED and re-enqueued. The GPU is returned to the idle pool. This handles both worker crashes and network partitions.
If the scheduler crashes mid-dispatch, any job left in DISPATCHING state for more than a short timeout (say 60 seconds) is also returned to QUEUED by the same watchdog.
Storage Split
- Task metadata (state, user_id, prompt, settings, timestamps, worker assignment): relational DB, low volume, high query rate.
- Video output: object store. Workers write directly to object storage and record the resulting URL in the metadata DB on completion. This decouples video bandwidth from the API tier entirely.
Part 2 — Fair Queueing
Clarifications that shape the answer
Fairness is defined per user account by default, but the mechanism should be adjustable to apply per organization or subscription tier. When only one user has pending jobs, they may use the whole fleet — fairness applies only when there is actual competition. A returning user who has been idle should not be permanently penalized by accumulated virtual time (more on this below).
Option A: Weighted Fair Queuing (WFQ) via Virtual Time
Assign each user a virtual clock that advances by the job's estimated cost (GPU-seconds, derived from resolution × clip length) each time a job is dispatched. The scheduler always picks the job belonging to the user with the smallest virtual clock. Users with equal weight converge to equal GPU consumption over time.
Weakness: estimating job cost before it runs is noisy. Underestimates let one user unfairly dominate a window; overestimates penalize users on the next job. Also, a user idle for a long time accumulates a very small virtual clock, so when they return they can drain the queue before others get a turn.
Idle handling: cap the virtual clock at current_max - K * average_job_cost. This prevents a returning user from claiming an unlimited burst while still giving them a small advantage.
Option B: Token Bucket per User
Each user refills tokens at a fixed rate (tokens per second). Submitting a job costs tokens proportional to its estimated cost. If a user has insufficient tokens, their jobs wait. This naturally throttles heavy users without starving occasional users.
Weakness: token buckets limit burst throughput even when the fleet is otherwise idle, which wastes GPU capacity. It also requires choosing a refill rate and bucket depth per subscription tier, which adds operational complexity.
Recommended Choice: WFQ with idle capping
WFQ matches the stated goal (fair share of GPU-seconds consumed) more directly than token buckets, and it makes full use of idle capacity. The idle cap addresses the main edge case. Token buckets are better suited to rate-limiting API traffic, not allocating shared compute.
Scheduler state on restart
The virtual clock values are the only critical scheduler state. Write them to the metadata DB (a per-user row updated on each dispatch). On restart, the scheduler reads these values back and continues without losing fairness history.
Part 3 — Cancellation
State-by-state behavior
QUEUED: the simplest case. Mark the job CANCELLED in the DB, then remove it from the queue (or, more robustly, leave it in the queue and have the dispatcher check the DB before handing it to a worker — this avoids a distributed delete race).
DISPATCHING: this is the race condition. The cancel API marks CANCELLED in the DB. The dispatcher, which is about to hand the job to a worker, reads the DB one more time before sending — if CANCELLED, it skips dispatch and returns the GPU to the pool. If the dispatcher has already sent the work to the worker before the cancel is written, the cancellation falls through to the RUNNING case.
RUNNING: the job is executing on a known worker. The cancel must reach that worker.
DONE/FAILED/CANCELLED: no-op. Return success (cancellation is idempotent by design — any cancel request on a terminal state returns 200/204 without error).
Direct RPC vs. command channel
Direct RPC to the worker (the proposal to evaluate): the cancel API looks up worker_id from the DB and makes an HTTP or gRPC call directly to that worker telling it to stop. Given the one-GPU-per-task constraint, the worker address uniquely identifies the job in progress, so no disambiguation is needed. Given that cancellations are rare, the extra network hop and the need to maintain worker address records is manageable.
This is sufficient for a moderate-sized fleet where workers have stable addresses and the cancel volume is low. It's a reasonable starting point.
Where it breaks down: if the worker is unreachable (network partition, crash in progress), the RPC fails and the job is not stopped. The caller receives an error but the GPU keeps running. You need a fallback: write a cancel_requested flag to the DB, and have the worker poll that flag (or check it on each generation step). This also handles the case where the worker restarts and picks up the flag on recovery.
Alternative — command via the task metadata DB: instead of a direct RPC, the cancel API writes cancel_requested = true to the job row. The worker polls this flag every few seconds and self-terminates. This adds latency (seconds, not milliseconds) but is more robust to network topology changes, worker restarts, and fleet scaling. It also removes the requirement that the cancel API know worker addresses.
Recommended approach: combine both. The direct RPC gives fast cancellation in the common case (worker reachable, job running). The DB flag acts as a durable fallback. The worker checks the flag on startup and periodically during generation. Either path leads to the same outcome: the job is marked CANCELLED, the partial output is discarded, and the GPU is returned to the idle pool.
Delivery guarantees
- Idempotency: cancel requests use the job_id as the key. Cancelling an already-cancelled job is a no-op returning success.
- Unreachable worker: the DB flag ensures eventual cancellation when the worker recovers. The watchdog's heartbeat timeout will eventually reclaim the GPU if the worker never recovers.
- GPU return: the GPU is added back to the idle pool only after the worker confirms termination (via a callback or heartbeat stop). The scheduler must not assume the GPU is free based solely on the cancel request being accepted.
Common mistakes
- Forgetting the DISPATCHING state entirely, which creates a window where a cancelled job still starts running.
- Making cancel non-idempotent and returning a 404 or 409 on a job that already finished — this breaks client retry logic.
- Returning the GPU to the pool before the worker has actually stopped, which can cause two jobs to share one GPU briefly.