Search code examples
databasebackendsystemsystem-design

system design for concurrent requests on a ecommerce platform


Suppose you have 1 item in stock but at any instance 1 million requests came to purchase the product how will you design a system that will prevent selling of product more than once?


Solution

  • This is where the ACIDity of relation database comes into the picture. If one item will be sold more than once, then DB will go into an inconsistent state(for example, 10 items sold, 11 items purchased) and transaction query of the database will prevent this as per C(consistency) in ACID. In this case, one transaction will go through while all other transactions will be aborted.

    Apart from this, you could also implement locking on the resource(optimistic vs pessimistic locking). For example, you could lock a particular itemId. You could either implement locking in the database layer or application layer.

    Under pessimistic locking, one thread will lock the item and all other threads will be told that the item is sold.

    In optimistic locking, all threads will lock the resource and one thread that goes through first(assume payment done for that item) will mark the item sold and all other threads will be told that item is sold at the very last moment.

    This is a short answer, but hopefully, this gives you an idea.