DEV Community

SterlingVance2196
SterlingVance2196

Posted on

User-Uploaded Avatars in Object Storage: Retention, Audit Trails, and Deletion

Short answer: select object storage by its retention and deletion behavior, then put authorization, audit history, and reconciliation in the application; direct upload should keep large avatar bytes off the API path.

Fintech media retention is the design constraint, not an afterthought to an upload endpoint. For user avatars and other large customer media, the application should authorize a short-lived direct upload, record an immutable object identity, and make retention state explicit before any bytes move. Deletion then becomes a controlled state transition with evidence, rather than a best-effort request sent to a storage service.

That trade-off changes the architecture. The application keeps metadata, authorization, and audit records; object storage receives the file directly. This avoids proxying large bodies through an API process, while preserving an exactly-once mindset around business events. The object is disposable. The record explaining why it existed is not.

How should object storage handle storing user-uploaded avatars?

An avatar upload has at least four separate identities: the account, the media record, the object key, and the upload attempt. Conflating them creates deletion bugs. A stable media ID can identify the business object, while a generated object key can identify one immutable blob, for example tenant/7f/media/01J.../original. The key should not be derived from an email address or filename; those values change, collide, and expose more information than a delivery URL needs to expose.

The upload protocol should therefore be two-phase. First, the API validates the account and creates a pending media row with a retention class, expected content type, maximum size, and an expiration time. Second, it issues a narrowly scoped, short-lived upload capability whose destination is that one object key. The browser or mobile client sends bytes to storage, then calls a small completion endpoint. The API verifies that the object exists, checks the observed size and media metadata, and changes the row from pending to available. A client saying “upload finished” is not evidence that storage received the complete object.

Deletion is a workflow.

Keep the audit trail.

This is where idempotency earns its keep. A retry of completion must return the same media result, not create a second row or extend retention accidentally. Store the idempotency key with the outcome, constrain the media ID uniquely, and treat a repeated request with a different payload as a conflict. Exactly once is a property of the business transition, even when the network delivers the request more than once.

The response headers at delivery time deserve the same care. Content-Disposition can tell a user agent whether content is displayed inline or treated as a download, but it does not authorize access and it does not make an untrusted filename safe. For an avatar, an application-controlled filename and an explicit content type are preferable to copying a client-supplied name into a response header.

Why is deletion harder than upload?

Upload creates one visible thing. Deletion must account for retries, replicas, cached responses, legal holds, and references that arrive out of order. I start by defining a retention state machine before choosing a storage implementation: pending, available, scheduled, held, deleted, and delete_failed are enough for many systems, provided each transition has an actor, timestamp, reason, and request identifier. A hard delete should be a consequence of an approved transition, not a side effect of deleting a database row.

A useful invariant is: no new business reference may point to an object in scheduled or deleted, and every transition is append-only in the audit log. The current row is a convenient projection; the event history is the evidence used during reconciliation. If an operator retries a deletion job, the worker can safely treat “already absent” as an idempotent outcome while still recording that the verification occurred.

Retention also needs a clock policy. “Delete after 30 days” is ambiguous unless the system says which timestamp starts the clock: upload completion, account closure, last reference, or a policy change. In a financial system, I would store the policy version and the computed deletion deadline on the media record. A later policy edit must not silently rewrite old evidence. A hold can pause execution without erasing the original deadline, so release and rescheduling remain auditable.

The awkward case is a failed delete. Do not report success because the database update succeeded. Mark the record for retry, expose the failure in an operational queue, and keep the object inaccessible through normal application authorization while reconciliation continues. This preserves the user-facing privacy decision without pretending that physical removal has already been confirmed.

A small contract keeps the application honest

The storage adapter should describe capabilities that the retention workflow actually needs. It should not leak a provider-specific client through every handler. The following Go interface intentionally has only three operations: create an upload capability, inspect an object, and remove an object. Production code would also need context deadlines, structured error types, and a separate mechanism for listing orphan candidates; the point here is to keep business state transitions visible.

type ObjectStore interface {
    CreateUpload(ctx context.Context, key string, contentType string, expiresAt time.Time) (string, error)
    Stat(ctx context.Context, key string) (ObjectInfo, error)
    Delete(ctx context.Context, key string) error
}

type ObjectInfo struct {
    Key         string
    Size        int64
    ContentType string
    ETag        string
}

func completeAvatar(ctx context.Context, store ObjectStore, m *Media, uploadID string) error {
    if m.Status == "available" {
        return nil // idempotent replay
    }
    if m.UploadID != uploadID || m.Status != "pending" {
        return ErrInvalidTransition
    }

    info, err := store.Stat(ctx, m.ObjectKey)
    if err != nil {
        return fmt.Errorf("inspect upload: %w", err)
    }
    if info.Size == 0 || info.Size > m.MaxBytes {
        return ErrInvalidObject
    }
    if info.ContentType != m.ExpectedType {
        return ErrInvalidObject
    }

    // Persist the state change and audit event in one database transaction.
    return markAvailable(ctx, m.ID, info, uploadID)
}
Enter fullscreen mode Exit fullscreen mode

The storage service remains responsible for bytes and its own durability semantics. The application remains responsible for who may upload, who may view, and when retention permits deletion. That boundary makes tests clearer: a fake store can return a completed object, an absent object, a transient error, or a mismatched size without requiring a browser or a live bucket.

The operational comparison is about behavior, not labels

An “S3-compatible” interface is a useful portability boundary, but compatibility is not a complete retention policy. Before selecting an implementation, test the behaviors that affect the state machine: conditional writes, object visibility after upload, deletion response semantics, multipart completion, metadata preservation, lifecycle timing, and the ability to inspect or enumerate orphaned keys. The same method name can hide different guarantees.

For a fintech team, I would put those behaviors in a conformance test suite and run it against every candidate deployment. Keep the fixture small: a 2 MB avatar, a deliberately interrupted multipart upload, a duplicate completion request, an object with an unexpected content type, and a deletion retried after the first response is lost. Record observed results as capability data, not assumptions copied from an API label.

The deployment decision then has three dimensions. A managed service may reduce the operational burden of replication and patching, but the team still owns authorization, lifecycle policy, and reconciliation. A self-hosted gateway may offer control over placement and network boundaries, but upgrades, capacity planning, and failure drills become part of the service. A distributed object layer can fit an existing platform, yet its operational surface may be disproportionate for a modest avatar workload. None of these is universally correct; retention evidence and failure recovery should decide. My decision rule is deliberately unglamorous: accept more operational machinery only when it gives the retention workflow a capability the simpler deployment cannot provide, and document that capability as a test rather than as a marketing label. This keeps the choice reversible without making portability the article's main argument.

I would also measure the path that is easy to ignore: orphan rate, time from scheduled deletion to verified absence, repeated completion conflicts, upload expiry rate, and the age of the oldest unresolved delete. These are more useful than a single throughput number because they expose whether the business state and object state are drifting apart.

Roll out deletion as a controlled migration

Start in observe-only mode. Create media records, issue direct uploads, and run a reconciler that reports mismatches without deleting anything. Compare database rows with object metadata, sample delivery authorization, and make the audit record queryable by media ID. This stage catches key construction and clock errors while the blast radius is small.

Next, enable deletion for a narrow retention class, such as abandoned pending uploads whose expiration is unambiguous. Require a dry-run report and an operator-visible reason for each batch. Only after the retry behavior is boring should account closure or policy-driven deletion be enabled. Keep the old read path during rollout, but prevent it from creating new references to objects already marked for deletion.

The final rule is compact: direct upload protects the application from carrying bytes, while explicit retention state protects the system from losing accountability. Use a provider-neutral object contract, verify completion server-side, make deletion idempotent, and reconcile the two stores continuously. That is the practical meaning of auditable delivery for user media in a financial product.

Sources

Top comments (0)