Open dartartem opened 3 years ago
5 x why.
Please provide more context:
@cer
What test is failing?`
I caught it when writing queries using MongoClient.
What is the sequence of Eventuate events (e.g. as shown by logging) that cause this scenario to occur? Presumably two event handlers are executing concurrently.
In theory creating 2 orders in the same time can produce that error: https://github.com/eventuate-tram-examples/eventuate-tram-examples-micronaut-customers-and-orders/blob/master/end-to-end-tests/src/test/java/io/eventuate/examples/tram/ordersandcustomers/endtoendtests/CustomersAndOrdersE2ETest.java#L78-L82
5 x why.
There is race condition because of concurrent update of orders array of user in mongodb. upsert does not prevent from it.
2 concurrent threads tries to add order to customer:
{ id: 1, name: "Main Customer", orders: [] }
{id : 1, orderTotal : 2.0} {id : 2, orderTotal : 3.0}
upsert option prevents only from overwriting, but produces error in case of concurrent update. It works just like JPA optimistic locking.
I reproduced it here: https://github.com/eventuate-tram-examples/eventuate-tram-examples-micronaut-customers-and-orders/pull/29/files#diff-8ff3767511223c5af33f8ff52662af599abc762440887e5955f793621ca518adR31
This code:
Can produce following error:
reproduced on updated mongo (4.2.12)
https://stackoverflow.com/questions/29305405/mongodb-impossible-e11000-duplicate-key-error-dup-key-when-upserting
Looks like the only solution is to repeat insert operation.
It can be also actual for other examples.