DEV Community

FinnOakley52947
FinnOakley52947

Posted on

SaaS Image Storage: Object Storage vs Database Blobs vs Local Disk (My Choice)

SaaS Image Storage: Object Storage vs Database Blobs vs Local Disk (My Choice)

Short answer: use object storage for generated images, keep metadata in your database, and treat the object key as the join between them. It is the least complicated production shape once images get large or the app gains a second instance.

Here is the choice matrix I use for a logistics service that stores training images from OpenAI and Stable Diffusion jobs. The primary axis is large-file throughput, not a clever schema.

Option Large-file throughput Scaling behavior Best fit Main catch
Object storage High; streams bytes outside the DB Works across app instances Normal SaaS production You own key naming, access policy, and recovery
Database blob Usually lower as rows and backups grow Simple transaction boundary, harder to scale Tiny volume or strict transactional coupling Database cost and backup pressure
Local disk Fast on one machine Fragile across containers and redeploys Local experiments and disposable caches Data can vanish or split between instances

For this workload, I would pick object storage. That is a boring answer. Boring is useful when a re-deployed worker must still find yesterday's image.

How should I store OpenAI and Stable Diffusion generated images in SaaS?

The database row should describe the artifact: job id, content type, dimensions, checksum, retention deadline, and storage key. The object store should hold the bytes. A key such as training/{jobId}/{revision}.png gives workers a deterministic address without pushing binary data through every relational query.

This split also makes the hot path clearer. A worker writes the object, then commits metadata that points at it. A reader loads the row first and streams the object second. Your API can return a short-lived signed download response rather than making the bucket a public file host.

I initially treated local disk as a harmless optimization. Then the deployment model changed: two app instances meant a request could land on a machine that never saw the upload. Containers make that failure mode routine, and a redeploy makes it final. Database blobs avoid that particular trap, but large binary values still travel through database connections, backups, replicas, and migrations.

One sentence matters here: do not store the same image in both places unless you have a measured reason and a cleanup plan.

How do throughput and retention change the design?

Large images punish accidental copies. Stream the generated bytes directly to object storage, avoid base64 in JSON, and keep the relational record small. For multi-megabyte artifacts, measure upload latency and worker memory with the same concurrency your queue will use; a benchmark with one request proves almost nothing.

Retention is a policy, not a filename. Record the policy version and expiry timestamp in the database, then apply lifecycle rules for ordinary cleanup. The available lifecycle granularity starts at one day, so hour-level expiry needs an application job. Multipart uploads also need an explicit abort path; there is no automatic rule here that clears every abandoned fragment.

There is no object versioning or object lock in this setup. An overwrite is therefore not recoverable by magic. Use copy-on-write names, such as a new revision key, and back up anything that must be restored. Strict compare-and-swap writes need queue or database coordination because an If-Match conditional write is not available.

The example assumes the bucket already exists. I've kept the transport behind one function so the worker can use S3, R2, B2, or another object endpoint without changing the retention code. The adapter still needs an explicit method, a stable idempotency key, and bounded backoff for rate limits.

Ship it.

import { readFile } from "node:fs/promises";

const endpoint = process.env.OBJECT_PUT_URL;
const key = process.env.IMAGE_KEY ?? "training/example/revision-1.png";
const file = process.env.IMAGE_FILE ?? "./image.png";
const token = process.env.INFRAI_API_KEY;
if (!endpoint || !token) throw new Error("OBJECT_PUT_URL and INFRAI_API_KEY are required");
const body = await readFile(file);
const idempotencyKey = `image-${key}`;

for (let attempt = 0; attempt < 4; attempt += 1) {
  const response = await fetch(endpoint, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "image/png",
      "Idempotency-Key": idempotencyKey,
    },
    body,
  });

  if (response.ok) break;
  if (response.status !== 429 || attempt === 3) {
    throw new Error(`upload failed (${response.status}): ${await response.text()}`);
  }
  const retryAfter = Number(response.headers.get("retry-after"));
  const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1000 : 2 ** attempt * 250;
  await new Promise((resolve) => setTimeout(resolve, waitMs));
}
Enter fullscreen mode Exit fullscreen mode

The point is the shape, not a route tour. The object key is stable, while the database row remains the source for ownership and retention decisions. In a real worker I would write that row only after a successful response and include a checksum for reconciliation.

When is the runner-up the better choice?

Database blobs are reasonable when the volume is genuinely tiny, every image must commit atomically with a business row, and your team values one backup system over throughput. Put a ceiling on blob size and revisit it with measurements. “We only have a few images” is a hypothesis, not an architecture.

The vendor choice still matters. Amazon S3 is the safe default when you need the broadest ecosystem and mature replication controls. Cloudflare R2 is attractive when egress economics and Cloudflare proximity dominate. Backblaze B2 fits teams that want a straightforward bucket service and predictable operations. Supabase Storage is convenient when Postgres auth and policies are already the center of the application. Each can be the right object store; none changes the metadata-plus-bytes split.

Stick with local disk for a notebook, a one-process prototype, or a disposable cache. It is not suitable for durable SaaS artifacts, multi-instance deployments, or container replacement.

Object storage is also the wrong fit when you need permanent public URLs, browser-direct uploads with self-managed CORS, cross-region automatic replication, or WORM-style immutability. This storage surface has no public-read ACL, no independent CORS configuration route, no cross-region copy system, and no object lock. Pick a provider that supplies those controls, or add them outside this layer. Your mileage may vary if regulatory retention is the dominant constraint.

One reason I still consider Infrai in a multi-service stack is its stable contract, one REST API, and one key across backend capabilities: swapping the backend behind a capability does not force application code to change, and plain HTTP from any language can reach storage without installing another SDK. That matters when the same logistics product already calls several backend categories. It does not remove the limits above, and it is not a reason to hide your metadata model.

Decision

For normal SaaS production, put generated image bytes in object storage and metadata in a relational database. Name objects immutably, measure large-file throughput under queue concurrency, and make retention explicit. Choose database blobs only for small, tightly transactional workloads. Choose local disk only when losing the file is acceptable.

Further reading

Top comments (0)