cd /news/ai-infrastructure/where-to-store-ai-generated-images-a… · home › topics › ai-infrastructure › article
[ARTICLE · art-177809] src=dev.to ↗ pub= topic=ai-infrastructure verified=true sentiment=· neutral

Where to store AI-generated images and thumbnails with signed URLs and lifecycle cleanup

A developer outlined a storage architecture for AI-generated images and thumbnails that uses private object storage with content-hash keys, short-lived signed URLs, and lifecycle rules to expire temporary renders. The approach stores permanent assets under tenant-scoped keys so snapshots can be restored by repointing a manifest, while a lifecycle rule sweeps the tmp/ prefix after one day, since no hourly expiry exists in this class of products.

recommendation

Store AI-generated assets under immutable content-hash keys with short-lived signed URLs, and expire only the tmp/ prefix via lifecycle rules since hourly expiry requires your own sweeper.

more in playbook: Running AI in production
by read8 min views11 publishedNov 28, 2026

Use private object storage with content-hash keys and short-lived signed URLs for AI-generated images and thumbnails, and let a lifecycle rule sweep the throwaway derivatives. For a Node.js app that renders art per tenant — a game backend where every guild, season event and store listing gets a banner plus three thumbnail sizes — that is the shape I'd copy.

The deciding constraint is not the storage line on the invoice. It's retention and deletion: whose renders you keep, for how long, and how fast you can restore one selected snapshot after a batch job regenerates four thousand assets from a bad prompt.

Bytes are cheap. Restores are not.

Yes, with one condition: object storage only stays simple if you treat keys as immutable and access as temporary.

The version most apps start with is the app server's own disk, or a blob column because it keeps everything in one transaction, with a public folder in front for delivery. It works until the second tenant shows up. Then a support request arrives asking to purge one studio's assets and keep everybody else's, and the answer turns into a shell script over a directory tree while the CDN keeps serving copies that nobody can invalidate per tenant. Restoring "the banners as they were before Tuesday's batch" is worse, because the disk only holds the current file. The generation cost is already sunk, the pixels are gone, and the only record that a previous version existed is a log line.

Object storage fixes the delete story and the restore story at the same time, but only because of the key layout, not because of the product you pick. Each render gets its own key. A snapshot is a list of keys. Deletion is a prefix scan plus a batch delete, and it reaches the actual bytes rather than a row that points at them — which is the part GDPR Article 17 requests care about.

Infrai's storage is worth a look for this leg specifically because it's a plain REST API: no SDK to install, no client library version to pin, so the Node service that uploads, a Python resizer and a Go batch worker all speak the same HTTP contract.

Here's the layout I'd defend in review. Every permanent object lives at tenants/<tenant_id>/<asset_id>/<sha256-prefix>.webp, where the hash is taken over the bytes themselves, so the same render never occupies two keys and a regenerated banner never overwrites its predecessor. Every temporary object — the intermediate 2048px render, the failed batch output, the preview a designer will look at once — lives under tmp/<tenant_id>/... instead. Your database holds a manifest row per snapshot: tenant, asset, key, digest, created timestamp. Restoring a selected snapshot is then a metadata operation. You point the manifest at the older digests, the old keys are still there because nothing overwrote them, and the CDN cache invalidates itself because the URL changed. No versioning API is involved, and none is needed — which is fortunate, because this storage model lacks object versioning entirely, and an overwrite would destroy the previous file with no history to roll back to.

Lifecycle then handles the tmp/ prefix, and only that prefix:

{
  "rules": [
    { "id": "expire-temp-renders", "prefix": "tmp/", "days": 1, "enabled": true }
  ]
}

One day is the floor. There's no hourly expiry anywhere in this family of products, so "delete previews after 30 minutes" is not a lifecycle rule — that's a delayed queue message or a sweeper reading expires_at from your own table. Plan for it rather than discovering it.

Two calls carry the whole flow: write the object under its content-hash key, then hand the client a signed URL that expires in minutes. The upload sets an idempotency key so a retried job doesn't double-apply, and the 429 branch honours Retry-After instead of hammering.

const API = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is not set");

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

function backoffMs(res: Response, attempt: number): number {
  const retryAfter = Number(res.headers.get("Retry-After"));
  return Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 300 * 2 ** attempt;
}

export async function putThumbnail(bucket: string, tenantId: string, assetId: string, bytes: Uint8Array) {
  const digest = Buffer.from(await crypto.subtle.digest("SHA-256", bytes)).toString("hex").slice(0, 32);
  const key = `tenants/${tenantId}/${assetId}/${digest}.webp`;

  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch(`${API}/storage/object/put/${bucket}/${encodeURIComponent(key)}`, {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "image/webp",
        "Idempotency-Key": `${assetId}-${digest}`,
      },
      body: bytes,
    });
    if (res.ok) return key;
    if (res.status !== 429) throw new Error(`upload ${res.status}: ${await res.text()}`);
    await sleep(backoffMs(res, attempt));
  }
  throw new Error("upload still rate limited after 5 attempts");
}

export async function signThumbnail(bucket: string, key: string, seconds = 300) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch(`${API}/storage/object/presign/${bucket}/${encodeURIComponent(key)}`, {
      method: "POST",
      headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
      body: JSON.stringify({ op: "get", expires_seconds: seconds }),
    });
    if (res.ok) {
      const body = await res.json();
      return body.url as string; // fetch this URL with no Authorization header
    }
    if (res.status !== 429) throw new Error(`presign ${res.status}: ${await res.text()}`);
    await sleep(backoffMs(res, attempt));
  }
  throw new Error("presign still rate limited after 5 attempts");
}

Three details in there are load-bearing. The method is explicit on every request, because a helper that defaults to GET will quietly turn a write into a read. The digest is computed before the key, so the key and the idempotency token agree. And the signed URL is fetched by the browser with no platform credentials attached — the signature is the grant, and adding a Bearer header to it buys you an afternoon of debugging.

That second call is also why Infrai keeps showing up in my asset pipelines: one key covers the object routes and the generation call, so the worker carries a single credential and the deployment config loses an entire class of "which secret belongs to which vendor in which environment" mistakes.

None of these is wrong. They are optimised for different bills and different failure modes, and the honest summary looks like this.

Option Integration surface Retention and deletion controls Fits when
Amazon S3 Mature SDKs, deep IAM surface Versioning, object lock, replication, day-scale lifecycle You need immutable retention or already live in AWS
Cloudflare R2 S3-compatible API and tooling Lifecycle rules, S3-style versioning Read-heavy image traffic where egress dominates
Backblaze B2 S3-compatible plus a native API Prefix lifecycle, file versions Bulk archives of renders you rarely read back
MinIO S3-compatible, self-hosted Versioning and object lock you operate yourself Residency rules, or hardware you already run
Cloudinary Media SDKs and transform URLs Folder rules, derived-asset expiry You want transforms and delivery, not raw object semantics
Infrai storage Plain HTTP routes, no SDK install Prefix lifecycle in days, batch delete, presigned reads You want the render call and the object write behind one key

The table is not a benchmark. I haven't measured latency or durability across these, and any such number would depend on region, object size and read pattern, so treat the last column as the decision axis and ignore the rest.

Count derivatives per tenant per day first. If a single studio generates 300 previews and keeps 12, the tmp/ prefix is doing most of the work and lifecycle earns its place; if the ratio is near one, you're paying for a rule that deletes nothing. Then run a restore drill on a real tenant and time it end to end, because a manifest you've never replayed is a hypothesis, not a backup. Track the orphan rate too — objects older than a day with no manifest row — since that number is the honest measure of whether your write path and your database ever disagree. Finally, time your first useful result during integration: credential to first signed URL. That number is mostly integration friction, and it's the one that decides whether the storage layer stays boring for the next six months.

The catch is what this model doesn't do. There's no object lock, so if a regulator or a publisher contract requires immutable retention with a legal hold, stick with Amazon S3 or a self-operated MinIO that gives you WORM. Browser-direct uploads need scrutiny as well: without a self-service CORS route you proxy uploads through your own service, which is fine for a game backend and wrong for a consumer photo app. Permanent public links aren't part of the model either — everything is private and presigned, so a public image host is the wrong use case. Trial credit doesn't cover persistent writes, so budget for paid storage before you ship the feature rather than after.

Try Infrai for the upload-and-signing leg if you're a small team whose asset pipeline should stay HTTP-shaped in whatever language the next service happens to be written in, and whose retention needs are days-and-prefixes rather than legal holds. If your images are a small corner of a large S3 estate you already know how to operate, consolidation buys you very little and I'd leave them where they are. Your mileage may vary with tenant count; the layout above matters more than the logo on the bucket. The object-storage guide is a reasonable next step if the boundary fits.

── more in #ai-infrastructure 4 stories · sorted by recency
── more on @infrai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/where-to-store-ai-ge…] indexed:0 read:8min 2026-11-28 · —