Database – How to prevent two users from registering at the same instant with same username

databasemultithreading

We cannot serialize registrations as there are millions of users registering at the same time. Parallel registrations need to happen.

Let's say the database doesn't contain username 'user1'. When two users try to register at the same moment with 'user1' it'll accept it. But it will later cause problems. This shouldn't happen.

I'm looking for a logical solution. Not anything specific. Just an idea to solve this.

Best Answer

Let's say the database doesn't contain username 'user1'. When two users try to register at the same moment with 'user1' it'll accept it.

Why would it accept it? It's simple to apply a unique constraint, use username as a primary key, or simply run the check in application code inside a transaction.

You should absolutely be able to use a database transaction to use the database to prevent this from occurring. Otherwise, no application would be able to maintain invariants in database data.

In terms of scaling, databases already invented the technologies you need, like various modes of locking depending on exactly what kind of consistency you need, distributed databases for multiple database servers, etc.

Related Topic