Building a Diffusion App
After this lesson, you will be able to:
- Lay out a text-to-image service as a line of steps: receive, check, generate, post-process, deliver
- Choose where the GPU lives (a hosted service for a prototype, a pay-per-second GPU service for production, rented or owned GPUs for the lowest cost at volume) and add a cache so repeated requests are answered instantly
- Build a three-stage safety pipeline: check the prompt, check the output, mark every image as AI-made, in line with provenance standards (C2PA) and the EU AI Act marking duty (check the current dates)
- Cut the cost per image by mixing model tiers (a fast 4-step preview, a full-quality final) and log every stage so any image can be reproduced and audited
Before you start
A line of steps where each step takes what the last one produced and passes its result on.
A store of answers already made, so a repeated request is served without running the model again.
The share of requests that the cache can answer. A hit rate of 0.6 means 6 requests in 10 are repeats.
The wait between sending a request and seeing the result.
One level in a menu of models, from fast and cheap to slow and best. The app picks a tier for each request.
A cap on how many requests one user may send in a given time, so one user cannot use up the GPUs.
A mark placed in an image, often invisible, that shows the image was made by AI.
An industry standard for attaching a signed record of where a file came from and how it was made.
Each box in this lesson is a plain step: a function that takes something in and passes something on. A queue is a waiting line for requests, a cache is a store of finished answers, and a filter is a check that can say no. Once you see the steps in order, the moving parts are easy to follow.
#The End-to-End Architecture
Read the diagram left to right along the top, then back along the middle row. A cache hit skips the whole second row, which is why the cache saves so much money. The same request path is the order of the steps in the code later in this lesson.
#Backend Choices: Where the GPU Lives
| Backend | Best for | How you pay (check current prices) | Cold start |
|---|---|---|---|
| Hosted inference service (such as Hugging Face) | Prototypes, demos | Per call or per credit | seconds |
| Replicate | Production, simple ops | Per second of GPU time | seconds |
| fal.ai | Real-time UX, low latency | Per call | short |
| Modal | Custom Python, serverless | Per second of GPU time | seconds |
| RunPod / Lambda Labs | Lowest cost at scale | Per GPU-hour | minutes |
| Self-hosted (k8s + GPU node) | Maximum control | Hardware + ops cost | minutes |
Picture first: a GPU rented at $2 an hour costs about 0.056 cents each second. An image that keeps the GPU busy for 4 seconds therefore costs about 0.22 cents. Storing and sending the file adds a little. The formula below is that sum.
The cost formula is a unit conversion plus an addition. Open the derivation if the 3600 or the three terms look arbitrary.
#The Caching Layer Is the Margin
Picture first: take 100 requests, and suppose 60 of them are repeats the cache can answer. The 40 new ones cost 0.3 cents each, which is 12 cents. The 60 repeats cost 0.003 cents each, which is 0.18 cents. The total is about 12.2 cents instead of 30 cents, a saving of about 59 percent. The formula below is that average.
The effective cost is just an average over the two things that can happen to a request. The derivation also shows how much a cache can save at most.
(prompt, seed, model_id, lora_list, controlnet_inputs) — anything user-controlled that affects output.#The Three-Stage Safety Pipeline
You're shipping a free-tier image generator. Daily traffic spikes 10x because of a viral TikTok. Your GPU bill is exploding. Which production decision maximizes margin without harming the experience?
#Cost Optimization: The Tier Stack
A modern diffusion app doesn't run one model — it runs three or four. The numbers below are illustrative, chosen to show the shape of the trade-off; they are not quotes:
Tier 0: Cached blob → CDN ($0.0001/image, 50ms)
Tier 1: LCM-LoRA + SDXL (4 steps, low quality) ($0.0008/image, 1.5s)
Tier 2: Full SDXL (50 steps, full quality) ($0.005/image, 6s)
Tier 3: SDXL + Real-ESRGAN 4x upscale ($0.012/image, 12s)
Tier 4: Premium hosted model ($0.04/image, 8s)
The tier costs follow from how sampling works: generation time grows with the number of denoising steps, but not all of it. The derivation fits the two time figures in the list above.
The product UX picks the tier. Type-as-you-prompt? Tier 1. Press "Generate"? Tier 2. Click "Final HD"? Tier 3. Pay for "Pro Quality"? Tier 4.
#A FastAPI Skeleton
fastapi and pydantic, which are not available in the browser, so copy it to Colab or your own machine (pip install fastapi uvicorn). A runnable stand-in written in plain Python follows it.# COPY TO COLAB or your own machine (needs fastapi, pydantic, uvicorn; will not run in the browser)
# Minimal production diffusion app skeleton
# Run: uvicorn app:app --workers 4
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import hashlib, time, os
app = FastAPI()
# --- Stub clients (real impl: diffusers, redis, S3, OpenAI Moderation) ---
class FakeStorage:
def __init__(self): self.store = {}
def exists(self, key): return key in self.store
def get(self, key): return self.store.get(key)
def put(self, key, val): self.store[key] = val
class FakeRateLimiter:
def __init__(self): self.counts = {}
def allow(self, user_id, max_per_min=10):
now = int(time.time() // 60)
bucket = (user_id, now)
self.counts[bucket] = self.counts.get(bucket, 0) + 1
return self.counts[bucket] <= max_per_min
storage = FakeStorage()
limiter = FakeRateLimiter()
# --- Safety stubs (real: HF safety classifiers, OpenAI Moderation API) ---
BANNED_TERMS = ["[csam-keyword]", "[weapons-keyword]"] # real list is much longer
def input_safety(prompt: str) -> bool:
return not any(t in prompt.lower() for t in BANNED_TERMS)
def output_safety(image_bytes: bytes) -> bool:
# Real impl: pass through SD safety_checker or NSFW classifier
return True
def add_watermark(image_bytes: bytes, metadata: dict) -> bytes:
# Real impl: Stable Signature embed + C2PA manifest
return image_bytes # stub
# --- Generation tier picker ---
def pick_tier(user_tier: str, intent: str) -> str:
if intent == "preview": return "lcm_lora_sdxl"
if user_tier == "free": return "lcm_lora_sdxl"
if user_tier == "pro": return "full_sdxl"
if user_tier == "premium": return "flux_pro"
return "full_sdxl"
def generate(prompt: str, seed: int, model_tier: str) -> bytes:
# Real impl: diffusers pipeline call
print(f"[GEN] {model_tier} | seed={seed} | '{prompt[:60]}...'")
time.sleep(0.1) # stub
return f"image_bytes_for_{model_tier}".encode()
# --- The endpoint ---
class GenerateRequest(BaseModel):
prompt: str
seed: int = 42
user_id: str
user_tier: str = "free"
intent: str = "final" # 'preview' | 'final'
@app.post("/generate")
def gen_endpoint(req: GenerateRequest):
# 1. Rate limit
if not limiter.allow(req.user_id):
raise HTTPException(429, "Rate limit exceeded")
# 2. Input safety
if not input_safety(req.prompt):
raise HTTPException(400, "Prompt rejected by safety filter")
# 3. Cache
tier = pick_tier(req.user_tier, req.intent)
key = hashlib.sha256(f"{tier}|{req.prompt}|{req.seed}".encode()).hexdigest()
if storage.exists(key):
return {"url": f"https://cdn.example.com/{key}", "cached": True}
# 4. Generate
image = generate(req.prompt, req.seed, tier)
# 5. Output safety
if not output_safety(image):
raise HTTPException(422, "Output rejected by safety filter")
# 6. Watermark + store
watermarked = add_watermark(image, {"prompt": req.prompt, "model": tier, "user": req.user_id})
storage.put(key, watermarked)
return {"url": f"https://cdn.example.com/{key}", "cached": False, "tier": tier}
# Frontend streaming idea (Server-Sent Events), left as a challenge:
# from sse_starlette.sse import EventSourceResponse
# @app.get("/generate-stream")
# async def stream(prompt: str, user_id: str):
# async def event_generator():
# for step in range(50):
# yield {"event": "step", "data": json.dumps({"pct": step / 50})}
# await asyncio.sleep(0.05)
# yield {"event": "done", "data": json.dumps({"url": "..."})}
# return EventSourceResponse(event_generator())The runnable twin keeps the same stations in the same order, but replaces FastAPI and pydantic with a small exception class and a dataclass. It adds a rate-limit demo so you can see the 429 path.
Tests: Verify rate-limited users get 429. Verify the cache returns the same URL with cached=True on repeat. Verify banned prompts get 400 before any generate call. Verify pro vs free tier picks different models.
#Latency Budget: Where Every Millisecond Goes
#Observability: What You Must Log
Every generation request should log:
request_id,user_id,prompt_hash,seed,model_tier,lora_list,controlnet_inputs- Timestamps for each pipeline stage (queue, filter, generate, post, deliver)
- Output:
image_hash,cache_hit,safety_filter_result,watermark_id - Errors: which stage failed, with stack trace
request_id, you can replay the exact image. Auditability means: when a content-policy violation gets reported, you can find every related output via prompt-hash lineage.#Key Takeaways
- The pipeline is the product. Model weights are widely available; orchestration (rate limiting, safety, caching, watermarking, observability) is what separates a hackathon project from a service people can rely on.
- Cache aggressively, hash everything user-controlled. Your hit rate depends on your product, so measure it; a cache hit that is about 100x cheaper than generation (the lesson's example) makes caching the highest-margin optimization wherever prompts repeat.
- Mix model tiers; let UX intent pick the tier. LCM-LoRA for previews, full SDXL/FLUX for finals; reserve premium tiers for paid users; don't pay premium prices for someone hammering "Generate" speculatively.
- Three-stage safety is non-negotiable. Input prompt filter (cheap, blocks GPU waste), output NSFW classifier (catches what input missed), provenance marking (the EU AI Act's marking rule was scheduled from August 2026; check the date). All three, every request.
- Observe everything for reproducibility and audit. Log
request_id → prompt_hash → seed → model_tier → output_hash; one bad-content report should be traceable in seconds, not a forensics exercise.
#Quick Check
Your free-tier diffusion app gets 10x normal traffic from a viral moment. Your GPU bill spikes alarmingly. What's the highest-leverage move?