pg_snowid
pg_snowid · Generate thread-safe, time-sorted Snowflake-like IDs in PostgreSQL
Overview
PostgreSQL · 18, 19
Usage
Sources:
pg_snowid generates time-ordered 64-bit Snowflake-like identifiers and compact Base62 representations in PostgreSQL. It keeps per-key generators in shared memory and needs a distinct node ID for each PostgreSQL instance in a distributed deployment.
Core Workflow
Add pg_snowid to shared_preload_libraries, restart PostgreSQL, create the extension, and set the node before generating any ID:
The generator key passed to snowid_generate is an integer-like OID value. Keep a stable, documented key per ID domain; it selects shared generator state but is not encoded in the resulting ID.
Important Objects
snowid_set_nodesets node ID 0 through 1023 before any generator is created; the default is 1.snowid_get_nodereturns the active node ID.snowid_generateandsnowid_generate_base62generate one numeric or Base62 ID.snowid_try_generateandsnowid_try_generate_base62return null instead of moving logical time ahead.snowid_generate_batchandsnowid_try_generate_batchreserve up to 100,000 IDs.snowid_get_timestampandsnowid_get_timestamp_base62extract the millisecond timestamp.snowid_statsreports node and generator state.
Operational Notes
Under sustained load, normal generation advances a logical timestamp rather than waiting, so an embedded timestamp can be ahead of wall-clock time. The try variants preserve wall-clock behavior but may return null or a short batch. Node ID is not derived automatically; reusing it across instances risks collisions, and changing it after a generator exists requires a PostgreSQL restart. Separate generator keys are independent and the key is absent from the bit layout, so do not assume global uniqueness across keys without an application-level test and constraint strategy.
Version 3.3.0
Version3.3.0 moves to pgrx0.20.1 and supports PostgreSQL18 and19. Install the binary for the selected major and restart to replace the preloaded module. Inspect available SQL upgrade paths before altering an existing installation; the release version alone does not prove an upgrade script exists. Preserve the node-ID and generator-key policy across failover.