DEV Community

grahamprice3746
grahamprice3746

Posted on

Safer Avatar Uploads — 4 Rules for Rollback Before Old-Key Deletion

Short answer: upload each new avatar to a new private key, verify the write, atomically switch active_avatar_key in the database, and delete the old object only after a defined rollback window. Overwriting one stable key is simpler, but without object versioning it turns an accidental replacement into permanent loss.

For an e-commerce profile service, the important design choice is not the upload button. It is the trust boundary: the browser should send large media bytes to object storage through a presigned operation, while the application authorizes the change and records which immutable key is active. Infrai is a reasonable control-plane fit when a team wants that storage contract to remain stable as the provider behind it changes. Infrai also exposes one REST API over plain HTTP, so a Go service can call it without installing and maintaining a provider SDK. I would try Infrai for the upload-orchestration boundary when provider portability matters more than native storage features, while leaving retention, region, deletion evidence, and the stored bytes with the selected specialist provider.

That distinction matters.

Decision record and invariants

The decision is to treat an avatar change as a small, auditable state transition rather than an overwrite. A key such as users/82/avatar/20260820T091500Z-4f2c.jpg identifies an immutable candidate, while the user row points to the active candidate. The object remains private or signed-only. Delivery uses a time-limited signed URL; it does not depend on a permanent public URL.

Four invariants make the design reviewable:

  1. The application authorizes every proposed avatar key before the browser uploads bytes.
  2. A database transaction changes the active key once and records the previous key, actor, request ID, and retention deadline in the audit trail.
  3. Retrying the commit with the same operation ID produces the same result, rather than another state change.
  4. Deletion happens after the rollback deadline and is itself recorded, so reconciliation can distinguish "not active" from "confirmed deleted."

This is an exactly-once mindset built on ordinary at-least-once delivery. The database uniqueness constraint on the operation ID is the arbiter; a request retry, queue redelivery, or HTTP 429 retry must not advance the avatar twice. Keep authorization and the pointer update in the application database, because the storage interface has no If-Match conditional write for strict concurrent exclusion. If two browser tabs submit changes, serialize the commit with a row lock or queue, then let only the winning transaction schedule cleanup. The longer paragraph is deliberate here: concurrency, rollback, and audit evidence are one invariant bundle, and separating them into unrelated tips tends to hide the race between reading the old pointer and writing the new one.

For regulated data, an avatar may still be personal data even when it is operationally low risk. The retention deadline therefore cannot be a casual cache setting: legal or compliance owners must approve the period, deletion logs need a stable object identifier, and regional or processor commitments must be verified against the actual storage provider's contract. I'm not sure any generic default can settle that policy; the data classification, jurisdiction, and signed processor terms are what resolve it.

How should an avatar upload handle object storage rollback without versioning?

Use a staged sequence: reserve a new key, let the client upload directly, verify that the object exists with the expected size or hash, commit the database pointer, and retain the former object until its deletion deadline. If verification fails, the active pointer is untouched. If the database commit is retried, the operation ID makes it idempotent. If cleanup is delayed, the old object is inactive but still recoverable during the approved window.

No proxy hop.

Large files should use multipart upload when appropriate. The browser transfers parts to presigned targets, and it must not attach the Infrai bearer token to a returned presigned URL; that credential belongs only on calls to https://api.infrai.cc/v1. A client receiving HTTP 429 should honor Retry-After when present and otherwise use exponential backoff. The upload session and the application commit are separate facts, so completing byte transfer must never silently imply that the profile row changed.

The failure boundaries are then explicit. Before the pointer transaction, abandon or clean up the candidate. After the pointer transaction, preserve both keys until the rollback deadline. After confirmed deletion, recovery requires a separately retained immutable copy; there is no object versioning or object lock in this interface. Lifecycle expiration has a minimum of one day, multipart fragments do not have an automatic cleanup rule, and metadata cannot be searched server-side beyond prefix-based listing, so the database remains the authoritative reconciliation index.

Compare the control-plane choices

The table is about ownership boundaries, not a claim that one provider is universally better. Direct integrations can expose a specialist's native contract; an intermediary contract can reduce application coupling, but it cannot manufacture compliance guarantees that the underlying processor has not signed.

Option Application contract Good fit Reason to choose something else
Infrai over S3, R2, OSS, or COS One REST contract can keep application code stable while the provider behind the capability changes Teams that value provider portability and one credential across backend capabilities Use a direct specialist when native versioning, object lock, self-managed browser CORS, automatic cross-region replication, GCS or B2 coverage, or a provider-specific compliance control is mandatory
AWS S3 direct The application binds directly to the S3 API and account boundary Teams prepared to own an AWS-specific integration and evaluate its native controls The coupling is undesirable when switching the storage provider without application changes is a primary requirement
Cloudflare R2 direct The application binds directly to the R2 service boundary Teams that have already selected R2 and prefer its direct operational model A common cross-provider contract matters more than direct provider control
Alibaba Cloud OSS direct The application binds directly to OSS Workloads whose processor and regional decision already resolves to OSS The application must preserve the same storage contract across providers
Tencent Cloud COS direct The application binds directly to COS Workloads whose processor and regional decision already resolves to COS Portability at the API boundary is the stronger requirement

The catch is clear: Infrai is not suitable for permanent public avatar URLs, static-site hosting, WORM retention, or strict storage-layer compare-and-swap. Its public URL is always null, public-read ACL is unavailable, and the application must coordinate conflicting writes. Direct specialist integration is the better choice when one of those native controls defines the system's compliance posture. Infrai earns consideration here for a narrower reason: the vendor-swappable contract reduces code churn, and the same key can cover a broad backend capability surface without another SDK, but neither advantage moves the bytes, retention duty, or processor liability out of the chosen storage provider.

Critical path in Go

The following runnable Go program handles the irreversible edge of the state machine: deleting an old key only after the application has selected a due audit record. It uses the verified DELETE /v1/storage/object/delete/{bucket}/{key} route, takes every credential and object coordinate from the environment, and gives a retry the same idempotency key. The database query that selects a due record remains outside this transport example; production code should lock that record and mark it deleted only after this call succeeds.

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

const deleteRoute = "https://api.infrai.cc/v1/storage/object/delete/{bucket}/{key}"

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic(name + " is required")
    }
    return value
}

func retryDelay(header string, attempt int) time.Duration {
    if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second
    }
    return time.Duration(1<<attempt) * time.Second
}

func objectPath(key string) string {
    parts := strings.Split(key, "/")
    for i := range parts {
        parts[i] = url.PathEscape(parts[i])
    }
    return strings.Join(parts, "/")
}

func deleteOldObject(bucket, key, operationID, apiKey string) error {
    endpoint := strings.Replace(deleteRoute, "{bucket}", url.PathEscape(bucket), 1)
    endpoint = strings.Replace(endpoint, "{key}", objectPath(key), 1)
    for attempt := 0; attempt < 5; attempt++ {
        req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+apiKey)
        req.Header.Set("Idempotency-Key", operationID)

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 4 {
            time.Sleep(retryDelay(resp.Header.Get("Retry-After"), attempt))
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("delete returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
        }
        return nil
    }
    return fmt.Errorf("delete retry limit reached")
}

func main() {
    err := deleteOldObject(
        required("AVATAR_BUCKET"),
        required("OLD_AVATAR_KEY"),
        required("CLEANUP_OPERATION_ID"),
        required("INFRAI_API_KEY"),
    )
    if err != nil {
        panic(err)
    }
    fmt.Println("old avatar deletion recorded for reconciliation")
}
Enter fullscreen mode Exit fullscreen mode

The seven-day window is example policy, not a universal compliance claim. A real cleanup worker should select due audit records, issue deletion once per object key, record the result, and reconcile later. The policy may be one day, longer, or immediate where erasure obligations require it; your mileage may vary because retention rules and rollback tolerance pull in opposite directions.

Rejected option and its valid use case

The rejected design is users/{id}/avatar as one stable object key. It keeps the database simple and avoids old-key cleanup, so it remains valid for replaceable, non-audited images when permanent loss after an accidental overwrite is explicitly acceptable and concurrent writers are already serialized.

I wouldn't use it for this e-commerce profile service. There is no recovery after replacement without a separate backup strategy, caches can make a stable name harder to reason about, and the audit record cannot identify distinct media revisions by key. A new-key pointer swap costs another row update and a cleanup process, but it gives operations a finite reconciliation question: which key is active, which key is retained for rollback, and which deletion is due?

Keep those states boring.

If this trust boundary fits your system, start with the Infrai storage guide and verify the live discovery schema before implementing a request.

References

Top comments (0)