Skip to content

Instantly share code, notes, and snippets.

@webstrand
Last active July 18, 2021 21:46
Show Gist options
  • Select an option

  • Save webstrand/768ae9f65102e0175593f3e3a620e9db to your computer and use it in GitHub Desktop.

Select an option

Save webstrand/768ae9f65102e0175593f3e3a620e9db to your computer and use it in GitHub Desktop.
Generate a int64/bigint unique id using 41 bits of timestamp and 10 bits of sequence.
# https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c
CREATE SEQUENCE IF NOT EXISTS object_id_seq AS smallint
MINVALUE 0
MAXVALUE 1023
CYCLE;
CREATE OR REPLACE FUNCTION object_id_epoch()
RETURNS bigint
LANGUAGE sql
VOLATILE
AS $$
SELECT floor(extract(EPOCH FROM clock_timestamp()) * 1000) - 1626644283413
$$;
COMMENT ON FUNCTION object_id_epoch IS
'Get the current object_id timestamp in milliseconds. '
'Not the same as the UNIX epoch.';
CREATE OR REPLACE FUNCTION next_object_id()
RETURNS uint8
LANGUAGE sql
VOLATILE
AS $$
SELECT 0
| object_id_epoch()::uint8 << 23 /* [23..64) 41 bits */
| nextval('object_id_seq')::uint2 /* [0..10) 10 bits */
$$;
COMMENT ON FUNCTION next_object_id IS
'Obtain the next object_id. '
'Collision only occurs when more than >1024/ms ids are created.';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment