Menu

Our ID generator is 22 lines, sorts by creation time, and gets two IDs from the same millisecond in the right order half the time
📰

Our ID generator is 22 lines, sorts by creation time, and gets two IDs from the same millisecond in the right order half the time

DEV Community: postgres·Daniel Pertu·2 days ago
#iVd66UQj
#devtopostgresql#devto#dev#random#millisecond
Long article (837 words) — no AI summary yet.
Reading 0:00
15s threshold

Munchable's support tickets, their messages, reward ledger rows and product revisions all take their primary keys from the application, not the database. The key is a ULID: a 48-bit millisecond timestamp followed by 80 random bits, written in Crockford base32, 26 characters in all. Because the timestamp is the prefix, IDs sort by creation time as plain strings, which makes them good keyset-pagination tiebreakers and pleasant to read in a log.

There is a well-known package for this. We did not install it, because the whole thing fits in a file smaller than most licence headers:

const ENC = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' ;

export function ulid ( now : number = Date . now ( ) ) : string { let ts = '' ; let t = now ; for ( let i = 0 ; i < 10 ; i ++ ) { ts = ENC [ t % 32 ] + ts ; t = Math . floor ( t / 32 ) ; } const bytes = crypto .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.