Double spending means spending the same money twice. As we know, any transaction can be processed only in two ways. One is offline, and another is online.
Offline: A transaction which involves physical currency or cash is known as an offline transaction.
Online: A transaction which involves digital cash is known as an online transaction.
Let us consider this example:
You go to Restaurants and order a cappuccino worth $5. You pay in cash. The service provider at Restaurants instantly confirmed that you have paid, and you received your coffee in exchange for the money. Now is it possible to spend the same $5 somewhere else to make another purchase? The answer is NO. But what if the answer is YES? It means the same person can use the same cash more than one times. This type of problem is known as Double Spending Problem.
In a physical currency, the double-spending problem can never arise. But in digital cash-like bitcoin, the double-spending problem can arise. Hence, bitcoin transactions have a possibility of being copied and rebroadcasted. It opens up the possibility that the same BTC could be spent twice by its owner.
How Bitcoin handles the Double Spending Problem?
Bitcoin handles the double-spending problem by implementing a confirmation mechanism and maintaining a universal ledger called blockchain.
Let us suppose you have 1 BTC and try to spend it twice. You made the 1 BTC transaction to Alice. Again, you sign and send the same 1 BTC transaction to Bob. Both transactions go into the pool of unconfirmed transactions where many unconfirmed transactions are stored already. The unconfirmed transactions are transactions which do not pick by anyone. Now, whichever transaction first got confirmations and was verified by miners, will be valid. Another transaction which could not get enough confirmations will be pulled out from the network. In this example, transaction T1 is valid, and Alice will receive the bitcoin.
What happened if both the transactions are taken simultaneously by the miners?
Suppose two different miners will pick both transactions at the same time and start creating a block. Now, when the block is confirmed, both Alice and Bob will wait for confirmation on their transaction. Whichever transaction first got confirmations will be validated first, and another transaction will be pulled out from the network.
Now suppose if both Alice and Bob received the first confirmation at the same time, then there is a race will be started between Alice and Bob. So, whichever transaction gets the maximum number of confirmations from the network will be included in the blockchain, and the other one will be discarded.