'Race condition in amplify datastore

When updating an object, how can I handle race condition?

final object = await Amplify.Datastore.query(Object.classtype, where: Object.ID.eq('aa');
Amplify.Datastore.save(object.copywith(count: object.count + 1 ));
  1. user A : execute first statement
  2. user B : execute first statement
  3. user A : execute second statement
  4. user B : execute second statement

=> only updated + 1



Solution 1:[1]

Apparently the way to resolve this is to either

1 - use conflict resolution, available from Datastore 0.5.0

One of your users (whichever is slowest) gets sent back the rejected version plus the latest version from server, you get both objects back to resolve discrepancies locally and retry update.

2 - Use a custom resolver
here..

and check ADD expressions

You save versions locally and your vtl is configured to provide additive values to the pipeline instead of set values.

This nice article might also help to understand that

Neither really worked for me, one of my devices could be offline for days at a time and i would need multiple updates to objects to be performed in order, not just the last current version of the local object.

What really confuses me is that there is no immediate way to just increment values, and keep all incremented objects' updates in the outbox instead of just the latest object, then apply them in order when connection is made..

I basically wrote in a separate table to do just that to solve my problem, but of course with more tables and rows, comes more reads and writes and therefore more expense.

Have a look at my attempts here if you want the full code lmk

And then i guess hope for an update to amplify that includes increment values logic to update values atomically out of the box to avoid these common race conditions.

Here is some more context

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lewy