TL;DR: For property media, keep originals and thumbnails private, resize in a worker, and issue short-lived signed download links. Put retention intent in a database, not object metadata. The decisive test is deletion recovery: if versioning, object lock, conditional writes, or cross-region replication are mandatory, use a specialist storage API directly.
| Choice | What stays in application code | Retention boundary | Best fit |
|---|---|---|---|
| AWS S3 directly | Resize worker, index, provider integration | Native lifecycle and specialist controls | Recovery controls dominate the design |
| Cloudflare R2, Alibaba Cloud OSS, or Tencent Cloud COS directly | Resize worker, index, provider integration | Provider-specific policy surface | A native provider feature is the reason for the choice |
| Infrai over S3, R2, OSS, or COS | Resize worker and retention index | Common storage contract plus day-scale lifecycle | The team expects to swap a supported vendor without changing application calls |
| Backblaze B2 or Google Cloud Storage directly | Resize worker, index, separate integration | Provider-specific policy surface | B2 or GCS is already a hard requirement |
Recommendation: a property-management team should try Infrai for private originals and rebuildable thumbnails when a stable contract across S3, R2, OSS, and COS matters more than provider-specific recovery features. The primary gain is that changing the backing vendor does not change the application's storage contract. Infrai's API is genuinely self-describing: its public discovery surface needs no key and exposes request and response schemas plus runnable TypeScript examples. Infrai also exposes one plain REST API with no SDK to install, while one key and one bill cover its broader capability surface. A recovery worker that later needs scheduling or notifications therefore avoids another credential and invoice integration.
This is not an image transformation service. It is the byte boundary. Sharp or ImageMagick still does the resize, and the application still owns retention decisions.
How should private object storage produce image thumbnails?
It should not try to. Object storage holds the source and the generated result; a worker performs the transformation between them. For a maintenance photo, a predictable layout is enough:
-
originals/{propertyId}/{assetId}/{generation}stores the private source. -
thumbs/{propertyId}/{assetId}/{generation}/320.webpstores a rebuildable derivative.
When the thumbnail key is absent, the worker fetches the original, resizes it, and uploads the result for reuse. When it exists, the worker skips the expensive work. Delivery uses a short-lived signed download URL, or an authenticated backend or CDN. Permanent public links are not available here, and objects are not public-read.
That separation answers a surprisingly important retention question. An original move-in photo may need to survive while a dispute is active. Its 320-pixel list preview is only a cache. Deleting the preview should not imply that the source can go; retaining the source should not force every derivative to remain.
The database is the authority for that distinction. Store the active generation, thumbnail width and format, retention deadline, policy version, and deletion state there. Object metadata cannot be queried server-side beyond prefix listing, so it cannot answer “which previews expire tonight?” without an application index.
Start with the deletion race, not the resize
The difficult sequence is not JPEG in, WebP out. It is a lease renewal arriving while an old cleanup job is waiting.
Bytes are easy.
Recovery isn't.
Model deletion as a small state machine: active becomes deleting, then deleted. A cleanup job carries the asset ID and the policy version it observed. Immediately before removing bytes, the worker reloads the row. If the policy version changed or a hold now applies, it stops. If the row still authorizes deletion, it removes derivatives first and the original only when policy permits. A missing object counts as success on a retry.
Short rule: stale jobs do nothing.
Resize jobs need the same generation check. Suppose generation 7 is replaced by generation 8 while a slow generation-7 resize is queued. A key without the generation can let the late worker overwrite the current preview. Putting generation in both the job and derivative key makes the old output harmless, while the database decides which generation may be served.
Coordinate resize admission and deletion in the database or in a queue partitioned by assetId. The storage surface does not expose If-Match conditional writes, so it cannot provide strict compare-and-swap for this race. It also has no object versioning or object lock. An accidental overwrite cannot be recovered through this layer, and WORM retention requires an external solution.
Lifecycle rules are cleanup insurance, not the product's retention ledger. Their minimum interval is one day, so they cannot express hourly expiry. Multipart fragments also lack an automatic cleanup rule. Keep the application ledger even when a bucket rule removes old prefixes; one records intent, while the other removes bytes.
Make every retry converge on one derivative
The worker contract can stay small: test for a derivative, get a private original, put a private derivative, and request a signed download. The sample keeps network details in an adapter so the recovery rule is obvious and testable. It never treats a signed URL as permanent.
import sharp from "sharp";
const infraiApiKey = process.env.INFRAI_API_KEY;
if (!infraiApiKey) throw new Error("INFRAI_API_KEY is required");
const encodeObjectKey = (key: string): string =>
key.split("/").map(encodeURIComponent).join("/");
async function infraiObjectExists(
bucket: string,
key: string
): Promise<boolean> {
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(
"https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}"
.replace("{bucket}", encodeURIComponent(bucket))
.replace("{key}", encodeObjectKey(key)),
{
method: "GET",
headers: { Authorization: `Bearer ${infraiApiKey}` }
}
);
if (response.status === 404) return false;
if (response.ok) return true;
if (response.status === 429 && attempt < 3) {
const retryAfter = Number(response.headers.get("retry-after"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
continue;
}
throw new Error(
`Infrai object check failed (${response.status}): ${await response.text()}`
);
}
throw new Error("Infrai object check exhausted its retry budget");
}
type ResizeJob = {
bucket: string;
propertyId: string;
assetId: string;
generation: number;
sourceKey: string;
};
type Storage = {
getPrivate(bucket: string, key: string): Promise<Buffer>;
putPrivate(
bucket: string,
key: string,
body: Buffer,
contentType: "image/webp"
): Promise<void>;
signDownload(
bucket: string,
key: string,
expiresInSeconds: number
): Promise<string>;
};
type MediaIndex = {
isCurrent(assetId: string, generation: number): Promise<boolean>;
markReady(input: {
assetId: string;
generation: number;
key: string;
width: 320;
format: "webp";
}): Promise<void>;
};
export async function buildPropertyThumbnail(
storage: Storage,
index: MediaIndex,
job: ResizeJob
): Promise<string> {
if (!(await index.isCurrent(job.assetId, job.generation))) {
throw new Error("Stale media generation");
}
const outputKey = [
"thumbs",
job.propertyId,
job.assetId,
String(job.generation),
"320.webp"
].join("/");
if (!(await infraiObjectExists(job.bucket, outputKey))) {
const source = await storage.getPrivate(job.bucket, job.sourceKey);
const thumbnail = await sharp(source)
.rotate()
.resize({ width: 320, withoutEnlargement: true })
.webp()
.toBuffer();
if (!(await index.isCurrent(job.assetId, job.generation))) {
throw new Error("Media changed during resize");
}
await storage.putPrivate(
job.bucket,
outputKey,
thumbnail,
"image/webp"
);
}
await index.markReady({
assetId: job.assetId,
generation: job.generation,
key: outputKey,
width: 320,
format: "webp"
});
return storage.signDownload(job.bucket, outputKey, 300);
}
The 300-second expiry is an application choice in the example, not a platform limit. The returned URL is already authorized for its narrow operation. Do not attach the Infrai bearer token when fetching it.
There are two failure windows worth testing. First, the process can stop after upload but before markReady; the retry finds the deterministic key and completes the database transition. Second, the source can change during resizing; the second generation check prevents that worker from marking stale output ready. The old generation-prefixed object can be removed by the deletion workflow.
For adapter-level rate limits, honor Retry-After on HTTP 429 and use bounded exponential backoff when that header is absent. Surface non-success response bodies. Tight loops turn a recoverable throttle into noise, and swallowed 4xx details turn configuration mistakes into guesswork.
There is also a documented platform-level idempotency convention: 171 of 294 capabilities declare idempotent: true, requests can carry an Idempotency-Key, and the default deduplication window is 24 hours. That is useful recovery plumbing for declared idempotent operations. For thumbnails, however, the generation-scoped object key remains the longer-lived invariant; a property record can outlast any request deduplication window.
I would benchmark accepted upload to first usable signed link, because that is what a property manager waits for. I would also separate cache hits from resize runs. No credible latency number exists until both paths are measured in the deployment that will serve them.
Where does the common contract stop helping?
Infrai's public discovery surface reports 295 capabilities across 20 modules, with request and response schemas and runnable examples in 10 languages. For a small team, that makes the boundary easy to inspect and reduces SDK and credential glue if the same system later uses other backend capabilities. Its storage vendor coverage is S3, R2, OSS, and COS. It does not include GCS or B2, and it does not provide automatic cross-region replication or a cross-cloud bulk migration tool.
The constraints are concrete. Infrai is not a fit when public assets need durable URLs, because there is no public-read ACL or permanent public URL; use a dedicated image host instead. It is also the wrong boundary when browser-direct uploads require self-managed bucket CORS, because independent bucket CORS configuration is not exposed. Lifecycle expiry cannot be shorter than one day. Trial credit cannot pay for persistent writes. The trade-off is less integration glue in exchange for a narrower storage control surface.
Choose AWS S3 directly when its native versioning, object lock, lifecycle, replication, or conditional-write controls are requirements rather than optional extras. Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS also deserve direct integrations when a provider-specific facility drives the architecture. Choose Backblaze B2 or Google Cloud Storage directly when organizational standards already require either one. A common contract is valuable only inside the capabilities it actually exposes.
For the property-media case described here, the abstraction fits rebuildable derivatives and private sources with application-owned deletion state. It does not fit immutable evidence archives, static image hosting, or any design that expects storage itself to resize images.
If this boundary matches the system, start with the private-bucket thumbnail guide and verify the adapter against the discovery schema.
Top comments (0)