Skip to content

Concurrency issue #7

Description

@debianw

I noticed a concurrency issue.

Here’s how you can reproduce it:

  1. Stop (shut down) the Customer Service.

  2. 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 AddCartItem in the Customer Repository.
  • AddCartItem first 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:

  1. Making atomic operations in MongoDB instead of querying the document and then set updates to it
  2. Pull messages one by one instead of delivering all messages to the consumer

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions