ULID: Like UUID but Sortable (2019)
github.com
github.com
So I spent the weekend creating "UPID"[1], which is like ULID but prefixable! Up to four characters for the prefix, 40 bits of time (256ms precision, but could change in a revision) and still 64 bits of randomness. So you can do pretty Stripe-style IDs without losing the benefits of a neat 128-bit UUID column. Have implemented it for Python, Rust and Postgres, maybe worth a kick around for someone!
Most of the effort, honestly, went into the compatibility layer when bridging which version of the ID was accepted on a given API, and ensuring that this major change was implemented between services universally (i.e., is service B going to fail if I send a prefixed ID?).
All of this to say, I am hesitant to generally recommend migrating from UUID -> prefixed UUID, but I will be considering starting future projects of my own with UPID
Would be great to hear about it if you do give it a spin. On projects with simpler domain models I can't imagine a huge benefit, but as soon as you have piles of tables it's quite nice that every row tells you up-front exactly what it is.
A more minor benefit maybe is that they're natively presented with the prefix in the DB, so eg communicating with non-technical team while running SQL queries doesn't involve constantly adding/removing prefixes...
Then, whenever the API includes an id in a response, it adds the appropriate prefix. When receiving an id in a request, validate that the prefix is correct and then strip the prefix.
That gets you all the advantages of prefixed IDs but still keep all 128bits (or however many bits, you don't have to stick to UUIDs) for the actual id.
Or, to put it another way, there's no need to store the prefix in the column because it will be identical for all rows.
EDIT: this is not to knock your work - quite the opposite. If you do have a use case where you need rows in the same table to have a dynamic prefix, or the client takes the IDs and needs to put them in their own database, then your solution has a lot of advantages. I think what I'm getting at is that if you're using prefixes then it's a worthwhile discussion to be had about where you apply the prefix.
As for doing the translation at the API boundary, my only gripe is that it's likely to be error-prone: every dev needs to remember to add/strip the correct prefix in every route. Of course you can add some middleware that is context-aware, but still there will be cases (eg live querying while talking to non-tech team) where not having to translate back-and-forth would be great!
Anyway, appreciate the comment and definitely agree that for most teams just using a UUID and adding a bit of code is a more obvious route than using a new ID format someone just made up!
The main differences:
- typeid allows up to a 63 byte prefix
- typeid follows it with a full 128-bit UUID
I prefer your implementation generally I think - I like the fixed size - just wanted to link something similar.
I left 4 bits out in UPID as a version specifier, so could theoretically add a version with longer prefixes or more/less timestamp precision if that seemed useful to anyone.
So when you call the new function, it will generate a UUIDv7, base32 encode it, and then prepend the prefix. Then at the database layer it will translate that to a UUIDv7 for storing and translate back to the string version when loading.
Another small benefit of UPID is that it works even for raw SQL sessions, but this obviously requires that it's installed into Postgres, which unfortunately for most is much harder than installing an Elixir/whatever lib.
But even if you just store them as u128/UUID, a nice thing is the IDs always know what their prefix is, so eg if you dump data into a warehouse, the IDs don't lose their context and an analytics person can still find what they're looking for.
In short, it seems UUIDv7 is storage-wise compatible with ULID but not vice versa due to UUID’s versioning bits.
(238 points, 6 years ago, 129 comments) https://news.ycombinator.com/item?id=18768909
(213 points, 3 years ago, 100 comments) https://news.ycombinator.com/item?id=29794186
(33 points, 2 years ago, 23 comments) https://news.ycombinator.com/item?id=34281969
Now that UUIDv7 is lexicographic, does that mean there is no use for ULID? (19 points, 26 days ago, 6 comments) https://news.ycombinator.com/item?id=40712872
> Within the same millisecond, sort order is not guaranteed
And:
> Monotonic sort order (correctly detects and handles the same millisecond)
Which is it?
To make it more confusing, the spec later contains a section about monotonic sort order[1]. And looks like not all libraries implement it [2].
[1]: https://github.com/ulid/spec?tab=readme-ov-file#monotonicity
Issues to think about before you switch:
- The ID includes the timestamp of it's creation. If you don't want to leak it, you should use another identifier along with it. (I've never needed this in my use cases)
- You won't be able to see the ID in its common representation format if you are using a database GUI. (I'm using Postico 2 for postgresql and the developer was kind enough to add "display as Crockford Base 32" to bytea columns making this a non-issue for me. UUIDv7 will also fix this.)
Here's a great list of many IDs if you haven't got enough dillema on what to use. Everyone is welcome to contribute
I would definitely just use a ULID or UUIDv7 as my sole primary DB key for new projects going forward. You get the benefit of ascending ordered primary keys, but the key is still globally unique so can be used as public keys.
If client-generation is not needed, then UUID is stupid to begin with, because any incremental id can be transformed ("encrypted") to arbitary different format (which hides the real id). Also UUID is usually much larger: Waste of db/index space, degraded performance. But I guess if people push everything in the cloud, they don't even realize they are paying more than needed...
Conclusion: I don't understand what you people are trying to "solve". All those different UUID versions leads me to believe the issue is not the id, but developer confusion.
Including the timestamp only tells someone the time the UUID was generated. Unlike incrementing numeric IDs (which can simply be subtracted from one another to measure a change in database records), there’s no way to meaningfully count change over time.
> any incremental id can be transformed ("encrypted") to arbitary different format (which hides the real id)
Easier said than done… You then have the overhead of encrypting/decrypting every client-facing ID before querying the database. You’ll also need to code workarounds in many frameworks, to bypass conventions where they expect keys in URL paths (for example).
> Also UUID is usually much larger: Waste of db/index space, degraded performance
With older UUIDs, sure, but sorted ones (like ULIDs) have consistent prefixes, allowing for very efficient indexing and querying with a binary tree search.
You are right, should have finished my morning coffee first =) I guess for client-side generation it makes sense then. But how often is that really needed? I don't know...
As for the other points. I still don't buy that. For example implementing UUIDs vs implementing the transformation: CPU cost is negligible (you don't need to use cryptographic secure cypher). UUID might be a little simpler to implement, but combined with space and performance savings it's well worth it: 16 byte vs 4/8 byte (which might be stored multiple times in related tables) - it adds up and fills resources. Again I understand, most people don't seem to care about that, because they were born into cloud culture and have no clue what they are doing in terms of efficiency money/resource-wise.
Maybe I'm just too old fir this!
- you can merge databases while guaranteeing ids won't conflict
- first hand support across various databases/systems
- you use it and never have to deal with ids again
You mean combining logically (or even physically) separated databases, collapsing their tuples into one? Why would you do that, and how often does that occur?
> first hand support across various databases/systems
UUIDs? Of the RDBMS most likely to be used (MySQL, Postgres, SQLite) only Postgres has a UUID type. The others store them as strings (please no) or binary types. MariaDB and Oracle have UUID types, and SQL Server has a GUID (essentially the same thing) type, but those are all less commonly seen.
What does have universal support is integers. They scale just fine (PlanetScale uses them [0] internally), and you can use them in a distributed system – if you even need one in the first place – via a variety of methods: interleaved ranges or a central server allocating chunks are two popular methods that come to mind.
[0]: https://github.com/planetscale/discussion/discussions/366
They have no clue about how computers work, full stop. Sure, they know programming languages, but generally speaking, if you ask them about IOPS, disk or network latency, NUMA, cache lines, etc. they’ll tell you it doesn’t matter, and has been abstracted away for them. Or worse, they’ll say sub-optimal code is fine because shipping is all that matters.
There is certainly a difference between sub-optimal and grossly un-optimized code. Agonizing over a few msec outside of hot loops is probably not worthwhile from an efficiency standpoint, but if it's trivial to do correctly, why not do it correctly? One recent shocking example I found was `libuuid` in its various forms. util-linux's implementation [0] at its most recent tag is shockingly slow in larger loops. I'm fairly certain it's due to entropy exhaustion, but I haven't looked into it enough yet.
MacOS uses arc4random [1] (which for Linux, is in glibc as of v2.36, but you can get it from libbsd-dev otherwise), and it's much, much faster (again, on large loops).
I made some small C programs and a shell runner to demonstrate this [2].
[0]: https://github.com/util-linux/util-linux/blob/stable/v2.40/l...
[1]: https://man7.org/linux/man-pages/man3/arc4random.3.html
[2]: https://gist.github.com/stephanGarland/f6b7a13585c0caf9eb64b...
As opposed to the overhead of generating a UUID? It may be fast, but it’s still overhead.
> code workarounds in many frameworks … they expect keys in URL paths
I personally despise this practice, not least of which because then your URL has a UUID (because it’s always UUIDs) in it, which is ugly; it also gives ammunition to the argument of using v4 so as to not expose time-based information. I still doubt that the latter matters, and think that it’s a hypothetical dreamt up by the same kind of people who shard their database and use Kafka at tiny startups because “we might need it.”
> very efficient indexing
You are of course correct that the sorted prefix helps the B+tree immensely, but you can’t get around the 16 bytes (or worse, if stored as a string) vs. 8 bytes or smaller for other types. Despite what people seem to think, this does add up, it does impact your buffer pool, and it does slow down queries.
It is possible to do as you say ofc but what is the advantage?
Another advantage is that you don't need to "think" about using sortable id, numeric serial id is sortable by default. It also helps with index size and insertion speed for primary key index and often foreign key indices.
Using completely random UUID leaks no data about record creation time. It might not look like sensitive information, but generally it's better to be on a cautious side about leaking information.
Generating sortable ID is far from generally accepted solution. You need to find obscure libraries or write non-trivial code yourself for all languages you're using. It'll be solved in time, as UUIDv7 became standard, but we're not there yet. UUID v4 is available in any language (and generally trivial to generate).
Columnar databases like Clickhouse don’t have the kind of indices that you’d be used to if you only used OLTP databases like eg Postgres. Instead, you essentially get one index per table, which is the order that things are laid out on disk*
The problem is that you might want 2 access patterns, one for aggregating data within a time range, and another for looking up / joining data by its ID. So which do you use as the index? Timestamp or ID? If the ID is a uuidv4 and you index by ID, your time range queries need to scan the entire table, and vice versa. If the ID is time-sortable (eg uuidv7), this stops being a problem, and you don’t need some kind of workaround*
* it’s a little more complicated than this but that not in a way that affects the example
* eg a projection of your data with a different index