Blog / API, MCP & agents

How to run an image generation API in production

Running an image generation API in production? Queue the calls, take results by signed webhook, and retry and cache so no row renders or bills twice.

Remy LemeunierVP Eng & Co-founder10 min read
Published

Key takeaways

  • To run an image generation API in production, queue one asynchronous request per row and keep several in flight: on Abyssale's API, one worker waiting for each answer reached only 1.6 requests a second.
  • An image generation API in production should report results by signed webhook: the receiver answers within 15 seconds and skips deliveries it has already handled, while polling a whole batch shows results late.
  • In production, an image generation call is never resent blindly: retry only the format that failed, and after a timeout wait for the row's files, found by the key in their file name, or the row is billed twice.
  • Files from an image generation API in production are copied to your own storage when the webhook arrives and cached by Design, format and values, since in our tests the same request returned the same file.
  • Abyssale's official Node.js and Python SDKs run the production side for you: they retry failed reads, never resend a generate call, and verify webhook signatures without an API key.
A queue log of Kinetic rows sent to POST /async/…/generate, three answered with 4 files, next to the Kinetic landscape, square and story ads and a NEW_BANNER_BATCH tag

Five hundred product ads are due before a launch. The first batch runs, then a 429 stops a third of the calls, a webhook arrives twice, and a week later the request ids your code kept answer 410. The render worked every time; the trouble was in the code around the API.

Running an image generation API in production means queuing the requests, taking results by signed webhook, retrying only what failed, and keeping your own copy and cache of the files.

This guide builds that pipeline on Abyssale, a template rendering API where your data fills a design made in advance. How template-based image generation APIs work covers the render itself.

How an image generation API runs in production

An image generation API runs in production as a pipeline of five stages, and only one of them runs at the API. The other four are yours: they decide whether a batch of 500 goes through unnoticed or takes the weekend.

The production pipeline in five stages: your app queues one job per row and sends every format in one asynchronous call, under 10 calls a second; Abyssale renders every format and lists a failed one in errors; your webhook receiver answers 200 within 15 seconds, verifies the signature and skips deliveries already seen; your storage keeps a copy of each file when the webhook arrives. Polling is the fallback between sending and receiving, and a failed format goes back to the queue alone
The five stages, numbered like the sections below. Polling and the retry of a failed format run under them.
  1. Queue the jobs. One job per row of your data, with a key that identifies it. A row already rendered is served from the cache.
  2. Send asynchronously. One call per row renders every format, at a pace the rate limit accepts.
  3. Render. The API renders each format. A format that fails is listed with its reason; the others still render.
  4. Receive. A webhook reports the files. Your receiver checks the signature, answers fast and ignores repeats.
  5. Store. Each file is copied to your own storage, under the job’s key.

We ran this pipeline on our production API in November 2026, against a test Design for Kinetic, a fictional sportswear brand, with four formats. The first run sent 50 rows, the second 20 rows with ten requests in flight. The numbers below come from those two runs.

The Node.js and Python SDKs

Our official SDKs, @abyssale/sdk for Node.js and abyssale for Python, cover the stages your code runs: sending, receiving and the polling fallback. Every sample in this guide uses them.

npm install @abyssale/sdk   # Node.js 20.3 or later
pip install abyssale        # Python 3.10 or later

Both read your key from ABYSSALE_API_KEY, and both are built for the failures this guide covers:

  • Retries that never bill twice. A failed read is retried after 1, 2 and 4 seconds, and a Retry-After is honored. A generate call is never retried for you, because a second call is a second render (Node.js SDK).
  • Errors you can branch on. The Node.js SDK never throws on an HTTP error: each method returns { data, error, response }. The Python SDK raises typed errors, such as AbyssaleRateLimitError with its retry_after (Python SDK).
  • A receiver that holds no key. Signature checks come from a separate import that loads no client, so the webhook server cannot spend credits.
  • Polling built in. waitForGenerationRequest and wait_for_generation_request poll one request with a growing interval, for scripts and tests.

Send requests from a queue

Send one asynchronous request per row, and let the request render every format. On our API, an asynchronous call without template_format_names renders every format of the Design, so a row is one call whether the campaign has two sizes or ten.

The call answers at once with a generation_request_id; the files come later. Put the job’s key in file_name: it comes back in each file’s file.filename, so any result can be traced to its row, even one whose request id you never recorded.

  1. import abyssale from '@abyssale/sdk'; // reads ABYSSALE_API_KEY
  2. const { data, error } = await abyssale.generateMultiFormatMedia('{designId}', {
  3. file_name: 'KT-1001-{format_name}',
  4. elements: {
  5. headline: { payload: 'RUN THE TRAIL.' },
  6. price: { payload: '$140' },
  7. },
  8. });
  9. if (error) console.error(error.id, error.message);
  10. else await jobs.markSent('KT-1001', data.generation_request_id); // jobs: your own job table
  1. from abyssale import Abyssale # reads ABYSSALE_API_KEY
  2. with Abyssale() as client:
  3. accepted = client.generate_multi_format_media("{designId}", {
  4. "file_name": "KT-1001-{format_name}",
  5. "elements": {
  6. "headline": {"payload": "RUN THE TRAIL."},
  7. "price": {"payload": "$140"},
  8. },
  9. })
  10. jobs.mark_sent("KT-1001", accepted.generation_request_id) # jobs: your own job table
  1. curl -X POST https://api.abyssale.com/async/banner-builder/{designId}/generate \
  2. -H "x-api-key: $ABYSSALE_API_KEY" \
  3. -H "Content-Type: application/json" \
  4. -d '{
  5. "file_name": "KT-1001-{format_name}",
  6. "elements": {
  7. "headline": { "payload": "RUN THE TRAIL." },
  8. "price": { "payload": "$140" }
  9. }
  10. }'

{format_name} is filled in by the API, so row KT-1001 comes back as KT-1001-landscape.png, KT-1001-square.png and so on.

Pace and concurrency

Our API accepts 10 requests per second per workspace, across every endpoint (rate limits). A worker that waits for each answer never gets near that ceiling. In our first run, one worker sent the 50 rows in 31.2 seconds, about 1.6 a second, because each call took about 650 ms to be accepted.

1.6 a second

The pace one worker reached when it waited for each answer before sending the next row, far under the ceiling of 10.Source: Abyssale production API, 26 November 2026

So run several workers, and pace them together. In our second run, ten requests in flight were each accepted as fast as one alone, in 634 ms at the median, and none was refused. The ceiling counts polls and reads too, so keep some headroom below 10. The loop below starts at most eight calls a second across all workers:

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let nextStart = 0;
// One start every 125 ms, shared by all workers
const slot = async () => {
  const wait = Math.max(0, nextStart - Date.now());
  nextStart = Math.max(nextStart, Date.now()) + 125;
  await sleep(wait);
};

// jobs is your own job table (a database table, one row per job); queue holds the jobs still to send
async function worker(queue) {
  for (let job; (job = queue.shift()); ) {
    await slot();
    const { data, error, response } = await abyssale.generateMultiFormatMedia(job.designId, job.body);
    if (!error) { await jobs.markSent(job.key, data.generation_request_id); continue; }
    if (/credits/i.test(error.message ?? '')) return jobs.stopBatch('out of credits');
    if (response?.status === 429) {              // refused: nothing rendered
      await sleep(1000 * Number(response.headers.get('retry-after') ?? 1));
      queue.push(job);
    } else if (!response || response.status >= 500) {
      await jobs.markUnknown(job.key);           // it may have rendered
    } else {
      await jobs.markFailed(job.key, error);     // a 400 or 404
    }
  }
}

await Promise.all(Array.from({ length: 8 }, () => worker(queue)));

A refused request still counts against the limit, so a loop that retries a 429 at once only digs deeper. Wait for Retry-After when it is there, a second when it is not. A 429 that says Not enough credits is not a pace problem: stop the batch.

Receive results by webhook

A webhook tells you when a request’s files are ready, so nothing in your system waits or polls. When an asynchronous request completes, our API sends a NEW_BANNER_BATCH event with the request’s generation_request_id, each file in banners and each failed format in errors (banner events).

There are two ways to receive it. A webhook set up in the dashboard receives every batch of the workspace. A callback_url in the request body sends that one request’s event to that address. Both are retried. They differ when your receiver stays down: a dashboard webhook can be switched off, while a callback_url delivery that keeps failing is simply lost. Either way, the reconciliation job below finds what never arrived.

Three rules make a receiver safe:

  • Verify the signature. Once your workspace has a signing secret, every delivery carries X-Abyssale-Signature, an HMAC-SHA256 of the raw body and a timestamp. Hash the bytes exactly as received, before any JSON parsing (signature verification).
  • Answer within 15 seconds. Anything other than a 200 or 201 in time counts as a failure. Acknowledge first, then hand the work to your own queue.
  • Skip repeats. A failed delivery is sent again, up to six attempts over about three hours, with the same X-Abyssale-Delivery-Id each time. Store the ids you have handled and answer 200 to a repeat without doing the work twice.
  1. import express from 'express';
  2. import { verifyWebhookSignature } from '@abyssale/sdk/webhooks'; // needs no API key
  3. const app = express();
  4. app.post('/webhooks/abyssale', express.raw({ type: 'application/json' }), async (req, res) => {
  5. const ok = verifyWebhookSignature({
  6. body: req.body, // the raw bytes, before any parsing
  7. header: req.headers['x-abyssale-signature'],
  8. secret: process.env.ABYSSALE_SIGNING_SECRET,
  9. });
  10. if (!ok) return res.sendStatus(401);
  11. // seen: your table of handled delivery ids; add() returns false for a repeat
  12. const isNew = await seen.add(req.headers['x-abyssale-delivery-id']);
  13. res.sendStatus(200); // answer first, work after
  14. if (!isNew) return; // a repeat: already handled
  15. const event = JSON.parse(req.body);
  16. // work: your background job queue, for the slow part
  17. if (event.event_type === 'NEW_BANNER_BATCH') await work.push('store-files', event);
  18. });
  19. app.listen(3000);
  1. import json, os
  2. from flask import Flask, request
  3. from abyssale.webhooks import verify_webhook_signature # standard library only, no API key
  4. app = Flask(__name__)
  5. @app.post("/webhooks/abyssale")
  6. def abyssale_webhook():
  7. if not verify_webhook_signature(
  8. request.get_data(), # the raw bytes, exactly as received
  9. request.headers.get("X-Abyssale-Signature"),
  10. os.environ["ABYSSALE_SIGNING_SECRET"],
  11. ):
  12. return "", 401
  13. # seen: your table of handled delivery ids; add() returns False for a repeat
  14. if seen.add(request.headers.get("X-Abyssale-Delivery-Id")):
  15. event = json.loads(request.get_data())
  16. if event.get("event_type") == "NEW_BANNER_BATCH":
  17. work.push("store-files", event) # work: your background job queue
  18. return "", 200

The secret comes from GET /signing-secret; the first call creates it, and that switches signing on for the whole workspace. Ignore event types you do not recognize: new ones may be added.

Polling as the fallback

Polling GET /generation-request/{id} answers 202 while the request runs and 200 with is_finalized: true once it is done. It suits a script or a receiver that is down, not a whole batch. Polls have their own budget of 600 a minute, inside the 10 a second ceiling. The SDKs’ polling helpers do this for one request.

Our first run shows the cost. It polled 50 open requests in turn, one poll every half second. Seen that way, the median request finished 26.9 seconds after it was sent. A single request on its own had finished in 5.4 seconds, so the delay came from waiting for a turn in the loop. A webhook arrives when the request completes, whatever the size of the batch.

Retry without paying twice

An image generation call that failed should be retried for what failed, and only that. A template render fails for a reason in the data, so the same data sent again fails again, and a call resent after a timeout may render the whole row a second time. Our API documents no idempotency key for generate calls, so making a retry safe is the client’s job.

What happened What you see What to do
One format failed that format listed in errors, with its reason; the other files are there fix the input, then resend the row for that format alone
The call was refused a 429 wait, then resend: nothing rendered
The call timed out or got a 5xx no request id wait for the row’s files by webhook, matched on their file names; resend only if none come
The call was rejected a 400 or 404, such as an unknown format fix the data or the format name; resending never helps

An unreachable image or a text that cannot fit its box are the usual format failures. To resend one format, set template_format_names to that format alone. The reason names the layer to fix, as in Element text_title error: The text cannot fit…. Failed generations cost no credit, so the retry of one format costs one.

The timeout is the trap. A 504 does not mean nothing rendered, which is why the SDKs never retry a POST for you. The job key in file_name is what makes the wait safe: when the files of KT-1001 arrive, the job is done, whatever request id produced them. Pick how long to wait before resending, and accept that a resend after that window may bill the row twice.

Store and cache the files

Your pipeline should copy every file to its own storage when the webhook arrives, under the job’s key. A generation request answers 410 generation_request_gone after seven days, and the CDN URLs we return have bandwidth limits by plan, so your copy is the one to serve.

The cache goes in front of the API. A template render follows the Design, so the same request should return the same file, a check how template-based image generation APIs work puts to the test. So a row that comes back unchanged, a nightly feed where most prices did not move, needs no render at all.

Key the cache on what changes the output: the Design, a revision number you bump when the Design changes, the format and the values. The SDKs have no cache helper, so the key is yours to build.

  1. import { createHash } from 'node:crypto';
  2. // Sort object keys so the same values always give the same hash
  3. const canonical = (v) => Array.isArray(v) ? v.map(canonical)
  4. : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical(v[k])]))
  5. : v;
  6. const cacheKey = (designId, revision, format, elements) =>
  7. createHash('sha256').update(JSON.stringify(canonical([designId, revision, format, elements]))).digest('hex');
  1. import hashlib, json
  2. def cache_key(design_id, revision, fmt, elements):
  3. # sort_keys: the same values always give the same JSON, so the same hash
  4. raw = json.dumps([design_id, revision, fmt, elements], sort_keys=True, separators=(",", ":"), ensure_ascii=False)
  5. return hashlib.sha256(raw.encode()).hexdigest()
  1. # jq -S sorts the keys, -j drops the newline, then the JSON is hashed
  2. jq -jcS --arg d "$DESIGN_ID" --arg r "$REVISION" --arg f "$FORMAT" '[$d, $r, $f, .]' elements.json \
  3. | shasum -a 256 | cut -d ' ' -f 1

Before a row is queued, look up its key for each format. Formats with a stored file are skipped; the others go into template_format_names.

Two caches on our side help too. Image URLs we have already fetched are cached, so a logo or a product photo used by a thousand rows is downloaded once. And for an image shown in a page or an email, a render link puts the values in the URL and renders each unique set once.

Control cost and watch the pipeline

On Abyssale’s API, a static format costs one generation credit, so a row costs as many credits as it has formats (credits). Our two runs cost 280 credits, one per file. Failed generations, polls and reads are free.

Check the balance before a batch with GET /credits, and stop when it cannot cover rows × formats. Then watch four numbers:

  • Failure rate by format. A rise on one format points to the data or to a Design change, rarely to the API.
  • Webhook lag. The time from send to webhook. When results stop arriving, check your receiver first.
  • 429s by kind. A refusal at the ceiling means slow down; one whose message says Not enough credits means stop.
  • Open requests. Requests sent with no result after your window, for the reconciliation job.

To build this pipeline, start with one Design, your longest row and a webhook receiver on a test URL, then a small batch. The Abyssale API is on the Pro plan and above, and the 14-day trial includes it, with 30 generation credits: seven rows of four formats. Choosing between APIs is covered in creative automation platforms with an API compared.

Share this article