1

I'm currently trying to figure out sign-up for my app. Right now, at sign up I ask users for a username alongside an email and password (for firebase_auth).

The thing is, I don't want more than one user with a username, so I need to check my database if there already exists a user with that username before signing up the user with firebase_auth and adding this new user to my database.

I'm concerned about a race condition that could arise if two users try to create an account with the same username at the same time. I'm trying to use TransactionHandler, but im not sure exactly how I can do this as I hear that a transaction might be run up to 5 times, and we shouldn't do anything that should not be run multiple times (i.e. sign up with firebase_auth?).

Any ideas as to how I can work around this?

Shiv
  • 109
  • 6

1 Answers1

1

There is no way to create a user account and create a document in the database atomically. So you'll have to instead find a way to deal with it in your application code.

Typically this comes from thinking of account creation as a sequence of steps. For example, this is quite common:

  1. Create account in Firebase Authentication, based on the credentials the user enters.
  2. Have the user verify their email address, so that you can reach them.
  3. Have the user claim their unique user name.

You'll see that none of these steps depends on a step that comes after it, so you can execute them in order. And when you do that, step 3 should work fine in a transaction that may run multiple ties.

Just keep in mind: if you want something to be unique on Firestore, you need to use that value as the IDs of your documents. There is no way with client-side access (not even with transactions) to guarantee uniqueness of values across documents. For some more questions on that topic, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807