How to implement unique usernames from a list of phrases

by AnonymousCoward   Last Updated April 16, 2018 04:05 AM

I am looking to create a random username based on a set of existing phrases plus an integer since there can be multiple users with the same phrase. For now lets assume there's 12 phrases such as AnonymousPotato, so a user who signs up could randomly receive AnonymousPotato12345 as a unique username. The user would be stored in a MySQL table that has an auto incremented int primary key. I thought of using the id, but I don't think exposing the user's id is a good idea as it might expose information such as how many users exist.

The issue I am trying to work out is collision. How can I ensure the username generated is unique without having to expose an auto incremented database ID?

Tags : design mysql

Answers 1

If you want to ensure its unique, two ways immediately come to mind:

  • pre-generate 1,000,000 unique user names (or whatever amount you think you might need). When a user signs up, pull one from the list and mark it as used.

  • After generating one, simply check if it is already in the database, and if it is, try again, and keep trying until you have a unique one.

I agree with you, you probably shouldn't use the user id as a public ID. What I usually do is assign a public facing guid (in a column I call 'public_hash', usually a hash of the user name and some other info) to that user, which gets used in public facing urls.

April 16, 2018 03:35 AM

Related Questions