The code below will fetch a new address from an external API if the user doesn't yet have one:
def create_address
if current_user.address.blank?
data = AddressAPI.create_address
current_user.update!(address: data['address'])
end
render json: { address: current_user.address }
end
If two concurrent create_address
requests come in, it's possible they'll both pass the current_user.address.blank?
check and two addresses will be created (whatever will call update!
last will override the other one).
How do we prevent this? Do we need to use some sort of locking mechanism?