Understanding ULID: Features, Specification, and Python Usage
This article explains ULID (Universally Unique Lexicographically Sortable Identifier) as a time‑based, collision‑resistant alternative to UUID, outlines its specifications, highlights its advantages, and provides practical Python examples for generating and manipulating ULIDs.
ULID (Universally Unique Lexicographically Sortable Identifier) is introduced as an alternative to UUID, offering time‑based ordering, high collision resistance, and a more compact, URL‑safe string representation.
Unlike UUID’s five versions, ULID combines a 48‑bit millisecond timestamp with 80‑bit cryptographically strong randomness, yielding 1.21×10^24 unique values per millisecond and lexicographic sortability.
Key characteristics include 128‑bit compatibility with UUID, Crockford’s Base32 encoding (no ambiguous characters), case‑insensitivity, URL safety, monotonic ordering within the same millisecond, and binary layout in network byte order.
The specification details the timestamp (48‑bit UNIX time in milliseconds, valid until year 10889) and randomness (80‑bit, preferably generated with a cryptographic source). The binary layout consists of four 32‑bit and one 16‑bit fields.
Typical application scenarios are replacing auto‑increment primary keys, providing globally unique ordered keys in distributed systems, and enabling time‑based sharding or partitioning in databases.
Python usage is demonstrated with the ulid-py library: installation via pip install ulid-py , creating new ULIDs, converting from UUIDs, timestamps, or raw randomness, and accessing timestamp() and randomness() methods.
pip install ulid-py >>> import ulid
>>> ulid.new()
<ULID('01BJQE4QTHMFP0S5J153XCFSP9')> >>> import ulid, uuid
>>> value = uuid.uuid4()
>>> ulid.from_uuid(value)
<ULID('09GF8A5ZRN9P1RYDVXV52VBAHS')> >>> import datetime, ulid
>>> ulid.from_timestamp(datetime.datetime(1999, 1, 1))
<ULID('00TM9HX0008S220A3PWSFVNFEH')> >>> import os, ulid
>>> randomness = os.urandom(10)
>>> ulid.from_randomness(randomness)
<ULID('01BJQHX2XEDK0VN0GMYWT9JN8S')>Once a ULID object is created, the timestamp() method returns the 48‑bit time component and the randomness() method returns the 80‑bit random component.
For further details and source code, see the GitHub repository at https://github.com/ahawker/ulid .
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.