2

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?

Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
randomguy
  • 12,042
  • 16
  • 71
  • 101

1 Answers1

4

For example you have to use lock on current_user:

current_user.with_lock do
  if current_user.address.blank?
    data = AddressAPI.create_address
    current_user.update!(address: data['address'])
  end
end
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69