Build an Async Text-to-Video Service on a Shared GPU Cluster
System DesignModel answerLast updated
Design an asynchronous text/image-to-video platform: job lifecycle, moderation, GPU scheduling, checkpoint-based recovery, and autoscaling for a mixed H100/A100 fleet.
Problem
You are asked to design a backend for an asynchronous video generation product. Users send a text prompt (optionally with a reference image) and receive a rendered video clip some minutes later. The underlying diffusion model is very heavy: one generation typically occupies a full 8-GPU node for several minutes.
Functional requirements
- Submit and track: a request carries a prompt, an optional image, clip duration, resolution, and a model version. Clients must be able to poll for status, subscribe to a progress stream, or register a webhook.
- Two-stage moderation: inputs (text and image) are screened before any GPU time is spent, and the rendered frames are screened again before the result is released.
- Job control: users can cancel at any time. Transient infrastructure failures are retried a bounded number of times. Publishing the finished artifact to object storage must be idempotent.
- Versioning: several model checkpoints and inference runtime versions must run side by side.
Scale and non-functional targets
- 50,000 requests per day. The brief describes this as roughly 2-5 requests/s on average with bursts up to 15 requests/s.
- A typical generation takes about 3 minutes on one 8-GPU node.
- A heterogeneous fleet of 2,000-4,000 GPUs (for example H100 and A100-80GB).
- Hardware faults (out-of-memory errors, silent data corruption, host reboots) must never lose a user's job or leave a GPU stuck forever.
- GPU utilization above 80%, elastic scaling, and per-tenant rate and cost limits.
What your answer should cover
- Public API and a durable job state machine (for example
QUEUED,MODERATING,SCHEDULED,RUNNING,VALIDATING,SUCCEEDED,FAILED,CANCELLED). - Overall architecture, separating control plane, scheduler, and compute/data plane.
- Scheduling and fleet management: placement that accounts for GPU memory and where model weights are already loaded, lease-based heartbeats, and draining nodes.
- Mid-generation checkpointing and how you limit wasted compute when a worker disappears.
- Autoscaling and cost control, given slow GPU provisioning, spot/preemptible capacity, and per-user concurrency quotas.
State your assumptions and sanity-check the numbers given above.
Hints
Hint 1
Convert the traffic numbers into GPU-hours and into a maximum sustainable jobs-per-second for the fleet, then compare with the stated peak. What does that imply about the queue and about what the API promises users?
Hint 2
Think of every job as a row with a version and a fencing token (lease epoch). Which writes (state changes, checkpoint commits, artifact commits) must be rejected if they come from a worker whose lease has expired?
Hint 3
Diffusion sampling is iterative and the intermediate state (latents, step index, RNG state) is tiny compared with the model weights. Use that to decide what to checkpoint, how often, and why scheduling should prefer nodes that already hold the right weights.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sanity-check the numbers first
- Average arrival rate: 50,000 / 86,400 s is about 0.6 jobs/s, not 2-5/s. I would flag the mismatch and ask which is intended. The design below works either way.
- Steady GPU demand: 50,000 jobs x 3 min x 8 GPUs = 1.2M GPU-minutes, about 20,000 GPU-hours/day. That is roughly 830 GPUs busy around the clock, or about 1,050 provisioned for 80% utilization.
- Fleet throughput ceiling: 4,000 GPUs = 500 nodes. 500 nodes / 180 s is about 2.8 jobs/s.
- Burst demand: 15 jobs/s x 180 s x 8 GPUs would need about 21,600 GPUs at once. The fleet cannot do that.
Consequence: bursts cannot be served immediately. The system needs a durable queue, admission control, priority tiers, and honest ETAs. Average load fits comfortably in a fraction of the fleet, so the real problems are burst absorption and efficiency, not raw capacity.
2. API
POST /v1/videos {prompt, image_ref?, duration_s, resolution,
model_version, webhook_url?, idempotency_key}
-> 202 {job_id, status, eta}
GET /v1/videos/{id} -> {status, progress, attempt, artifact_url?, error?}
GET /v1/videos/{id}/events -> server-sent events for transitions and progress
POST /v1/videos/{id}/cancel -> 202
The idempotency key is scoped per tenant, so a client retry returns the existing job rather than creating a second one (and a second bill).
3. Durable state machine
Store jobs in a transactional database (Postgres or similar). Each transition is a compare-and-set on (state, version).
QUEUED -> MODERATING -> SCHEDULED -> RUNNING -> VALIDATING -> SUCCEEDED
- Any non-terminal state can go to
CANCELLEDorFAILED. RUNNINGorSCHEDULEDcan go back toSCHEDULEDon lease expiry or a transient fault, ifattempt < max_attempts.
Each row holds attempt, lease_epoch, checkpoint_uri, model_version, runtime_version, tenant_id, and cost_estimate. Every transition is also appended to an event log (Kafka or similar). Webhooks and SSE are consumers of that log, so notification delivery never blocks the state change.
4. Architecture
- Control plane (stateless): gateway, auth, quota checks, job store. It validates, persists, enqueues, and returns 202. Nothing slow runs on request threads.
- Moderation workers: pre-check text and image with small classifiers on CPUs or small GPUs in a separate pool. Post-check samples frames during
VALIDATING. - Scheduler: priority queues partitioned by model version, tier, and tenant; a placement engine; a lease manager.
- Compute plane: a node agent on each 8-GPU host manages the runtime container, a local NVMe weight cache, heartbeats, checkpoint upload, and health probes.
- Data plane: object storage for weights, checkpoints, and outputs; CDN for delivery; metrics for utilization and cost.
5. Scheduling and fleet management
Placement = filter, then score.
- Filter: right GPU class and VRAM for the requested resolution and duration, compatible runtime version, node healthy and not draining.
- Score: weights already in VRAM beat weights on NVMe beat cold; keep NVLink domains intact; limit fragmentation; match spot versus on-demand to the job's priority.
Cold-loading 50-100 GB of weights can take minutes, a large share of a 3-minute job, so cache locality should dominate the score. Use sticky model pools: size the node count per model version to its queue demand and rebalance slowly to avoid reload thrash.
Leases and fencing. The scheduler grants (job_id, node_id, epoch, ttl ~30 s). The agent heartbeats about every 10 s with its step count. If heartbeats stop, the lease expires and the job returns to SCHEDULED with epoch + 1. Every worker write (checkpoint commit, artifact commit, state change) carries its epoch, and the store rejects stale epochs. This stops a partitioned "zombie" worker from publishing a duplicate result.
Progress watchdog. A heartbeat only proves the agent is alive. If the step counter does not advance for several expected step times (for example an NCCL hang), kill the job and quarantine the node.
Draining. Mark the node DRAINING (no new leases), let jobs finish or checkpoint and release them, then report idle so the node can be patched or reclaimed.
Silent data corruption. Run periodic golden-input tests (known seed must yield known latents within tolerance), check latents for NaN/Inf each step, and auto-quarantine nodes that fail.
6. Checkpointing and retries
Diffusion sampling is iterative (for example 50 denoising steps), and the resume state is small.
- Save: latent tensor (tens to hundreds of MB), sampler state and step index, RNG state and seed, model and runtime versions.
- Cadence: every K steps or about 30 s, plus once after denoising and before VAE decode, since decode is memory-hungry and failure-prone.
- Write path: synchronous to local NVMe, asynchronous to object storage under
ckpt/{job_id}/{epoch}/{step}, then commit the pointer with the fence token. - Resume: reschedule on a node with the same model and runtime versions, load the latest checkpoint. Loss is at most K steps rather than the full 3 minutes.
- Retry policy: maximum of about 3 attempts, only for classified transient faults (host loss, ECC errors, preemption). Deterministic failures (moderation block, OOM at a given config) are not retried; an OOM may fall back once to a larger GPU class.
Idempotent publish: upload to out/{job_id}/{epoch}/video.mp4, run post-moderation, then atomically CAS the job to SUCCEEDED with the artifact pointer, only if the epoch is still current. Losing writers leave orphan objects that a garbage collector removes. Cancellation is a state flip plus a signal to the agent, which stops at the next step boundary and frees the GPUs.
7. Autoscaling and cost control
- Signal: scale on queue depth and oldest-job age per model pool, converted to required nodes (
backlog x 180 s / target wait), not on CPU or GPU utilization alone. - Slow provisioning: GPU nodes take minutes to appear and load weights, so keep a warm buffer, scale up early and aggressively, scale down slowly with hysteresis, and pre-pull weights on new nodes.
- Spot capacity: run low-priority and free-tier jobs on spot nodes. Checkpointing makes preemption cheap, and the preemption notice triggers a final checkpoint and release. Keep paid-tier latency-sensitive work on on-demand or reserved nodes.
- Quotas: per-tenant concurrency caps, rate limits, and a budget check against
cost_estimateat admission. Use weighted fair queuing so one tenant cannot starve others, and reject or defer with a clear ETA when the queue is too deep.
8. Common mistakes
- Taking the stated peak at face value and trying to provision for it.
- Heartbeats without fencing, which leads to duplicate or corrupt artifacts.
- Treating liveness as progress, so hung collectives hold GPUs forever.
- Ignoring weight-load time in placement.
- Retrying deterministic failures, or restarting from step 0 instead of from a checkpoint.
- Running moderation or webhook delivery on the request path.