Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure that item can only be bought by 1 person when 4000 people are trying to buy within a seconds

I run a marketplace iOS app and from time to time we have "competitions", where we have an especially sought after item for sale for a good price, that drops as a specific time. Sometimes thousands of people will try to buy this item within 1-2 seconds and I therefore need to make sure that only 1 person will get the item. The solution I have for it now feels kind of clumsy, so I was wondering how a good solution would look like when I use Firebase as my database.

The process is as such:

  1. User finds the item on his iOS app and clicks "Purchase".
  2. A request is sent to our API (build on RoR) that processes the purchase (usually takes 10-20 seconds for the purchase to go through).

Right now, I set the buyers ID temporarily as an attribute on the item, I wait a second and check whether the buyer ID is still the same on the item. It works, but it doesn't feel optimal.

Any suggestions on how I can make sure 2 people can't purchase the same item?

like image 931
Holger Sindbaek Avatar asked Dec 10 '22 17:12

Holger Sindbaek


1 Answers

To avoid something like this in your rails app, the keywords mutex and race condition should probably help you to find a bunch of appropriate gems.

I personally like to use redis for this kind of task, because in redis, transactions are atomic by default (https://en.wikipedia.org/wiki/Atomicity_(database_systems)).

So maybe this gem could suit your needs (untested): https://github.com/kenn/redis-mutex.

For the theory, refer to this articles:

  • https://en.wikipedia.org/wiki/Mutual_exclusion
  • https://en.wikipedia.org/wiki/Race_condition
like image 77
Alex Avatar answered Dec 13 '22 06:12

Alex