Short answer: Keep the generated image as a durable intermediate artifact, then retry object storage as a separate Node.js queue step with capped jitter and Retry-After support. A 429 rate limit from the upload side must never send a game product image back through generation.
The deciding constraint is large-file throughput: retries should move existing bytes, not spend generation capacity recreating them.
For a one-person SaaS that ships weekly, this boundary matters more than clever queue configuration. It turns an ambiguous job into two explicit outcomes: the image exists, and the tenant-owned object is committed. Each can fail without erasing the other.
How should a Node.js image pipeline retry a 429 rate limit?
A single queue handler often generates an image, uploads it, and marks the job complete. It looks economical. Then the object store responds with 429 Too Many Requests after generation succeeds. Retrying the whole handler calls the generator again. The first bytes may be lost, the next image may differ, and one catalog item has consumed two generation attempts.
That is a workflow bug, not a backoff bug.
It is easy to miss.
HTTP defines 429 as a rate-limiting response, and the server may include Retry-After. That header can be either a delay in seconds or an HTTP date. Honor a valid value while capping waits to an operational limit. When it is absent or invalid, exponential backoff with jitter prevents every worker from waking at the same instant.
The queue payload should carry identity, not image bytes: tenant ID, product ID, generation attempt ID, and a durable staging reference. Large binary payloads inflate queue storage and serialization work. More importantly, they obscure who owns cleanup.
The smallest workflow I would ship
I use three states: generating, staged, and committed. The transition to staged happens only after the exact generated bytes and their checksum are durably recorded. Upload retries start there. The destination key is deterministic, scoped by tenant, and derived from an immutable asset ID rather than a display filename.
type StagedAsset = {
tenantId: string;
assetId: string;
productId: string;
sourcePath: string;
sha256: string;
contentType: string;
byteLength: number;
};
type UploadResult =
| { kind: "committed"; objectKey: string }
| { kind: "retry"; delayMs: number; reason: string };
interface ObjectWriter {
put(input: {
key: string;
sourcePath: string;
contentType: string;
sha256: string;
}): Promise<{ status: number; retryAfter?: string }>;
}
const MAX_DELAY_MS = 15 * 60_000;
function retryDelayMs(
retryAfter: string | undefined,
attempt: number,
nowMs: number,
): number {
if (retryAfter) {
const seconds = Number(retryAfter);
const parsedMs = Number.isFinite(seconds)
? seconds * 1_000
: Date.parse(retryAfter) - nowMs;
if (Number.isFinite(parsedMs) && parsedMs >= 0) {
return Math.min(parsedMs, MAX_DELAY_MS);
}
}
const ceiling = Math.min(1_000 * 2 ** attempt, MAX_DELAY_MS);
return Math.floor(Math.random() * ceiling);
}
async function uploadStagedAsset(
asset: StagedAsset,
attempt: number,
writer: ObjectWriter,
nowMs = Date.now(),
): Promise<UploadResult> {
const objectKey = `tenants/${asset.tenantId}/products/${asset.productId}/${asset.assetId}`;
const response = await writer.put({
key: objectKey,
sourcePath: asset.sourcePath,
contentType: asset.contentType,
sha256: asset.sha256,
});
if (response.status >= 200 && response.status < 300) {
return { kind: "committed", objectKey };
}
if (response.status === 429) {
return {
kind: "retry",
delayMs: retryDelayMs(response.retryAfter, attempt, nowMs),
reason: "storage_rate_limited",
};
}
throw new Error(`Non-retryable upload response: ${response.status}`);
}
The tenant prefix never comes from user input. Authorization happens before a worker receives the staged record. A database uniqueness constraint on (tenant_id, asset_id) gives the application one logical asset, while the deterministic object key makes repeated attempts converge on the same destination.
There is a subtle edge. A connection can fail after storage accepted the bytes but before the worker received the response. The next attempt cannot know whether the prior write committed. Reusing the same key is essential. After an uncertain result, verify destination metadata or checksum before declaring success; never create a fresh key merely because the attempt number changed.
This design has a real limitation: durable staging creates another copy to retain, secure, observe, and eventually delete. For small, reproducible thumbnails where regeneration is explicitly acceptable, staging may add more operational state than it removes. For large generated product art, or any output that cannot be reproduced byte for byte, losing the artifact is the worse trade. I make that decision per asset class rather than pretending one workflow fits every file.
Backoff is admission control, not a timer trick
Retries still compete with new uploads. If every delayed job returns at once, jitter merely moves the spike. Cap active upload concurrency per tenant and globally, then let the queue schedule retries outside worker slots. Sleeping inside a worker wastes capacity during the exact period when throughput is constrained.
My initial configuration would be deliberately boring: a one-second exponential base, full jitter, a 15-minute delay cap, and a finite attempt budget. Those are operating parameters, not universal facts. Tune them from the observed 429 rate, Retry-After values, upload latency, object size distribution, and queue age. Generation needs a separate concurrency budget, so a storage slowdown cannot consume every generation worker.
This is where the revenue-per-hour lens helps. Building a novel scheduler does not improve a game catalog. A queue with delayed delivery, bounded attempts, and per-key concurrency is enough; outsource that undifferentiated machinery and keep the workflow contract in application code.
Track transitions rather than vague job failures. Useful fields include tenant_id, asset_id, stage, attempt, bytes, status, retry_delay_ms, and a correlation ID. Avoid filenames and signed URLs in logs. Alert on the age of the oldest staged asset and the count exhausting its upload budget. A raw 429 count can rise during a brief throttle while every asset still completes within its target window.
Tenant-scoped export comes after commitment
The export worker should read only committed asset rows for one authorized tenant. It should stream objects into an archive instead of loading a catalog into memory. That keeps memory bounded as product images grow, and it stops a staged or quarantined file from leaking into an export.
Use a snapshot boundary. Record an export ID and cutoff time, select the committed asset versions visible at that boundary, then write a manifest containing object key, byte length, media type, and checksum. If an export retry occurs, rebuild from that same manifest. Otherwise, products edited midway through the run can produce an archive whose contents disagree with its metadata.
For the download response, Content-Disposition: attachment signals a download, and a quoted filename plus RFC 5987-style filename* can provide an ASCII fallback and a UTF-8 name. Treat the filename as presentation. Tenant authorization must come from the authenticated export record, never from a path or requested archive name.
Do not hold the whole archive. Stream.
Slow exports are visible to users. Memory exhaustion is worse.
What I would change at scale
At modest volume, a durable local staging volume can be acceptable if a job is pinned to the node that owns it and node loss fits the recovery model. Once workers autoscale or files outlive a deployment, staging needs shared durability. That may be a separate object namespace with lifecycle cleanup, but the contract stays the same: generation writes once, upload retries read many times, and cleanup follows a confirmed terminal state.
For very large files, resumable or multipart transfer can reduce the bytes repeated after a broken connection. It also adds state: upload session IDs, completed part records, abort handling, and stale-session cleanup. I would add it only after object-size and failure telemetry shows whole-file retries hurting throughput. Complexity has rent.
Security requirements can alter the boundary. Encrypt transport, restrict object credentials to tenant-scoped prefixes where the platform permits it, and define retention for staging files and exports. If the workload has a government authorization requirement, evaluate the complete system boundary and current authorization status through the FedRAMP program rather than treating a storage feature as proof of compliance.
The final test matrix is compact but sharp: a 429 with delta-seconds, a 429 with an HTTP date, malformed Retry-After, success followed by a lost response, process death after staging, duplicate delivery, tenant-key tampering, checksum mismatch, and an export retry after a product changes. I also test two large tenant exports alongside fresh uploads. The pass condition is bounded memory and fair progress, not pretty average latency.
The rule is plain: generated bytes are an asset, not temporary control flow. Persist them before crossing the upload boundary, make commitment idempotent, and let measured pressure govern concurrency. That preserves weekly shipping speed without turning every throttle into another generation bill or a duplicate catalog image.
References
- https://www.rfc-editor.org/rfc/rfc6585#section-4
- https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Disposition
- https://www.rfc-editor.org/rfc/rfc5987
- https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- https://www.fedramp.gov/
Top comments (0)