Design a Fair Multi-Tenant Image Enhancement Compute Service
System DesignModel answerLast updated
Design a distributed compute platform for image processing using GPU workers, implementing dynamic weighted fair-queueing by compute time and resilient lease-based task execution.
You are designing the backend architecture for an asynchronous image upscaling SaaS platform. The core processing relies on a deep learning model running on a shared fleet of GPU accelerators. Each upscale task requires dedicated access to a single GPU for its entire execution (no GPU sharing or model sharding across multiple GPUs).
Operational Scale & Workload Profile
- Traffic Volume: Peak throughput is 3,000 incoming requests per minute (~50 requests/sec).
- Execution Time: Varies significantly based on requested scale factor (2x to 4x) and input image resolution:
- Short tasks (small images, 2x): ~2 seconds.
- Long tasks (4K images, 4x): 30 to 40 seconds.
- Median task duration: ~5 seconds.
- Average task duration ($\mu$): ~8 seconds.
- Customer Tiers: Tens of thousands of users distributed across three service tiers: Free, Pro, and Enterprise.
System Requirements
- Request Lifecycle & Storage: Define the API endpoints, state transition workflow, persistent schema, and worker-scheduler orchestration model.
- Fairness & Scheduling Strategy: Design a scheduling algorithm that allocates GPU compute power fairly across tenants, considering that task durations are highly variable (task-count-based queuing is insufficient). Address edge cases such as idle burst protection and concurrency limits.
- Resilience & Fault Tolerance: Describe how the system handles worker crashes, GPU hardware failures, poison-pill tasks (jobs that crash the GPU worker), and scheduler failover without losing state or double-billing compute capacity.
Hints
Hint 1
Little's Law can help calculate the required GPU fleet size: L = λ * W.
Hint 2
Because job runtimes vary from 2s to 40s, fair scheduling should be based on estimated GPU execution time (accelerator-seconds), not raw task count.
Hint 3
Worker node polling (pull model) combined with time-bounded leases prevents deadlocks when worker nodes crash.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture Overview
Below is the high-level request lifecycle and infrastructure flow:
+--------------------+ +---------------------+ +--------------------+
| API Gateway / | -----> | Durable Job | <----- | Scheduler |
| Ingestion Service | | Database | | Leader |
+--------------------+ +---------------------+ +--------+-----------+
| ^ |
v | v
+--------------------+ | +--------------------+
| Blob Storage (S3) | <-----------------+------------------ | GPU Worker |
| (Inputs / Outputs) | | Fleet |
+--------------------+ +--------------------+
Part 1: Architecture, Data Layer, and Execution Model
Capacity & Fleet Sizing (Sanity Check via Little's Law)
- Arrival Rate ($\lambda$): 3,000 requests / 60 seconds = 50 requests/sec.
- Average Service Time ($W$): 8 seconds.
- Average Concurrency ($L$): $L = \lambda \times W = 50 \times 8 = 400$ active GPU executions at any given instant.
- Assuming a target average utilization of ~66% to absorb traffic spikes, the minimum operational fleet size is: $$\text{Fleet Size} = \frac{400}{0.66} \approx 600 \text{ GPUs}$$
API & Data Access Layer
The platform exposes a stateless REST/gRPC API backed by an Object Store (e.g., AWS S3) and a relational metadata store (e.g., PostgreSQL / CockroachDB).
POST /v1/jobs- Request Payload:
{ image_url, scale_factor, callback_url } - Processing: Validates input specs, estimates GPU runtime, persists job record with
status = 'queued', and enqueues task notification. - Response:
202 Acceptedwith{ job_id, estimated_completion_sec }.
- Request Payload:
GET /v1/jobs/{job_id}- Response: Current lifecycle status (
queued,running,completed,failed), progress indicator, and pre-signed download URL if completed.
- Response: Current lifecycle status (
Relational Data Schema (jobs table)
| Column | Type | Description |
|---|---|---|
id | UUID (PK) | Unique job identifier |
tenant_id | UUID (FK) | Customer account identifier |
tier | Enum | FREE, PRO, ENTERPRISE |
status | Enum | QUEUED, LEASED, RUNNING, COMPLETED, FAILED, DEAD_LETTER |
estimated_cost_sec | Float | Pre-calculated GPU runtime estimate |
actual_cost_sec | Float | Actual GPU execution duration |
input_s3_url | Text | Input image location |
output_s3_url | Text | Scaled output location |
lease_id | UUID | Active worker assignment token |
lease_expires_at | Timestamp | Heartbeat expiration window |
attempt_count | Int | Retry execution count |
created_at | Timestamp | Job submission timestamp |
Pull-Based Dispatch Model
Instead of the scheduler pushing jobs directly to workers (which risks misallocating to overloaded or degraded nodes), workers use a pull-based lease pattern:
- When a GPU worker becomes idle, it polls the central Scheduler Leader requesting work, sending its capabilities (e.g., Available VRAM = 24GB).
- The Scheduler filters queued jobs by worker capability, selects the optimal task according to the fairness policy, acquires a temporary lease token in the Job DB, and returns the assignment to the worker.
- The worker streams the raw image from Blob Storage, processes the upscale model, uploads the generated image directly to Blob Storage, and notifies the DB to transition the state to
COMPLETED.
Part 2: Dynamic Weighted Fair-Queueing Policy
Why Simple FIFO / Round-Robin Fails
Counting jobs completed per account creates severe unfairness. A tenant submitting 10 small tasks (2s each = 20 total GPU seconds) would consume fewer resources than a tenant submitting 1 large 4K 4x task (40 GPU seconds). Therefore, fairness must be tracked in GPU-seconds consumed, not job counts.
Algorithm: Virtual Time Deficit / Weighted Fair Queueing (WFQ)
The system tracks each customer's normalized compute usage using a Virtual Consumption Counter ($V_c$) updated in memory by the Scheduler.
-
Weight Assignment ($W_c$):
Free: Weight = 1Pro: Weight = 5Enterprise: Weight = 20
-
Normalized Cost Calculation: When tenant $c$ executes a task requiring an estimated runtime $E$, their Virtual Consumption Counter updates: $$V_c \leftarrow V_c + \frac{E}{W_c}$$
-
Selection Rule: When a GPU worker requests work, the Scheduler selects the oldest queued job from the tenant currently exhibiting the lowest $V_c$ value.
import heapq
import time
class FairScheduler:
def __init__(self):
# Maps tenant_id -> weight
self.tenant_weights = {}
# Virtual consumption score per tenant: tenant_id -> float
self.virtual_consumption = {}
# Pending queues per tenant: tenant_id -> list of jobs
self.tenant_queues = {}
# Priority Queue tracking active tenants sorted by virtual_consumption
self.active_heap = []
def enqueue_job(self, tenant_id, job):
if tenant_id not in self.tenant_queues:
self.tenant_queues[tenant_id] = []
# Anti-burst adjustment for returning idle tenants
min_system_vtime = min(self.virtual_consumption.values()) if self.virtual_consumption else 0.0
self.virtual_consumption[tenant_id] = max(self.virtual_consumption.get(tenant_id, 0.0), min_system_vtime)
heapq.heappush(self.active_heap, (self.virtual_consumption[tenant_id], tenant_id))
self.tenant_queues[tenant_id].append(job)
def dispatch_next_job(self, worker_vram_gb):
temp_popped = []
selected_job = None
selected_tenant = None
while self.active_heap:
vtime, tenant_id = heapq.heappop(self.active_heap)
queue = self.tenant_queues.get(tenant_id, [])
if not queue:
continue # No active jobs for this tenant
# Find first job matching hardware constraints
for idx, job in enumerate(queue):
if job['required_vram'] <= worker_vram_gb:
selected_job = queue.pop(idx)
selected_tenant = tenant_id
break
if selected_job:
# Update Virtual Time based on job's estimated runtime
cost = selected_job['estimated_duration_sec']
weight = self.tenant_weights.get(tenant_id, 1.0)
new_vtime = vtime + (cost / weight)
self.virtual_consumption[tenant_id] = new_vtime
# Push back into heap if tenant still has queued work
if queue:
heapq.heappush(self.active_heap, (new_vtime, tenant_id))
break
else:
# Store tenant to re-insert after evaluation
temp_popped.append((vtime, tenant_id))
for item in temp_popped:
heapq.heappush(self.active_heap, item)
return selected_job
Multi-Tenant Edge Case Handling
-
Idle Tenant Burst Protection: If a tenant is inactive for days, their $V_c$ counter would remain static while active tenants' $V_c$ scores grow high. If the idle tenant suddenly submits thousands of requests, they would monopolize the entire GPU fleet until their $V_c$ catches up.
- Mitigation: When an idle tenant submits a job, set their $V_c$ to: $$V_c = \max(V_c, \min_{\text{active}} V_{\text{active}})$$
-
Hard Concurrency Limits: Even with weighted queueing, a single Enterprise customer could saturate all 600 GPUs if no other traffic exists. To guarantee system availability and multi-tenant isolation, enforce hard ceilings on active concurrent leases:
Free: Max 5 concurrent jobs.Pro: Max 30 concurrent jobs.Enterprise: Max 100 concurrent jobs.
-
Admission Control: When a tenant's queue depth implies an estimated wait time exceeding their SLA (e.g., > 2 minutes for Pro), the API Gateway immediately rejects incoming requests with
429 Too Many Requests.
Part 3: Failure Handling & Edge Cases
| Failure Scenario | Detection Mechanism | Recovery Mechanism | Prevention / Safeguards |
|---|---|---|---|
| Worker Process Crash / Node Failure | Missed heartbeats (e.g., no heartbeat for 15s). Lease expires (lease_expires_at < NOW()). | Sweeper process re-queues expired tasks (status = 'QUEUED'). Increment attempt_count. | Fencing tokens (lease_id) prevent stale workers from writing late results. |
| Poison-Pill Job (Crash-inducing image) | Job fails multiple times across different GPUs (attempt_count >= 3). | Job state transitions to DEAD_LETTER. Customer notified with terminal error. | Prevents bad payloads from indefinitely cycling through and crashing the GPU fleet. |
| GPU Hardware Degradation / Out of Memory | Worker catches CUDA errors or repeated timeout failures on distinct jobs. | Worker marks itself unhealthy, drains active tasks, and triggers auto-remediation. | Health-check endpoint removes degraded GPUs from the active scheduling pool. |
| Scheduler Process Crash | Active leader loses lock in Distributed Consensus (e.g., Redis/Etcd lock). | Standby scheduler node wins election, queries DB for active leases, and rebuilds $V_c$ state. | Zero job loss because state transitions and lease bounds reside in persistent storage. |
Idempotency & Fencing Tokens
To ensure a task is never processed twice or misbilled:
- Every assigned task receives a unique UUID
lease_id. - When completing a task, the worker executes a conditional update in the database:
UPDATE jobs SET status = 'COMPLETED', actual_cost_sec = $1, output_s3_url = $2 WHERE id = $3 AND lease_id = $4; - If the lease expired while the worker was stalled, the update returns
0 rows affected. The worker discards its output, preventing duplicate processing and incorrect fair-share accounting.