Private AI Image Storage: 3 Node.js Retention Rules for Signed Downloads
Short answer: keep generated images in a private object store, put an ownership and retention record in your database, and create a short-lived signed download only after authorization. For a marketplace, the cheapest de
Short answer: keep generated images in a private object store, put an ownership and retention record in your database, and create a short-lived signed download only after authorization. For a marketplace, the cheapest design is usually the one that deletes abandoned originals reliably; storage price alone is a poor decision rule.
A seller can generate five product images, close the tab, and never publish the listing. If those bytes remain forever, a small AI feature becomes an unbounded archive. I model each image as a database record plus an object key, not as a URL. The key survives link expiry; the link is disposable.
Tiny rule: no public bucket.
The retention-first data flow
Create a pending image row before the browser uploads anything. Give the browser a narrowly scoped upload target, so the application server does not proxy large media bytes. On completion, verify the object key, byte count, media type, and owner before changing the row to ready. A background worker then applies the marketplace policy: drafts expire quickly, published listing images stay while the listing is active, and deleted listings enter a grace period before physical removal.
That order matters. In my first sketch of this flow, I wanted to mark an image ready as soon as the upload request started. A dropped mobile connection produced a perfectly valid row pointing at nothing. The fix was boring: pending, ready, scheduled_for_delete, and deleted are explicit states, and only a completion check can advance the first one.
A deletion job should be idempotent. It can run twice, lose its lease, or see an object that was already removed. Record the last attempt and reason, retry transient failures with backoff, and alert on age rather than on a single failed run. Retention is an operational promise, not a cron expression.
The long-tail case is where the policy earns its keep: imagine a seller generating 40 images for a seasonal catalog while a worker is redeployed, then abandoning half the draft. Some uploads finish after the browser has gone away; others have metadata but no complete object; a retry can race the cleanup worker; and a listing can be deleted while its thumbnail is still cached at the edge. Treat each transition as an event with an idempotency key, make deletion conditional on the database state and deleteAfter timestamp, and retain an audit row after the bytes are gone. That lets support answer who deleted an image without keeping the image itself, and it prevents a late upload callback from resurrecting a draft that already crossed its retention boundary.
Not flashy.
How should an AI app handle private image storage and signed downloads?
The read path is intentionally short. The API checks the viewer's relationship to the listing, loads the object key from the database, and signs a GET for a small time window. It never accepts an arbitrary key from the browser, and it never treats a signed URL as a permanent identifier. Set response headers deliberately: Cache-Control can permit a private browser cache for an image that is safe to reuse, while a stricter policy is appropriate for sensitive drafts. MDN documents the header semantics and cache directives.
Here is the shape I use in a Node.js service. The storage client is an interface so the same policy can sit over an S3-compatible service, a self-hosted gateway, or another object storage alternative without changing authorization code.
type ImageState = "pending" | "ready" | "scheduled_for_delete" | "deleted";
interface ImageRecord {
id: string;
ownerId: string;
listingId: string;
objectKey: string;
state: ImageState;
deleteAfter?: Date;
}
interface PrivateStore {
signGet(key: string, expiresInSeconds: number): Promise<string>;
remove(key: string): Promise<void>;
}
async function createDownloadLink(
viewerId: string,
image: ImageRecord,
canViewListing: (viewer: string, listing: string) => Promise<boolean>,
store: PrivateStore,
): Promise<string> {
if (image.state !== "ready" || !(await canViewListing(viewerId, image.listingId))) {
throw new Error("image is not available");
}
return store.signGet(image.objectKey, 300);
}
Five minutes is a policy choice, not a magic security value. If a client needs resumable downloads, issue another link after the same authorization check. I am not sure one expiry fits every marketplace; your mileage may vary when sellers share previews with buyers or moderators.
What actually makes an object-storage option cheap?
Compare the full lifecycle, not a headline per-gigabyte rate. Include request charges, egress, minimum retention periods, replication, lifecycle-rule behavior, and the engineering time spent reconciling orphaned uploads. A service with a lower storage rate can cost more if every image is repeatedly downloaded through your application server. Conversely, a higher rate may be sensible when it includes the deletion and audit controls your team would otherwise build.
Keep the bucket private and the application authoritative. Public read ACLs turn a copied key into an access grant, and a predictable path leaks marketplace inventory. Signed links solve delivery authorization; they do not solve tenant isolation, malware scanning, or accidental overwrite. Use per-tenant prefixes, random identifiers, and immutable metadata from the database.
For generated images, store a small manifest beside the object record: model name, prompt hash, dimensions, and content checksum. The manifest makes deduplication and deletion review possible without scanning image bytes. It also gives you a way to distinguish a regenerated thumbnail from the original asset.
Where does the design fail?
The catch is that direct browser upload depends on a correct CORS policy and on clients handling interruptions. A signed target can be valid while the browser still blocks the request. Test preflight behavior in CI, and keep a server-side upload path for moderation or transformations that truly require inspection. MDN's XMLHttpRequest documentation covers upload progress events if the UI needs honest progress rather than a spinner.
Do not choose this pattern when the product needs public, permanent image URLs, cross-region replication with strict recovery objectives, or server-side queries over object metadata. Stick with a platform that natively supplies those controls, even if its API is less convenient. Also avoid promising deletion in seconds when lifecycle processing is asynchronous; publish a measurable deletion window and monitor it.
An operational checklist fits in prose: measure the age of pending rows, count objects with no database owner, sample signed-link authorization decisions, and rehearse a bulk deletion. Then review egress and cache behavior after launch. The decision is sound when a forgotten draft disappears on schedule, a published image remains available, and no public bucket is needed to make downloads work.
References
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.