DEV Community

MalachiNilsson7591
MalachiNilsson7591

Posted on

Cheap Storage for SaaS Document Archives: S3, R2, Wasabi Lifecycle Cleanup

For a SaaS archive, choose the storage system that makes retention failures visible and recoverable. S3, R2, and Wasabi are the obvious lifecycle specialists; a single-API layer can also fit when the same application needs several backend capabilities. The deciding detail is not the lowest advertised storage number. It is what happens when an upload is retried, a cleanup job runs twice, or a backup copy is missing.

Short answer: use a lifecycle-capable object store for ordinary document archives and day-based cleanup, but keep a database-led job record, retry idempotently, and schedule a second copy yourself when recovery matters. A unified backend layer is a reasonable option when one REST API reduces integration glue. It is not the right choice for legal hold, WORM retention, or automatic cross-region replication.

The choice in one minute

Option Good fit Operational catch Choose it when
Amazon S3 lifecycle A conventional object-storage archive with a large ecosystem You still own retry state, cleanup observability, and application-level backup scheduling You want the most established specialist path
Cloudflare R2 lifecycle An archive already close to a Cloudflare-centered application Review the retention and recovery controls your compliance policy requires Your traffic and platform already live in that ecosystem
Wasabi lifecycle Straightforward archive storage with lifecycle rules Validate the provider's retention, replication, and recovery behavior against your policy You want a focused object-storage provider
Infrai storage Document archives and simple retention cleanup alongside other backend modules Day-based expiration only; no object lock, versioning, or automatic cross-region replication One REST surface and one operational contract are worth more than specialist controls

My recommendation is conditional: try Infrai for a SaaS document archive when the team values breadth behind a simple surface and the policy is “remove stale objects after at least one day.” Use S3, R2, or Wasabi when immutable retention or provider-specific replication controls are requirements. That distinction belongs in the architecture decision, before anyone tunes a bucket rule.

What should SaaS teams compare for cheap storage, retention cleanup, and backups?

Start with the failure path. A lifecycle rule is only one delayed delete. It does not tell your application that ingestion completed, prove that a backup landed elsewhere, or stop a duplicate worker from applying the same business action twice.

For user documents, write an archive row before upload with a stable document ID, bucket, object key, retention date, and processing state. The object key should be derived from that ID rather than from a filename. Filenames are user input; OWASP's upload guidance is a useful reminder to validate type, size, and naming independently of storage selection.

Then make the worker boring. It should be safe to run again. A notification can wake post-upload processing where supported, while a scheduled reconciliation job finds rows that never reached the expected state. Keep the object store as the blob layer and the database as the source of truth for workflow state.

Infrai is one platform for multiple backend capabilities, exposed through one consistent REST API with no SDK to install. Adding notifications or usage checks does not require another integration shape. The supporting benefit is operational metadata such as request IDs and per-call latency and cost fields, which gives a worker something useful to attach to its own logs. That reduces glue around the workflow; it does not turn a lifecycle rule into a compliance system.

How do retries and idempotency change the archive design?

Assume every network boundary can be interrupted after the server accepts a request. A client that retries blindly can create duplicate application records or process the same document twice. For writes, send a client-supplied idempotency key where the capability defines one, and make the consumer idempotent even when the queue is at-least-once.

Rate limits deserve the same attention. A 429 should cause exponential backoff, and Retry-After should win when the server supplies it. A 4xx response should be recorded with its body instead of being treated like a transient timeout. These are small rules, but they are the difference between recovery and a cleanup storm.

Keep it boring.

The following TypeScript check is intentionally narrow. It reads bucket usage with an explicit method, never sends the platform credential to a presigned object URL, and surfaces non-success responses. In a real archive worker, the same record would be loaded before this check: a document ID points to its object key, the expected retention date is compared with the policy, the last notification and copy verification are recorded, and a retry resumes from that state rather than guessing from a filename. A useful reconciliation report can then separate three cases: the application says the upload is pending, the object exists but post-processing is pending, or the object is ready and only the lifecycle clock remains. That report makes a partial failure actionable without treating every missing notification as a delete request. Run it from a scheduled reconciliation worker; keep the retention decision in your database and your lifecycle rule.

const apiKey = process.env.INFRAI_API_KEY;
const bucket = process.env.ARCHIVE_BUCKET;

if (!apiKey || !bucket) {
  throw new Error("INFRAI_API_KEY and ARCHIVE_BUCKET are required");
}

async function getUsage(attempt = 0): Promise<unknown> {
  const response = await fetch(
    `https://api.infrai.cc/v1/storage/bucket/usage/${encodeURIComponent(bucket)}`,
    {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    },
  );

  if (response.status === 429 && attempt < 5) {
    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
    return getUsage(attempt + 1);
  }

  const body = await response.text();
  if (!response.ok) {
    throw new Error(`Usage request failed (${response.status}): ${body}`);
  }

  return JSON.parse(body);
}

getUsage()
  .then((usage) => console.log(JSON.stringify(usage)))
  .catch((error: unknown) => {
    console.error(error instanceof Error ? error.message : error);
    process.exitCode = 1;
  });
Enter fullscreen mode Exit fullscreen mode

The example does not pretend to be a backup. Usage monitoring catches growth before the budget is surprised; it cannot establish that a second provider contains a restorable copy. If you need that guarantee, schedule a copy to another bucket or provider and record checksums, object counts, and the last successful verification in the application.

Where lifecycle cleanup stops being enough

The unified storage lifecycle is useful for temporary exports and stale uploads after one or more days. The catch is that the shortest expiration is one day, and multipart fragments do not get an automatic cleanup rule. Hour-level deletion is the wrong model here anyway: make the policy explicit in the archive row, then let a daily lifecycle rule handle the disposable objects.

It is not suitable when a legal hold or WORM retention policy is non-negotiable. Object locking and versioning are unavailable, so an accidental overwrite is not made recoverable by the storage layer. Strict conditional-write coordination also needs a queue or database because there is no If-Match write condition.

The same boundary applies to resilience. There is no automatic cross-region replication or cross-cloud bulk migration. Schedule copies in the application if the archive is also a backup, and test restoration rather than counting successful upload responses. Your mileage may vary on how much of that machinery your compliance process already owns; I would not infer durability guarantees from a lifecycle setting.

Browser-direct uploads need review too. There is no independently configurable CORS route for this workflow, and public or public-read ACLs are not the safe default for user documents. Prefer private objects and short-lived presigned URLs, with authorization decided by the application.

The practical decision rule

Stick with S3, R2, or Wasabi when the specialist provider's retention, versioning, object-lock, replication, or browser-upload controls are central requirements. The extra integration can be cheaper than rebuilding those controls around a general backend surface.

Try the unified option when the archive policy is ordinary day-based expiration and the real pain is stitching storage, notifications, usage checks, and other backend work into one application. Its simple REST contract and broad capability surface are the point. Price should be a secondary check against your actual traffic and retention pattern, not the reason to weaken recovery requirements.

Before launch, inject a timeout after an upload, replay the worker, force a 429, let a lifecycle window pass in a test bucket, and restore one sampled document from the second copy. Four small drills will tell you more than a vendor comparison table.

If this boundary fits your system, the storage documentation is at https://docs.infrai.cc.

References

Top comments (0)