Design a Text-to-Image Generation Service

Users type a prompt such as "a watercolor fox reading in a library" and get four images back. The product has a free tier, a paid subscription and an enterprise API with a latency commitment. One generation takes about five seconds on a single high-end GPU, so every request has a real, measurable cost, and GPUs are scarce and slow to add.

Traffic is spiky: a viral prompt trend can triple load within an hour. Prompts and generated images must be checked for unsafe content, results must be stored and served quickly worldwide, and finance wants to know the cost per image by tier.

Design the service. In 45 minutes, cover the API shape, how requests are queued and scheduled onto GPUs by tier, how the GPU fleet scales, where safety checks go, how images are stored and delivered, and what one image costs.

Sketch on the HLD board, write your answer in the Design doc, and size it with the Estimator. Start the mock interview from the timer for a 45-minute run.

Design Path · AI & ML Systems · problem 52 of 70

Ask before you design. Try answering each yourself, then compare.

  1. What scale should we plan for?
    Typical answer

    About 2 M daily users making ~5 generations each: ~10 M generations (40 M images) a day.

  2. What latency does each tier get?
    Typical answer

    Enterprise: 95% within 15 s. Paid: median under 10 s, 95% within 20 s. Free: best effort, may be told to retry when busy.

  3. Which models?
    Typical answer

    One main model and a faster distilled variant with fewer steps; custom style adapters are a follow-up.

  4. What safety checks are required?
    Typical answer

    Block disallowed prompts, check every output image before it is shown, and add provenance metadata to every image.

  5. How long are images kept?
    Typical answer

    30 days for free users; paid and enterprise galleries keep them until deleted.

  6. What GPU capacity exists?
    Typical answer

    A reserved pool sized near average load, plus on-demand and cheaper interruptible capacity that takes several minutes to start.

  7. Do failed or filtered generations cost the user credits?
    Typical answer

    No. Users pay only for delivered images.

Calculate GPU-seconds per day first. That number sets the fleet size and the cost.
Five seconds of work should not hold an HTTP connection hostage. What should the create call return?
With three tiers sharing one fleet, what decides which job runs next when a GPU frees up?
New GPUs take minutes to arrive, but a spike arrives in seconds. What do you do in between?
Where in the flow is the cheapest place to stop a bad request, and where is the last place?

Requirements

Functional

  • Submit a prompt with parameters and receive four images asynchronously with progress updates.
  • Priority tiers: enterprise, paid and free, with quotas and credits.
  • Prompt and output safety filtering with provenance metadata on results.
  • Store images and serve them through a CDN; user galleries.
  • Per-request metering of GPU time and cost.

Non-functional

  • Enterprise p95 < 15 s; paid p95 < 20 s; free best effort with explicit shedding.
  • ~350 generations/s at peak.
  • GPU utilisation above 70% at peak while meeting paid targets.
  • No image is ever served before passing the output safety check.
  • Exactly-once charging per request even with retries.

Out of scope

  • Training or fine-tuning the model.
  • Image editing and inpainting.
  • Video generation.

Back-of-the-envelope estimates

  • Requests: 10 M/day ≈ 116/s average, ~350/s at peak.
  • GPU time: 5 GPU-seconds per request → ~580 GPUs busy on average and ~1,750 at peak. At a 75% utilisation target, plan ~2,300 GPUs at peak: a reserved base of ~800 plus on-demand and interruptible burst capacity.
  • Cost: at an assumed $2.50 per GPU-hour, 5 s ≈ $0.0035 per generation, ~$0.0009 per image, before safety checks, storage and egress. Idle GPUs cost the same as busy ones, so utilisation is the main cost lever.
  • Storage: 40 M images/day × ~400 KB ≈ 16 TB/day; free images expire after 30 days (~500 TB steady state) while paid galleries keep growing.
  • Delivery: ~3 views per image → ~48 TB/day of egress, mostly served from CDN caches.

GPU-seconds per request drives everything: fleet size, cost per image and how hard the scheduler must work.

API

POST /v1/generations {prompt, negative_prompt?, size:"1024x1024", n:4, seed?, quality:"standard|fast",
                      idempotency_key}            -> 202 {generation_id, status:"queued", eta_s}
GET  /v1/generations/{id}  -> {status: queued|running|filtered|succeeded|failed,
                               images:[{url, width, height}], gpu_seconds}
GET  /v1/generations/{id}/events                 # server-sent events: queued, progress %, done
GET  /v1/users/me/gallery?cursor=...

Creation is asynchronous (202 plus polling or events) because work takes seconds and queues can take minutes; the idempotency key makes client retries safe and prevents double charges.

Data model

Generations (relational, sharded by user_id): (generation_id, user_id, tier, prompt, params, status, model_version, gpu_seconds, cost, safety_verdicts, idempotency_key, created_at). Users query their own history, so shard by user.

Job queues: one durable queue per tier and model variant, holding only IDs and scheduling metadata (deadline, estimated runtime).

Images in object storage at /{yyyy}/{mm}/{dd}/{generation_id}/{i}.webp, with lifecycle rules for free-tier expiry; served through a CDN with signed URLs.

Credits ledger (relational, transactional): holds at submit, captures on success, releases on failure or filtering.

High-level design

Submit. The client calls the API gateway, which authenticates and applies per-user rate limits. The generation service sends the prompt to prompt safety, a fast text classifier plus blocklists. If allowed, it places a credit hold, writes a row to the generation DB, and enqueues the job on the tiered job queues. For free users it first checks the estimated wait, and returns "busy, try again" instead of queueing when the wait is too long. The client gets a 202 with an ETA.

Run. The GPU dispatcher pulls jobs by least slack within tier weights, groups compatible requests into batches, and sends them to diffusion workers that already have the right model loaded. Workers stream progress, then hand raw images to output safety, which classifies each image, blurs or drops failures, and adds provenance metadata. Approved images go to the image store; the generation row is updated with status, GPU-seconds and cost, and the credit hold is captured.

Deliver. The client receives signed URLs and loads images from the CDN. The autoscaler watches queue depth and slack and adds or removes GPU capacity.

Open the HLD board and press Reference to see the architecture diagram.

Deep dives

Scheduling three tiers on one fleet

Keep separate queues per tier and model variant. Enterprise has a guaranteed share of capacity, paid gets most of the rest, and free uses what is left. Inside those weights, the dispatcher picks the job with the least slack: deadline minus now minus expected runtime. A paid job close to its deadline jumps ahead of one that just arrived. Running jobs are never preempted, since they finish in seconds. Shedding happens at admission: if the estimated wait for a free request is over about 45 seconds, reject it right away with a retry hint. Fast, honest rejection is far better than a long spinner.

Keeping GPUs busy and cheap

Loading model weights takes tens of seconds, so workers keep a model resident and the dispatcher routes by model affinity rather than swapping. Batching requests of the same model, resolution and step count raises throughput per GPU. Half precision and compiled kernels cut step time; the free tier uses the distilled model with fewer steps. Capacity has three layers: reserved GPUs near average load, on-demand GPUs for daily peaks, and interruptible GPUs for free and batch work. Because new nodes take minutes, the autoscaler scales on forecast demand plus queue depth and keeps a small warm buffer. Jobs are idempotent, so work on a reclaimed interruptible node is simply requeued.

Layered safety

Check the prompt first, because it is the cheapest point: a text classifier, blocklists and rules for real people’s names. Some prompts can be rewritten rather than refused. The last line of defence is the output check: every image passes an image classifier for nudity, violence, minors and likeness of real people before any URL exists for it. Thresholds can differ by tier and region. Filtered requests are not charged, but they are counted per account: repeated attempts lower a trust score and tighten rate limits. Every image gets provenance metadata and an invisible watermark identifying it as generated, and verdicts are logged for audits.

Cost per image and fair billing

Meter actual GPU-seconds per job on the worker, including the batch share, then compute cost as GPU-seconds × price per second for that capacity type, plus safety inference, storage and egress. Roll it up by tier, model and customer so pricing and quotas are based on real numbers. Credits use a hold-and-capture ledger: reserve at submit, capture on delivery, release on failure or filtering, all keyed by the idempotency key so a retry never charges twice. Requests that repeat a prompt, parameters and seed exactly can be served from a cache of previous results.

Failure modes

  • If a GPU worker dies mid-job, the job lease expires and the dispatcher requeues it with its original deadline; the user sees a short delay, not a failure.
  • If demand spikes faster than the autoscaler, free requests are shed at admission while enterprise and paid keep their reserved share.
  • If output safety is down, finished images wait in private storage and are never published until checked.
  • If the CDN has trouble, signed URLs fall back to the object store origin with lower throughput.

Core algorithm in code

import random

random.seed(3)
RUNTIME = 5.0                                             # GPU-seconds per generation (batch of 4 images)
DEADLINE = {"enterprise": 15.0, "paid": 20.0, "free": 90.0}
FREE_MAX_WAIT = 45.0                                       # shed free work beyond this estimated wait


def simulate(arrivals, gpus):
    """Event-driven dispatcher: least slack first, with admission control for the free tier."""
    free_at = [0.0] * gpus
    pending, waits, shed, i = [], {t: [] for t in DEADLINE}, 0, 0
    while i < len(arrivals) or pending:
        g = min(range(gpus), key=lambda k: free_at[k])
        now = free_at[g]
        if not pending and arrivals[i][0] > now:
            now = free_at[g] = arrivals[i][0]
        while i < len(arrivals) and arrivals[i][0] <= now:
            t_arr, tier = arrivals[i]
            busy = sum(1 for f in free_at if f > t_arr)
            est_wait = (len(pending) + busy) / gpus * RUNTIME
            if tier == "free" and est_wait > FREE_MAX_WAIT:
                shed += 1                                 # "busy, try again shortly" instead of a 3-minute spinner
            else:
                pending.append((t_arr, tier))
            i += 1
        slack = lambda j: j[0] + DEADLINE[j[1]] - now - RUNTIME
        job = min(pending, key=slack)
        pending.remove(job)
        waits[job[1]].append(now - job[0])
        free_at[g] = now + RUNTIME
    return waits, shed


# A 2-minute spike at ~2.4 requests/s against 6 GPUs (capacity 1.2/s): 25% paid, 10% enterprise.
arrivals, t = [], 0.0
while t < 120:
    t += random.expovariate(2.4)
    r = random.random()
    arrivals.append((t, "enterprise" if r < 0.10 else "paid" if r < 0.35 else "free"))

waits, shed = simulate(arrivals, gpus=6)
for tier, w in waits.items():
    w = sorted(w)
    if w:
        late = sum(x + RUNTIME > DEADLINE[tier] for x in w)
        print(f"{tier:10} served={len(w):3} median wait={w[len(w)//2]:5.1f}s  max={w[-1]:5.1f}s  missed deadline={late}")
print("free requests shed by admission control:", shed)
cost = RUNTIME / 3600 * 2.50
print(f"GPU cost per generation at $2.50/GPU-hour: ${cost:.4f} (${cost/4:.4f} per image)")

Trade-offs

  • Asynchronous jobs make queues and retries manageable but cost a more complex client with polling or event streams.
  • Batching raises GPU throughput but costs some latency while a batch fills, so batch windows are capped at a few hundred milliseconds.
  • Interruptible GPUs cut cost sharply but cost requeues and uneven free-tier latency.
  • Shedding free requests early protects paid latency but costs free-user satisfaction during spikes.
  • Strict output filtering prevents harmful images but costs false positives that frustrate legitimate users.

What a strong answer shows

  • Starts from GPU-seconds per request and sizes the fleet and cost from it.
  • Chooses an asynchronous API with idempotency.
  • Designs tier scheduling with deadlines, reserved shares and admission control.
  • Handles slow GPU scale-up with forecasting, buffers and mixed capacity.
  • Places safety checks both before and after generation.
  • Computes a cost per image and ties billing to delivered results.

Mistakes to avoid

  • Holding a synchronous HTTP request open for the whole generation.
  • One FIFO queue for all tiers.
  • Assuming GPUs autoscale in seconds like stateless web servers.
  • Publishing image URLs before the output safety check.
  • Ignoring that idle reserved GPUs still cost money.

Follow-ups to expect

  • How would you support custom style adapters? (Load small adapter weights on top of a resident base model; route by adapter popularity.)
  • How would you add progressive previews? (Stream low-resolution intermediate steps over the event channel.)
  • How do you run across regions? (Region-local queues and fleets; spill free-tier work to regions with spare capacity.)
  • How would you detect abuse at scale? (Per-account filter rates, prompt similarity clustering, trust scores.)

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url