Race conditions occur when multiple threads access shared resources simultaneously, potentially leading to conflicts. If your system manages large data volumes, implementing multi threading can help handle multiple requests at once but also introduces the risk of race conditions.
Example of a race condition: Imagine your business account has a balance of ₹10,000. At the same time, one teammate is paying ₹8,000 to someone, and you’re attempting to withdraw ₹7,000. Since both transactions occur simultaneously, one must fail or the balance may go negative due to conflicting actions. This is a race condition.
How do you detect them? No need to delete. You have to handle that
How do you handle them? Use Exclusive Lock / Optimistic lock
Finally, how do you prevent them from occurring? No need to prevent Let me explain you how to handle this situation
So we an above discussion to handle this situation you need to use Exclusive Lock / Optimistic lock
In databases, every query is a transaction, processed in sequence, even with multithreading. The CPU processes transactions rapidly, giving the impression they run simultaneously, but they still operate in a queue. A SELECT query can lock a row, preventing other transactions from accessing it until the lock is released.
Example of Locking: Use the following to select with a lock:
select * from tableName where Condition Limit 1 FOR UPDATE SKIP LOCK.
FOR UPDATE SKIP LOCK this like will make you selection and put lock DB engine will understand to not allow to give some one to write operation
when you put the transaction you need to start with BEGIN on top and COMMIT once update. when you commit system will automatically remove exclusive lock from transaction.
So the final how your query will be
BEGIN select * from tableName where Condition Limit 1 FOR UPDATE SKIP LOCK. update tableName set key1=value1, key2=value2. COMMIT;
Let me know if any doubt.