How do the companies that sell tickets guarantee that no more tickets will be sold?
For example, you have 40 available and sold 39, 2 people at the same time start to buy, both will have the information that that ticket is available, but as soon as one person completes the purchase, the other would still have the false information that has ticket available and the purchase would not be blocked.
How to solve this?
As soon as one person enters the workflow for purchase, flag that ticket as unavailable (with an expiration of some sort, perhaps 20 minutes), so that other shoppers cannot also purchase that ticket. If a second shopper tries to enter the purchase workflow, tell them the ticket is no longer available.
"Entering purchase workflow" is defined as a "critical section", where only one person is allowed to enter at a time. It will be impossible for two people to claim the last available ticket simultaneously.
When the first person makes the purchase, permanently decrement the available tickets. If the first person cancels the purchase or abandons the workflow, release the reserved ticket back into the available pool.