简体   繁体   中英

Mongodb transactions scalability WriteConflict

I am using:

  • Mongodb (v4.2.10)
  • nodejs + Mongoose

I am still in the development phase of my application and I am facing a potential problem ( WriteConflict ) using transactions in mongodb. My application gives the possibilities for users to add posts and to like posts. When liking a post, here what is happening on the back-end side :

  • Start transaction
  • Find the post with the given ID in the Post collection
  • Add a document to the Like collection
  • Update the like count of the post in the Post collection
  • Update the likes given count of the user in the User collection
  • Update the likes received count of the user in the User collection
  • Add a notification document in the Notification collection
  • Commit the transaction

I'd say the average execution time is 1 second, so it means that for 1 second, I am locking :

  • 1 Post document
  • 2 User documents

I can see that as huge scalability problem, especially if a user has many popular posts that will often be liked by others.

What would you recommend me to do?

I don't think I can stop using transactions because if something goes bad during the execution of the function, I want to revert potential changes made to the DB

Thanks

Transactions are not required for this.

  • Once a like is in the likes collection, you can recalculate all counts.
  • Notifications cannot be calculated (since you don't know when one was sent), but generally they are ephemeral anyway and if you have an outage requiring database restore users will most likely forgive some lost notifications.

When updating counts, use $inc instead of read-modify-write (writing out the new value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM