Designing a Video Generation Backend: From Request to Result

15 min read0 views

How a video generation request travels from the API through BullMQ to a ComfyUI worker and into S3-compatible storage.

System Design

Running an open-source model is one problem. Putting it behind a product is another. I've also documented my journey building a product around local-first, open-source models. This post covers the second problem for a different kind of workload: media generation, where a single request can occupy a GPU for minutes.

I'll follow one video generation request from the moment a user submits a prompt to the moment the file reaches them. The building blocks are ComfyUI for inference, BullMQ on Redis as the queue, and S3-compatible storage (Cloudflare R2) for results.

Requirements

Before any tooling, write the requirements down. I assume video generation with MiniMax H3, and two answers shape everything after them:

  1. How long does one generation take?
  2. How long can a user wait? This sets how much quality we can trade for speed.

Resolution, clip length and audio are the settings you mix and match until those two answers fit.

These answers also drive the model and GPU choice. H3 comes in several formats, from the full model to quantized and GGUF versions, and each trades quality for a lighter load. The goal is the smallest one that still gives good results for your requirements.

Memory planning has to count more than the diffusion model, because the VAE and the text encoders take VRAM too. As an example, a main model of 20+ GB next to components that add another 20 GB rules out a 32 GB card if everything is loaded at once.

I'm writing a separate post on how to choose. The rest of this post needs only two numbers from that choice: the VRAM one job takes and the time one generation takes. On my setup those are 48 GB of VRAM and 400 to 500 seconds. Model load can be ignored for now, because a pod only uses one diffusion model and it is cached after the first load. Bringing up a new pod is a different matter, and I come back to it in the section on scaling.

Why the system needs a queue

On my setup a generation takes 400 to 500 seconds. I plan around 400 seconds, which comes from the initial benchmark and is also the figure we used to calculate cost and profit. The moving parts around the generation, mainly I/O, add more. The 30 seconds I allow for them is a worst case for upserting records and uploading the result, so I settle on about 430 seconds per request. The slow end of the range is closer to 530 seconds, so lock and acknowledgment settings should be sized for that and not for the average.

That duration settles the first design question. A request that takes about seven minutes cannot stay open as a normal HTTP call. Connections time out, users close tabs, and a dropped connection would lose the job. So the API has to accept the request, answer right away with the generation marked as queued, and do the work in the background.

Two more requirements apply to this pipeline:

  1. Every generation ends with either a result or a clear error. If a component fails in the middle of a generation, the system retries it up to N times (in my case, 3), then fails the generation.
  2. A big batch of requests makes each job wait longer for its result. That is expected, but the system must keep working under it.

Together, these point to a queue. A queue holds a job while the generations ahead of it finish, and it can hand a job to another worker when one fails. I used BullMQ on Redis because it is easy to set up and we already had Redis available. This part can be swapped for another queue, as long as it offers locking, redelivery when a worker disappears, and acknowledgment after the work is done.

One request, end to end

Request lifecycle from API to result

Here is the path of one request:

  1. The user submits a prompt. The backend creates a generation row with status queued and adds a job to the queue.
  2. The backend answers right away, and the user sees the generation as queued.
  3. A worker takes the job. When ComfyUI is free, the worker sets the status to processing and submits the workflow.
  4. ComfyUI generates the video.
  5. The worker uploads the result to storage and sets the status to done.
  6. The worker publishes a status message, and the backend notifies the user.
  7. The worker acknowledges the job.

The sections below cover the decisions behind each step.

The backend

The backend creates the generation row first, then publishes the job. The row is the source of truth for what happened to a request, and the queue only carries work. If Redis loses its data, the queue can be rebuilt from the rows that are still queued.

The two steps can fail separately. If the row is created but the publish fails, the row stays queued with no job behind it. The timeout eventually fails such a row.

The user sees the generation as queued and waits. Since we cannot know how long a generation will take, the flow has to be asynchronous. The backend also polls for status changes. A generation that is not done within X seconds is deemed failed, and we can act on that, for example by refunding the user. X is a configuration value, and I'll come back to how to size it in the section on bursts.

Job state

A generation has four states:

StateMeaningSet by
queuedAccepted, waiting for a workerBackend, when it creates the row
processingComfyUI has started itWorker, when ComfyUI starts processing the job
doneResult uploaded and availableWorker, after the upload
failedGave up, with a clear errorWorker after N attempts, or backend on timeout

Both the backend and the workers can write the state. The backend needs to, because it owns the timeout. The workers need to, because they see failures first. We let workers write to the database directly instead of calling the backend API, to keep the workers decoupled from the backend. A finished generation can be recorded even while the backend is down or being deployed. The cost is that every pod needs database credentials and knows the row's schema.

Two writers means two writers can disagree, so done and failed are final. Updates are conditional: set done only if the row is currently processing, and never change a row that is already done or failed. This stops a late worker from overwriting a timeout, and the other way around.

The allowed moves are queued to processing, processing to done or failed, and processing back to queued for a retry.

The row also holds an attempt counter, and N is the maximum number of attempts. Crash recovery counts toward the same limit as ordinary failures. When a worker is about to start processing a job, it reads the counter. If the counter has already reached N, the worker fails the generation and logs the reason. Otherwise it increments the counter and continues. If the generation then fails, the worker puts the row back to queued and requeues the job. BullMQ tracks stalled jobs and failed attempts as separate settings, so we count on the row instead.

For worker-to-backend status messages, I kept it simple and used the queue. Change data capture, where the backend watches the row for changes, would also work.

There is redundancy here: the backend polls for status changes, and the workers also send messages to the backend. That is deliberate, and it makes the system more reliable. As long as the final states are final, a missed message or a missed poll does no harm.

Workers and ComfyUI

A worker runs on the same machine as ComfyUI. In practice that is a pod with a GPU. The worker talks to ComfyUI through its API on a port that is only open inside the pod.

Putting the worker next to ComfyUI gives us control over how the GPU is used. For example, the worker can run a scheduler that checks ComfyUI's health at a set interval and restarts it if it stopped halfway through. We check every 5 seconds, and if ComfyUI does not respond after 5 tries, we restart it. The interrupted job is retried, so a hung ComfyUI does not leave a job stuck.

ComfyUI runs one inference at a time, so a pod gets one worker. The exception is splitting the GPU between two ComfyUI instances on one machine. I have not tried it, so I don't know yet whether it is possible.

When a worker receives a job, it does this:

  1. Check the generation status. If the generation is already done or failed, skip the job and acknowledge it.
  2. Wait until ComfyUI is free, then set the status to processing and tell the backend so it can notify the user.
  3. Submit the workflow to ComfyUI and wait for the result.
  4. Check the status again. If the generation failed in the meantime, for example from a timeout, discard the result.
  5. Upload the result, set the status to done, and publish a message.
  6. Acknowledge the job.

The worker claims the job when it takes it, but acknowledges only after the upload and the status update are finished. BullMQ locks an active job to the worker that took it, and the worker keeps renewing that lock while it runs. That is what keeps two workers from running the same job.

Keeping the GPU busy

A GPU that waits on an upload is wasted money. To avoid that, the worker separates the ComfyUI step from the I/O step. When one generation finishes, the next one starts right away, and the upload and status update of the previous one finish in the background. A semaphore around the ComfyUI call makes sure only one generation runs at a time, and the worker takes the next job before it acknowledges the last.

This has a cost. Each pod can hold one extra job that has been claimed but has not started. Its status stays queued until the semaphore frees up, so the user never sees processing for a job that has not started. During a burst, a pod you just added may find an empty queue while busy pods hold jobs that are waiting. The gain is also limited by how much of your time is I/O. If I/O is about 30 seconds of 430, the best case is around 7 percent of GPU time. I think the trade is worth it.

Delivering the result

Result paths are standardized, for example /output/{userid}/{generationid}.mp4. The worker uploads to that key, and the backend knows where to look without asking anyone.

That lets the backend poll two things: the generation status and the storage path. If the file is there and valid, the backend can send it, even when the status still says processing. This covers the case where the upload worked but the status update did not. Because the key comes from the generation ID, a retry writes to the same path.

How the result reaches the browser, whether through SSE, a WebSocket or a plain GET to the backend, is a separate choice that does not change this design.

When things go wrong

A worker dies mid-job

The worker stops renewing its lock. BullMQ detects the stalled job and, within its stall limit, makes it available to another worker. Check your version's defaults for the stall limit and lock duration, because the documented default allows only one stall. The status check at the start of the worker's routine makes a second run harmless if the first one actually finished.

A result arrives after the generation failed

Say the backend times out a generation and refunds it, then the worker finishes anyway. The worker's second status check discards the result. The conditional update closes the remaining gap: if the timeout lands while the worker is uploading, the worker's done write is rejected because the row is already failed. If the file still ends up in storage, we ignore it. We still record the output path, so a cleanup job can delete the file later.

The upload worked but the status update did not

The file is in storage and the row says processing. The backend poller finds the file at the standardized path, validates it, and delivers it.

A message gets lost

A worker can update the row and then fail to publish its status message. The row is the truth, the message is only a hint, and polling is the safety net. A lost message delays the notification, but it does not lose the result.

Bursts and scaling

When a burst arrives, the queue gets longer and every job waits longer. The system gets slower but does not break, as long as the timeout is larger than the worst-case wait.

The worst-case wait for the last job is roughly the number of jobs ahead of it times the time per job, divided by the number of pods. I use 430 seconds as a conservative time per job. Rearranged, a timeout can absorb about (timeout divided by time per job) times the number of pods in queued jobs before the oldest one starts to fail. As an example, a 2-hour timeout and 430-second jobs give about 16 jobs for a single pod. If the timeout is shorter than the worst-case wait, a burst turns into failures and refunds, which breaks the second requirement. That is why I benchmark and plan this early.

So when do we scale? Compare the time to bring a new pod online with the timeout. In my case a new pod takes 60 to 80 minutes: installing ComfyUI and its requirements, downloading the model, VAE, text encoders and LoRAs, setting up the worker, and a final test. With a 120-minute timeout, that leaves 40 to 60 minutes of queue we can afford while the new pod comes up. On one pod at 430 seconds per job, that is roughly 5 to 8 queued jobs.

In general, scale when the queue reaches about the number of pods times (timeout minus bring-up time) divided by time per job.

Operating it

A drain and undrain setting is worth having from the start. When you want to upgrade a worker, drain it first so it stops taking new jobs. It finishes what it has, you upgrade it, and then you undrain it. It is also useful for stopping a faulty worker or pod from taking more jobs. For example, if you run 5 workers and one keeps running out of memory, drain that pod and investigate without causing more failed generations.

Monitoring and results

Record the I/O time, the generation time and the total time of every generation, and plan improvements from that data.

GPU usage should be close to 100 percent while a generation runs. The problem is that you cannot be sure a generation is always queued. So measure utilization over the pod's whole lifetime, not just during generations. That shows how much of the capacity you used on each pod, and translates into what you pay for GPUs sitting idle. The target is close to zero.

Here is a worked example with mock numbers. The GPU is busy for the 400 seconds of generation, and the upload of the previous job overlaps with the next generation, so the I/O seconds do not reduce capacity.

MeasureValue
Generation time400 s
Capacity per day216 generations (86,400 ÷ 400)
Daily generations150
Capacity used69.44%
GPU idle share30.56%
Cost per hour$2.50
Idle cost per hour$2.50 × 30.56% ≈ $0.76
Idle cost per month$2.50 × 30.56% × 24 × 30 ≈ $550
Total cost per month$2.50 × 24 × 30 = $1,800
Cost per generation at 150 per day$1,800 ÷ 4,500 = $0.40
Cost per generation at full load$1,800 ÷ 6,480 ≈ $0.28

By this calculation alone, we can see which part of the system to improve. We can bring more users to fully use the capacity, or we can look for a cheaper model that better fits our daily generation projection.

The 60 to 80 minutes of bring-up cuts the other way too. Removing a pod to save idle cost means waiting that long to get it back.

Limitations and what comes next

These parts are not covered yet:

  • Redis restarts. The rows let us rebuild the queue, but I have not written down the recovery steps.
  • Poison jobs. A prompt that crashes ComfyUI every time will use up its attempts and fail. A place to keep such jobs for inspection would help.
  • Dockerization and infrastructure as code, so that adding a pod is a configuration change and not a manual task. If ComfyUI, its dependencies and the models are baked into an image or mounted from shared storage, the 60 to 80 minutes should shrink, and every minute saved raises the queue depth at which we have to scale. We already have the signal for when to scale up and down. The automation comes next.

If you run generation workloads, I'd like to hear how you size your queue timeout and when you add a pod.

Cheers!

Stay Updated

Get notified when I publish new ideas about technology, system design, and human-centered engineering.