I created a fintech app, right now i am using ->increment/decrement for the balance.. my current problem is that when a certain merchant has lots of traffic, it causes a problem it needs to wait before it updates because of the atomic lock.. I also have a ledger of the wallet transaction but using sum to get the real balance will be very expensive when it has a lot of records.. how do you handle this stuff?
Stop running increment() or decrement() during the HTTP request. Dispatch a job (e.g., UpdateMerchantBalance). The API responds immediately, and your queue workers deal with the lock waiting in the background. The workers will still wait on each other for that specific row, but your web server won't hang and the user won't experience timeouts.
@eskiesirius You shouldn’t be using a single column to hold the balance. You should instead of some form of ledger table, where you write individual increments and decrements as their own rows, and then derive the balance from the sum of those increments and decrements. It’s not “expensive” if you have a proper index in place.
@kai-init It can perhaps be a temporary solution, waiting for a better one ?
I thought about another solution : @eskiesirius what do you mean when you say a lot of trafic ? How many operations per second do you have to handle ?
And for your other problem about the sum, you can add a sum field in a table and this field will always have the sum of all transactions. But if you do so, you have take attention to really be sure that all transactions are really added to this field and prevent all malfunction.