The decisive trade-off is access control versus delivery simplicity: keep every tenant backup in private object storage, let the storage lifecycle delete objects after 30 days, and make the application authorize each selected-snapshot restore before any bytes leave storage. A direct download link is easier to ship, but application-mediated authorization provides a cleaner place to enforce tenant boundaries, record an audit decision, and reject replayed requests.
Short answer: use a private bucket, a narrow workload identity, a prefix-scoped 30-day expiration rule, and an idempotent restore coordinator whose database records the snapshot state and evidence needed for reconciliation.
This is deliberately two systems, not one. Object storage owns retention and deletion; the application owns who may create or restore a backup. Trying to make a bucket policy understand B2B SaaS membership usually couples authorization to object keys, while making an application scheduler delete every old object turns a durable storage control into a job that can be skipped during a deployment.
How should a Node.js app combine private backup retention and object storage lifecycle?
Treat the Node.js service as the control plane even if backup workers are written in another language. It accepts a tenant-scoped request, checks the caller against the tenant, creates a snapshot record, and dispatches work with a stable operation ID. The worker writes one archive under a non-user-controlled key such as backups/<tenant-id>/<snapshot-id>.tar, computes a digest while streaming, and reports completion through an idempotent state transition. The object key is an internal locator, never proof that a caller may read the object.
The storage account should expose only the actions each component needs. A backup writer can create objects under the backup prefix but cannot read arbitrary tenant archives. A restore worker can read a specifically authorized snapshot. The lifecycle administrator can change retention configuration, but the runtime identity cannot. Keep interactive users out of the bucket policy entirely; they belong in application authorization, where tenant membership and restore approvals are available.
The practical policy model is small:
| Principal | Object scope | Allowed operation | Deliberately absent |
|---|---|---|---|
| Backup worker | One tenant backup prefix | Create archive | Read, policy change |
| Restore worker | Authorized snapshot key | Read archive | List all tenants, policy change |
| Lifecycle administrator | Backup lifecycle configuration | Set and review expiry | Restore application data |
| Application user | None | Request through the app | Direct bucket access |
OWASP's file-upload guidance supports the surrounding controls: generate filenames in the application, constrain size and accepted content, authorize upload operations, and store files away from the application webroot or on a separate host. A backup archive is not a harmless blob merely because the application created it. Restore extraction must still reject path traversal, unexpected file types, and decompression that exceeds declared limits.
Keep the bucket private.
If the delivery path uses a time-limited signed URL, regard it as a bearer credential and issue it only after the same tenant check. That option reduces application bandwidth and may be appropriate for a controlled restore worker, but it weakens the application's ability to stop access after disclosure until the URL expires. Proxying the stream through the restore service costs operational capacity; in return, each read stays behind the live authorization decision. Your mileage may vary with archive size and the guarantees of the chosen object store, so decide from a threat model rather than convenience alone.
What fails when the 30-day retention clock is ambiguous?
“Delete after 30 days” sounds precise but leaves three different timestamps in play: when the export was requested, when its object upload completed, and when the catalog marked the snapshot restorable. Pick one as the contractual retention origin and persist all three. For a storage-native lifecycle rule, object creation time is normally the enforceable clock; the catalog should display that expiry basis rather than inventing an application deadline it cannot independently enforce.
Configure one rule scoped only to the backup prefix, with expiration at 30 days. Do not aim the rule at an entire shared bucket, because logs, restore reports, or unrelated tenant assets may have different retention obligations. Do not rely on object naming alone either. The rollout check should read the installed lifecycle configuration through the provider's supported control plane and compare its prefix and duration with the deployment's declared values.
The catch is that lifecycle deletion is asynchronous in many storage designs, so the application catalog should distinguish “retention deadline reached” from “deletion verified.” It must not promise that a snapshot remains restorable after the deadline, and it must not claim deletion evidence until an inventory or metadata check confirms absence. This distinction matters in an audit: a policy declaration, an eligibility timestamp, and observed deletion are separate facts.
A compact, provider-neutral configuration object keeps the intended rule reviewable without pretending that every service uses identical policy syntax:
package backup import "time" type LifecycleRule struct { Name string Prefix string ExpireAfter time.Duration Enabled bool } var BackupExpiry = LifecycleRule{ Name: "tenant-backup-expiry", Prefix: "backups/", ExpireAfter: 30 * 24 * time.Hour, Enabled: true, } Thirty days is an application retention choice, not a universal compliance answer. Contract terms, litigation holds, sector rules, recovery objectives, and deletion obligations can require a different period or a separate hold mechanism. A team that cannot demonstrate which obligation authorized the number should pause rollout; a lifecycle rule faithfully enforces a bad schedule just as readily as a good one.
Retention is only one clock-related failure mode. Backup queues, upload callbacks, and restore requests are usually retried, which means the architecture should pursue exactly-once business effects while accepting at-least-once message delivery. Give every create or restore request an idempotency key scoped to its tenant, store the resulting operation before dispatch, and make repeated submissions return the existing operation rather than allocate a second snapshot or start a second database replacement.
This is where a concrete failure is easy to miss: request restore-0187 can be delivered twice after a worker loses its acknowledgement, even though the first restore completed. Without a durable operation record, the second delivery can overwrite freshly written tenant data and produce two superficially successful audit entries. With a uniqueness constraint on (tenant_id, idempotency_key), both deliveries converge on one state machine. No guesswork.
The state machine needs few states, but its transitions should be explicit: requested, authorized, running, verified, and failed. Record the authenticated subject, tenant, snapshot ID, digest, policy version, request ID, timestamps, and transition reason. Never log signed URLs, raw credentials, or backup contents. The audit trail answers who approved a restore and what bytes were selected; the object store answers whether those bytes still exist.
package backup import ( "context" "errors" "io" ) var ErrExpired = errors.New("snapshot is outside the restore window") type Snapshot struct { TenantID string ID string ObjectKey string SHA256 string State string } type Catalog interface { BeginRestore(ctx context.Context, tenantID, snapshotID, idempotencyKey string) (Snapshot, bool, error) MarkVerified(ctx context.Context, tenantID, snapshotID, digest string) error } type Objects interface { Open(ctx context.Context, key string) (io.ReadCloser, error) } func Restore(ctx context.Context, catalog Catalog, objects Objects, tenantID, snapshotID, key string) error { snapshot, alreadyHandled, err := catalog.BeginRestore(ctx, tenantID, snapshotID, key) if err != nil || alreadyHandled { return err } archive, err := objects.Open(ctx, snapshot.ObjectKey) if err != nil { return err } defer archive.Close() digest, err := validateAndApplyArchive(ctx, tenantID, archive) if err != nil { return err } if digest != snapshot.SHA256 { return errors.New("snapshot digest mismatch") } return catalog.MarkVerified(ctx, tenantID, snapshotID, digest) } validateAndApplyArchive is intentionally a boundary rather than a few optimistic lines: safe extraction, schema compatibility, row-count reconciliation, transactional replacement, and post-restore invariants are domain work. For a ledger-like dataset, verify balanced aggregates and immutable identifiers before making restored data visible. For ordinary B2B SaaS records, validate tenant ownership on every imported row and reconcile counts by entity type. The selected archive may be authentic and still be incompatible with the current schema.
Which restore delivery boundary preserves tenant access control?
There are three defensible delivery shapes. Application proxying gives the strongest live authorization and simplest revocation story, but the service must carry archive traffic. A signed object URL removes that data path from the application, but possession grants access until expiry and audit correlation spans two systems. A dedicated restore worker keeps objects off user devices and is often the cleanest route for server-side recovery, though it adds a queue and worker identity to operate.
None wins universally.
Use application proxying when restores are small, interactive, and subject to immediate access revocation. Use a dedicated worker when restoration changes server-side tenant state or archives are large enough to make an API proxy awkward. Use signed delivery only when the consumer is trusted to handle the archive, the credential lifetime is appropriately narrow, and disclosure during that lifetime is an accepted risk. A public bucket is not suitable for private backups under any of these models.
This comparison also exposes the limitation of a pure lifecycle design: it expires objects but does not authorize restores, validate archives, reconcile application state, or prove that recovery works. Conversely, an application cleanup job may encode legal holds and catalog state more directly, but it assumes the scheduler, pagination, credentials, retries, and monitoring all continue to work. Prefer storage lifecycle for the base 30-day disposal invariant; add an application deletion workflow only when exceptions require business context the storage rule cannot express.
I'm not sure a single exception model can serve both ordinary retention and every legal hold regime; the deciding evidence is the organization's documented obligation and the selected store's supported hold semantics. If exceptions are frequent or individually adjudicated, keep them in a separately governed prefix or account rather than continually editing the base expiration rule.
How can a team prove recovery before archived data expires?
Start with one test tenant and a harmless dataset. Create a backup, verify the catalog metadata and digest, restore it into an isolated destination, and reconcile the restored records. Then install the lifecycle rule in observation mode where the platform permits review, confirm its exact prefix and 30-day value, and enable it through the normal change process. Record the policy revision in the audit log.
Before expanding, exercise duplicate create and restore messages, cross-tenant snapshot IDs, revoked membership, a corrupted archive, an archive built against an older schema, and a snapshot at the retention boundary. Monitor backup completion age, restore verification failures, catalog objects missing from storage, storage objects missing from the catalog, and objects observed beyond their deletion-eligible date. Alerts should carry tenant-safe identifiers and request IDs, not archive content.
Finally, rehearse policy rollback separately from data restore. Disabling a bad future expiration rule can prevent additional eligibility decisions; it cannot recreate an object already deleted. That asymmetry deserves an approval gate and an independent policy review. The compact decision rule is this: storage owns routine disposal, the application owns tenant authorization, and an auditable restore coordinator owns the handoff between them.
