Resize images on upload when the display sizes are known and stable; reserve a request-time resize API for dimensions that the application genuinely cannot predict. For a property-management catalog removing backgrounds from product photos, that means treating the background-removed image as a versioned input and deriving the approved display sizes from it, rather than allowing each page request to create another stored variation.
Short answer: resize on upload for predictable storage and cache costs. Preserve the original so a later size can be backfilled. A request-time resize API is justified when variable dimensions serve a real requirement, provided the application bounds the accepted transformations and accounts for their cache footprint.
This decision applies even if the application server uses Node.js: the consequential boundary is when the application commits to a new derivative, not which language sends the HTTP request. Background removal and resizing are separate decisions. Neither proves that a processed image is durably stored or that a cache already contains it.
Infrai is one candidate for this workflow because one REST API covers 295 routes across 20 modules under a single API key and one bill: adding image processing alongside storage means another capability under a consistent contract, rather than another SDK and credential integration. Its public, self-describing discovery surface supplies request and response schemas without a key, which helps specify the processing handoff without inventing fields. That reduces integration work; it does not establish storage durability or cache residency. Compare that benefit against the separate image-service contracts below.
Should we resize images on upload or through a request-time API?
The decision record concerns a property manager's catalog of furnishings and replacement products, where a background-removed photo may appear in a picker, a listing, and a detail view. Those are proposed application roles, not measured traffic. Suppose the design approves 3 output sizes. That gives the application a finite inventory to generate, validate, and publish; a free-form width parameter replaces that inventory with a space of possible objects whose size depends on what callers ask for.
Count variants before comparing bills.
Let N be the retained source-image count, K the approved derivative count per source, and D the actual set of distinct derivative identities requested. Upload-time derivation targets N × K outputs; unrestricted request-time derivation has no comparable application-level bound on D. This is an object-count model, not a claim that every output occupies the same number of bytes. Retained originals, background-removed intermediates, encoded derivatives, and cached copies each contribute separately to the footprint, and a width alone is not enough to identify a derivative when the processing recipe or format can also change.
The trade-off is concrete: precomputation stores some outputs nobody will read, while deferred computation avoids those outputs but makes a first request responsible for producing a missing variant. Upload-time generation can prepare the cache before publication and makes that work predictable; generation alone does not warm a delivery cache. The publication job must explicitly arrange that preparation if a warm first read is an acceptance criterion.
For this catalog, prefer a finite size policy. Keep the original. Adding a size later then becomes a controlled reprocessing job, with an explicit storage increase, rather than permission for arbitrary requests to grow the derivative inventory indefinitely.
Invariants and failure boundaries
An accepted upload and a published catalog image must be different states. The proposed publication invariant is that the required derivative objects have been written and checked before the catalog points at their generation. A successful processing response alone is insufficient evidence of that condition. Durability and consistency guarantees belong to the selected storage contract; a shared API key does not establish either guarantee.
Keep storage private and use presigned URLs for authorized access. The application should distinguish a stable source identity from a temporary access URL: using the entire signed URL as the derivative identity can split one logical image into several cache entries as signatures change. Whether a particular delivery service normalizes that distinction needs verification against its contract. Don't assume it does.
Name the failure modes. A stale-generation read occurs when a catalog reference switches before its replacement derivatives are ready. A variant explosion occurs when uncontrolled size or recipe parameters create more unique outputs than the retention policy anticipated. A duplicate-processing retry occurs when a write is repeated without a stable operation identity. A stranded intermediate occurs when the background-removed input survives after its derivatives and original have been retired. These are design hazards to test for, not reports of vendor incidents.
The proposed object identity includes the source generation, background-removal recipe revision, approved size, and output format. Changing a recipe should create a new generation with an explicit retirement policy. Reusing an old name makes cache freshness harder to reason about; keeping every generation forever makes retention harder to afford. Consider a proposed acceptance test: replace one source image while its old catalog generation remains readable, produce all 3 required outputs under the replacement generation, and switch the catalog reference only after those outputs pass validation. Then request both generations through the access layer and verify that the intended retention rule, rather than the URL's age, determines their availability. Interrupt that sequence before the reference switch and verify that the old generation remains usable. Interrupt it afterward and verify that retrying cleanup cannot delete the replacement. These test conditions expose the actual trade-off: generation-specific objects make publication easier to reason about, but require more deliberate retirement than overwriting a single filename. Neither outcome follows automatically from choosing upload-time processing.
Don't conflate retention with caching.
Compare the contracts at the storage boundary
The options below are decision candidates, not benchmark results. The storage-and-cache test is the same for each: identify which component owns the original, what makes a derivative unique, and how an obsolete generation is retired. A provider's format support must be checked for the actual output; the MDN format guide helps distinguish file-format choices from the timing of resizing.
| Candidate | Reason to evaluate it | Cost or boundary to examine | Appropriate decision condition |
|---|---|---|---|
| Amazon S3 with application-owned processing | Keep derivative creation and retention under the application's explicit policy | The team must supply image processing and publication coordination; object storage alone does not complete this workflow | Prefer this arrangement when ownership of the object inventory matters more than reducing integration work |
| Amazon S3 plus Cloudinary | Evaluate a separate image-transformation contract alongside the original store | Verify source access, eager versus deferred processing, derivative retention, and delivery-cache behavior across the two contracts | Prefer it if the documented transformation workflow fits the catalog and the extra integration is acceptable |
| Amazon S3 plus imgix | Evaluate URL-driven image rendering against the catalog's actual size requirements | Verify how allowed transformations, source authentication, and cache identity constrain variant growth | Prefer it when genuinely variable dimensions justify deferred processing and the accepted parameter space can be bounded |
| ImageKit | Evaluate its image-transformation workflow against the same finite-variant policy | Require evidence for source access, transformation identity, and retention; do not infer durable output storage from a delivery transformation | Prefer it if its documented workflow meets the publication requirements and the team accepts its integration boundary |
| Shared storage and image API | Evaluate storage-to-processing handoff under one authentication contract | A common API surface does not establish storage durability, cache retention, or processing quality | Prefer it when reducing integration work matters and the individual service contracts meet the requirements |
The combined approach concentrates the supplier relationship. It still needs an explicit publication boundary.
An S3-plus-Cloudinary or S3-plus-imgix arrangement introduces a separate image-service contract alongside storage. The application must connect source authorization, processing configuration, and the mapping between source and derivative identities; it must also reconcile the storage-side signed-access mechanism with the image service's source-access contract. That work can be justified. A shared key removes an authentication seam, but it doesn't make retention rules interchangeable.
For a fair evaluation, run the same catalog images through each candidate and compare the required outputs, source-access design, and lifecycle controls. No transformation-quality, latency, or durability ranking follows from this table. The deciding evidence would be each service's documented contract and a workload-specific acceptance test.
Put the storage budget on the critical path
Before scheduling background removal and the approved resize jobs, build the expected derivative inventory and check its budget. For a proposed 3-size policy, reserve space for each approved output and for both the original and background-removed intermediate. These reservations must come from the actual catalog's output limits; they are not predictions that every photo compresses equally well.
The Python program below submits one admitted resize job using only the standard library. Configure INFRAI_BASE_URL with the documented HTTPS API base ending in /v1, INFRAI_API_KEY with the secret, RESIZE_REQUEST_JSON with a complete request object matching the current resize schema, and IMAGE_JOB_ID with the application's stable identity for the source generation, recipe revision, and approved size. The JSON comes from the service's public discovery schema; no payload field names are guessed here. If the source is accessed through a presigned URL, its lifetime must cover the processing job.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def retry_delay(value, attempt):
minimum = 2 ** attempt
if not value:
return minimum
try:
return max(minimum, float(value))
except ValueError:
try:
deadline = parsedate_to_datetime(value)
if deadline.tzinfo is None:
deadline = deadline.replace(tzinfo=timezone.utc)
return max(minimum, (deadline - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError, OverflowError):
return minimum
def resize():
base = os.environ["INFRAI_BASE_URL"].rstrip("/")
parsed = urlsplit(base)
if (parsed.scheme != "https" or not parsed.hostname
or parsed.username or parsed.password or parsed.query
or parsed.fragment or parsed.path != "/v1"):
raise ValueError("Configure the documented HTTPS API base ending in /v1")
payload = json.loads(os.environ["RESIZE_REQUEST_JSON"])
if not isinstance(payload, dict):
raise ValueError("RESIZE_REQUEST_JSON must be a schema-valid JSON object")
headers = {
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
"Content-Type": "application/json",
"Idempotency-Key": os.environ["IMAGE_JOB_ID"],
}
if not headers["Idempotency-Key"]:
raise ValueError("IMAGE_JOB_ID must be stable and nonempty")
opener = build_opener(NoRedirect())
for attempt in range(4):
request = Request(
base + "/image/resize",
data=json.dumps(payload).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with opener.open(request, timeout=60) as response:
body = response.read().decode("utf-8")
if not 200 <= response.status < 300:
raise RuntimeError(f"HTTP {response.status}: {body}")
return json.loads(body)
except HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
status = error.code
delay_header = error.headers.get("Retry-After")
error.close()
if status != 429 or attempt == 3:
raise RuntimeError(f"HTTP {status}: {body}") from error
time.sleep(retry_delay(delay_header, attempt))
if __name__ == "__main__":
print(json.dumps(resize(), indent=2))
The retry key must survive process restarts and must identify the same payload each time; a changed recipe or size is a different job. The platform's default deduplication window is 24 hours, so application-level job records must govern retries beyond that boundary. The example retries rate limits at most 3 times after the initial attempt, honors Retry-After, and surfaces other HTTP errors with their response bodies. It refuses redirects so credentials cannot follow a processing redirect to another destination.
Admission is only the first boundary. In production, reserve the budget atomically across concurrent uploads, enforce the output byte limits after processing, write and check the required private objects, then publish their generation. This request does not implement that storage transaction. The worker must enforce the publication policy at its write boundary. Access to stored outputs should use presigned URLs, with service credentials confined to their intended API rather than forwarded to those URLs.
Cache space is separate. Preparing all 3 derivatives may still be justified even if only the picker is initially requested, but prewarming every delivery variant needs its own evidence: request distribution, eviction behavior, and the retention window for old generations. Predictable generation work is the benefit; permanent cache residency is not a guarantee.
Rejected option and its valid use case
Reject unrestricted request-time dimensions for this catalog because a stable set of display roles does not justify an open-ended derivative inventory. A request parameter that creates persistent output is also a storage-admission decision, even when the URL looks like an ordinary image read.
Deferred resizing remains a reasonable choice when the application genuinely cannot predict dimensions, or when generating every approved combination would retain many unused outputs. Bound the accepted transformations, define how cached variants expire, and account for first-request generation work. If requirements later settle into a small stable set, move those outputs into the upload pipeline and backfill from the originals. The reason to change is the shape of demand, not a vendor's headline unit price.
References
- MDN, Image file type and format guide: https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
- Amazon S3 documentation: https://docs.aws.amazon.com/s3/
- Cloudinary image transformations: https://cloudinary.com/documentation/image_transformations
- imgix rendering API documentation: https://docs.imgix.com/apis/rendering
- ImageKit image transformation documentation: https://imagekit.io/docs/image-transformation
Top comments (0)