Node.js Media Storage: Cheap User Documents Retention and Cleanup
TL;DR: Send large media straight from the browser to object storage with a short-lived, narrowly scoped upload URL. Keep retention in your own database, apply storage lifecycle rules as a backstop, and run a daily verifi
TL;DR: Send large media straight from the browser to object storage with a short-lived, narrowly scoped upload URL. Keep retention in your own database, apply storage lifecycle rules as a backstop, and run a daily verifier that proves expired objects are gone. Compare Amazon S3, Cloudflare R2, and Wasabi by testing that whole loop against your deletion deadline, not by sorting a price table.
For a one-person media SaaS, throughput is product work. Proxying a 4 GB source video through Node.js spends application connections, memory, and operator attention on bytes the app does not need to inspect in transit. Direct upload removes that data-plane hop. It does not remove the control-plane work: authorization, object naming, completion checks, retention decisions, and deletion evidence still belong to the application.
That separation protects the resource a solo operator cannot buy back: a weekly shipping cadence. Storage is undifferentiated infrastructure. The retention contract is part of the product.
How should cheap storage handle user documents retention cleanup?
A lifecycle rule is an asynchronous storage policy, not a customer-facing deletion receipt. A media service usually has at least three clocks: the business retention deadline recorded for the asset, the provider's lifecycle evaluation schedule, and the backup or version-retention window. Treating those clocks as one creates the dangerous failure mode here: the database says a file expired while readable bytes still exist somewhere.
There is a second mismatch. Direct upload lets the browser place bytes without passing them through the app, so the app cannot infer success from the request that created the upload grant. The client may abandon the transfer. It may upload fewer bytes than expected. A retry may create another object. The metadata row and the object can drift apart unless completion is explicit.
So the useful question is not which bucket has the best lifecycle feature in isolation. Ask which setup lets the application enforce and demonstrate these invariants:
- Every object key is bound to one tenant and one asset record.
- An upload grant permits one intended operation for a short period.
- The application marks an asset ready only after checking stored-object metadata.
- The database owns
deleteAfter; a bucket rule is defense in depth. - A scheduled worker retries deletion and records the result.
- A separate verifier searches for objects that survived past the deadline.
Those checks matter more than a small, changeable difference in storage price. One missed deletion request can consume more founder time than months of marginal byte charges.
This isn't free.
Direct upload adds browser CORS configuration, grant expiry, completion reconciliation, and another state transition to debug. It is a poor fit when policy requires synchronous inspection before any byte reaches durable storage, when clients cannot upload reliably to the object endpoint, or when the storage interface cannot issue narrowly scoped grants. In those cases, a controlled ingestion service is the clearer boundary even though it carries the traffic. I would accept the extra hop for that requirement; I would not accept it by default for large media.
The smallest control plane I would ship
The app needs two operations, not a file proxy: one creates an upload grant, and one confirms the completed object. The storage adapter below is intentionally generic. Provider-specific behavior belongs behind this boundary, while the domain code keeps the same retention states.
interface UploadGrant {
objectKey: string;
uploadUrl: string;
expiresAt: string;
}
interface StoredObject {
contentLength: number;
contentType?: string;
checksum?: string;
}
interface ObjectStore {
createPutGrant(input: {
key: string;
contentType: string;
expiresInSeconds: number;
}): Promise<UploadGrant>;
stat(key: string): Promise<StoredObject | null>;
delete(key: string): Promise<void>;
}
type Asset = {
id: string;
tenantId: string;
objectKey: string;
expectedBytes: number;
contentType: string;
status: "pending" | "ready" | "deleting" | "deleted";
deleteAfter: Date;
};
Generate object keys on the server. Do not accept a complete key from the browser. A random asset identifier under a tenant prefix keeps naming predictable without putting an original filename into a URI. Filenames are display metadata; RFC 3986 percent-encoding rules make them a poor authorization boundary.
import { randomUUID } from "node:crypto";
async function beginUpload(input: {
tenantId: string;
contentType: string;
expectedBytes: number;
retentionDays: number;
}, store: ObjectStore): Promise<{ asset: Asset; grant: UploadGrant }> {
const id = randomUUID();
const objectKey = `tenants/${input.tenantId}/assets/${id}/source`;
const deleteAfter = new Date(
Date.now() + input.retentionDays * 24 * 60 * 60 * 1000,
);
const asset: Asset = {
id,
tenantId: input.tenantId,
objectKey,
expectedBytes: input.expectedBytes,
contentType: input.contentType,
status: "pending",
deleteAfter,
};
await assets.insert(asset);
const grant = await store.createPutGrant({
key: objectKey,
contentType: input.contentType,
expiresInSeconds: 900,
});
return { asset, grant };
}
The 900 seconds is an example application decision, not a universal recommendation. Large uploads need a grant lifetime that covers the expected transfer on a slow connection. The safer design is still narrow scope plus explicit expiry, then a fresh grant for a legitimate retry.
Do not trust a browser-provided MIME type or filename as proof of file contents. The OWASP File Upload Cheat Sheet recommends allowlisting extensions, validating type and signature, changing filenames, setting size limits, restricting authorization, and storing uploads away from the web root. Direct upload changes where those controls run; it does not make them optional. A quarantine state works well: upload first, confirm metadata, scan or inspect, then make the asset available.
Confirmation should compare the stored length with the declared length before changing state. If the storage API exposes a checksum with semantics you have verified, compare that too. Avoid assuming that an entity tag always means a particular digest; adapter code should expose only guarantees its implementation can support.
async function confirmUpload(asset: Asset, store: ObjectStore): Promise<Asset> {
if (asset.status !== "pending") throw new Error("Asset is not pending");
const stored = await store.stat(asset.objectKey);
if (!stored) throw new Error("Uploaded object was not found");
if (stored.contentLength !== asset.expectedBytes) {
throw new Error("Uploaded object size does not match");
}
if (stored.contentType && stored.contentType !== asset.contentType) {
throw new Error("Uploaded object type does not match");
}
return assets.updateStatus(asset.id, "ready");
}
Short code, long boundary. Authentication must resolve the tenant before either operation, and reads should go through the same tenant-to-key mapping. Never authorize a download because a caller knows an object key.
Compare the deletion contract, not the logo
Amazon S3, Cloudflare R2, and Wasabi are candidates to put through the same acceptance suite because the decision is about lifecycle cleanup around object storage. Their names do not answer the operational question. Current documentation, account settings, API behavior, support boundaries, and the exact retention mode enabled all affect the result, so verify them in the environment that will be deployed.
Use a scorecard that stays stable when vendor pages or rates change:
| Test | Evidence to collect | Failure that matters |
|---|---|---|
| Direct large upload | Browser-to-bucket transfer plus application memory and connection metrics | App remains in the byte path or upload grants are too broad |
| Expiry selection | Asset row, object key, and deleteAfter timestamp |
Lifecycle age does not match the product's retention promise |
| Explicit deletion | Request ID, attempt time, result, and retry count | A transient error becomes silent retention |
| Lifecycle backstop | A deliberately orphaned test object disappears under the configured rule | Policy scope or prefix is wrong |
| Version cleanup | Tests cover current and noncurrent data where versioning is enabled | An old version remains recoverable |
| Incomplete transfer cleanup | An abandoned multipart or equivalent upload is exercised | Unreferenced parts accumulate |
| Immutability interaction | The test records the earliest legal deletion time | Product promises deletion before policy permits it |
| Inventory or listing | Reconciliation finds a seeded orphan | Absence cannot be demonstrated at useful scale |
Run the suite for each candidate. Keep the raw timestamps. The result can expose a hard limitation: a candidate may pass upload throughput yet require control-plane code that a solo SaaS cannot justify maintaining. That is a real trade-off, and the maintenance burden has a direct revenue-per-hour cost.
No logo fixes that.
There is no honest universal ranking without a workload and a deletion service-level objective. A media archive with frequent playback has a different request and transfer pattern from a backup that is almost never read. Model upload sizes, read frequency, retained bytes, deletion volume, and recovery drills. Then include engineering time: deployment, monitoring, SDK upgrades, incident diagnosis, and portability tests. Price belongs in the sheet, but it should not drive the architecture.
Retention needs a worker and a witness
The deletion worker should claim eligible rows, move them into a deleting state, issue idempotent deletes, and persist each outcome. A retry must not produce a new object key. Limit concurrency so a backlog does not exhaust database connections or storage request quotas.
async function deleteExpired(now: Date, store: ObjectStore): Promise<void> {
const batch = await assets.claimForDeletion({ before: now, limit: 100 });
for (const asset of batch) {
try {
await store.delete(asset.objectKey);
await assets.recordDeletion({
id: asset.id,
deletedAt: new Date(),
outcome: "deleted",
});
} catch (error) {
await assets.recordDeletionAttempt({
id: asset.id,
attemptedAt: new Date(),
message: error instanceof Error ? error.message : "Unknown error",
});
}
}
}
Deletion success is still not proof of system convergence. Add a witness job that samples recently deleted records and checks that objects are absent. Separately list or inventory the managed prefix and flag keys without live database rows. These two directions catch different drift: database-to-storage verification finds failed cleanup, while storage-to-database reconciliation finds orphaned uploads and lost metadata.
Watch four signals: pending uploads older than their grant window, eligible deletions still queued, repeated delete failures, and orphan count. Alert on age, not just count. A queue of ten stuck objects may be more serious than a fresh queue of ten thousand after a scheduled retention boundary.
Keep lifecycle policy as the safety net for abandoned objects and missed application work. Give that rule a longer window than the application deadline if early deletion would violate product behavior. The exact gap is a business decision. Document it, test it, and make the user-facing promise match what the system can demonstrate.
What I would change at scale
The first version can confirm a completed single-request upload and delete in batches. As media sizes and traffic grow, add resumable multipart uploads, event-driven completion hints, and storage inventory reconciliation. Events are hints because delivery can be delayed or duplicated; the database state transition must remain idempotent.
Separate original media, derived renditions, and backups into explicit retention classes. Deleting the source while leaving thumbnails, transcripts, preview clips, or noncurrent versions behind is not complete account cleanup. One asset record can fan out to several stored objects, so the deletion ledger needs every derived key or a prefix whose contents can be enumerated safely.
The trade is extra state. More rows and reconciliation work buy clearer proof, controlled retries, and less dependence on one provider's policy engine. That is worthwhile when deletion deadlines are contractual or when the media graph has many derivatives. For a small service with a simple archive, begin with one asset table, one adapter, one worker, and one daily witness. Ship it. Measure the backlog before adding machinery.
The final choice should survive a provider swap on paper and a failure drill in practice. Direct upload preserves large-file throughput. Application-owned deadlines preserve product semantics. Lifecycle rules catch strays. Verification closes the loop. That division of labor is the durable design; the storage brand is an implementation decision.
Further reading
- OWASP File Upload Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- RFC 3986, URI Generic Syntax: https://www.rfc-editor.org/rfc/rfc3986
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.