Architecting a Scalable Async Text-to-Video Generation Platform
System DesignModel answerLast updated
Design a robust ML system to handle asynchronous, long-running text-to-video inference, featuring state machine orchestration, GPU worker fault tolerance, and multi-tier scheduling.
Design an asynchronous, distributed backend system for a text-to-video generation service (similar to OpenAI Sora or Runway Gen-2).
Users provide textual descriptions, along with parameters like video length, resolution, frame rate, seed, and optional input media (e.g., initialization images). Because video diffusion models require anywhere from 30 seconds to several minutes of intensive GPU compute per clip, traditional HTTP request-response patterns are unviable. The platform must be fundamentally asynchronous: API calls immediately yield a job handle, while background infrastructure handles scheduling, compute, and artifact delivery via polling or webhooks.
Your design should address:
- API & Orchestration: Endpoint schema, request validation, and an explicit job state machine.
- GPU Worker & Resource Scheduling: How to efficiently allocate heterogeneous/expensive GPU compute while balancing fairness across user tiers (Free, Paid, API/Enterprise).
- Fault Tolerance & Worker Life Cycle: Mechanistic handling of worker crashes, Out-Of-Memory (OOM) exceptions, network partitions, and spot instance preemptions without job duplication or silent hangs.
- Safety, Artifact Storage & Delivery: Multi-stage safety moderation (prompt checking and post-generation visual validation), metadata storage, object storage strategy, and content provenance (watermarking/C2PA).
- System Metrics & Operations: Monitoring queue latencies versus compute execution, rate-limiting, and cost control.
Focus deeply on state transitions, worker fault isolation, and GPU queue management.
Key Requirements & System Constraints
- Compute Dynamics: A standard 5-second 720p 24fps clip takes ~60 seconds of un-batched A100/H100 execution time. GPU utilization must be optimized, minimizing idle overhead.
- Failures are Expected: GPUs run near thermal and memory limits. CUDA OOMs, hardware fault drops, worker node host terminations, and driver crashes occur routinely.
- Strict Execution Semantics: Exactly-once delivery of video artifacts per submission handle. No double-billing or leaking of partial execution results.
- Multi-Tenant Fairness: High-paying API customers must not be starved by thousands of free-tier requests.
Hints
Hint 1
Treat GPU nodes as untrusted, highly volatile execution units. Maintain job state ownership in a transactional store, using heartbeats and leasing mechanisms to detect dead workers.
Hint 2
Decouple job admission (pre-flight validation, rate limits, storage of prompt) from model execution. Always validate inputs (safety check on text) BEFORE pushing jobs into expensive GPU queues.
Hint 3
Avoid storing state on GPU worker nodes. If a worker fails mid-generation, make sure partial frames in ephemeral worker disk do not corrupt object storage or lead to duplicate active executions.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Level System Architecture
The system is separated into three main planes: Control Plane (API, DB, Orchestrator), Compute Plane (GPU Worker Fleet, Queues), and Storage/Delivery Plane (Object Storage, CDN).
[ User / Client ]
│
▼
┌──────────────┐ ┌────────────────┐ ┌──────────────────┐
│ API Gateway │────>│ Safety Service │────>│ Postgres Metadata│
└──────┬───────┘ └────────────────┘ └────────┬─────────┘
│ │
▼ │ State & Leases
┌──────────────┐ │
│ Orchestrator │<────────────────────────────────────┘
└──────┬───────┘
│ Push Job
▼
┌────────────────────────────────────────────────────────┐
│ Priority Job Queues (Redis) │
│ [ High-Priority (Paid) ] [ Normal ] [ Low (Free) ] │
└───────────────────────────┬────────────────────────────┘
│ Pull Job
▼
┌──────────────────────────────────┐
│ GPU Worker Fleet │
│ (Worker 1) (Worker 2) ... │
└────────────────┬─────────────────┘
│ Push Artifacts
▼
┌──────────────────┐
│ S3 / Cloudfront │
└──────────────────┘
1. Job Lifecycle & State Machine
A text-to-video job moves through a deterministic set of states managed by the Control Plane.
[ PENDING ] ──> [ QUEUED ] ──> [ PROCESSING ] ──> [ POST_PROCESSING ] ──> [ COMPLETED ]
│ │ │ │
└───────────────┴──────────────┼─────────────────────┴────────────> [ FAILED ]
│ (Preemption / Crash)
└──> [ RETRYABLE_FAIL ] ──> [ QUEUED ]
State Transition Breakdown
PENDING: API Gateway receives the HTTP POST request, validates payload parameters (duration, resolution, seed), generates a uniquejob_id, checks user rate limits/quotas, and commits the initial record to PostgreSQL.QUEUED: The synchronous pre-generation safety filter (text prompt moderation) passes. The job is pushed to the priority queue corresponding to the user tier.PROCESSING: A worker acquires a lease on the job, atomic state updates move it toPROCESSING, and the execution model runs frame generation steps.POST_PROCESSING: Frame generation is complete. The system runs output safety checks (NSFW/violence vision filters), embeds C2PA metadata/invisible watermarks, and encodes raw frames to H.264/MP4.COMPLETED: Video uploaded to S3, signed URLs are generated, and a terminal success state is reached. User receives a webhook or reads output via polling.FAILED: Terminal error state reached due to unrecoverable errors (safety violation, max retries exceeded, bad inputs).RETRYABLE_FAIL: Non-terminal fault detected (OOM, hardware loss). State is reset, attempt count incremented, and job is re-enqueued.
2. API Design & Endpoints
Submit Video Generation Job
POST /v1/video/generations
// Request
{
"prompt": "A cinematic shot of a red panda running through a neon-lit cyberpunk city, 8k resolution",
"aspect_ratio": "16:9",
"duration_sec": 5,
"fps": 24,
"seed": 42,
"webhook_url": "https://api.example.com/hooks/video_done"
}
// Response (HTTP 202 Accepted)
{
"job_id": "job_984f-20ac-4b11-9a7c",
"status": "QUEUED",
"created_at": 1711900000,
"estimated_wait_time_sec": 45,
"poll_url": "https://api.example.com/v1/video/generations/job_984f-20ac-4b11-9a7c"
}
Poll Job Status
GET /v1/video/generations/job_984f-20ac-4b11-9a7c
// Response (HTTP 200 OK - Processing)
{
"job_id": "job_984f-20ac-4b11-9a7c",
"status": "PROCESSING",
"progress": 0.65, // 65% of diffusion steps done
"result": null
}
// Response (HTTP 200 OK - Completed)
{
"job_id": "job_984f-20ac-4b11-9a7c",
"status": "COMPLETED",
"progress": 1.0,
"result": {
"video_url": "https://cdn.example.com/outputs/job_984f-20ac-4b11-9a7c.mp4?signature=...",
"thumbnail_url": "https://cdn.example.com/outputs/job_984f-20ac-4b11-9a7c.jpg?signature=...",
"duration_sec": 5.0,
"seed_used": 42
}
}
3. GPU Worker Scheduling & Fleet Allocation
Video generation models (e.g., Spatial-Temporal Diffusion Transformers) require substantial VRAM (e.g., 80GB H100s).
+-----------------------------------------------------------------------+
| REDIS QUEUES |
| [Priority 0: Paid API] [Priority 1: Web Paid] [Priority 2: Free] |
+-----------------------------------------------------------------------+
│
┌────────────────┴────────────────┐
│ Weighted Fair Queue Scheduler │
└────────────────┬────────────────┘
│
┌─────────────────────────┼─────────────────────────┐
▼ ▼ ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Reserved Fleet │ │ Dynamic Fleet │ │ Spot Fleet │
│ (On-Demand H100) │ │ (Auto-scaled) │ │ (Preemptible) │
└──────────────────┘ └──────────────────┘ └──────────────────┘
Queue Priority & Fairness
- Multi-queue Architecture: We maintain separate queues based on SLA tiers (
priority_0_enterprise,priority_1_paid,priority_2_free). - Weighted Fair Dequeuing: Workers consume jobs using weighted round-robin polling (e.g., 70% Enterprise, 20% Standard Paid, 10% Free) to ensure tier SLAs while preventing free-tier starvation.
- Parametric Admission Control: High-compute requests (10-second 1080p clips vs 5-second 720p clips) consume proportional billing/token credits. Users with insufficient credits are rejected upfront at the API Gateway.
Fleet Composition Strategy
- On-Demand Reserve Fleet (60%): Guarantees baseline throughput for paid tier customers without cold-start/preemption risk.
- Spot/Preemptible Fleet (40%): Utilized for batch/free-tier execution. Provides up to ~70% cost reduction per GPU-hour.
- Warm Model Cache: Model weights are pre-loaded in worker host memory (RAM) and pinned in VRAM using persistent worker processes. Workers avoid loading 20GB+ checkpoint files per job, keeping startup overhead under 500ms.
4. Robust Worker Life Cycle & Fault Tolerance
Because workers operate near compute and memory capacity, hardware failures and OOMs must be handled cleanly.
WORKER ORCHESTRATOR / DB
│ │
│────── Heartbeat (Every 5s via Redis) ──────>│
│ │
│── [ CUDA OOM / Driver Crash / Preemption ] │
X │
│ (Lease expires after 15s)
│
▼
[ Sweeper Job Triggers ]
│
├── Check Attempt Count
├── Attempt < 3 ?
│ ├── Increments attempt
│ └── Re-enqueue job
└── Attempt >= 3 ?
└── Mark job FAILED
Lease & Heartbeat Model
- When a worker pulls a job, it executes a database transaction setting:
UPDATE jobs SET status = 'PROCESSING', worker_id = 'worker_node_88', lease_expires_at = NOW() + INTERVAL '15 seconds', attempt_count = attempt_count + 1 WHERE job_id = 'job_984f-20ac-4b11-9a7c' AND (status = 'QUEUED' OR lease_expires_at < NOW()); - While processing, the worker sends a heartbeat every 5 seconds, extending
lease_expires_atby 15 seconds. - If a worker dies (Host preemption, CUDA kernel crash, node power drop), its heartbeat stops.
- An Orchestrator Sweeper process periodically queries for expired leases (
lease_expires_at < NOW() AND status = 'PROCESSING'). - Expiry triggers a retry flow:
- If
attempt_count < MAX_RETRIES(e.g., 3), the job status is set back toQUEUED. - If
attempt_count >= MAX_RETRIES, it is marked asFAILEDwith error codeEXCEEDED_MAX_RETRIES.
- If
Handling OOMs vs Unrecoverable Crashes
- CUDA OOM Detection: Worker processes catch
torch.cuda.OutOfMemoryError. Instead of crashing the whole container, the worker flushes the VRAM cache (torch.cuda.empty_cache()), flags the job retry with a reduced batch or context constraint if applicable, or fails gracefully without taking down adjacent jobs. - Idempotency Guard & Single Winner Publish: Outputs are saved in S3 with key formatting
/artifacts/{job_id}/{attempt_id}/video.mp4. The DB state update fromPROCESSINGtoCOMPLETEDenforces single-winner execution:
UPDATE jobs
SET status = 'COMPLETED',
result_url = 'https://cdn.example.com/.../video.mp4'
WHERE job_id = 'job_984f-20ac-4b11-9a7c'
AND attempt_count = 1 -- Only accept the outcome from the valid active attempt
AND status = 'PROCESSING';
If a partitioned slow worker finishes execution late after its lease expired and another worker succeeded, the SQL WHERE condition fails, and the late worker discards its result.
5. Multi-Stage Safety & Content Moderation
Generating synthetic video presents significant abuse vectors (NSFW content, deepfakes, copyright violations).
[ User Input ]
│
▼
┌───────────────────────────┐
│ Stage 1: Text Moderation │ ──(Violates Policy)──> [ Return 400 Bad Request ]
└─────────────┬─────────────┘
│ (Pass)
▼
┌───────────────────────────┐
│ Stage 2: Model Inference │
└─────────────┬─────────────┘
│ (Raw Frames)
▼
┌───────────────────────────┐
│ Stage 3: Frame Moderation │ ──(Violates Policy)──> [ Fail Job / Black Frame ]
└─────────────┬─────────────┘
│ (Pass)
▼
┌───────────────────────────┐
│ Stage 4: Provenance Embed │ (Apply C2PA Metadata + Invisible Watermark)
└─────────────┬─────────────┘
│
▼
[ Upload S3 & Return Result ]
- Pre-flight Text Safety (Synchronous): Prompts are screened using a fast text classification model and blocklist rules before queuing. Violations abort the request immediately at the API boundary.
- Post-generation Visual Safety (Asynchronous): Generated video tensors are processed through a visual moderation model (checking subsampled keyframes for NSFW/violence criteria) before final H.264 encoding.
- Watermarking & Provenance:
- Visual spatial watermarks (e.g., logo overlay) or invisible steganographic signatures are injected into the frame tensor array.
- Standard C2PA metadata manifests are embedded into the container header to establish cryptographic proof of AI generation.
6. Operational Considerations & Metrics
Key Observability Metrics
- Queue Wait Latency ($T_{\text{wait}}$): Time spent in
QUEUEDstate. Primary driver for autoscaling decisions. - Compute Latency ($T_{\text{compute}}$): Execution time inside the worker. An unexplained increase indicates hardware degradation or memory swapping.
- GPU Utilization Efficiency: Tracking SM (Streaming Multiprocessor) active percentage vs memory copy idle time.
- Job Failure Rate by Taxonomy: Categorizing failures across
SYSTEM_OOM,PREEMPTION,SAFETY_VIOLATION, andHARDWARE_FAULT.
Scalability & Cost Calculation (Back-of-the-Envelope)
- Target Rate: 10 requests per second (RPS) continuous load.
- Compute Time: Average 60 seconds of GPU compute per 5-second video.
- Required Concurrent Executions: $10 \text{ jobs/sec} \times 60 \text{ seconds} = 600 \text{ active concurrent GPU tasks}$.
- Node Estimation: Assuming 8x H100 nodes, system needs $\approx \lceil 600 / 8 \rceil = 75$ HGX H100 nodes.
- Autoscaling Logic: Kubernetes Custom Metrics Autoscaler (KEDA) scales the dynamic worker fleet based on target queue depth: $$\text{Target Workers} = \frac{\text{Queue Depth}}{\text{Target Wait Time SLA (sec)}} \times \text{Average Job Duration}$$
Summary Checklist of Trade-Offs
| System Component | Strategy Chosen | Alternative Considered | Primary Reason for Choice |
|---|---|---|---|
| Communication | Async Push/Poll (Webhook / REST GET) | WebSockets / HTTP Long-Polling | Avoids holding millions of open socket connections for long multi-minute generation tasks. |
| Worker Lease | Distributed Heartbeat with DB Locks | Pure Message Queue Ack/Nack | Prevents split-brain state duplication when workers hang or experience silent network partitions. |
| Model Caching | Warm GPU Memory Pinning | Cold-loading model from network drive per job | Saves ~20-40 seconds of weight transfer per job, increasing overall GPU ROI. |
| Queue Architecture | Multi-priority Weighted Queues | Single FIFO Queue | Guarantees SLAs for paying enterprise tier without completely starving free-tier users. |