Last active
September 18, 2018 19:43
-
-
Save ichux/1b5d15129370341811fb12eb7e333917 to your computer and use it in GitHub Desktop.
sharding id at instagram
This file contains 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
-- create the needed sequence | |
CREATE SEQUENCE table_id_seq; | |
-- change the public to schema of choice | |
CREATE OR REPLACE FUNCTION public.next_id(OUT result bigint) AS $$ | |
DECLARE | |
our_epoch bigint := 1314220021721; | |
seq_id bigint; | |
now_millis bigint; | |
shard_id int := 5; | |
BEGIN | |
SELECT nextval('table_id_seq'::regclass) % 1024 INTO seq_id; | |
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis; | |
result := (now_millis - our_epoch) << 23; | |
result := result | (shard_id << 10); | |
result := result | (seq_id); | |
END; | |
$$ LANGUAGE PLPGSQL; |
This file contains 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
-- insert into the table | |
INSERT INTO public.our_table (enabled) VALUES(TRUE) RETURNING id; | |
INSERT INTO public.our_table (enabled) VALUES(False) RETURNING id; |
This file contains 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
-- select from the table | |
SELECT * FROM our_table ORDER BY id DESC LIMIT 100; |
This file contains 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
CREATE TABLE IF NOT EXISTS public.our_table ( | |
id BIGINT DEFAULT public.next_id() NOT NULL, | |
enabled BOOLEAN NOT NULL | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment