Short answer: upload each replacement under a new tenant-scoped key, then conditionally switch a small metadata pointer; never overwrite the object that readers currently use. For a B2B SaaS that processes receipts, keep the original receipt as an immutable audit record and apply the same pointer pattern only to replaceable derivatives such as avatars, thumbnails, or corrected display attachments.
The decision is mostly about isolation, not upload syntax. A stable filename such as avatar.jpg looks convenient until two browser tabs, a retrying worker, and a cache disagree about which bytes are current. A unique object key keeps those writes apart. A compare-and-swap on the database row decides which one becomes visible.
It is a small split with a useful consequence: storing bytes and publishing bytes become two different operations.
1. How should an avatar upload replace an existing file without an object storage race condition?
Use an immutable-object, mutable-pointer flow. The client starts a logical upload with an idempotency token. The server derives a key containing the tenant ID, subject ID, and that token, writes the bytes only if that key does not exist, validates the stored result, and then changes the subject's current-object pointer only if its revision is still the revision the client read. Readers resolve the pointer; they do not guess a conventional filename.
Consider two updates that both read revision 17. Update A stores tenants/acme/avatars/u42/up-a, while update B stores tenants/acme/avatars/u42/up-b. Both objects can exist without collision. If A advances the pointer from revision 17 to 18, B's conditional pointer update must fail rather than silently replacing A. Under HTTP conditional request semantics, a failed precondition is represented by status 412. B can fetch the new state and ask the user to retry, or an explicitly documented product rule can choose a winner. The storage layer should not invent that policy through timing.
This matters more for receipt processing. The original file is evidence, so an apparent "replacement" should usually create a new audit revision and preserve the earlier one. A derived preview can use a current pointer, but the immutable receipt ledger remains append-only. Mixing those lifecycles is how an innocent avatar helper turns into an audit deletion path.
Fast first. Correct second is expensive here. Make the order explicit.
2. Why should every write use a tenant-scoped immutable key?
A UUID alone prevents accidental name collision, but it does not express ownership. Put the tenant boundary into both the key and the authoritative metadata row. Then require every read, publish, and cleanup query to match that tenant. The prefix adds defense in depth and useful operational context; authorization still belongs in the application and storage policy. Do not accept a complete object key from the browser and trust its prefix.
A practical key shape is tenants/{tenantId}/{kind}/{subjectId}/{uploadId}. The uploadId must remain stable across retries of the same logical upload. Generating a fresh value inside every retry loop defeats idempotency and leaves extra objects. Avoid user-controlled filenames in the key. Keep the original filename as escaped metadata if the interface needs it, and validate content type and size independently of the extension.
The write primitive needs create-only behavior. Different object stores expose preconditions with different names, so keep that detail behind a narrow interface and test the adapter. Google Cloud Storage, for example, documents request preconditions and object generations; the architecture does not require the rest of the application to know those terms.
import { createHash } from "node:crypto"; type StoredObject = { key: string; sha256: string; size: number; }; interface ObjectStore { putIfAbsent(input: { key: string; body: Uint8Array; contentType: string; }): Promise<StoredObject>; } function objectKey(input: { tenantId: string; subjectId: string; uploadId: string; }): string { const safe = /^[a-zA-Z0-9_-]+$/; for (const value of Object.values(input)) { if (!safe.test(value)) throw new Error("invalid key component"); } return `tenants/${input.tenantId}/avatars/${input.subjectId}/${input.uploadId}`; } function sha256(body: Uint8Array): string { return createHash("sha256").update(body).digest("hex"); } putIfAbsent is deliberately boring. Its contract is the important part: the same logical request may confirm the already-created object only when the stored digest and length equal the request, while a different payload under the same key is a conflict. That rule makes client retries safe without turning an object overwrite into an undocumented last-writer-wins decision.
3. Publish one pointer with a precondition
After the object write succeeds, publish a record such as { tenantId, subjectId, objectKey, sha256, revision } in the transactional database. The update predicate must include the tenant, subject, and expected revision. Checking only the user ID is a cross-tenant risk in systems where identities can appear in more than one workspace. Checking only the revision is worse.
Here is the core boundary in TypeScript. The repository can be backed by SQL, but its public contract says what the workflow depends on.
type CurrentFile = { tenantId: string; subjectId: string; objectKey: string | null; revision: number; }; interface CurrentFileRepository { read(tenantId: string, subjectId: string): Promise<CurrentFile>; compareAndSwap(input: { tenantId: string; subjectId: string; expectedRevision: number; nextObjectKey: string; sha256: string; }): Promise<boolean>; } async function publishAvatar( store: ObjectStore, files: CurrentFileRepository, input: { tenantId: string; subjectId: string; uploadId: string; body: Uint8Array; contentType: string; expectedRevision: number; }, ): Promise<{ objectKey: string; revision: number }> { const key = objectKey(input); const stored = await store.putIfAbsent({ key, body: input.body, contentType: input.contentType, }); if (stored.sha256 !== sha256(input.body) || stored.size !== input.body.byteLength) { throw new Error("stored object verification failed"); } const published = await files.compareAndSwap({ tenantId: input.tenantId, subjectId: input.subjectId, expectedRevision: input.expectedRevision, nextObjectKey: stored.key, sha256: stored.sha256, }); if (!published) { throw new Error("precondition failed: refresh before replacing the file"); } return { objectKey: stored.key, revision: input.expectedRevision + 1 }; } The function leaves an unpublished object when it loses the pointer race. That's expected state, not data corruption. Record the upload attempt before writing, mark it published in the same transaction as the pointer change, and let a later collector remove only attempts that stayed unpublished beyond a conservative grace period. A request handler should not delete the old object immediately: a reader may have resolved the previous pointer just before the update, a CDN may still be serving it, and audit policy may forbid deletion altogether.
Conditional HTTP requests offer the same idea at an API boundary. Return an ETag for the metadata representation, require If-Match on replacement, and reject a stale validator with 412. RFC 9110 defines If-Match for preventing the lost-update problem. Don't confuse that metadata ETag with a universal checksum promise for uploaded bytes; keep an application digest when byte identity matters.
4. Separate audit retention from replacement cleanup
There are at least three clocks in this system: how long an upload attempt may remain unpublished, how long a superseded avatar or preview remains readable, and how long an original receipt must be retained for audit. They should be separate policy fields. One generic "delete old file" job cannot safely represent all three.
For receipts, store an immutable document record for every accepted original, including tenant ID, object key, digest, ingestion time, and processing status. Corrections append another record and may update a display pointer, but they don't mutate history. For avatars, a shorter superseded-object policy may be reasonable once no current pointer references the object. I'm not sure a fixed retention window is right for every SaaS; legal obligations, restore expectations, and CDN behavior decide it. The invariant is clearer than the duration: cleanup must prove that an object is unpublished, outside its retention window, and owned by the tenant being scanned.
The catch is extra storage and a little more metadata. This pattern is not suitable when the object store itself must be the sole source of truth and the application cannot maintain a conditional pointer. In that constrained system, stick with native object versioning plus carefully tested generation or version preconditions, and accept that reads, rollback, and garbage collection will be coupled to that provider's model. If files are tiny, private, and transactionally stored in the same database as their pointer, a database BLOB can also be the simpler choice.
No magic. The design buys deterministic publication by paying for immutable copies, a metadata transaction, and deferred cleanup.
5. Test reorderings, not just successful uploads
The useful tests control timing. Start two replacements from revision 17, pause both after object creation, then release their pointer updates together. Assert that exactly one advances the row, the current key belongs to the correct tenant, and the losing key is eligible for cleanup but never returned by the read path. Repeat with the same idempotency token and identical bytes; it should resolve to the same object. Repeat with the same token and different bytes; it should be rejected.
Add a negative tenant test in every layer. A repository call with tenant beta and subject u42 must not see acme's row even if the subject identifier matches. A cleanup scan for beta must not delete a key under tenants/acme/. Logs and metrics should carry a hashed or internal tenant identifier, upload-attempt ID, expected revision, resulting revision, byte count, and outcome, but not receipt contents or signed download URLs. Track precondition conflicts separately from validation failures because the first can reflect ordinary concurrent edits while the second indicates bad input or a broken adapter contract.
Before deployment, exercise interrupted uploads, retried publication, stale clients, cleanup during an active read, and restoration from the audit index. Then canary the change for a small tenant set and watch conflict rate, unpublished-object age, cleanup backlog, and pointer reads that reference a missing object. The operational checklist is short in prose: a write is uniquely named, verified, conditionally published, observable, recoverable, and cleaned only after ownership plus reachability checks pass. If any verb lacks an explicit test, the upload path isn't ready.
