An image service is a queue in front of GPUs. Keep every GPU 90% busy: with one GPU a job waits 72 s, with 185 GPUs it waits 0.05 s.
Design an image-generation service like Midjourney from zero: the async job, the queue, the fleet, the GPU worker, storage, failures and cost.
Pick a fleet size, then drag how busy each GPU is. Watch the queue. Then we build, piece by piece, the job, the gateway, the lanes, the sizing rule, the worker and the bill that sit behind this one curve.
You need a little Python and a rough idea of what a server and a request are. We build the rest from zero.
Midjourney publishes little about its internals. We cite the few facts it has stated where they appear. Everything else is how you would design a service like it, with illustrative numbers worked by script.
Illustrative: each job holds one GPU for 8 s on average, and arrivals are random. The wait is the Erlang C formula from Chapter 5, so it treats service times as random too. The cells and queue dots draw the average state, not a real trace.
Chapter 0
See why a web-page reply cannot serve a prompt, and why the answer is a job you store
You type /imagine a fox reading a newspaper in Discord. About ten seconds later, four images appear. A web page answers in 50 ms. Why does this take two hundred times longer?
Each image runs a diffusion model: a network that starts from random noise and removes a little noise per step, for dozens of steps. Every step is a full pass through a network with billions of weights. In 2022 Midjourney's founder, David Holz, told The Register that every image takes "thousands of trillions of operations", and that he did not know "whether it's five or 10 or 50" petaops.
So the work is long and it lives on a GPU, a chip built for this kind of arithmetic. That fact drives the whole design. The first place it bites is the front door.
A Discord bot receives each slash command as an interaction. Discord's docs say the bot must send an initial response within 3 seconds. It may send a deferred response (type 5) that says "working on it", then edit the message later. The token for those edits is valid for 15 minutes.
The red line is Discord's 3-second limit. Choose how the bot replies, then drag the GPU time.
The 3-second limit, response type 5 and the 15-minute token are from Discord's interaction docs. The finish times are illustrative: about 10 s for a fast job, many minutes for a low-priority job in a long queue.
Drag the time past 3 s with "Reply when done". The interaction fails. With "Defer, then edit", the bot answers in 0.1 s and the work goes on elsewhere. That is the async job pattern: accept fast, store the work as a job (a record with the prompt, the user and the state), process it later, push the result.
Failure. The symptom is "This interaction failed" in the chat. Measure the time from receipt to first response at the bot. The fix is to defer at once, before any slow check. Past 15 minutes the edit token expires, so a long-queued job must post a new bot message instead.
Chapter 1
Turn a daily job count into the number of GPUs that are busy at any moment
You run a service like this one. Your dashboard says 600,000 jobs a day. Each job is one prompt that makes a grid of four images. How many GPUs do you need? Start with the average, then the peak.
Call the jobs that arrive per second the arrival rate, λ. Call the GPU time one job holds a GPU the service time, S. Their product is the offered load, a: how many GPUs are busy on average.
a equals lambda times S.
Each second, lambda new jobs arrive. Each one keeps a GPU busy for S seconds. So at any moment, lambda times S GPUs are working.
With made-up numbers: 600,000 jobs a day is λ = 600,000 / 86,400 = 6.94 jobs/s. With S = 8 s, a = 6.94 × 8 = 55.6 GPUs busy on average.
Traffic is not flat. People make images in the evening, so the busiest hour can run at about three times the daily average. At 3×, λ = 20.8 jobs/s and a = 167 GPUs. You must own the peak, but you are busy at the average.
Blue bars are GPUs busy on average and at the peak. Drag the three inputs.
All inputs are illustrative. Midjourney has not published its job volume or its GPU time per job.
Count jobs, not images. One job makes four images, so 2.4 million images is 600,000 jobs. If you count images as jobs, every later number is four times too big.
Failure. The symptom is a plan that is off by a factor of 3 or 4. Measure λ per minute from the gateway log and S from the worker log, for a full week. Fix the plan to the busiest hour of that week, not the daily mean.
Chapter 2
Follow one job through the layers, and count how many jobs are open at once
A GPU dies four seconds into your job. In a design that holds the request open, the user gets an error. In a design that stores the job, a second GPU picks it up and the user waits a little longer. The difference is where the job lives.
The design has six layers. Each layer does one thing and talks to the next through the job record.
| Layer | Job | Grows with |
|---|---|---|
| Client | Discord bot or web app: take the prompt, show the result | users |
| Gateway | check the user, the limits, the prompt; create the job | requests |
| Queue | hold jobs in priority lanes until a GPU is free | jobs waiting |
| GPU workers | run the model, send progress | GPU-seconds |
| Storage | keep images and job metadata | all images ever made |
| Delivery | CDN and message edits that push the result | views |
The job moves through five states: received, queued, processing, uploading, done. A worker that holds a job sends a heartbeat, a small "still alive" message, every few seconds. If the heartbeats stop, the job goes back to queued.
Press Play to send a job. Press "Kill the GPU" while it is processing. Compare the two designs.
The layers and states are a standard design for long-running jobs, not Midjourney's published design. Stage times are illustrative.
How many jobs are open at once? Call the average time a job spends in the system, from received to done, W. Call the number of open jobs L.
L equals lambda times W.
If lambda jobs come in each second and each stays W seconds, then lambda times W jobs are inside at any moment. This is Little's law. It holds for any queue that is stable.
With made-up numbers: at the peak λ = 20.8 jobs/s and W = 12 s (8 s of GPU plus 4 s of the rest). L = 20.8 × 12 = 250 open jobs.
So the job table holds about 250 live rows at the peak. That is small. The hard part is not the count. It is that each row must survive a crash of any layer.
Failure. The symptom is jobs stuck in "processing" for minutes. Measure the age of the oldest job in each state. The fix is a heartbeat timeout that returns stale jobs to the queue, with a seed so the re-run draws the same images.
Chapter 3
Order the checks so that the cheapest one throws out the most work before a GPU sees it
A GPU-second is the most expensive thing in the building. A database lookup costs a millisecond of CPU. So the gateway, the service that turns a request into a job, runs its checks from cheapest to dearest. Each check can reject the request before the next one runs.
--ar 16:9) and check each value.Every gateway copy must share one concurrency count. If two copies each read "2 open jobs" for a user with a limit of 3, both accept, and the user runs 4. An atomic counter in one store, such as Redis INCR, fixes that.
Red is GPU time spent on images nobody will see. Drag the share of prompts the policy blocks, then switch where the text filter runs.
Illustrative: 600,000 jobs a day, 8 s of GPU each, $2.50 per GPU-hour. Midjourney has not published its block rate. The image check after the GPU stays in both designs, because some harmless prompts make images that break policy.
Worked number: if 2% of prompts break policy, that is 0.02 × 600,000 = 12,000 jobs a day. At 8 s each, that is 96,000 GPU-seconds, or 26.7 GPU-hours a day. A text filter on a CPU removes all of it before the queue.
Failure. The symptom is GPU time that grows faster than delivered images. Measure the share of finished jobs that the image check rejects, per prompt category. If one category dominates, move a rule for it into the text filter.
Chapter 4
See the wait blow up as one GPU nears full, then split the queue so paying jobs skip the line
Start with one GPU and one line. Jobs arrive at random. If the GPU is busy 80% of the time, how long does a new job wait? Not 0.8 of a job. Much longer, because random arrivals bunch up.
Call the share of time the GPU is busy the busy share, ρ (rho): here ρ = λ × S for one GPU. Call the average time a job waits before it starts Wq. For one server with random arrivals and random service times (the M/M/1 queue):
W-q equals S times rho, divided by one minus rho.
Divide the busy share rho by the idle share one minus rho. Multiply by the service time S. As rho nears 1, the idle share nears 0, and the wait grows without limit.
With S = 8 s: at ρ = 0.8, Wq = 8 × 0.8 / 0.2 = 32 s. At ρ = 0.9, 8 × 0.9 / 0.1 = 72 s. At ρ = 0.95, 152 s. Ten more points of busy cost two more minutes of wait.
Now add tiers. Midjourney's docs describe three speed modes: Fast draws on the plan's monthly GPU time, Turbo runs faster and costs double the GPU time, and Relax does not use the allowance but waits in a queue. In a design like this, each mode is a lane: a separate queue, and the dispatcher always takes from the highest non-empty lane.
Add a burst of Relax jobs, then a Fast job. In one line the Fast job waits behind the burst. In lanes it goes next.
The three mode names and Turbo's double GPU cost are from Midjourney's docs. The lane dispatcher, the four GPUs and the job times (8 s, and 4 s for Turbo) are illustrative and run at four times real speed.
Lanes give each tier its own busy share. If paying lanes use 60% of the fleet, a Fast job sees a lightly loaded system, even when Relax jobs pile up. Relax soaks up the rest.
Failure. The symptom is a Relax lane that never drains: starvation. Measure the age of the oldest Relax job. The fix is aging (a job gains priority as it waits) or a reserved share of GPUs for Relax.
Chapter 5
Find the fewest GPUs that keep the wait under a target, and see why one big pool beats two small ones
One GPU at 90% busy makes jobs wait 72 s. A fleet of 185 GPUs at 90% busy makes them wait 0.05 s. Same busy share. The difference is that a job in a big fleet only waits if every GPU is busy at once, and that is rare.
The tool for many servers is the Erlang C formula. It uses the offered load a = λ × S from Chapter 1 and the number of GPUs c. First it gives C, the chance that an arriving job finds all c GPUs busy. Then it gives the mean wait.
W-q equals C of c and a, times S, divided by c minus a.
Take the share of jobs that must wait, C. A waiting job waits for the first of the spare GPUs to free up, about S divided by c minus a. Multiply the two to get the average over all jobs.
With made-up numbers from Chapter 1: a = 166.7 at the peak, S = 8 s, c = 180. Erlang C gives C = 0.221. Wq = 0.221 × 8 / 13.3 = 0.13 s. So 22% of jobs wait, and the average wait is 0.13 s.
C(c, a) = B / (1 − ρ + ρ × B), with ρ = a / c
B is the Erlang B blocking chance. Start at B = 1 and repeat for k = 1 to c: B = a × B / (k + a × B). The loop avoids huge factorials. The script in Chapter 10 does exactly this.
The curve is the mean wait for each fleet size. The green dot is the smallest fleet under the target. Split the pool and watch it move right.
Illustrative inputs. "Two pools" sends half the jobs to each half of the fleet, as when each GPU keeps only one model version loaded. Erlang C treats service times as random; real diffusion jobs are close to fixed, so true waits are lower.
Split the pool to see pooling. One pool of 180 GPUs: 22% of jobs wait, 0.13 s on average. Two pools of 90, each with half the load: 37% wait, 0.44 s on average. Same GPUs, same jobs, three times the wait, because one pool can lend idle GPUs to the other's burst.
Failure. The symptom is a fleet that looks half idle on the dashboard while users wait. Measure the wait per pool, not per fleet. If one model version's pool is hot and another's is cold, let workers swap weights, or route more versions to each worker.
Chapter 6
Count the operations in one image, then see what a batch of four buys and what it costs
Where does S = 8 s come from? Midjourney does not publish its model, so take an illustrative diffusion transformer (DiT): a transformer that denoises an image cut into patches. A 1024 × 1024 image becomes a 128 × 128 latent grid; its 2 × 2 patches make 4,096 tokens.
A transformer does about two operations per weight per token in one pass. Call the weights N, the tokens T and the denoising steps K. The operations for one image are F:
F is about two times N times T times K.
Each of the T tokens meets each of the N weights once per pass, for a multiply and an add. Repeat the pass K times.
With made-up numbers: F = 2 × 3×109 × 4,096 × 30 = 7.4×1014 per image, so 2.9×1015 for a grid of four. That is about 3 petaops: "thousands of trillions", as Holz said, a little under his lowest guess of five. Attention adds about a fifth more at this size.
NVIDIA rates the H100 near 989 trillion operations per second (dense, 16-bit). At an assumed 40% of that, the grid takes 2.9×1015 / 3.96×1014 = 7.4 s. The text encoder and image decoder bring S to about 8 s.
Why four images per job? Prompt encoding, queueing and delivery run once per job. Call that fixed cost t0 and the time per image t1. A batch of b images takes t(b):
t of b equals t-zero plus b times t-one.
Pay t-zero once. Then pay t-one for every image. Divide t of b by b to get the time per image.
With made-up numbers: t(1) = 1.0 + 1.75 = 2.75 s per image. t(4) = 1.0 + 7.0 = 8.0 s, or 2.0 s per image. The batch gives 1.375 times more images per GPU-second, and the user waits 8.0 s instead of 2.75 s.
Blue is time per image; yellow is how long the user waits for the job. Drag the batch size and the steps.
Illustrative: t0 = 1.0 s, t1 = 1.75 s at 30 steps, and t1 scales with the step count. At 4,096 tokens the GPU is already busy with one image, so the batch gain is modest.
Failure. The symptom is jobs that crash at large sizes: the GPU runs out of memory. Measure peak memory per job by batch and aspect ratio. The fix: the dispatcher reads a memory table and sends a 2K job to a worker with room.
Chapter 7
Put the archive, the CDN and the GPUs on one bill, and watch which line keeps climbing
The worker finishes. Four images sit in GPU memory. It encodes them, writes them to object storage (a store of files by key, such as Google Cloud Storage), saves the job's metadata in a database, and hands the user a URL. A CDN, a set of caches near the users, serves the views.
With made-up numbers: 2.4 million images a day at 2 MB each is 4.8 TB a day. Users keep their history, so you delete nothing. After a year the archive holds 4.8 × 365 = 1,752 TB.
Purple bars are bytes; the blue bar is the GPU fleet for scale. Drag the months and the CDN hit rate.
Illustrative prices: storage $0.02 per GB-month, CDN delivery $0.02 per GB, origin egress $0.08 per GB, GPUs $2.50 per hour for 180 GPUs. Users view each image 3 times. Real contract prices are lower and differ by provider.
Worked numbers at 12 months: storage holds 1,752 TB at $0.02 per GB, so $35,040 a month. Views move 14.4 TB a day; the CDN serves it for $8,640 a month, and with an 80% hit rate the origin sends 2.88 TB a day for $6,912. The GPUs cost $324,000 a month. GPUs dominate; among the rest, storage is the line that never stops growing.
Two design choices follow. Move old images to colder, cheaper storage classes by age, since most views come in the first hour. And serve through signed URLs that expire, so other sites cannot hotlink your egress bill.
Failure. The symptom is a storage bill that rises every month while traffic is flat. Measure bytes by age bucket. The fix is a lifecycle rule that moves objects older than 30 days to a cold class.
Chapter 8
Break each layer and see which failures users notice and which they never see
A GPU fails on step 21 of 30. What should the user see? A short delay, and then their image. That is possible only if the job is idempotent: running it twice gives the same result and does no harm. A stored seed makes the images the same; a job id makes the upload and the message edit safe to repeat.
Worked number, made up: the GPU dies 70% into an 8 s job, at 5.6 s. The heartbeat timeout is 10 s. A free GPU reruns the job in 8 s. The image lands at 5.6 + 10 + 8 = 23.6 s instead of 8 s. The user waits 15.6 s more and sees no error.
Press a layer's button to break it. Press it again to repair it. The read-out says what users see.
The effects follow from the design in Chapter 2. They are not Midjourney's incident history.
| What breaks | What users see | The defence |
|---|---|---|
| One GPU | a few seconds of delay | heartbeat timeout, re-queue, seed |
| A GPU that fails again and again | many delays | a circuit breaker: after 3 failures in 10 minutes, take the GPU out of the pool |
| Storage writes | a late result | retry with backoff; keep the job in uploading |
| Moderation service | no new results | stop; never ship unchecked images |
| Discord | no Discord replies | queue the edits; the web app keeps working |
The table has one row where the right answer is to stop. If the image check is down, the system must refuse to deliver. A late image is a delay; an unchecked one is a harm.
Failures also come at a rate. With made-up numbers, if each GPU fails once per 1,000 hours, a fleet of 180 sees 180 × 24 / 1,000 = 4.3 failures a day. That is weather, not an incident.
Failure. The symptom is a retry storm: a bad worker takes jobs, fails them, and takes more. Measure failures per worker per hour. The circuit breaker is the fix.
Chapter 9
Price one grid from the GPU-hour, and see how a low-priority lane cuts it in half
A fleet sized for the evening peak is mostly idle at 4 am. You pay for every hour anyway. So the true cost of a job is its GPU time divided by the share of paid hours that do useful work.
Call the price of one GPU-hour p, the GPU time per job S in seconds, and the fleet's average busy share u: busy GPU-hours divided by paid GPU-hours. The cost per job k:
k equals p times S, divided by thirty-six hundred times u.
Turn the price per hour into a price per useful second: divide p by 3600 times u. Multiply by the S seconds the job uses.
With made-up numbers: 1,333 busy GPU-hours a day on 180 GPUs is u = 1,333 / 4,320 = 0.31. Then k = 2.50 × 8 / (3600 × 0.31) = $0.018 a grid. Fill idle hours to u = 0.70 and k = $0.0079.
This is what a Relax-style lane does in a design like this. It accepts work that can wait, and runs it in the hours the peak leaves idle. The fleet is the same size. The paid hours do more work, so every job costs less.
The curve is GPUs busy over one day; the dark area is idle paid time. Turn on the low-priority lane, then move the price. Each job takes 8 s of GPU.
Illustrative: a smooth daily curve with a 3× evening peak, 180 GPUs, and a low-priority lane that lifts the busy share to 0.70. Midjourney has not published its busy share or GPU prices.
| Choice | You gain | You pay |
|---|---|---|
| Discord bot first | accounts, chat, mobile apps and sharing on day one | the 3-second rule, its rate limits, an outage you cannot fix |
| Async jobs | crash safety, retries, any wait length | a job store, a state machine, push delivery |
| Priority lanes | fast paid jobs, a cheap way to fill idle hours | starvation risk for low lanes |
| One big pool | shorter waits for the same GPUs | weight swaps when versions mix |
| Batch of four | 1.4× more images per GPU-second here | a longer wait for the first image |
One public fact fits this picture. In a 2023 Google Cloud press release, Holz said Midjourney trained "on the v4 TPUs with JAX" and ran "inference on huge clusters of GPUs". Training and serving were separate fleets with separate jobs.
Failure. The symptom is a cost per image that rises while prices are flat. Measure u per hour of the day. If nights are idle, add or grow a low-priority lane; if the peak is short, rent burst capacity for it.
Chapter 10
Keep the numbers, the checklist and the code for the next service you design
An image service is a queue in front of GPUs. Accept fast and store the job. Size the fleet to the peak with Erlang C. Keep one big pool. Fill the valleys with work that can wait. Make every job safe to run twice.
| Term | Meaning | Worked value (illustrative) |
|---|---|---|
| λ, arrival rate | jobs per second | 6.94 average, 20.8 peak |
| S, service time | GPU seconds per job | 8 s for a grid of four |
| a = λ × S | offered load, GPUs busy | 55.6 average, 167 peak |
| L = λ × W | open jobs (Little's law) | 250 at W = 12 s |
| M/M/1 wait | S × ρ / (1 − ρ) | 72 s at ρ = 0.9 |
| Erlang C wait | C × S / (c − a) | 0.13 s at c = 180 |
| F ≈ 2NTK | operations per image | 7.4×1014; 2.9×1015 per grid |
| t(b) = t0 + b t1 | batch time | 8.0 s for 4; 1.375× throughput |
| k = pS / 3600u | cost per job | $0.018 at u = 0.31; $0.0079 at 0.70 |
| Discord limits | first response; edit token life | 3 s; 15 min (Discord docs) |
pythondef erlang_c(c, a): # c GPUs, a erlangs of offered load if a >= c: return 1.0 # the queue never drains B = 1.0 for k in range(1, c + 1): # Erlang B by recursion: no factorials B = a * B / (k + a * B) rho = a / c return B / (1 - rho + rho * B) # chance an arriving job must wait def fleet_for(lam, S, target_wait): # jobs/s, GPU-s per job, seconds a, c = lam * S, int(lam * S) + 1 while erlang_c(c, a) * S / (c - a) > target_wait: c += 1 return c def worker_loop(queue, gpu, store, deliver): while True: job = queue.claim(lanes=["turbo", "fast", "relax"], lease_s=10) # highest lane first with queue.heartbeat(job): # lease renews while we work imgs = gpu.generate(job.prompt, seed=job.seed, batch=4) # [4, 3, H, W] if not image_check(imgs): queue.fail(job, "policy"); continue urls = store.put(f"{job.id}/", imgs) # keyed by job id: a rerun overwrites deliver.edit(job.reply_to, urls) # same edit twice is harmless queue.done(job) print(fleet_for(20.8, 8, 1.0)) # 172 GPUs for a 1 s mean wait
Now press Present or Teach and explain from memory: why the job is async, how a = λS becomes a fleet size, why one big pool waits less, and what the busy share does to the cost of an image. Then go back to the hero and find the busy level where 10 GPUs stop keeping up.
Stated by Midjourney or a platform it uses: David Holz in The Register, 2022 (operations per image); the Google Cloud press release, 2023 (TPU v4 and JAX for training, GPU clusters for inference); Midjourney's docs (Fast, Relax and Turbo modes); Discord's interaction docs (3 s, type 5, 15 min). Every other number on this page is an illustrative design value, worked by script.