# AI Image Storage: Private Originals, Thumbnails, Variants, and Lifecycle Deletion

> Source: <https://dev.to/grahamprice3746/ai-image-storage-private-originals-thumbnails-variants-and-lifecycle-deletion-ib6>
> Published: 2026-11-28 23:39:38+00:00

**Recommendation:** Gate signed-URL issuance on a database row's tenant, status, legal-hold and delete_at checks, and pair lifecycle rules with an idempotent reconciler to catch objects whose rows were never written.
More in the playbook "Running AI in production": <https://wpnews.pro/playbooks/production-ops>

Short answer: store AI-generated originals, thumbnails, and variants as immutable objects in a private bucket, keep authorization and deletion deadlines in a database, and mint short-lived signed links only after an access check. Lifecycle rules handle broad cleanup; an idempotent reconciler handles the gaps. For signed marketplace documents, access control wins over delivery simplicity because a leaked URL must not outlive the document's retention policy.

That decision is an architecture record, not a vendor preference. The invariants are straightforward: one tenant owns each object, an object key never changes, a document has one effective deletion deadline, and every destructive action leaves an audit event. The failure boundaries matter more than the happy path. A worker can die after writing bytes but before writing a row; a client can retry a generation request; a signed URL can be copied into a ticket. Each case needs a deterministic outcome.

Use object storage for bytes and a relational table for intent. A row such as `asset(tenant_id, generation_id, kind, object_key, checksum, created_at, delete_at, legal_hold)` is the authorization and retention record. `kind` distinguishes `original`, `thumbnail`, and `variant`; it should not be inferred from a display filename. Generate a random generation ID and use it in the key, for example `tenants/t_42/generations/g_8f2/original/source.png`. Prefixes help policy reviews, but they are not authorization.

The application checks the row's tenant, status, and retention state before issuing a read capability. The URL is a capability with an expiry measured in minutes, not a column to hand to another service forever. Store the key and an audit record; mint another link for the next authorized request.

Keep it private.

Here is the critical path in Go. The adapter is deliberately generic, which keeps policy tests independent of a particular SDK.

```
package storage

import (
    "context"
    "errors"
    "time"
)

type Asset struct {
    TenantID   string
    ObjectKey  string
    Status     string
    DeleteAt   time.Time
    LegalHold  bool
}

type PrivateStore interface {
    PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error)
}

func SignedAssetLink(ctx context.Context, store PrivateStore, asset Asset, requester string, now time.Time) (string, error) {
    if asset.TenantID != requester || asset.Status != "ready" || asset.LegalHold {
        return "", errors.New("asset unavailable")
    }
    if !asset.DeleteAt.IsZero() && !now.Before(asset.DeleteAt) {
        return "", errors.New("asset expired")
    }
    return store.PresignGet(ctx, asset.ObjectKey, 5*time.Minute)
}
```

The five-minute value is a policy choice, not a security theorem. A download that must survive a slow mobile connection can use a range-capable client and a renewed link, while a sensitive contract preview may use a shorter TTL. Log the request ID, tenant, object key, and policy decision; never log the signed query string.

The table records the trade-off I would put in a design review. “Simple” means fewer moving parts, not fewer ways to violate a deletion deadline.

| Pattern | Access control | Delivery simplicity | Retention behavior | Appropriate use | 
|---|---|---|---|---|
| Public bucket URLs | Weak once copied | High | Hard to enforce | Non-sensitive, intentionally public derivatives | 
| Private objects plus API streaming | Strong central policy | Lower; API carries bytes | Precise database decision | Small files and strict audit requirements | 
| Private objects plus signed links | Strong at issuance | High for browsers and CDNs | Pair with lifecycle and reconciler | Originals, contracts, and large variants | 
| Database blobs | Strong in one transaction | Low at scale | Transactional but operationally heavy | Small records, not image batches | 

For a marketplace that retains signed documents, private objects plus signed links is the useful default. Public URLs make revocation aspirational. Database blobs make every thumbnail read compete with transactional work. API streaming remains valid when every byte must pass through a policy engine, such as a watermarking or per-request redaction service.

Exactly-once is a mindset rather than a promise from an object store. Give each generation and export an idempotency key, enforce a unique constraint on `(tenant_id, generation_id, kind)`, and make completion conditional on the expected checksum. A retry can then return the existing result instead of producing a second original.

The database clock answers “may this tenant still access the document?” The object-store lifecycle clock answers “when should these bytes be removed?” They can disagree by minutes or hours, so the application must deny access at `delete_at` even if physical deletion is pending. A legal hold should suspend deletion and be visible in the audit trail; it must not silently extend access for unrelated tenants.

Run a reconciler at least daily. It compares ready rows with object metadata, records orphaned objects, and queues deletion only when `delete_at` has passed and `legal_hold` is false. Lifecycle rules should expire incomplete multipart uploads and old exports as a backstop. Neither mechanism replaces the other: a lifecycle rule cannot understand a legal hold, while a database job cannot see bytes left by a crashed worker.

Consider a concrete race. At 23:59 a document worker finishes an upload, receives the object version and checksum, and then loses its process before committing the asset row. At 00:00 the tenant's retention deadline passes. A bucket-only policy sees bytes with no business context and leaves them behind; a database-only job sees no row and cannot find them. The reconciler therefore lists metadata only within the tenant's prefixes, matches object keys against committed rows, and places the orphan on a quarantine queue. A second pass checks whether a late commit arrived, then deletes the object and records the key, checksum, deadline, and actor in an append-only audit event. This sequence is deliberately conservative: a false positive delays cleanup, while a false negative can expose a signed contract after its promised deletion time. The queue is retryable, and each decision is keyed by the object version so a replay cannot create a second audit outcome.

The long-running purge should be resumable and boring. Claim a batch, delete by immutable key, write an audit event, then mark the row purged. If the process stops after the delete but before the mark, the next attempt treats “not found” as an already-completed delete and records that fact. This is where an exactly-once mindset pays for itself.

Test policy with a matrix, not a single happy-path integration test: another tenant's row, an expired deadline, an active legal hold, a non-ready asset, a replayed idempotency key, and a signed link after its TTL. Test storage separately with interrupted multipart uploads, checksum mismatch, and a worker crash between object completion and database commit.

I use 32 MB, 200 MB, and 1 GB fixtures when choosing multipart thresholds, then record p50 and p95 upload time, retry bytes, and thumbnail lag. Those numbers are workload-specific; your mileage may vary with browser memory, region distance, and concurrency. A tiny thumbnail should take a single put. Multipart orchestration is unsuitable when its bookkeeping costs more than the object.

Observability closes the loop: emit counters for presign denials, orphan bytes, purge age, and lifecycle expirations; attach tenant and generation IDs to traces; alert when the oldest eligible deletion exceeds its deadline. Do not put deletion in an interactive request. Queue it, bound retries, and expose a status that support can audit.

The catch is that this design asks the team to operate a metadata table, a reconciler, and retention policy alongside the bucket. Stick with a simpler public delivery path when the image is intentionally public and revocation has no business meaning. Choose API streaming when policy must inspect every response. For private marketplace documents, accepting that operational work is the price of enforceable access control.

Begin with immutable tenant-scoped keys, private objects, metadata rows, five-minute signed reads, and a lifecycle rule for incomplete uploads. Add a reconciler before launch if deletion deadlines are contractual. Add multipart uploads only after the fixture measurements show that retries or latency justify them. Review the audit trail as carefully as the bytes: a system that deletes correctly but cannot prove why is still an operational liability.
