Sortable UUIDs - when I use them
One string to universally and uniquely identify entities, and sequentially order them? Sounds great. UUIDv7 and ULID fit the bill. For most practical purposes, they are the identical. I prefer the visual look of the ULID charsequence. That’s what I use.
With sortable UUIDs, when I want to find entities older than entityA
, I send one query to the datastore to “find entities with ID less than entityA”. One step. Sortable UUIDs FTW. Query optimized.
A brand new feature in Ongoing Things will ask people - before they add a development (aka post) to their things - for a “When did this happen?” date. A thing is a chronological stream of developments. The queries of the app are reliant on the UUIDs for sorting by creation time. The new feature renders those queries obsolete.
To keep the machine optimization in place, an insane person might have a thought pass their mind: generate the sortable UUID with a clock they control - example ulid.nextValue(whenDidThisHappenDate)
for use with sulky-ulid. They could simply keep all else intact, queries included. Use the spare time to read HN.
Hmm. That? Not me!
The proper solution optimizes for the problem. The machine optimization is not worth it.
Adding a mutable property for the happened_on
date will serve me better. The timestamp from the UUID can be used as the default value for existing entities - Postgres (the db I use) supports extensions that can extract the timestamp from a UUIDv7 and ULID. The developments have an existing published_at
property that I’ll use as default.
The machine smirks a bit now - it will perform two steps 1) “find entityA by ID” so we can use a property from it to 2) “find entities with property lesser than entityA.property”. The human however, does not care.
I’ll keep picking sortable UUIDs as my default choice in the future. Will limit their use:
- as IDs for entities that
- as a developer I can understand when they were created, and
- order them relative to other events in the system.
There will be cases where the domain problem asks for ordering entities by creation date. That is on my list too, another valid use case for sortable UUIDs.