Building a Reliable AI Image Pipeline: Tasks, Failures, and Credit Refunds
Most AI image generators look like a prompt box with a Generate button. That is also how my first version started. But once real users entered the workflow, the difficult problems appeared somewhere else: browser refreshes, external task IDs, reference images, partial failures, credit refunds, private assets, and public artwork moderation. While building Magggic , I learned that an AI image generator is less like a form submission and more like a small distributed job system. This article covers the decisions that made that workflow more reliable. The code samples below are intentionally simplified. The important part is the shape of the workflow, not a specific database or image provider. The prompt box is only the beginning A synchronous prototype is easy to imagine: const images = await provider . generate ( prompt ); return images ; That version works until the request takes a minute, the provider times out, one of four requested images fails, or the user refreshes the page. The production workflow I needed looked more like this: Prompt + references ↓ Create a local queued task ↓ Charge credits with an idempotency key ↓ Submit work to the image provider ↓ Persist every completed output immediately ↓ Finalize the task and refund failed outputs ↓ Keep the result private until the user publishes it The provider request is only one step. The local task is the source of truth for what the user sees. 1. Persist the task before calling the provider The first important decision was to create a generation record before making the external API request. A generation stores the information needed to reconstruct the job: type Generation = { id : string ; userId : string ; idempotencyKey : string ; prompt : string ; referenceImages : string []; model : string ; ratio : string ; resolution : string ; count : number ; cost : number ; status : " queued " | " generating " | " completed " | " failed " ; outputs : string []; providerRequestIds : string []; failureReason : string |