Why it is better to use UUIDs over auto increment ids
In this tutorial, we will dive deep into why UUID is better than Auto increment ids, But first we will understand some basic information about UUID & Auto increment ids(i.e. Primary key).
Auto increment primary keys.
The auto-increment key allows a unique number to be generated when a new record is inserted into a table. So every time we want to create a new record the database engine creates primary key automatically, and its responsibility is that this key is unique to the table.
Sample value looks like:
ID Value
-- -----
1 Cat
2 Dog
3 Cow
4 Horse
UUID
UUID also known as GUID is an alternative primary key type for SQL databases. This is 16-octet / 128 bit type compatible with most common GUID and UUID generators.It is represented by 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens, in the form 8–4–4–4–12 for a total of 36 characters (32 alphanumeric characters and four hyphens).UUID is a random string in a predefined format.
Sample value looks like:
ID Value
------------------------------------ -----
6H7FC84A-AD47-47EE-842C-29E969AC5131 Cat
f9734AE4-R5EF-4D77-9F84-51A8365AC5A0 Dog
9LE2E8DE-4F0E-4630-B3CB-166131D35C21 Cow
45ED815C-WD1C-4011-8667-7158982951EA Horse
Non-public information reveal in URLs
I assume you have a RESTful application. A primary key value is usually publicly discoverable in URLs and API network logs. Because of sequential IDs, I can guess previous identifiers should be able to receive information of a user that is not mine by entering an ID before mine:
https://example.com/api/v1/users/113.
Obviously, the server should have implemented some permission features, but the request will hit to the database & find the user (because this ID exists) and then restricts it.
Switching to UUID like this 45ED815C-WD1C-4011–8667–7158982951EA , it is impossible to guess another user identifier. And this is a very good thing!
When we are providing IDs in URLs, end user might know the numbers of records.
This is not harm full when you are a small company, but if you give this info to your competitor this is massive impact on your product.
Ex. Lets say there is a User table in the database.
If you create a new record, the server will store incremented ID in the database. So if your user id is 23134. You can guess the total number of users in the database.
Give the freedom to frontend developer
Generate new objects with UUID as a primary keys allow frontend applications to independently generate new record if this is not already exist in the database. This way, frontend developers have more freedom and do not have override API calls.
Like, Share or Leave A Comment!
If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it and leave a comment! Stay tuned for more exciting blogs on Javascript, React, Ruby, etc.
Thanks