Search code examples
mongodbuser-registrationdatabase

Handling simultaneous user registrations in mongoDB?


I have a mongodb collection of registered users with index on the userID field. Every time an user tries to register, a lookup is done on the existing user IDs to check if the user ID chosen by the registering user is available or not. I was just wondering what happens when two users enter the same userID for registration at the same time and the lookup is done at the same time. Would both of them end up having the same userID? Does mongodb handle such a scenario on its own? One of the purposes of the unique userID would be to give each user an URL based on the userID.

I'll be using the PyMongo module.


Solution

  • Preventing duplicate usernames is an example of Concurrency Control, a broad area which has many issues and many ways in which databases and apps can be designed to avoid problems.

    In the case of a collection of users where you are concerned to avoid duplicate userIDs, I would suggest the following design pattern:

    1. Create a unique index on the userID field
    2. In your app, make it check the response when creating a user; if it gets a Duplicate Key Error, then it knows that the userID has been taken, and it must ask the user to choose a different userID

    Other approaches are also possible; for example you could have the database assign the userIDs, which would be a different way to guarantee uniqueness.