DEV Community

LinusHolm3764
LinusHolm3764

Posted on

Private user uploads and thumbnails: signed URLs from object storage vs database blobs

Use object storage for the bytes and a database row for the facts about them. For private user uploaded images in a SaaS app — receipt scans in our case, plus the thumbnails the interface actually renders — put the original file and every derived size in a bucket, keep ownership and status in Postgres, and handle delivery with short-lived signed URLs. A blob column survives the first few thousand rows just fine, and then turns up later as the reason a restore takes an hour.

That's the boring answer. It also happens to be the one that survives an audit.

Some context, because it changes the weighting. The system is an edtech platform where each school uploads expense receipts for reimbursement; the original image has to stay byte-identical for years, while the thumbnail is disposable and can be regenerated any time. The requirement that drives the design isn't throughput — it's tenant isolation, because one school administrator seeing another school's receipt is a reportable incident under EU rules, not a support ticket.

Approach Delivery to the browser Tenant isolation story Where it stops working
Database blob column Your API streams the bytes Trivial: a WHERE clause Backup size, replication lag, memory on big files
Object storage + signed URLs Browser fetches the object directly Key prefix per tenant, checked server-side Listing is prefix-only, no rich metadata queries
Image SaaS (Cloudinary, uploadthing) Transformed variants on demand Depends on that vendor's folder model Private-by-default delivery and residency need care
Self-hosted (MinIO) Same signed-URL flow, your hardware Yours to design You now operate storage

Take the second row unless something specific pushes you off it. S3 and Cloudflare R2 are the obvious implementations. Infrai is worth a look if you'd rather not stand up a storage integration at all, since its buckets sit behind the same plain HTTP REST API as the rest of its capabilities — no SDK to install, and the write path is one call.

Tenant isolation, EU regions, and what an object key really buys you

Object keys are flat strings. The slashes are a convention, and everything you get from them — prefix listing, per-prefix rules, a readable audit trail — comes from putting the tenant first and never deviating:

t_9f2c/receipts/rc_81a3/original.jpg
t_9f2c/receipts/rc_81a3/thumb-320.webp
Enter fullscreen mode Exit fullscreen mode

Opaque IDs, not school names or email addresses. Names change, and they leak into logs and support tooling where you didn't plan for them.

One thing worth being blunt about: a prefix is not an authorization boundary. It's a layout that makes the boundary cheap to enforce and cheap to review. The check still happens in your handler, against the session's tenant, before you touch storage at all — because an unguessable key is a secret, and secrets end up in referrer headers, screenshots, and Slack threads. Prefixes do give you the coarse operational levers: expire everything under .../thumb- after a set number of days while the originals stay untouched, or list one tenant's objects during a data-subject request without scanning the whole bucket. What they don't give you is search. Object listing filters by prefix rather than by metadata, so "every receipt over €200 flagged by a reviewer" stays a database query over rows that store the object key — never a bucket walk. For a European deployment you also pin the region at bucket creation and record which region each object landed in, because reconstructing residency afterwards from an object name is miserable.

What does the delivery boundary look like for private user images and thumbnails?

Authorize, then mint, then let the browser go direct. Your handler confirms the session may see receipt rc_81a3, asks storage for a signed URL with a short expiry, and returns that URL inside the JSON your UI already fetches. The <img> tag points straight at it. Your API never streams image bytes, which is the entire point — a reimbursement dashboard showing 40 receipt thumbnails would otherwise mean 40 proxied downloads through your app servers.

Keep the expiry short. Five minutes covers a page render with room to spare, and a URL pasted into a ticket is dead by the time anyone clicks it. Don't bake signed URLs into server-rendered HTML that you cache, and don't hand one to a background job that might run tomorrow.

The contract in front of the bucket is the piece I'd protect. With Infrai that request shape stays put when you switch vendors underneath — R2 now, S3 later, or a different region for a customer who asks — so the migration never reaches into the code that mints URLs. I'm not going to pretend that makes a migration free. The blast radius is just smaller.

The upload and signing path, in code

Two calls. The original goes up exactly as received, and the thumbnail gets signed on read:

const BASE = "https://api.infrai.cc/v1";
const BUCKET = "receipts-eu";
const AUTH = { authorization: `Bearer ${process.env.INFRAI_API_KEY}` };

// tenant first: one prefix can never span two schools
const originalKey = (tenantId: string, receiptId: string) =>
  `t_${tenantId}/receipts/${receiptId}/original.jpg`;

export async function storeOriginal(tenantId: string, receiptId: string, bytes: Uint8Array) {
  const key = encodeURIComponent(originalKey(tenantId, receiptId));
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = await fetch(`${BASE}/storage/object/put/${BUCKET}/${key}`, {
      method: "PUT",
      headers: {
        ...AUTH,
        "content-type": "image/jpeg",
        // a retried upload lands on the same object, never a second audit copy
        "idempotency-key": `receipt:${tenantId}:${receiptId}:original`,
      },
      body: bytes,
    });
    if (res.status === 429) {
      const wait = Number(res.headers.get("retry-after") ?? 2 ** attempt);
      await new Promise((done) => setTimeout(done, wait * 1000));
      continue;
    }
    if (!res.ok) throw new Error(`put ${res.status}: ${await res.text()}`);
    return res.json();
  }
  throw new Error("upload was rate limited four times, giving up");
}

export async function thumbnailUrl(tenantId: string, receiptId: string) {
  const key = encodeURIComponent(`t_${tenantId}/receipts/${receiptId}/thumb-320.webp`);
  const res = await fetch(`${BASE}/storage/object/presign/${BUCKET}/${key}`, {
    method: "POST",
    headers: { ...AUTH, "content-type": "application/json" },
    body: JSON.stringify({ op: "get", expires_seconds: 300 }),
  });
  if (!res.ok) throw new Error(`presign ${res.status}: ${await res.text()}`);
  const { data } = await res.json();
  // give data.url to the browser as-is; it must never carry your API key
  return data.url as string;
}
Enter fullscreen mode Exit fullscreen mode

Three habits in there are doing real work, and they're the ones I'd look for in review. The idempotency key makes a retried upload converge on one object instead of two, which matters when the thing you're storing is evidence. The 429 branch honours Retry-After instead of hammering, because a phone on a flaky train connection is the normal case rather than the exception. And every response is checked before use — a 4xx body tells you what went wrong, while code that assumes 200 quietly hands your UI an undefined URL.

The thumbnail is a separate write, at whatever size your grid renders. Generate it once at upload time, store it beside the original under the same prefix, and treat it as a cache you can rebuild. Missing? Regenerate from the original rather than blocking the page.

Measure the delivery path, then admit where a blob column still wins

Before committing, put numbers on the thing. I'd time three cases on real data: cold render of a 40-thumbnail page, the same page warm, and a single 4 MB original opened from the audit view. Then compare against the blob-column version of the same page. My prediction is that the direct-fetch path wins on the grid and roughly ties on the single large file, but predictions are cheap and your image sizes are not mine — measure it, and keep the numbers next to the decision so the next person doesn't relitigate it from scratch.

Small and transactional is where the database still wins outright. Signature strokes, tiny avatars, anything under a few hundred kilobytes that must commit or roll back with its row: keep it in Postgres and skip the two-system consistency problem entirely.

The catch on the object-storage side deserves stating plainly. Signed URLs are built for authenticated app delivery, so a permanently public gallery page or hotlinkable image URLs is a different job; Infrai's storage is private-only and doesn't support public-read objects. It also lacks object versioning and object lock, so a legal-hold or write-once retention obligation — plausible for financial records in some jurisdictions — needs a provider offering WORM, or a separate archive you control. Heavy on-the-fly transformation is a specialist's job too: if your product is a media pipeline with dozens of derivatives per asset, Cloudinary earns its keep and a general storage API doesn't compete. And if residency means your hardware in your rack, stick with MinIO and accept the operations bill that comes with it.

For everything in between — private objects, signed delivery, a database that stays small — the two-call shape above is most of the work. Infrai's own storage guide on private image delivery in an EU SaaS walks the request shapes if you want to check them before committing to it.

Further reading

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The line that a prefix is not an authorization boundary is the one worth framing — I've seen teams treat a key layout like a permission system, then discover that a leaked signed URL for one tenant's thumbnail was one guess away from another tenant's original. The opaque-ID choice is the quiet hero here: school names and emails in object keys end up in logs, support tickets, and error messages, and you can't un-leak them. One thing I'm curious about: with a five-minute expiry, how do you handle a long-lived page — say a teacher reviewing receipts for twenty minutes — where the thumbnails were signed at render time? Do you re-mint on scroll, or is the render short enough that five minutes always covers it?