Atomic transactions

Many blockchain events list the ā€œamount changeā€ value (the ā€œamountā€ in an erc-20 transfer event is a common example). To build up a picture of current user balances, youā€™d likely do an ā€œafterSaveā€ on that event, and increase/decrease the balance by the appropriate amount.

Butā€¦ is there an atomic increment/update available here? Or do we have to worry about race conditions and write collisions?

2 Likes

Hi @barclander

If transaction happens all data about balances and transactions updates automatically at the same time

Is that true on a server, though? What about an afterSave call that includes an http call (api lookup for example) or some other long-running task. Does that http call block all other actions on the server until it completes?

I think that the balances and transactions that get synced on your Moralis Server are not computed on your Moralis Server and separately on Moralis infrastructure and only synced to your server.

Iā€™m not talking about the sync part. Iā€™m talking about calculations and updates done through afterSave and through cloud functions. Thatā€™s where thereā€™s potential for collisions. A simple example:

A user wants to store a ā€œtotal transferredā€ value for an erc-20, which is the total of all transfers that ever happened. To do that, theyā€™d write an afterSave function on the synced transfer event, which (a) loads the data object, (b) updates it by adding the eventā€™s value to the stored value, and Ā© saves it. Does the server process these cloud functions sequentially, so if 2 events come in the same block, the afterSave function for event #2 doesnā€™t get invoked until the afteSave function for event #1 completes

To be sure that no problem happens, for that particular case, you can do that processing in sequence in a job and not in an afterSave event. And mark the rows that were successfully processed so that you can rerun that job for the new entries.