I am building an API for webshop. I need to implement following scenario:
x (let's say
500) digital items, which will have same price (let's say each item costs
10$), but unique serial number. There will be a sale on specific date. I need to prepare for "optimistic" scenario, where there will be more than
x (more than
500, let's say
1000) users trying to purchase item all at once or at least on very close timeframe. Ideally first
500 users should be able to purchase items, rest of users should receive exception that stock is empty. Serial number order does not have to be linear, as all items costs the same, but it must be unique, so no duplicates.
Technology stack I am using for API:
.Net 5 WebApi with
Azure Sql Db.
Azure storage queue for messaging. Everything is hosted on azure services.
Possible solutions I am thinking could be implemented:
Creating a item objects in advance, then wrapping purchase in a transaction which would update owner of a non-purchased item object. This works in theory, I also tested it in small usage scenario, but I am not sure if I will not run into some problem when there will be a lot of concurrent users. (Like deadlocks, timeouts or etc.)
Creating all items in message queue and then each user (client) just reads a message from a queue. This also could work, but I found that Azure storage queue does not ensure that data will be read only once, meaning I would need to implement some other message queue, so I prefer first scenario over this one, as it requires additional infrastructure.
note - as a precaution to enforce uniqueness I am thinking to use unique constraints on the databse
- Could the possible solutions work?
- Is there any other pattern I could use to solve this?