Managing concurrency with MongoDB
In this recipe, we will implement a feature to exchange player cards between users. Some cards are more difficult to get, which results in them having a higher demand. So, while many users try to find them, only one may get it. This is a scenario of high concurrency.
A user can exchange or buy another user’s card using a certain number of tokens. The process we will implement consists of the following steps:
- First, we need to check that the buyer has the tokens they promised.
- Then, we’ll subtract the number of tokens from the buyer and add them to the seller.
- Finally, we will change the card owner.
MongoDB supports optimistic concurrency control through a document’s versioning system. Each document has a version number (often called a revision or version field) that is incremented whenever the document is modified. When multiple clients attempt to update the same document simultaneously, the version numbers...