Batch image optimization: one bad file does not stop the batch
A batch call returns one result per image and charges only the images that succeed. Tests cover a mixed batch, an all-failed batch and a refused internal URL.
A batch call returns one result for each image, in the order you sent them. A bad file gets status: "failed" and an error code, and the other images still come back. You pay only for the images that succeed. If every image fails, the job ends as failed and nothing is charged.
Batch jobs are where one error costs the most. Send 200 product photos, let one of them be a corrupt file, and a client that stops at the first error loses 199 good results and starts the run again. This post covers what the batch endpoint returns, which error codes you will see, what gets billed, and how to write a client that keeps the files that worked.
The image routes have 32 gateway tests, and they pass. The client below was tested against a local stub. We did not call the live API for this article.
One request, one result per image
Send a list of images, one options object that applies to all of them, and per_image_options for the exceptions:
{
"images": [
{ "url": "https://example.com/photos/front.jpg", "ref": "front" },
{ "url": "https://example.com/photos/side.heic", "ref": "side" }
],
"options": { "width": 1600, "format": "webp", "quality": 76 },
"per_image_options": { "side": { "width": 2400 } },
"idempotency_key": "order-4471-photos"
}
Each image is { "url": ... } or { "file_id": ... }. A batch does not accept base64. ref is your identifier. If you leave it out, the position in the list is used, so send your own. One request takes up to 250 images. Up to 25 get their answer in the same request. Above 25, or with "mode": "async", the call returns 202, and you read the result from GET /v1/jobs/{id} or from a webhook.
The results array comes back in the same order as the ref values you sent. Each item has these fields:
| Field | When it appears | What it means |
|---|---|---|
ref |
Always | The identifier you sent |
status |
Always | ok or failed |
url, expires_at |
ok |
A signed download link and the time it stops working |
bytes, content_type, width, height |
ok |
The size and type of the output |
error.code, error.message |
failed |
Why this image failed |
The response also has a summary with total, succeeded and failed, and a billing object with the amount charged.
The error codes you will see
| Code | What caused it in our tests | What to do |
|---|---|---|
invalid_source |
An address on the internal network, http://169.254.169.254/. The URL never reaches the worker. |
Check that every URL is public. Do not retry it. |
unsupported_format |
The worker reported that the file is not an image. | Open the file on your computer. If it opens, check the format. Otherwise send another file. |
processing_failed |
A corrupt file. | Open the file on your computer. Send another file. |
file_not_found |
A file_id that belongs to another account. |
Check the id. Files belong to the account that uploaded them. |
What gets billed
The API reserves credit for every image when the job starts. It then settles only the images that succeed.
In our test, four images went in. Two succeeded. One was an internal URL, and one was a file the worker could not read. The reservation covered all four. The charge covered two, and only those two outputs were stored.
If every image fails, the job ends as failed, nothing is settled, and no output is kept.
Per-image options
per_image_options changes one image and leaves the rest of the batch alone. In our test, the batch set width to 1200 and quality to 76. One image had its own width of 2400. That image kept quality 76 and took the wider width.
A client that keeps the good files
The client below sends a batch of up to 25 images. It checks the response before it writes anything. The refs must come back in the order you sent them, the total must match your count, and each download must have the size the API reported. Outputs go into one folder. Failures go into failed.json, with the code and the message.
It does not retry. Each failure code points at the file or the URL, so sending the same thing again gets the same answer. Fix the file, then send it in a new batch with a new key.
The key goes in the body as idempotency_key, and you should use one key per batch. The idempotency guide explains what a repeated request does. Download each output before its expires_at. The download expiry guide explains the window.
// batch-client.mjs ยท Node 22, no dependencies
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
const API = process.env.JUSTAPI_BASE ?? 'https://api.justapi.tech';
const KEY = process.env.JUSTAPI_KEY;
const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp' };
/**
* Sends up to 25 images in one request, saves the outputs that worked and
* writes the failures to failed.json. Throws if the response does not match
* what was sent, before any file is written.
*/
export async function optimizeBatch(images, options, { idempotencyKey, outDir }) {
if (images.length > 25) {
throw new Error('more than 25 images: send mode "async" and read GET /v1/jobs/{id}');
}
for (const image of images) {
// Refs become file names, so keep them to letters, digits, dash and underscore.
if (!/^[A-Za-z0-9_-]{1,64}$/.test(image.ref ?? '')) throw new Error(`bad ref: ${image.ref}`);
}
const res = await fetch(`${API}/v1/image/batch`, {
method: 'POST',
headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ images, options, idempotency_key: idempotencyKey }),
});
if (!res.ok) throw new Error(`batch failed with HTTP ${res.status}: ${await res.text()}`);
const body = await res.json();
// Results come back in the order you sent them. Check before you write anything.
const sent = images.map((image) => image.ref);
const got = body.results.map((result) => result.ref);
if (got.length !== sent.length || got.some((ref, i) => ref !== sent[i])) {
throw new Error('results do not match the refs you sent');
}
if (body.summary.total !== sent.length) {
throw new Error('summary total does not match the request');
}
await mkdir(outDir, { recursive: true });
const failed = [];
for (const result of body.results) {
if (result.status !== 'ok') {
failed.push({ ref: result.ref, code: result.error.code, message: result.error.message });
continue;
}
const file = await fetch(result.url); // signed link, no key needed; valid until expires_at
if (!file.ok) throw new Error(`download failed for ${result.ref}: HTTP ${file.status}`);
const bytes = Buffer.from(await file.arrayBuffer());
if (bytes.length !== result.bytes) throw new Error(`size mismatch for ${result.ref}`);
const ext = EXT[result.content_type];
if (!ext) throw new Error(`unexpected type ${result.content_type} for ${result.ref}`);
await writeFile(join(outDir, `${result.ref}.${ext}`), bytes);
}
await writeFile(join(outDir, 'failed.json'), JSON.stringify(failed, null, 2));
return { succeeded: body.summary.succeeded, charged_micros: body.billing.charged_micros, failed };
}
What we ran
- The gateway test file for image routes.
vitest run src/routes/image.test.tspassed all 32 tests. These tests run the routes with a mocked worker and a mocked ledger. The batch cases cover the mixed batch above, the all-failed batch, the internal URL and afile_idfrom another account. - The client. It ran against a local stub that returns the response shape above. Five cases passed. A mixed batch wrote two files and one failure record. Results out of order stopped the run. A summary that did not match the request stopped the run. Twenty-six images were refused before any request was sent. A ref with
../was refused. - No live call. We did not call the live API for this article. Run the client once on a small batch with your own key before a large run.
Limits to plan for
- Up to 250 images per request. Above 25, the call becomes asynchronous.
- On the single-image route, an image over 50 MB is rejected before the job starts.
- For
file_idsources, the original is deleted after processing unless you sendkeep_source: true. - Rate limits and concurrent jobs depend on your plan. See rate limits and concurrency by plan.
Before you ship
- Use your own ids as
ref, and keep a map from eachrefto your record. - Treat
failedas data. Write it to a queue or a report, and let the run finish. - Download each output inside its
expires_atwindow. - Compare
summary.totalwith the number of images you sent. - Open a few outputs before you trust a large batch.
For more on the batch endpoint, read 250 photos in one API call and responsive image sizes in one batch. For the format choice, read WebP output from an image API.
To try it, start free. New accounts get 1 USD of credit.