Answer the question
In order to leave comments, you need to log in
Many-to-many how to avoid Race conditions?
There are 3 tables: Users, Subscriptions, UsersSubscriptions(join table). When adding a new entry to UsersSubscriptions, you need to check the number of user subscriptions, if it exceeds a certain value, then do not insert.
Pseudocode:
If(!usersSubscriptions.userCanSubscribe()) throw new Exception('Subscriptions exceeded!'); /** ( SELECT COUNT(*) FROM UsersSubscriptions WHERE userId = currentUserId ) < maxSubscriptions */
UsersSubscriptions.addRecord(); /** INSERT INTO UsersSubscriptions (subscriptionId, userId)
VALUES (currentSubscriptionId, urrentUserId); */
Users.updateOne( {_id: userId, $expr: { $lt: [ { $size: '$subscriptions'}, maxSubscriptions] } } }, updateObject );
Answer the question
In order to leave comments, you need to log in
How can this be avoided?
I see two solutions - use queues or perform checks at the level of database triggers.
An adequate solution seems to be to create a layer that will process the requests of streams one after another, i.e. some kind of bottleneck that will not allow threads to work as threads. Then the race condition will be impossible.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question