Short answer: use a new, immutable object key for every avatar upload, then update the user's database pointer with a compare-and-swap or transaction. Do not make the browser overwrite users/42/avatar; that turns an image replacement into a race between uploads, caches, and database writes.
This is the decision I would make for a marketplace that stores per-tenant backups and lets operators restore a selected snapshot. Avatar files are small compared with backups, but the correctness rule is the same: bytes need an identity, metadata needs a version, and a replacement needs an explicit commit point. The larger the file, the more painful it is to discover that the upload was never tied to a durable version.
The incident lesson: an overwrite is not a replacement
The dangerous design looks tidy. Every tenant gets one path, such as tenant/42/avatar.jpg, and a successful upload replaces the bytes at that path. The application then stores that path on the user row. A CDN may cache the old object, an upload can finish after a newer upload, and a retry can repeat a request whose result is unknown. The final path tells you none of that history.
That is a race condition, not a cosmetic cache problem. Imagine upload A starts, then upload B starts. B finishes first and the database points to B. A finishes later and overwrites the shared key; the database still says “avatar,” so the system now serves bytes that do not match the intended version. The same ordering problem appears when two browser tabs submit different files.
The timeline gets worse once retries enter the picture. A worker sends upload A, the storage service accepts the bytes, and the network drops before the worker receives the response. The worker retries against the same shared key. Meanwhile, upload B has completed and the profile row has been updated. Depending on which write arrives last, the database and object can disagree without either request looking unsuccessful in isolation. Add a CDN with a cached response and an operator restoring a selected tenant snapshot, and the symptom may look like “the wrong image” even though the actual defect is that one mutable name was asked to carry identity, version, delivery state, and rollback semantics at the same time. I have seen enough missed-job and duplicate-delivery incidents to treat that as an ownership failure: no single component can answer which bytes are authoritative. The design has to make that answer explicit.
Small failure.
The invariant I want is straightforward: an object key identifies one immutable upload, and the database pointer identifies the version the application has committed. A cleanup job may remove old, unreferenced objects later. It must never decide which avatar is current by looking at object arrival order.
HTTP gives us useful pieces for this design. RFC 9110 defines conditional requests such as If-Match; a write can require that the representation still has the expected entity tag. That protects a known version from being replaced by a stale writer. It does not, by itself, make a database update and an object upload one transaction.
Should an avatar upload replace an existing object or create a unique key?
For user avatars, create a unique key. Keep the logical name in application data and make the physical object name versioned, for example tenants/42/users/7/avatar/01J.... A UUID also works. The exact identifier format matters less than uniqueness, non-reuse, and the ability to associate the key with an upload record.
A unique key changes the failure surface in a useful way. If an upload is abandoned, it is an uncommitted object that a lifecycle job can find. If an upload is retried, the retry can use an idempotency token and resolve to the same upload record. If two uploads finish out of order, neither can destroy the other's bytes. The database commit decides which one wins.
| Strategy | What it makes easy | What you still own | Use it when |
|---|---|---|---|
| Shared logical key | Simple reads and a small-looking namespace | Lost updates, cache invalidation, stale writers, difficult rollback | Almost never for user-controlled replacements |
| Unique key per upload | Rollback, auditability, retries, and delayed cleanup | Pointer updates, garbage collection, metadata validation | The default for avatars and selected backup snapshots |
| Unique key plus conditional commit | Version-safe promotion of a candidate | Conflict handling and a clear client response | Concurrent edits must not silently win |
The catch is storage lifecycle. Unique keys create objects that need ownership metadata and cleanup. That is an operational cost, not a reason to reintroduce destructive overwrites. For a tiny internal tool with one writer and no cache, a shared key may be acceptable; for a marketplace with multiple workers, retries, and tenant isolation, I would keep unique keys.
Do not put an untrusted filename in the key. File extensions can be retained as display metadata, but the key should be generated by the service. Validate content type and size from the bytes you receive, and treat the client-provided MIME type as a hint. Those checks belong before promotion, not after the object becomes current.
A commit path that makes stale uploads harmless
The upload should have two phases: stage and promote. Staging writes the bytes under a new key and records an upload row containing the tenant, user, key, content digest, size, and state. Promotion is a guarded database update from the expected current avatar version to the staged version. Only after promotion should the object become the value read by normal avatar requests.
Here is the part I want engineers to reason about, rather than copy as a vendor-specific SDK recipe. The storage interface represents the guarantees the adapter must provide. The database operation is the real serialization point.
type ObjectRef struct { Key string ETag string } type Upload struct { TenantID string UserID string Object ObjectRef Digest string Bytes int64 } type ObjectStore interface { PutImmutable(ctx context.Context, key string, body io.Reader, contentType string) (ObjectRef, error) Delete(ctx context.Context, key string) error } // Promote only if the caller still owns the version it read. func promoteAvatar(ctx context.Context, db *sql.DB, upload Upload, expectedVersion int64) error { tx, err := db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() result, err := tx.ExecContext(ctx, ` UPDATE user_avatars SET object_key = ?, object_etag = ?, version = version + 1 WHERE tenant_id = ? AND user_id = ? AND version = ?`, upload.Object.Key, upload.Object.ETag, upload.TenantID, upload.UserID, expectedVersion) if err != nil { return err } changed, err := result.RowsAffected() if err != nil { return err } if changed != 1 { return fmt.Errorf("avatar version changed before promotion") } return tx.Commit() } The example assumes the object adapter rejects replacement at a key and returns the stored object's validator, such as an ETag. That is a contract to test against the chosen storage implementation. The application should never report success until both staging and promotion have succeeded. If promotion loses the compare-and-swap, leave the staged object for a bounded cleanup path and return a conflict so the client can refresh.
There is a subtle ordering choice here. Writing the object first means a failed database commit leaves an unreferenced object. Writing the database pointer first means a request can point at bytes that are not available yet. For large-file throughput and restore workflows, I prefer stage-then-promote because an unreferenced object is detectable and recoverable. The object store and database are still separate systems, so the state machine needs staged, promoted, abandoned, and deleted states.
The cleanup worker must be tenant-aware. It should delete only objects with an expired staging record, or objects proven not to be referenced by any current or retained snapshot. Never delete by prefix alone while a restore or promotion can still be in flight. I am not sure a universal retention window exists; the right value depends on maximum upload duration, retry policy, and restore time, so measure those before setting the lease.
How do unique keys and conditional writes handle overwrite race conditions?
They solve different races. A unique key prevents one upload from destroying another upload's bytes. A conditional database update prevents a stale request from changing which version is current. A storage precondition can prevent accidental replacement of a key, while an HTTP conditional request can protect a representation when the adapter exposes that validator. Combining the controls is more reliable than treating any one header as a transaction.
For a selected backup restore, use the same model with a different commit target: stage the large file under a snapshot-specific key, verify its digest and size, then atomically change the tenant's restore pointer or create a restore record that names that snapshot. A restore request should carry an idempotency key. A retry after a timeout must look up the prior operation instead of starting a second restore blindly.
This is where throughput changes the design. Large files make retries expensive, so use resumable or multipart transfer where the storage system supports it, but do not confuse a resumable transfer with a committed application version. Track transfer progress separately from promotion. Measure end-to-end throughput, time to first usable version, failed-part retry rate, and the queue delay before cleanup. A fast upload that races the commit is still a failed upload.
For a backup restore, I would record the transfer and promotion as separate spans with the same operation ID. The transfer span answers how long the bytes took and which parts were retried; the promotion span answers when the tenant began reading the selected snapshot. That distinction matters during an on-call handoff. “Restore completed” should mean the committed pointer is readable, not merely that the last multipart request returned success. It also makes alerting less noisy: a slow transfer can be investigated without paging on every abandoned candidate, while a promotion conflict can be counted as a correctness event. The runbook should say what to inspect, which staged objects are safe to delete, and how to resume an operation after a worker restart. Keep those answers in the system's state records, because an undocumented assumption is usually the first thing lost during a midnight incident.
The operational checks should include at least these cases: two uploads finishing in reverse order; a client retry after an accepted write; a process crash after staging; a database conflict during promotion; an object that passes size checks but fails content validation; and a restore requested while cleanup is scanning. Run them with tenant IDs that differ, because isolation bugs often hide when tests use one global namespace.
I would also expose the current object key only through the application record, not as a mutable public convention. Readers can receive a short-lived URL or a redirect generated from the committed pointer. Cache headers and URL versioning then follow the immutable object key naturally. A purge can still be needed for an old shared URL, but the preferred read path does not depend on purging a reused name.
When is overwrite acceptable, and when should you keep the unique-key design?
A direct overwrite is suitable only when the object is genuinely disposable, there is one writer or an equivalent lock, stale reads are harmless, and rollback is unnecessary. Even then, document the guarantee and test retries. “It is only an avatar” is not a concurrency policy.
Keep unique keys when uploads come from browsers, workers can overlap, objects are cached, audit or rollback matters, or a tenant can restore a selected snapshot. Choose a storage adapter with explicit conditional-write and resumable-transfer semantics when those are requirements. Choose a simpler adapter when the workload is small and the team cannot justify operating cleanup, but keep the application-level version check.
The decision rule is simple: immutable bytes, explicit ownership, guarded promotion, and delayed deletion. That architecture costs more metadata and background work than one shared filename. It buys a failure mode you can inspect instead of a mystery overwrite that happened between two successful requests.
