Avatar Upload Replacement: A Safe Unique-Key Strategy for Object Storage Races
Replacing an avatar is a small feature with a surprisingly sharp failure mode. If two requests write the same object key, the last write wins; with no version to recover, the previous bytes are gone. Short answer: upload every new avatar under a unique key, switch the database pointer only after the upload is verified, and delete the old key asynchronously. That is the useful before/after mental…
Replacing an avatar in object storage can be tricky due to the failure mode where writing the same object key results in the last write winning without any versioning to recover previous data. To avoid this, upload every new avatar under a unique key, update the database pointer only after verifying the upload, and delete the old key asynchronously in the background.
By treating the database as the owner of identity and each object key as immutable application history, a profile read follows the current pointer while an audit job can still locate the exact object selected at that time.
To prevent object storage overwrite races, ensure the key is unique per upload, not merely unique per user. Using a UUID as the key, such as avatars/{userId}/{uuid}.jpg, helps avoid filename collisions and retry issues. The write sequence should be straightforward: accept the upload, create a new key, store the bytes, and optionally check if the object exists.
Set the users.avatar_key in a single database transaction, queue the deletion of the previous key, and ensure a failed cleanup doesn't roll back a successful profile update.
Infrai offers a simple way to handle storage calls over plain HTTP, providing request and response schemas for a small upload worker to inspect the contract without needing an SDK. A TypeScript client can be created to perform the upload steps, using an explicit method, fetching the key from the environment, allowing retries with an idempotency key, and implementing exponential backoff on 429 responses instead of overloading the service.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.