Last active
July 18, 2021 21:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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