Short answer: keep every generated image private, issue a new short-lived download link only after an application authorization check, and schedule deletion from durable metadata rather than from the upload request. Choose the cheapest object storage only after measuring stored bytes, request volume, delivery bytes, and the operational cost of missed cleanup.
That ordering matters for a B2B SaaS application. A low storage rate doesn't rescue a design that exposes one tenant's images to another tenant, and an elegant signed-link flow doesn't help when expired objects accumulate forever. Access control is the hard requirement. Delivery simplicity is the variable to optimize after it.
The runbook has four moves: write an immutable object under a tenant-scoped key, record its retention deadline, authorize each download before signing it, and run an idempotent deletion worker.
Keep it boring.
Replay the cleanup incident before selecting a byte store
Start with the signals that can wake an operator, not a provider comparison page. For private AI-generated images, the useful failure set is small: an unauthorized principal receives bytes, an authorized principal can't retrieve bytes before expiry, an object survives its retention deadline, or a retry causes an inconsistent record. Each signal maps to an invariant that can be tested without knowing which storage service is underneath the interface.
The first invariant is object.tenant_id == caller.tenant_id. The second is that link expiry can never exceed the object's retention deadline. The third is that deletion is safe to repeat. The fourth is that a database record never claims an upload is ready until the object write has succeeded. A public bucket breaks the first invariant by construction because possession of a stable object URL becomes the access decision; a private bucket or equivalent private object namespace keeps that decision in the application.
Don't optimize a single posted rate. Model monthly cost as stored byte-months + write requests + read requests + delivered bytes + scheduled worker cost, then add the engineering burden of the access path. I'm not sure which term will dominate your workload until you have production distributions for image size, retention age, downloads per image, and cache hit rate. A seven-day sample with per-tenant counters will answer more than a generic “cheapest storage” table.
Treat S3, R2, and other object storage alternatives as rows in that same test harness, not as architectural identities. The decision record should contain measured inputs, the required privacy behavior, and an exit test. It shouldn't contain a winner chosen from one attractive line item.
Before implementation, replay this specific race on paper. At 01:59:59, an authorized browser asks for an image whose retention deadline is 02:00:30; the service would normally issue a five-minute link, but it caps this one at 31 seconds. At 02:00:00, cleanup selects the same image. At 02:00:02, a duplicate cleanup delivery selects it again because the first worker's lease expired. At 02:00:03, the first delete succeeds but its database acknowledgement is delayed. The second delete observes an absent object and treats that as success. At 02:00:04, both workers try to mark the row deleted; the state transition is conditional, so one changes the row and the other observes the final state. At 02:00:30, no new link can be issued. The exercise exposes three requirements at once: signing must share the retention clock, deletion must tolerate an already absent object, and the record transition must be idempotent. If an adapter can't satisfy all three under concurrency, its attractive storage rate is irrelevant to this workload.
How can an AI app retain data with private image storage and signed download links?
Separate the control plane from the byte path. The application owns tenants, authorization, retention, and audit events. The object store owns opaque bytes addressed by an unguessable application key. A scheduler scans durable records whose delete_after has passed; it doesn't rely on an in-process timer created during upload, because a deployment or process restart would erase that timer.
For an upload, use a key such as tenants/{tenant-id}/images/{image-id}. Do not put the original filename, prompt, email address, or other user data in that key. Persist an image row with pending state and a deletion deadline, write the object privately, then mark the row ready. If the write fails, leave no downloadable record and retry through the normal job mechanism. If the database transition after a successful write is uncertain, reconciliation should compare pending rows with object existence and converge on one state; uncertainty is a state to repair, not permission to publish the bucket.
For a download, authenticate the caller, load the image row, compare tenant ownership, reject expired records, and only then mint a link whose expiry is min(now + linkTTL, deleteAfter). The link is a bearer credential — anyone holding it can use it until it expires — so keep the lifetime short enough for the product flow and never place the full URL in routine logs. Return 404 for an image outside the caller's tenant if revealing its existence would leak information. Return 410 for an image the same authorized tenant once owned but whose retention period has ended; that distinction gives the client an actionable state without crossing the tenant boundary.
Expiry is not revocation.
The following runnable Go program captures the scheduling boundary. BlobStore and Signer are deliberately generic: adapters can implement them for an object store, a self-hosted service, or an application download gateway without changing the authorization rule.
package main
import (
"context"
"errors"
"fmt"
"time"
)
var ErrNotFound = errors.New("not found")
type Image struct {
ID string
TenantID string
ObjectKey string
State string
DeleteAfter time.Time
}
type BlobStore interface {
PutPrivate(context.Context, string, []byte) error
Delete(context.Context, string) error
}
type Signer interface {
SignDownload(context.Context, string, time.Time) (string, error)
}
type Repository interface {
CreatePending(context.Context, Image) error
MarkReady(context.Context, string) error
Get(context.Context, string) (Image, error)
DueForDeletion(context.Context, time.Time, int) ([]Image, error)
MarkDeleted(context.Context, string) error
}
type Service struct {
Blobs BlobStore
Links Signer
Images Repository
Now func() time.Time
}
func (s Service) Upload(ctx context.Context, tenantID, imageID string, data []byte, retention time.Duration) error {
now := s.Now()
img := Image{
ID: imageID,
TenantID: tenantID,
ObjectKey: fmt.Sprintf("tenants/%s/images/%s", tenantID, imageID),
State: "pending",
DeleteAfter: now.Add(retention),
}
if err := s.Images.CreatePending(ctx, img); err != nil {
return err
}
if err := s.Blobs.PutPrivate(ctx, img.ObjectKey, data); err != nil {
return err
}
return s.Images.MarkReady(ctx, img.ID)
}
func (s Service) DownloadLink(ctx context.Context, tenantID, imageID string, ttl time.Duration) (string, error) {
img, err := s.Images.Get(ctx, imageID)
if err != nil || img.TenantID != tenantID || img.State != "ready" {
return "", ErrNotFound
}
now := s.Now()
if !now.Before(img.DeleteAfter) {
return "", ErrNotFound
}
expires := now.Add(ttl)
if expires.After(img.DeleteAfter) {
expires = img.DeleteAfter
}
return s.Links.SignDownload(ctx, img.ObjectKey, expires)
}
func (s Service) DeleteDue(ctx context.Context, batchSize int) error {
images, err := s.Images.DueForDeletion(ctx, s.Now(), batchSize)
if err != nil {
return err
}
for _, img := range images {
if err := s.Blobs.Delete(ctx, img.ObjectKey); err != nil && !errors.Is(err, ErrNotFound) {
return err
}
if err := s.Images.MarkDeleted(ctx, img.ID); err != nil {
return err
}
}
return nil
}
func main() {
fmt.Println("wire BlobStore, Signer, and Repository adapters in the service process")
}
The important detail is the delete order. Remove the bytes first, then mark the record deleted. If the worker stops between those operations, the next run repeats the object deletion and completes the record transition. Reversing the order can leave bytes behind while the database has forgotten where they are. That's a quiet retention failure, and quiet failures last.
Implement the two-clock state machine as a production job
Run DeleteDue from a scheduler that provides at-least-once execution, and assume every invocation can overlap with another. Claim rows with a lease or database lock, process a bounded batch, and renew the lease only while work is progressing. The worker should emit a stable image ID and tenant ID in structured events, but it should not emit image bytes, prompts, or signed URLs.
Use three counters: records selected, objects deleted, and records marked deleted. Add a histogram for deletion lag, calculated as deleted_at - delete_after. Alert on sustained lag rather than one late object. Also alert when selected records rise while deleted objects remain flat; that ratio catches authorization, credential, or adapter problems without requiring the scheduler to classify every possible cause.
Retries are normal.
A retry budget needs a terminal path. After the normal attempts are exhausted, move the job to a review queue while leaving the image row eligible for reconciliation. Do not extend retention to make the alert disappear. For a duplicate invocation, both workers may attempt deletion, and both should treat “already absent” as success. Idempotency isn't an optional refinement here; it's the difference between a page that resolves on retry and a page that creates more cleanup work.
Schedule reconciliation separately, at a lower frequency. It should find ready database rows whose objects are absent, pending rows older than the upload SLO, and private objects without a corresponding live row. The last check may require a prefix inventory rather than a full scan. Set its cadence from the maximum acceptable retention drift and the cost of listing, then test that a partially completed batch resumes from a durable cursor.
Test the races at authorization and expiry boundaries
Verification should exercise identities and time, not just a happy-path URL. Freeze the clock in tests and assert that tenant A can request its ready image, tenant B receives no evidence of that image, a link never outlives delete_after, an expired row cannot be signed, and two deletion runs leave the same final state. Add a concurrency test in which two workers claim the same due record. The result must be one absent object and one deleted record, regardless of call order.
For browser uploads, progress reporting is a client concern. MDN documents upload progress events through XMLHttpRequest.upload; choosing that mechanism doesn't require making the object public. Keep the authorization boundary on the server that creates an upload capability or accepts the upload. Test cancellation at 1%, 50%, and after the final byte so abandoned multipart data or pending records don't escape reconciliation.
Caching needs an explicit decision because a signed URL and a private object are separate controls. Set response Cache-Control according to whether a shared cache may retain the response; MDN's directive definitions are the reference, and the safe policy depends on the delivery path. Verify the actual response header at the browser-facing endpoint. A signature expiring does not, by itself, prove that an already cached response vanished.
Roll out by tenant and preserve the previous private path
Roll out behind a per-tenant flag. Start with synthetic images, then a small internal tenant, and compare authorization denials, signing latency, deletion lag, bytes stored, writes, reads, and delivered bytes against the old path. The rollback is to stop issuing links through the new adapter and return traffic to the previous private adapter; keep the new cleanup worker running for objects already written there. Never roll back by making a bucket public.
Rollback must preserve privacy.
The catch is that signed download links trade continuous authorization for delivery simplicity. They are not suitable when access must be revoked immediately after issuance, when every byte range must be authorized against current policy, or when a compliance rule requires the application to mediate every download. In those cases, keep the objects private and stream through an authenticated application gateway, accepting the extra bandwidth, latency, and capacity planning.
Stick with a managed object store when the team wants a small operational surface and can express its controls through a generic adapter. Consider a self-hosted object store when deployment control is mandatory and the team is prepared to own durability, upgrades, capacity, and recovery testing. For very small images with transactional access patterns, database storage may be easier to reason about, but it couples database growth and backup behavior to the image workload. None is universally cheapest.
| Delivery path | Access check | Operational load | Main limitation |
|---|---|---|---|
| Short-lived signed link | At link issuance | Storage adapter plus cleanup worker | Policy changes do not revoke an issued link |
| Authenticated application gateway | On every request | Gateway bandwidth and capacity | More latency and a larger serving surface |
| Database-backed image response | On every query | Database growth and backup load | Couples image traffic to transactional capacity |
The final decision rule is operational: select the private storage path that passes cross-tenant authorization tests, bounds link lifetime by retention, survives duplicate cleanup delivery, and wins on your measured total-cost inputs. Re-run the comparison when image size, retention, or download frequency shifts. The schedule is part of the storage design, not housekeeping added later.
Top comments (0)