Reliable clients do four things: classify the failure, retry only when recovery is plausible, make write operations safe to repeat, and record every attempt under one logical operation. A blanket “retry three times” rule is not enough.
Image workflows are especially exposed to ambiguous outcomes. Uploads are large, transformations can be asynchronous, and a connection may close after the provider accepted a request but before your client received the response.
Classify before you retry
Start with error classes that map to an action.
- Request invalid: Unsupported format, bad crop, or missing field. Fail and fix the request.
- Unauthorized: Expired signature, invalid credential, or forbidden asset. Fail; refresh authorization only when appropriate.
- Conflict: Duplicate public ID, stale version, or an operation already completed. Inspect the current resource state.
- Rate limited: Provider quota or burst limit. Wait according to provider guidance and reduce concurrency.
- Temporary provider failure: A 502, 503, 504, or transient processing error. Use a bounded retry with backoff and jitter.
- Network ambiguity: Timeout, connection reset, or lost response. Look up operation state before repeating a write.
- Permanent processing failure: Corrupt source, unsupported decode, or moderation rejection. Fail to a visible recovery or review state.
Do not retry validation or authorization failures unchanged. It adds load while hiding a deterministic problem. Do not immediately retry every rate limit response in parallel; that can extend the incident.
Cloudinary’s upload documentation advises reducing concurrency and using exponential backoff when an account is rate limited. Provider-specific status codes and headers vary, so make the mapping configurable rather than assuming every API uses the same response.
HTTP method semantics are the starting point
The HTTP semantics specification defines idempotent methods as methods whose intended effect is the same after one or several identical requests. It also cautions clients against automatically retrying a non-idempotent request unless they know the request semantics are idempotent or know the original request was not applied.
That means:
- retrying a
GETfor asset metadata is usually straightforward; - retrying a versioned
PUTmay be safe when the contract defines replacement idempotently; - retrying a
POSTupload can create duplicate assets unless the operation has another identity; - retrying a delete may be operationally safe even if the second response is “not found,” but your client must define the desired final state.
The method alone is not the whole contract. Read the provider’s guarantees.
Give every logical write an operation identity
An idempotency key identifies the application action, not a single HTTP attempt.
logical operation: upload order-847 product-front image
operation_id: imgop_01J...
attempt 1 → timeout
attempt 2 → same operation_id
lookup → same operation_id
webhook → same operation_id
Store the operation record before making the remote call. Include the tenant, user, purpose, expected source checksum when available, provider, current state, and provider asset ID once known.
If the provider supports an idempotency key, send the same key on every attempt. If it does not, use a deterministic provider identifier or query by your external operation ID before repeating the write. A checksum can help detect duplicate content, but it may not capture the distinction between two legitimate uses of the same file.
Resolve ambiguous completion
The hardest case is not a clean 500 response. It is a timeout after the server may have committed the operation.
Use this recovery order:
- mark the local operation
unknown, notfailed; - query the provider by idempotency key, external ID, or deterministic asset ID;
- if the resource exists and matches the intended request, record success;
- if the provider confirms no operation, retry within the remaining budget;
- if state cannot be determined, stop automatic retries and move the operation to reconciliation.
Creating another upload immediately is the wrong default. It trades a temporary uncertainty for permanent duplicates and cost.
Use bounded exponential backoff with jitter
For recoverable errors, space attempts so the dependency can recover and clients do not synchronize into another spike.
A practical policy has:
- a small first delay;
- exponential growth between attempts;
- random jitter;
- a maximum delay;
- a maximum attempt count or total elapsed-time budget;
- support for a valid provider
Retry-Afterinstruction; - cancellation when the caller no longer needs the result.
Pseudo-code:
deadline = now + 30 seconds
for attempt in 1..5:
result = call_image_api(operation_id)
if result.success: return result
if not result.retryable: raise result.error
if result.write_is_ambiguous:
reconcile(operation_id)
delay = provider_retry_after ?? jittered_exponential(attempt)
if now + delay > deadline: break
wait(delay)
raise retry_budget_exhausted
Retries need a budget at every layer. If an HTTP library, SDK, queue worker, and job orchestrator each retry independently, a single logical operation can multiply into dozens of calls. Choose one owner for each retry boundary and expose attempt counts in telemetry.
Separate upload, processing, and delivery states
Do not represent the whole image lifecycle with one success boolean.
Useful states include:
authorization_created
upload_in_progress
original_accepted
processing_pending
ready
rejected
retry_wait
reconciliation_required
failed_permanent
An original can be accepted while a requested derivative fails. Preserve the successful stage and retry only the failed work. A delivery request can temporarily fail while the source and derivative remain valid.
This state model produces better user interfaces too. “Still processing,” “upload expired,” and “source rejected” each suggest a different next action.
Trace one operation across every attempt
Generate a correlation or trace ID before the first remote request. Carry it through:
- the application request;
- upload authorization;
- provider call;
- queue message;
- webhook handler;
- transformation job;
- asset database update;
- delivery verification.
The OpenTelemetry HTTP semantic conventions define common attributes for HTTP spans, metrics, and logs. Follow your instrumentation library’s stable convention version rather than inventing conflicting field names.
Record safe, useful attributes:
- operation and attempt number;
- provider and endpoint category;
- HTTP method and status code;
- timeout phase and retry reason;
- asset purpose and media type;
- byte count and decoded dimensions where known;
- queue wait and processing duration;
- provider request ID;
- final outcome and reconciliation path.
Do not record API secrets, signatures, bearer tokens, full signed URLs, private asset URLs, or raw personal metadata.
Metrics should reveal user impact and dependency health
Track both the operation and each attempt.
Operation metrics answer:
- What percentage of uploads become ready?
- How long does the complete workflow take?
- How many operations require user action or reconciliation?
- How often do we create duplicate assets?
Attempt metrics answer:
- Which status codes and timeout phases are increasing?
- How many attempts does a successful operation require?
- Which endpoints or regions are slow?
- Are rate limits caused by burst concurrency?
Useful service-level indicators include successful logical operations, time to ready, webhook age, transformation failure rate, delivery 4xx/5xx rate, and reconciliation backlog. Alert on a sustained user-impacting condition, not every individual retry.
Test the failures you intend to handle
Create repeatable tests for:
- connection closed before request bytes finish;
- provider accepts the upload but the response is lost;
- signature expires between authorization and transfer;
- rate limit with and without a delay hint;
- temporary 5xx response followed by success;
- webhook delivered twice and out of order;
- transformation fails while the original remains valid;
- worker restarts after the remote call but before the local commit;
- retry budget expires;
- reconciliation finds an asset with mismatched parameters.
Assert final state, number of provider calls, duplicate count, telemetry, and user-visible status. A retry test that only checks “eventually returned 200” is incomplete.
A compact production policy
Use this default until the provider contract demands a stricter one:
- Treat validation and permission failures as permanent for that request.
- Retry rate limits and temporary dependency failures with bounded, jittered backoff.
- Respect documented delay instructions.
- Never automatically repeat an ambiguous write without an idempotency or reconciliation strategy.
- Keep one logical operation ID across attempts, jobs, and webhooks.
- Preserve successful workflow stages.
- Stop at a defined deadline and expose a recoverable state.
- Measure logical outcomes separately from HTTP attempts.
The result is not a client that retries more often. It is a system that knows when retrying is safe, proves what happened, and gives operators a controlled way out when the answer is uncertain.
Read the image API architecture guide for the resource model, and secure direct uploads for the trust boundary where idempotent upload operations begin.
