Short answer: give every avatar upload a new, tenant-scoped object key, then replace a versioned pointer in Postgres only after the new object has been verified; never overwrite the object named by the current pointer. This makes simultaneous uploads a database concurrency decision rather than an object-storage timing contest, while private downloads remain authorization checks followed by short-lived signed links.
That distinction matters in a customer-support system. A profile image may look harmless, yet the same upload path often handles private screenshots, transcripts, and diagnostic files. If two agents update one user's avatar, the system must be able to say which revision became current, prove which tenant authorized it, retry without creating a second logical operation, and avoid granting one tenant a usable reference to another tenant's object. A successful PUT alone answers none of those questions.
This is an architecture decision record, not a claim that object storage is unreliable. The storage service should durably hold bytes under a key. Publication, isolation, idempotency, and auditability belong to the application protocol around that write.
How should an avatar upload replace an existing file without an object storage race?
The decision is to model an avatar as two resources: immutable bytes in object storage and a mutable, versioned database pointer. A key such as tenants/t_73/avatars/u_204/up_01J... identifies one upload attempt; an avatars row identifies the revision currently visible for that tenant and user. The key contains opaque server-issued identifiers, not an email address, filename, or other user-supplied path fragment.
Five invariants define correctness:
- An object key belongs to exactly one tenant and one upload operation.
- Repeating the same idempotency key resolves to the same upload operation and object key.
- A finalize operation can publish only the revision it expected to replace.
- A download link is created only after tenant authorization and expires after a deliberately short interval.
- Every accepted or rejected publication attempt leaves an audit record with the tenant, actor, upload, expected revision, and outcome.
The third invariant is the hinge. Suppose uploads A and B both begin while revision 18 is current. Both may write valid objects; there is no danger in that because their keys differ. A finalizes first and advances the row to revision 19. B's conditional database update, still expecting 18, affects zero rows and becomes a conflict. B's bytes are now an unreferenced candidate for later deletion, not an accidental replacement of A.
Keep that loser.
At least temporarily, an unreferenced object is evidence that the protocol behaved correctly. A sweeper can remove candidates after a retention delay, but deletion must not be coupled to the request that publishes the winner. Immediate cleanup creates a new race: a delayed retry may refer to an upload record whose bytes were already removed, and an operator loses useful evidence while reconciling the attempt. The exact retention period depends on support policy, privacy obligations, and storage lifecycle configuration; I'm not sure there is a responsible universal value. The decision needs input from data retention and incident-response owners.
There are four relevant failure boundaries. Before object creation, a retry should return the existing upload intent. After object creation but before finalization, a retry should verify and finalize that same intent. During finalization, the database compare-and-swap chooses one visible revision. After finalization, repeated calls should return the recorded result. None of these states requires overwriting a live object.
Compare concurrency controls at the publication boundary
Object stores expose different names for conditional operations, so the portable design should depend on a small internal contract rather than leak one provider's token throughout business code. Amazon S3 documents conditional writes with HTTP precondition headers, Google Cloud Storage exposes generation and metageneration preconditions, and Azure Blob Storage documents ETags and conditional headers. Those mechanisms can protect an object operation, but they do not replace the application transaction that binds a tenant, user, idempotency record, audit event, and current-avatar pointer.
| Choice | Concurrency authority | Useful property | Boundary or cost |
|---|---|---|---|
| Immutable object key plus Postgres pointer | Conditional row update | One auditable place decides the visible revision; storage retries cannot overwrite current bytes | Requires orphan retention and a cleanup job |
| Mutable object key plus storage precondition | Object-store validator or generation | Can reject a write against an unexpected object version | The database may still disagree about the current user revision unless a separate reconciliation protocol exists |
| Storage-native object versioning | Provider version identifier | Preserves multiple physical versions behind one logical key | Provider semantics and restore procedures enter the application contract |
| Serialized per-user worker | Queue ordering | Makes publication order explicit inside one worker topology | Replays, worker failover, and alternate writers still require idempotency and a durable comparison point |
The first choice is the default here because tenant isolation and auditability are the primary decision axis. It gives the relational transaction, already responsible for identity and authorization, authority over visibility. It also keeps provider-specific validators behind the storage adapter.
This isn't exactly-once delivery.
Distributed systems do not gain that property from a hopeful retry loop. This is an exactly-once effect for one idempotency key, enforced by durable uniqueness and a conditional state transition.
The compliance consequence is easy to miss. A signed URL is a bearer capability until it expires, so the application should never treat possession of an old avatar URL as continuing authorization. Authorize the authenticated actor against the tenant and object record first, issue a short-lived URL second, avoid logging the query string, and record issuance separately from object access. Your mileage may vary on whether storage access logs satisfy the audit requirement: the answer depends on what identity, retention, and integrity guarantees the relevant control framework demands.
Put the critical path in one Go transaction
The storage adapter below is intentionally narrow. CreateUpload allocates an immutable key and returns whatever upload mechanism the adapter supports. Stat verifies that the expected object exists and binds its opaque validator and size to the finalize request. The application does not accept a final object key from the browser; it looks up the server-created upload record under the authenticated tenant.
package avatar
import (
"context"
"errors"
"fmt"
"io"
"time"
)
var ErrConflict = errors.New("avatar revision conflict")
type ObjectInfo struct {
Validator string
Size int64
}
type ObjectStore interface {
Put(ctx context.Context, key, contentType string, body io.Reader) (ObjectInfo, error)
Stat(ctx context.Context, key string) (ObjectInfo, error)
SignGet(ctx context.Context, key string, expiresAt time.Time) (string, error)
}
type FinalizeCommand struct {
TenantID string
UserID string
ActorID string
UploadID string
IdempotencyKey string
ExpectedRevision int64
}
type Repository interface {
UploadForFinalize(ctx context.Context, tenantID, userID, uploadID string) (key string, stored ObjectInfo, err error)
PublishAvatar(ctx context.Context, cmd FinalizeCommand, key string, actual ObjectInfo) (newRevision int64, changed bool, err error)
RecordConflict(ctx context.Context, cmd FinalizeCommand) error
}
type Service struct {
objects ObjectStore
repo Repository
}
func (s *Service) Finalize(ctx context.Context, cmd FinalizeCommand) (int64, error) {
key, expected, err := s.repo.UploadForFinalize(ctx, cmd.TenantID, cmd.UserID, cmd.UploadID)
if err != nil {
return 0, fmt.Errorf("load upload: %w", err)
}
actual, err := s.objects.Stat(ctx, key)
if err != nil {
return 0, fmt.Errorf("verify upload: %w", err)
}
if actual.Validator != expected.Validator || actual.Size != expected.Size {
return 0, errors.New("uploaded object does not match the recorded receipt")
}
revision, changed, err := s.repo.PublishAvatar(ctx, cmd, key, actual)
if err != nil {
return 0, fmt.Errorf("publish avatar: %w", err)
}
if !changed {
if err := s.repo.RecordConflict(ctx, cmd); err != nil {
return 0, fmt.Errorf("record conflict: %w", err)
}
return 0, ErrConflict
}
return revision, nil
}
PublishAvatar must execute one database transaction. First it inserts or reads the result keyed by (tenant_id, idempotency_key). Then it updates the avatar row with a predicate equivalent to tenant_id = ? AND user_id = ? AND revision = ?; on success it increments the revision, stores the immutable key and object validator, appends the audit event, and records the idempotent response before commit. On a repeat, it returns the recorded response rather than advancing the revision again.
Notice that TenantID appears in every repository lookup, not merely in the object-key prefix. Prefixes organize objects and help constrain scoped storage credentials, but a prefix is not an authorization decision. Database uniqueness should likewise include the tenant: a globally reused user identifier or idempotency key must not cross a tenant boundary.
The download path is shorter.
Load the current pointer using (tenant_id, user_id), authorize the support role against that tenant, ask the adapter to sign exactly that stored key with a bounded expiration, return the URL without persisting it, and append an issuance event. Cache the underlying immutable object if policy permits, but do not cache a private signed URL beyond its authorization context.
Testing should attack interleavings, not merely endpoints. Start two finalizations from revision 18, release their database updates together, and assert that one reaches revision 19 while the other receives a conflict. Replay both idempotency keys. Confirm that the winner remains current, the loser is eligible for deferred cleanup, no audit sequence is missing, and a tenant with the same UserID cannot read either record. Then inject a process stop after object creation and another immediately before commit; retries should converge on the recorded state. Three words: assert the ledger.
Record the rejected overwrite decision and its valid use case
The rejected option is overwriting avatars/{userID}/current in place and adding a cache-busting query parameter. It offers a stable object name, but that convenience is a poor fit for private customer-support uploads: two writers target the same bytes, the database cannot independently prove which payload a pointer represented, caches may have their own validator behavior, and deletion or rollback depends on storage-specific version history. A timestamp suffix alone is also insufficient because clock resolution and trust do not establish idempotency; use a server-issued, random upload identifier with a database uniqueness constraint.
The catch is operational weight. Immutable keys require an upload-intent table, a cleanup process, lifecycle monitoring, and reconciliation between database references and stored objects. This design is not suitable when every object must keep a permanent public URL and the organization cannot tolerate a redirect or indirection layer. In that case, stick with a stable public delivery name backed by a controlled publication pipeline, and retain immutable source revisions behind it.
For a genuinely single-writer, non-sensitive asset pipeline, an in-place overwrite guarded by a storage precondition can also be reasonable. The decision changes when there is one publication authority, stale content has low impact, rollback is defined by provider-native versioning, and no cross-tenant authorization claim depends on the key. Document those assumptions. If a second writer or private attachment path appears later, revisit the record rather than pretending the original boundary still holds.
Deployment needs the same discipline. Roll out the schema and dual-read capability before switching writers; monitor conflicts, unfinalized upload age, orphan bytes, cleanup lag, signed-link issuance, and audit insertion failures; rehearse restoration from the database pointer plus immutable objects. Cost review should include retained orphan bytes, request volume from verification, audit retention, and cleanup listing, because the cheapest write path can produce the most expensive reconciliation path.
References
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110
- Google Cloud Storage documentation: https://cloud.google.com/storage/docs
Further reading
- Amazon S3 conditional writes: https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html
- Google Cloud Storage request preconditions: https://cloud.google.com/storage/docs/request-preconditions
- Azure Blob Storage concurrency management: https://learn.microsoft.com/azure/storage/blobs/concurrency-manage
Top comments (0)