DEV Community

Cover image for Rant: UUIDs and primary keys
Muhammad Ali Naeemi
Muhammad Ali Naeemi

Posted on • Updated on

Rant: UUIDs and primary keys

Disclaimer:This post is about my experience regarding using UUIDs as primary keys. If you defer from my opinion and you have "real world experience" on this matter, then please correct me, politely.

In this episode of rants with Ali, we will touch a subject about, why I don't use UUIDs as primary keys anymore.

After having built a fairly complex application with UUIDs as sole primary keys and later switching them back for ints, but still keeping UUIDs for public..that was painful..

You see, UUIDs work fairly fine if you are just going to call db for fairly simple things, i.e. fetch me this by id. However, this whole thing starts to fall apart, when you have complex joins or a lot of inserts/updates, due to nature of UUIDs.

Now, among many things, the indexing cannot be ordered and so that is going to affect inserts and update. Besides, it is going to take a lot more resources, because UUIDs are bulky and your joins will suffer a lot!

In most applications, you wouldn't really mind having slow updates or inserts but sacrificing on joins..they are quite important, specially if you want to keep your application fast without too many roundtrips and in memory calculations where db is almost always going to win. And having a crippling system defeats any "elegant" solution that anyone can muster!

Now one could argue that they will go with NoSQL where everything is "repeated". Sure. You can. But you will still need aggregations at some point (Not talking about DDD aggregations) and that will still be slower anyways due the database being inherently slower at such tasks.

So, what I instead do now is keep int as primary key (in relational database at least) while adding UUID for public facing entities. This gives me best of both worlds.

I am not going to provide exact "numbers" since you can find it all over the internet.

And finally, please don't base your decisions off of 10 minutes of "googling" around..

Top comments (0)