-
Notifications
You must be signed in to change notification settings - Fork 298
Open
Description
I noticed a concurrency issue.
Here’s how you can reproduce it:
-
Stop (shut down) the Customer Service.
-
While it’s offline, send the following requests:
- Add to Cart → Product 1, Qty: 1
- Add to Cart → Product 1, Qty: 2
- Add to Cart → Product 1, Qty: 3
- Add to Cart → Product 1, Qty: 4
The expected final state in the shopping cart should be:
Product 1 with Quantity: 4
Now, restart the Customer Service.
At this point, the service will consume all the pending messages from RabbitMQ. However, all of them will compete to update the same customer document. Here’s what happens internally:
- Each of the 4 events runs
AddCartItemin the Customer Repository. AddCartItemfirst queries the customer and retrieves the document with version_v: 1.- It modifies the cart items and attempts to save the document.
- The first update succeeds, incrementing the document version to
_v: 2. - But the other updates are still trying to write using the outdated version
_v: 1. - This causes MongoDB to throw a version conflict error, because those writes are no longer valid against the latest document version.
In other words, the concurrency issue arises because multiple messages are processed in parallel, each assuming the same initial document version, which leads to conflicting writes.
The only way I see to solve this is:
- Making atomic operations in MongoDB instead of querying the document and then set updates to it
- Pull messages one by one instead of delivering all messages to the consumer
Metadata
Metadata
Assignees
Labels
No labels