-1

I am building an API for webshop. I need to implement following scenario:

There are 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:

  1. 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.)

  2. 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

Questions:

  • Could the possible solutions work?
  • Is there any other pattern I could use to solve this?
New contributor
Ramūnas is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

Approach 1 is the clear winner, especially if there's only 500 objects. Microsoft's benchmarks say you can do 75,000 transactions per second, so I think realistically on a non-premium system you should be able to handle your 500 objects selling out in a few seconds.

You probably don't want to put a message queue in the middle at all - just do it the old fashioned way where the page makes a blocking query with timeout to the database. Then when the query returns you know whether you've secured a purchase or not.

Your Answer

Ramūnas is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.