Short answer: for a Node.js API that must import supplier images at scale, make the original bytes immutable, deduplicate them by a cryptographic content digest, and create three purpose-specific derivatives behind a manifest-driven batch boundary. For a property catalogue, those derivatives should correspond to the actual viewing contexts: a small search result, a larger listing view, and a high-detail inspection view. Do not repeatedly recompress one derivative into another, and do not let a supplier URL become the image identity.
Bytes first.
This decision puts the quality-versus-bandwidth argument where it belongs: in a versioned policy that can be tested against representative apartment interiors, exterior brickwork, floor plans, and inspection evidence. Node.js can own the intake API and job orchestration; the critical path below is Python because the processing contract matters more than the web framework. The boundary is deliberate.
How should an API import supplier images at scale?
Four invariants define the system. Original bytes are retained without transformation. A digest is computed over those bytes before decoding, so identical inputs converge even when filenames, query strings, or supplier records differ. Every derivative records the source digest and policy version that produced it. Finally, publishing a manifest is atomic from the catalogue reader's point of view: readers see either the previous complete set or the next complete set, never a half-written mixture.
The failure boundaries follow from those invariants. Network fetches can time out, return a non-image body, exceed the intake limit, or change between retries. Decoders can reject malformed input or consume unreasonable resources on hostile dimensions. Encoders can succeed yet produce a file that fails the visual acceptance set. Object writes can complete while the database transaction fails. A queue can deliver a job more than once. None of these cases should corrupt an existing listing.
Retries happen.
There is a less obvious distinction here: byte equality is not visual equality. A digest safely answers “have these exact bytes arrived before?” It does not answer “are these two differently encoded photographs perceptually the same?” Perceptual matching can help reviewers find likely duplicates, but using it as an automatic deletion key risks collapsing distinct exposures, crops, floor-plan revisions, or inspection evidence. Keep that signal advisory unless the business can define an acceptable false-positive rate.
Decision record: content identity before image transformation
The chosen design separates intake, normalization, and publication. Intake streams the response through a byte limit and digest calculation into immutable storage. A decoder then validates the stored object and applies orientation consistently. A versioned policy produces derivatives directly from that original. Workers write results under deterministic keys, while a final coordinator verifies the expected set and advances the listing's manifest pointer.
| Approach | Duplicate handling | Quality and bandwidth control | Failure behavior | Decision |
|---|---|---|---|---|
| Transform during the supplier request | Usually tied to URL or record ID | Fast feedback, but policy and transport are coupled | A slow decode holds the request open; partial work is awkward to resume | Rejected for bulk intake |
| Queue one independent job per output | Source digest can be shared | Each size can be tuned separately | Retries are simple, but publication needs an explicit completeness gate | Valid with a manifest coordinator |
| Queue one job per source and create all outputs | One decode feeds several encodes | Policy stays together and avoids derivative-to-derivative loss | A late failure retries more work; worker resource limits must cover the largest source | Chosen for three bounded derivatives |
| Store originals and transform on every read | Exact-byte dedupe remains possible | Decisions can follow request context | Read latency and cache behavior become part of correctness | Valid for highly variable, low-reuse requests |
Three derivatives are a policy choice, not a universal number. Property search and listing pages have stable layouts and high reuse, while an inspection viewer needs more detail; precomputing those bounded contexts keeps runtime negotiation understandable. If clients later require arbitrary crops or a wide density matrix, the on-read option becomes more credible, provided cache keys include every transformation input and the original remains the source.
This approach has real limits. It is not suitable when each request needs a novel crop, when a catalogue rarely reuses an asset, or when the team cannot operate decoders safely; an on-read transformation service or a separately managed image pipeline can be a better boundary in those cases. The trade-off is predictable reads and finite cache identity in exchange for storage amplification, batch latency, and policy migrations whenever derivative requirements change.
Format selection also belongs in policy. MDN's image-format guide documents broad JPEG support and its suitability for photographs, PNG's lossless behavior, and modern formats such as WebP and AVIF. That does not justify converting every source to the newest codec. Floor plans with thin text and flat regions need different acceptance samples from room photographs, and compatibility requirements come from the actual client population. Measure the whole set.
The critical path is replayable, bounded, and boring
The intake endpoint should return after it has durably recorded the source and work request, not after every derivative exists. HTTP semantics help here: a successful asynchronous acceptance can use 202 Accepted, whose definition explicitly says processing has not been completed and may ultimately fail. The API therefore needs a separate job status representation, but status is not publication; only the manifest pointer tells readers which complete image set is live.
This Python sketch shows the worker contract. It omits transport and storage implementations on purpose. The useful details are the byte cap, digest-derived identity, direct derivation from the original, deterministic keys, and conditional manifest commit.
from dataclasses import dataclass from hashlib import sha256 from io import BytesIO from typing import BinaryIO, Protocol from PIL import Image, ImageOps MAX_SOURCE_BYTES = 40 * 1024 * 1024 POLICY_VERSION = "property-photo-v3" class ObjectStore(Protocol): def put_if_absent(self, key: str, data: bytes) -> None: ... def get(self, key: str) -> bytes: ... @dataclass(frozen=True) class Derivative: name: str max_width: int quality: int DERIVATIVES = ( Derivative("search", 480, 76), Derivative("listing", 1280, 82), Derivative("inspection", 2400, 88), ) def read_bounded(stream: BinaryIO) -> bytes: data = stream.read(MAX_SOURCE_BYTES + 1) if len(data) > MAX_SOURCE_BYTES: raise ValueError("source exceeds the configured byte limit") return data def ingest(stream: BinaryIO, store: ObjectStore) -> str: source = read_bounded(stream) digest = sha256(source).hexdigest() store.put_if_absent(f"original/sha256/{digest}", source) return digest def render(digest: str, store: ObjectStore) -> list[str]: source = store.get(f"original/sha256/{digest}") written = [] with Image.open(BytesIO(source)) as decoded: oriented = ImageOps.exif_transpose(decoded).convert("RGB") for spec in DERIVATIVES: image = oriented.copy() image.thumbnail((spec.max_width, spec.max_width)) output = BytesIO() image.save(output, format="JPEG", quality=spec.quality, optimize=True) key = ( f"derived/{POLICY_VERSION}/{digest}/" f"{spec.name}.jpg" ) store.put_if_absent(key, output.getvalue()) written.append(key) return written The numbers are explicit so they can be reviewed, not copied blindly. A 40 MiB byte ceiling does not constrain decoded pixel count, so production decoding also needs dimension and resource limits appropriate to its image library and worker memory budget. Likewise, the three JPEG quality values are starting policy inputs, not evidence of equivalent visual quality across content or encoders. The acceptance suite decides whether they survive. RFC 9110 defines 202 Accepted as noncommittal: acceptance says that processing has not completed, and it gives no later asynchronous response for the eventual result. That limitation is why the job representation and manifest commit cannot be hand-waved as queue plumbing; they are part of the external correctness contract, especially when a supplier repeats a 10,000-item batch after its own request times out.
The coordinator should expect exactly three keys for this policy, verify their metadata, and then compare-and-swap the manifest from its previously observed version. A retry that reaches put_if_absent is harmless. A superseded supplier batch can finish without becoming visible. This is why batch identity must be separate from listing identity: the listing may receive another batch while the first is still running.
Quality is a release gate, not an encoder argument
A useful acceptance corpus is stratified by content that fails differently: dim bedrooms with shadow gradients, bright windows beside dark interiors, red brick or roof tiles with repeated texture, maps and floor plans with small labels, and inspection close-ups where scratches or damp marks matter. Preserve redistribution rights for that corpus and keep its source digests fixed. Otherwise, a changing test set can make an encoder change look better or worse without the policy changing.
For each proposed policy version, record encoded byte size, dimensions, format, encode duration, and a visual comparison result against the original. Automated metrics can rank suspicious changes, but they cannot define business acceptability alone. A floor-plan label becoming unreadable is more consequential than a small metric improvement elsewhere. Human review should be blind to encoder settings and concentrated on borderline samples, then captured as a release decision rather than an anecdote.
The operating rule is concrete: no policy ships merely because its aggregate bytes fall. It ships when the corpus meets the agreed visual thresholds, critical detail classes have no unacceptable regressions, and the bandwidth distribution improves for the target page contexts. If those conditions conflict, preserve the inspection derivative and seek savings in search results first; a leasing gallery and damage evidence do not have equal loss budgets.
Detail wins.
Observe the pipeline by stage and policy version. Track fetch failures by status class, bytes rejected at intake, decode failures, source dimensions, duplicate-byte rate, encode duration, output-size distributions, retry count, dead-letter count, and time from acceptance to manifest publication. Avoid putting supplier URLs or listing IDs into high-cardinality metric labels. Logs and traces can carry those identifiers under the system's retention and access rules.
Why reject a synchronous normalization API?
It makes the easiest demo and the wrong batch boundary. One request that downloads a supplier asset, decodes it, creates three files, stores them, and updates the catalogue forces the caller to wait across several independently fallible systems. A timeout leaves an ambiguous result: the client does not know whether to retry, while the server may already have written some outputs. Idempotency can reduce the damage, but it does not make a long request a good progress protocol.
Synchronous transformation still has a valid use case. An editorial tool processing one bounded local upload may need immediate preview feedback, and the user is present to resolve a decode error. Keep that path separate from catalogue bulk import, apply the same source and dimension limits, and publish only through the same manifest rule.
That exception matters.
Batch orchestration has its own trap: “batch complete” cannot mean that the queue is empty. Workers may be retrying, delayed, or processing a newer batch. Completion is a database fact derived from the batch manifest: every declared source is in a terminal state, every successful source has the required derivative set for the recorded policy, and the allowed failure threshold has been evaluated. Failed sources should retain machine-readable reasons so an operator can distinguish a transient fetch failure from an unsupported or malformed file.
Backpressure belongs at intake. Bound supplier concurrency, worker concurrency, object size, decoded dimensions, and pending bytes rather than relying on queue length alone. Queue depth counts a 20 KiB icon and a 40 MiB photograph as two equal jobs even though their memory, network, and decode costs differ sharply.
Counts can lie.
The resulting contract
The catalogue stores references, not transformed bytes: source digest, supplier provenance, batch ID, policy version, processing state, and the active manifest version. Clients request semantic variants such as search or inspection; they do not supply arbitrary encoder knobs. That keeps cache identity finite and lets the service change dimensions or encoding only by issuing a new version.
The decision is intentionally conservative. Preserve originals, use exact-byte dedupe for authority, treat perceptual similarity as review data, derive every output from the original, and expose only complete versioned manifests. Bandwidth matters, but lost property detail cannot be reconstructed from an aggressively compressed derivative.
References
- https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
- https://www.rfc-editor.org/rfc/rfc9110.html#name-202-accepted
- https://www.rfc-editor.org/rfc/rfc9110.html#name-idempotent-methods
- https://pillow.readthedocs.io/en/stable/reference/ImageOps.html#PIL.ImageOps.exif_transpose
- https://csrc.nist.gov/pubs/fips/180-4/upd1/final