Skip to content

Instantly share code, notes, and snippets.

@bradleyhodges
Created May 24, 2025 06:15
Show Gist options
  • Save bradleyhodges/a98598084767e04d68a5a790a02c2a46 to your computer and use it in GitHub Desktop.
Save bradleyhodges/a98598084767e04d68a5a790a02c2a46 to your computer and use it in GitHub Desktop.
Ultra-tuned PL/pgSQL Snowflake ID generator for Supabase Postgres. Provides 41-bit millisecond timestamps, 10-bit node IDs, and a 12-bit cached, cycling sequence entirely within a dedicated schema. No C extensions required.
-- Create separate schema for Snowflake logic. See: https://supabase.com/docs/guides/database/extensions?queryGroups=database-method&database-method=dashboard#enable-and-disable-extensions#:~:text=To%20avoid%20namespace%20pollution,%20we%20do%20not%20recommend%20creating%20other%20entities%20in%20the%20extensions%20schema.
CREATE SCHEMA IF NOT EXISTS snowflake_ext;
-- High-performance 12-bit sequence
CREATE SEQUENCE IF NOT EXISTS snowflake_ext.sequence_12bit
AS BIGINT
START 0
INCREMENT 1
MINVALUE 0
MAXVALUE 4095
CYCLE
CACHE 1024;
-- The generator function (this is marked VOLATILE for per-call freshness)
CREATE OR REPLACE FUNCTION snowflake_ext.gen_snowflake_id()
RETURNS BIGINT
LANGUAGE plpgsql
VOLATILE
AS $$
DECLARE
_epoch CONSTANT BIGINT := 1600000000000;
_node CONSTANT BIGINT := 1;
_now_ms BIGINT;
_seq BIGINT;
BEGIN
SELECT
nextval('snowflake_ext.sequence_12bit'),
FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT
INTO
_seq,
_now_ms;
RETURN
((_now_ms - _epoch) << 22)
| ((_node & 1023) << 12)
| (_seq & 4095);
END;
$$;
-- Use this with `SELECT snowflake_ext.gen_snowflake_id();` or make `snowflake_ext.gen_snowflake_id()` your tables' primary key default value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment