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.

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.

- 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.
- Send asynchronously. One call per row renders every format, at a pace the rate limit accepts.
- Render. The API renders each format. A format that fails is listed with its reason; the others still render.
- Receive. A webhook reports the files. Your receiver checks the signature, answers fast and ignores repeats.
- 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 laterBoth 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-Afteris 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 asAbyssaleRateLimitErrorwith itsretry_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.
waitForGenerationRequestandwait_for_generation_requestpoll 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.
import abyssale from '@abyssale/sdk'; // reads ABYSSALE_API_KEYconst { data, error } = await abyssale.generateMultiFormatMedia('{designId}', {file_name: 'KT-1001-{format_name}',elements: {headline: { payload: 'RUN THE TRAIL.' },price: { payload: '$140' },},});if (error) console.error(error.id, error.message);else await jobs.markSent('KT-1001', data.generation_request_id); // jobs: your own job table
from abyssale import Abyssale # reads ABYSSALE_API_KEYwith Abyssale() as client:accepted = client.generate_multi_format_media("{designId}", {"file_name": "KT-1001-{format_name}","elements": {"headline": {"payload": "RUN THE TRAIL."},"price": {"payload": "$140"},},})jobs.mark_sent("KT-1001", accepted.generation_request_id) # jobs: your own job table
curl -X POST https://api.abyssale.com/async/banner-builder/{designId}/generate \-H "x-api-key: $ABYSSALE_API_KEY" \-H "Content-Type: application/json" \-d '{"file_name": "KT-1001-{format_name}","elements": {"headline": { "payload": "RUN THE TRAIL." },"price": { "payload": "$140" }}}'
{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
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-Ideach time. Store the ids you have handled and answer 200 to a repeat without doing the work twice.
import express from 'express';import { verifyWebhookSignature } from '@abyssale/sdk/webhooks'; // needs no API keyconst app = express();app.post('/webhooks/abyssale', express.raw({ type: 'application/json' }), async (req, res) => {const ok = verifyWebhookSignature({body: req.body, // the raw bytes, before any parsingheader: req.headers['x-abyssale-signature'],secret: process.env.ABYSSALE_SIGNING_SECRET,});if (!ok) return res.sendStatus(401);// seen: your table of handled delivery ids; add() returns false for a repeatconst isNew = await seen.add(req.headers['x-abyssale-delivery-id']);res.sendStatus(200); // answer first, work afterif (!isNew) return; // a repeat: already handledconst event = JSON.parse(req.body);// work: your background job queue, for the slow partif (event.event_type === 'NEW_BANNER_BATCH') await work.push('store-files', event);});app.listen(3000);
import json, osfrom flask import Flask, requestfrom abyssale.webhooks import verify_webhook_signature # standard library only, no API keyapp = Flask(__name__)@app.post("/webhooks/abyssale")def abyssale_webhook():if not verify_webhook_signature(request.get_data(), # the raw bytes, exactly as receivedrequest.headers.get("X-Abyssale-Signature"),os.environ["ABYSSALE_SIGNING_SECRET"],):return "", 401# seen: your table of handled delivery ids; add() returns False for a repeatif seen.add(request.headers.get("X-Abyssale-Delivery-Id")):event = json.loads(request.get_data())if event.get("event_type") == "NEW_BANNER_BATCH":work.push("store-files", event) # work: your background job queuereturn "", 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.
import { createHash } from 'node:crypto';// Sort object keys so the same values always give the same hashconst canonical = (v) => Array.isArray(v) ? v.map(canonical): v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical(v[k])])): v;const cacheKey = (designId, revision, format, elements) =>createHash('sha256').update(JSON.stringify(canonical([designId, revision, format, elements]))).digest('hex');
import hashlib, jsondef cache_key(design_id, revision, fmt, elements):# sort_keys: the same values always give the same JSON, so the same hashraw = json.dumps([design_id, revision, fmt, elements], sort_keys=True, separators=(",", ":"), ensure_ascii=False)return hashlib.sha256(raw.encode()).hexdigest()
# jq -S sorts the keys, -j drops the newline, then the JSON is hashedjq -jcS --arg d "$DESIGN_ID" --arg r "$REVISION" --arg f "$FORMAT" '[$d, $r, $f, .]' elements.json \| 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 creditsmeans 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.





