Load a diffusers pipeline (FLUX.1 [schnell] or SDXL) once at start-up in a FastAPI app, accept requests at POST /v1/images, put each job on an asyncio queue, and let one worker run the GPU and save results. Clients poll GET /v1/jobs/{id} and download the image. Run one process per GPU to scale.
- Stack
- FastAPI + uvicorn + diffusers + PyTorch
- Pattern
- Accept job, return 202 and an id, queue, single GPU worker, poll for result
- Commercial-friendly models
- FLUX.1 [schnell] (Apache 2.0), SDXL (Open RAIL++-M)
- Capacity, FLUX.1 [schnell] on H100 PCIe (est.)
- ≈2,400 images per hour at ~1.5 s each
- Uvicorn workers per GPU
- 1 (each worker would load its own model copy)
- Suggested GPU for BF16 FLUX
- L40S 48 GB at $1.89/hr
A hosted image API charges per image and sends your users' prompts to someone else's servers. Your own API on a rented GPU costs per GPU-hour, keeps prompts on your machine, and lets you choose the model, the LoRAs and the limits. The code is short. What makes it work in practice is the shape around the model: load it once, queue jobs, run one generation at a time per GPU, and return results asynchronously. This tutorial builds exactly that with FastAPI and diffusers.
It assumes you have already generated an image on a GPU; if not, start with how to run Stable Diffusion on a cloud GPU.
What does an image generation API need?
An image API needs five parts: a model loaded once, an HTTP front end, a queue, a single GPU worker, and storage for results. Everything else (auth, limits, webhooks) is added around those.
| Part | Job | In this tutorial |
|---|---|---|
| Model | Turns prompts into images | diffusers FluxPipeline (FLUX.1 [schnell]) loaded at start-up |
| HTTP front end | Validates requests, returns job ids | FastAPI |
| Queue | Holds jobs, applies back-pressure | asyncio.Queue with a maximum size |
| Worker | Runs one generation at a time on the GPU | An asyncio task calling the pipeline in a thread |
| Storage | Keeps finished images | Local disk; object storage in production |
Why not generate inside the request handler? Generations take seconds, the GPU should run one at a time per model copy, and HTTP clients and proxies time out. Returning 202 Accepted with a job id and letting the client poll is the standard pattern.
Step 1: Launch a GPU and install the stack
Pick the GPU for your model. FLUX.1 [schnell] in full BF16 needs about 34 GB, so this tutorial uses a 48 GB L40S; the notes show how to use a 24 GB RTX 4090 instead. Choose the Root way in: on Wandering Giants Compute that is SSH into Ubuntu with CUDA and PyTorch installed.
ssh -p PORT USER@HOST
sudo apt-get update && sudo apt-get install -y python3-venv tmux
python3 -m venv ~/imgapi --system-site-packages
source ~/imgapi/bin/activate
pip install -U pip diffusers transformers accelerate safetensors sentencepiece protobuf \
fastapi "uvicorn[standard]" pydantic
mkdir -p ~/imgapi-app && cd ~/imgapi-appFLUX.1 [schnell] is Apache 2.0, which matters for an API you might charge for. FLUX.1 [dev] is non-commercial; SD 3.5 models are free for commercial use only below US$1 million in annual revenue. The licence is on each model card, for example [FLUX.1 [schnell]](https://huggingface.co/black-forest-labs/FLUX.1-schnell).
Step 2: Write the API with a job queue
Save this as app.py. It loads the model once, accepts jobs, queues them and processes them one at a time.
# app.py
import asyncio, os, secrets, time, uuid, pathlib
from contextlib import asynccontextmanager
import torch
from diffusers import FluxPipeline
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
API_KEY = os.environ["IMAGE_API_KEY"]
OUT = pathlib.Path(os.environ.get("OUT_DIR", "outputs")); OUT.mkdir(exist_ok=True)
MAX_QUEUE = int(os.environ.get("MAX_QUEUE", "100"))
class ImageRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=2000)
width: int = Field(1024, ge=256, le=1536, multiple_of=16)
height: int = Field(1024, ge=256, le=1536, multiple_of=16)
steps: int = Field(4, ge=1, le=8)
seed: int | None = None
jobs: dict[str, dict] = {}
state: dict = {}
def generate(req: ImageRequest, path: pathlib.Path) -> None:
seed = req.seed if req.seed is not None else secrets.randbelow(2**31)
image = state["pipe"](
req.prompt, width=req.width, height=req.height,
num_inference_steps=req.steps, guidance_scale=0.0, max_sequence_length=256,
generator=torch.Generator("cpu").manual_seed(seed),
).images[0]
image.save(path)
async def worker() -> None:
queue: asyncio.Queue = state["queue"]
while True:
job_id, req = await queue.get()
job = jobs[job_id]
job.update(status="running", started=time.time())
try:
path = OUT / f"{job_id}.png"
await asyncio.to_thread(generate, req, path) # keeps the event loop responsive
job.update(status="done", file=str(path))
except Exception as exc: # report, don't crash the worker
job.update(status="error", error=str(exc))
finally:
job["finished"] = time.time()
queue.task_done()
@asynccontextmanager
async def lifespan(app: FastAPI):
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell",
torch_dtype=torch.bfloat16)
pipe.to("cuda") # 24 GB card: use pipe.enable_model_cpu_offload() instead
state["pipe"] = pipe
state["queue"] = asyncio.Queue(maxsize=MAX_QUEUE)
task = asyncio.create_task(worker())
yield
task.cancel()
app = FastAPI(title="Image API", lifespan=lifespan)
def check_key(x_api_key: str = Header(...)) -> None:
if not secrets.compare_digest(x_api_key, API_KEY):
raise HTTPException(status_code=401, detail="Invalid API key")
@app.get("/healthz")
async def healthz():
return {"ok": True, "queued": state["queue"].qsize()}
@app.post("/v1/images", status_code=202, dependencies=[Depends(check_key)])
async def create_image(req: ImageRequest):
job_id = uuid.uuid4().hex
jobs[job_id] = {"status": "queued", "created": time.time()}
try:
state["queue"].put_nowait((job_id, req))
except asyncio.QueueFull:
del jobs[job_id]
raise HTTPException(status_code=429, detail="Queue full, retry later")
return {"id": job_id, "status": "queued", "queue_depth": state["queue"].qsize()}
@app.get("/v1/jobs/{job_id}", dependencies=[Depends(check_key)])
async def job_status(job_id: str):
job = jobs.get(job_id)
if job is None:
raise HTTPException(status_code=404, detail="Unknown job")
return {k: v for k, v in job.items() if k != "file"} | {"id": job_id}
@app.get("/v1/jobs/{job_id}/image", dependencies=[Depends(check_key)])
async def job_image(job_id: str):
job = jobs.get(job_id)
if job is None or job.get("status") != "done":
raise HTTPException(status_code=404, detail="Image not ready")
return FileResponse(job["file"], media_type="image/png")Key choices, briefly:
- One worker, one GPU. The worker processes one job at a time, so VRAM use is predictable and requests never collide.
asyncio.to_thread. The pipeline call blocks for seconds; running it in a thread keeps FastAPI answering status requests meanwhile.- Bounded queue. When 100 jobs are waiting, new requests get
429rather than silently waiting for ten minutes. Clients can retry with backoff. - Validated input. Width and height are limited and must be multiples of 16 (FLUX's requirement); steps are capped so one request cannot occupy the GPU for minutes.
The FastAPI documentation covers dependencies, lifespan events and responses in more depth.
Step 3: Run it and test it
Generate a key, start the server inside tmux, and use exactly one uvicorn worker:
export IMAGE_API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
echo "$IMAGE_API_KEY" > ~/imgapi-app/.key && chmod 600 ~/imgapi-app/.key
tmux new -s api
uvicorn app:app --host 127.0.0.1 --port 8000 --workers 1From your computer, tunnel the port and call it:
ssh -N -L 8000:127.0.0.1:8000 -p PORT USER@HOST &
KEY=... # the key you generated
curl -s -X POST http://localhost:8000/v1/images \
-H "X-API-Key: $KEY" -H "Content-Type: application/json" \
-d '{"prompt": "a lighthouse made of glass on a stormy coast", "seed": 7}'
# {"id":"3f2c...","status":"queued","queue_depth":1}
curl -s http://localhost:8000/v1/jobs/3f2c... -H "X-API-Key: $KEY"
curl -s http://localhost:8000/v1/jobs/3f2c.../image -H "X-API-Key: $KEY" -o out.pngThe first job after start-up includes some warm-up; later ones settle to steady speed. FastAPI also serves interactive docs at http://localhost:8000/docs.
Step 4: Make it production-shaped
The code above is a working core. Before real users rely on it, add the following.
- Persistent job state. The
jobsdict lives in memory, grows forever and disappears on restart. Use Redis or a database, and expire finished jobs after a day. - Object storage for images. Upload finished images to S3-compatible storage and return a signed URL, rather than serving files from the GPU machine's disk.
- Webhooks. Accept an optional
callback_urland POST the result when the job finishes, so clients need not poll. - Per-key rate limits and usage records. Count images per key per day; it is your billing data and your abuse control.
- Content policy. Decide what prompts you refuse and log decisions. Hosted APIs do this for you; self-hosted, it is your responsibility.
- A process supervisor. Run uvicorn under systemd with
Restart=always, so a crash at 3 a.m. restarts itself. - TLS and a public address. For public traffic, put a reverse proxy such as Caddy or nginx with TLS in front of uvicorn, or use an outbound tunnel such as Cloudflare Tunnel. Never expose uvicorn directly.
If you have already built an LLM endpoint, the same front-end patterns apply; see how to build an open-source LLM API.
Step 5: Batch for throughput
When the queue is often non-empty, process several compatible jobs in one pipeline call. diffusers accepts a list of prompts:
# Inside the worker: gather up to 4 waiting jobs with the same size and steps
batch = [await queue.get()]
while len(batch) < 4 and not queue.empty():
batch.append(queue.get_nowait())
# group by (width, height, steps), then call:
# state["pipe"]([r.prompt for _, r in group], width=..., height=..., num_inference_steps=...)Batching raises GPU utilisation and images per hour, at the cost of a little extra latency for the first job in each batch. Remember to call queue.task_done() once per job you take.
Step 6: Scale to more GPUs
Run one copy of the API per GPU and balance across them. On a machine with four GPUs:
for i in 0 1 2 3; do
CUDA_VISIBLE_DEVICES=$i tmux new -d -s api$i \
"uvicorn app:app --host 127.0.0.1 --port $((8000+i)) --workers 1"
doneThen point a reverse proxy at ports 8000–8003. With per-process in-memory job state, a status request must reach the same process that took the job, so move job state to Redis before load balancing, or switch to a design where a shared queue feeds GPU workers. That design, which also handles video and bursts, is in how to build a scalable AI image and video generation platform. The multi-GPU mechanics are in how to generate AI images faster using multiple GPUs.
What does a self-hosted image API cost per image?
Your cost per image is the GPU's hourly price divided by the images it actually produces in an hour. Utilisation, the share of time the GPU is busy, matters as much as speed.
Capacity per GPU = 3,600 ÷ seconds per image. The speeds are our rough estimates for 1024×1024 images, not measurements.
| Model on GPU | Seconds per image (est.) | Max images per hour | GPU-hours per 1,000 at 100% busy | Our cost per 1,000 at 100% busy | At 25% busy |
|---|---|---|---|---|---|
| FLUX.1 [schnell] on L40S | 3.5 | ~1,030 | 0.97 | 0.97 × $1.89/hr ≈ $1.83 | 3.89 × $1.89/hr ≈ $7.35 |
| FLUX.1 [schnell] on H100 PCIe | 1.5 | ~2,400 | 0.42 | 0.42 × $4.99/hr ≈ $2.10 | 1.67 × $4.99/hr ≈ $8.33 |
| SDXL on RTX 4090 | 4.5 | ~800 | 1.25 | 1.25 × $1.59/hr ≈ $1.99 | 5.00 × $1.59/hr ≈ $7.95 |
| FLUX.1 [schnell] on RTX 4090 (offload) | 5 | ~720 | 1.39 | 1.39 × $1.59/hr ≈ $2.21 | 5.56 × $1.59/hr ≈ $8.84 |
The last column is the real-world warning: an API that is busy a quarter of the time pays four times as much per image as one that is busy all the time. That is the core trade-off against hosted per-image APIs, which cost more per image at full load but nothing when idle. Self-hosting wins when traffic is steady or when privacy and control matter more than the last cent. GPU utilisation and cost efficiency goes deeper on that sum.
When does renting from Wandering Giants Compute fit?
Renting from us fits an image API that needs a dedicated GPU you fully control: root access, Ubuntu, CUDA and PyTorch ready, from a 24 GB RTX 4090 to a 96 GB RTX PRO 6000, or up to eight of the same card in one machine. Your users' prompts and images stay on your machine, and we do not read them or train on them. Billing is by the minute from prepaid credit, and if credit runs out the machine stops rather than running up a bill, so keep credit topped up for a live service.
Be clear about what we do not offer: no uptime SLA, no autoscaling or scale-to-zero endpoints, and our API way in serves language models, not image models. If your traffic is spiky and you need scale-to-zero, a serverless GPU platform or a hosted image API may suit better. For steady traffic and full control, pick a GPU and run the code above.
Frequently asked questions
Why use a queue instead of generating inside the request?
A GPU can only run one generation efficiently at a time per model copy, and generations take seconds. A queue stops concurrent requests fighting over VRAM, lets you return immediately with a job id, and gives you a natural place to reject work with HTTP 429 when the backlog is too long.
Can I run several uvicorn workers on one GPU?
Not usefully for this design. Each worker is a separate process that would load its own copy of the model into VRAM and compete for the same GPU. Run one worker per GPU and put a load balancer in front if you have several GPUs.
Which image model can I use for a commercial API?
FLUX.1 [schnell] is Apache 2.0 and SDXL is under the CreativeML Open RAIL++-M licence, which permits commercial use with use restrictions. FLUX.1 [dev] is non-commercial and SD 3.5 models are free commercially only below US$1 million annual revenue. Check each model card.
How many images per hour can one GPU serve?
Divide 3,600 by seconds per image. At estimated figures, FLUX.1 [schnell] at about 1.5 seconds on an H100 is about 2,400 images an hour, and SDXL at about 4.5 seconds on an RTX 4090 is about 800. Your resolution and steps change this.
Should clients poll or should I use webhooks?
Polling a status endpoint is simplest and works everywhere. For production, add an optional webhook URL per job and POST the result when it finishes, or use server-sent events, so clients do not need to poll.
Does the Wandering Giants API option serve image models?
No. Our API way in is an OpenAI-compatible endpoint served by vLLM for language models. For image generation you use the Root way in and run your own server, as in this tutorial.
Rent the GPU for this, by the minute.
Run your own image API on a dedicated L40S or H100 with root access and CUDA ready, billed by the minute, with your users' prompts staying on your machine.
Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.
Keep reading
- Complete guideHow to Run Stable Diffusion on a Cloud GPU
- GuideHow to Build a Scalable AI Image and Video Generation Platform
- TutorialHow to Build Your Own Open-Source LLM API
- GuideHow to Generate AI Images Faster Using Multiple GPUs
- ComparisonBest GPU Infrastructure for AI SaaS Startups
- GuideHow to Calculate GPU Utilisation and Cost Efficiency
About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.
Last reviewed 25 November 2026.