Skip to content

Commit 4e2cf5c

Browse files
committed
perf: add idx cache
1 parent efcb5db commit 4e2cf5c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
-- using group by and max is slow. as the store grows, latency is creeping up.
2+
-- get a handle on it!
3+
-- Really this sort of workload (lots of aggregation) is better suited to OLAP,
4+
-- but let's just stick with postgres until we can't any more
5+
6+
create table store_idx_cache(
7+
id bigserial primary key,
8+
user_id bigint,
9+
10+
host uuid,
11+
tag text,
12+
idx bigint
13+
);
14+
15+
16+
create or replace function cache_store_idx()
17+
returns trigger as
18+
$func$
19+
begin
20+
if (TG_OP='INSERT') then
21+
update store_idx_cache set idx = (select max(idx) from store where user_id=new.user_id and host=new.host and tag=new.tag) where user_id=new.user_id and host=new.host and tag=new.tag;
22+
23+
if not found then
24+
insert into store_idx_cache(user_id, host, tag, idx)
25+
values (
26+
new.user_id,
27+
new.host,
28+
new.tag,
29+
(select max(idx) from store where user_id = new.user_id and host=new.host and tag=new.tag)
30+
);
31+
end if;
32+
end if;
33+
34+
return NEW; -- this is actually ignored for an after trigger, but oh well
35+
end;
36+
$func$
37+
language plpgsql volatile -- pldfplplpflh
38+
cost 100; -- default value
39+
40+
create or replace trigger tg_cache_store_idx
41+
after insert on store
42+
for each row
43+
execute procedure cache_store_idx();

0 commit comments

Comments
 (0)