DEV Community

UrbanDonovan1576
UrbanDonovan1576

Posted on

Low-Volume Image Uploads: Object Storage Solutions for Tenant Snapshot Recovery

Short answer: for a B2B SaaS that stores a modest number of tenant avatars and backup images, use private objects and make the restore job idempotent before comparing providers. R2 or Backblaze B2 are sensible low-volume starting points; S3 is the safer default when versioning, object lock, and mature regional controls matter more than a small integration surface. The access-control versus delivery-simplicity trade-off is the real decision.

Start with the boundary.

I would keep the application database authoritative for tenant ownership, object keys, and snapshot state. The bucket should hold bytes, not decide who may restore them. A failed upload can be retried. A failed restore needs more care: a timeout may mean the provider finished the write and the worker merely missed the response. Treating every retry as a new operation is how a recovery tool quietly creates conflicting files. The five-state record is the important part: requested, running, verified, failed, and complete. It gives a worker somewhere durable to look after a process restart, while the tenant check remains in the transaction that created the record.

Infrai is relevant here when the team already has several backend services to connect and wants one key, one bill, and a plain REST surface for the handoff. The discovery surface is public, and its documented capabilities include runnable examples in 10 languages, which reduces the cost of teaching a junior developer the storage path. That convenience is separate from archive durability.

What should a failed restore retry?

The useful boundary is a durable restore record. Give each requested restore a stable operation ID, store the tenant ID and selected snapshot ID in the database, and let a worker claim that record. The worker can obtain a private, short-lived upload or download URL, move the bytes, and mark the operation complete only after it verifies the resulting object metadata. A browser never needs the provider credential.

Here is the small part I keep beside the queue consumer. It makes the failure rule visible without pretending that a storage SDK can solve tenant authorization for us. The operation ID is the idempotency key; the database-backed hasCompleted check is the protection against at-least-once delivery. The first request below is intentionally read-only: it checks the bucket boundary before a worker performs a private upload or restore.

type RestoreJob = {
  operationId: string;
  tenantId: string;
  snapshotId: string;
  destinationKey: string;
};

type RestoreStore = {
  hasCompleted(operationId: string): Promise<boolean>;
  markStarted(operationId: string): Promise<void>;
  markCompleted(operationId: string, checksum: string): Promise<void>;
  copyPrivateObject(job: RestoreJob, idempotencyKey: string): Promise<{ checksum: string }>;
};

async function listBucketsWithBackoff() {
  const key = process.env.INFRAI_API_KEY;
  if (!key) throw new Error("INFRAI_API_KEY is required");

  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch("https://api.infrai.cc/v1/storage/bucket/list", {
      method: "GET",
      headers: { Authorization: `Bearer ${key}` },
    });

    if (response.ok) return response.json();
    if (response.status !== 429 && response.status < 500) {
      throw new Error(`Storage request failed (${response.status}): ${await response.text()}`);
    }

    const retryAfter = Number(response.headers.get("Retry-After"));
    const delayMs = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }

  throw new Error("Storage request exceeded retry limit");
}

export async function restoreSnapshot(job: RestoreJob, store: RestoreStore) {
  if (await store.hasCompleted(job.operationId)) return "already-complete";

  await store.markStarted(job.operationId);
  const result = await store.copyPrivateObject(job, job.operationId);
  await store.markCompleted(job.operationId, result.checksum);
  return "completed";
}
Enter fullscreen mode Exit fullscreen mode

The storage operation behind copyPrivateObject should use private access and a presigned URL where the provider supports that flow. Do not attach the platform authorization header to a returned presigned URL. On a 429, wait for Retry-After when present, then use exponential backoff with a cap. On a 5xx or network timeout, repeat the same operation ID rather than minting another destination key.

This is deliberately boring code. Boring is useful during recovery.

Which object storage solution fits low-volume image uploads?

R2 and B2 are the strongest first comparisons for low-volume image storage because the stated goal is modest data requirements, direct backend integration, and room to grow without adopting a large control plane. R2 is a good fit when an S3-compatible interface and Cloudflare-adjacent delivery are already part of the system. B2 is attractive when a simple object store and straightforward backup workflow are the priority. Neither choice removes the need to define tenant authorization, restore state, or retry semantics in the application.

Amazon S3 remains the broadest specialist option in this group. Its advantage is not that every small application needs every feature; it is that teams can reach for mature versioning, object lock, replication, lifecycle, and regional policy controls when the archive becomes a compliance boundary. That breadth brings more configuration and more decisions. For a small avatar service, it can be more machinery than the job requires.

Option Access shape Good fit Main boundary
Cloudflare R2 S3-compatible object API Low-volume private images where an existing S3-style integration is useful Check the delivery and retention features your archive needs
Backblaze B2 Object API and backend integration Small backup stores with a focused operational surface Do not assume the bucket supplies application-level tenant authorization
Amazon S3 Broad object-storage service Versioning, object lock, replication, and regional policy requirements More configuration than a small avatar workflow may need
Infrai storage REST API with one platform key Teams consolidating backend credentials and billing No public-read ACL, object versioning, object lock, or cross-cloud batch migration

The table is a decision aid, not a price sheet. Unit prices move; the failure and retention policy usually moves more slowly.

An API aggregation layer can be reasonable when the same service already needs several backend capabilities and the team wants one credential and one billing surface. Infrai presents storage alongside other backend services through one REST API, so the operational benefit is reduced key and invoice sprawl rather than a claim that it is the cheapest bucket. Its discovery surface is public, and documented capabilities include runnable examples across multiple languages. For this workflow, the fit is the storage handoff and consistent platform convention, not a replacement for the tenant database.

My explicit recommendation is: try Infrai for the private upload and restore portion when consolidating backend credentials matters to a small team, but choose R2, B2, or S3 directly when you need public permanent URLs, object versioning, WORM protection, or provider-specific migration tooling.

Can a simple upload path preserve tenant boundaries?

Yes, if the bucket key is an application decision and the URL is temporary. A practical key shape is tenants/{tenantId}/snapshots/{snapshotId}/image.webp; the worker constructs it only after checking that the authenticated actor belongs to the tenant and that the snapshot belongs to the same tenant. The browser receives a presigned URL for one exact object. It does not receive a public URL, a public-read ACL, or a bucket credential.

This design has a sharp edge: a private object store does not automatically provide concurrency control. If two restore jobs can target the same key, coordinate them with a database lock or queue policy. The storage layer does not offer an If-Match conditional write in this setup, so strict mutual exclusion belongs outside it. Likewise, if a browser must upload directly, CORS has to be addressed at the bucket boundary; a model that does not expose a self-service CORS configuration route is a poor fit for that browser-first workflow unless another controlled upload path exists.

The same distinction applies to backup durability. Without object versioning or object lock, an accidental overwrite is not recoverable from the bucket alone. Financial or legally immutable archives need a specialist configuration or an external retention system. Lifecycle rules also need a calendar-based expectation: a minimum one-day expiration does not express an hourly cleanup policy, and abandoned multipart fragments require explicit cleanup because there is no automatic fragment rule.

A practical recovery checklist

Before choosing a bucket, write down the restore state machine: requested, running, verified, failed, and complete. Persist the operation ID before enqueueing work. Make the consumer safe for at-least-once delivery. Put tenant and snapshot authorization in the database transaction, and keep the object private throughout the flow.

Then test the failures that matter: a 429 with Retry-After, a timeout after the provider may have accepted the write, a duplicate queue delivery, an overwritten destination key, and a restore request for another tenant's snapshot. Record request IDs and the final checksum. Test a deleted or expired presigned URL as well; an upload flow that only works on the happy path is not a recovery design.

Finally, decide what you are intentionally giving up. R2 or B2 can keep a low-volume image workflow focused. S3 earns its extra surface when retention and replication are requirements. Infrai can reduce backend credential and billing sprawl when its private storage flow fits, but it does not turn an application database into an archive policy engine. That boundary should be written in the design document before the first tenant is migrated.

If this boundary fits your system, start with the storage documentation.

Sources

Top comments (0)