Benchmarking UUID v4 vs ULID

Butterfly Beach, Goa, Feb 2023

tl;dr

ULID offers better performance compared to UUIDs (v4) since ULIDs are monotonic. Another advantage is ULID values can be stored in the UUID column type that postgres offers.

ULID Generation

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE OR REPLACE FUNCTION generate_ulid() RETURNS uuid
    AS $$
        SELECT (lpad(to_hex(floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint), 12, '0') || encode(gen_random_bytes(10), 'hex'))::uuid;
    $$ LANGUAGE SQL;

SELECT generate_ulid();

Benchmarks

UUID (mean = 0.4531, median = 0.48)

ULID (mean = 0.0708, median = 0.037)