You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Okay cool. It works when we are trying it locally. But imagine something. What if two users are calling the same endpoint at the same time ? What will happen ?
90
+
Okay cool. It works when we are trying it locally. But imagine something. What if two users try to transfer money to the same account at the same time ?
91
+
92
+
Let's consider the following scenario :
93
+
- User A wants to transfer 100$ to Account C
94
+
- User B also wants to transfer 100$ to Account C
95
+
- Account C has a balance of 1000$
96
+
97
+
What will happen if both request are almost simultaneously executed ?
87
98
88
-
1. User A's request reads the balance of Account X.
89
-
2. Concurrently, User B's request also reads the balance of Account X.
90
-
3. User A's request deducts the transfer amount from Account X and saves it.
91
-
4. Almost simultaneously, User B's request does the same, but it was unaware of the change made by User A's request because it read the old balance.
99
+
1. User A's request reads the balance of Account C : **We get 1000$**
100
+
2. Concurrently, User B's request also reads the balance of Account C: **We also get 1000$ since User A's request hasn't been fully executed yet**
101
+
3. User A's request adds 100$ to Account C's balance : **Account C now has 1100$**
102
+
4. Almost simultaneously, User B's request does the same. But remember, we stored the balance of Account C in a variable, and we added 100$ to it. So we also get **1100$ + 100$ = 1200$**.
92
103
93
-
As a result, Account X's balance end up totally incorrect. This is a classic example of what we call race condition.
104
+
See the problem ? That means, Account C will end up with 1100$ instead of 1200$. And even worse, User A and User B have been debited 100$ each, but only 100$ has been credited to Account C.
105
+
106
+
As a result, we lost 100$ somewhere. And that's not good. This is what we also call a **race condition**.
107
+
108
+
---
94
109
95
-
They are multiple ways to solve this problem. A simple one would be to use a lock. By adding a lock, we are preventing concurrent requests from accessing the same piece of code at the same time :
110
+
They are multiple ways to solve this problem. But let's use a lock here. By adding a lock, we are preventing concurrent requests from accessing the same piece of code at the same time :
0 commit comments