perf(db): Use statement trigger for marking deleted sessions

When sessions are deleted, a trigger is used to insert records into the
session_deleted table. This table is utilized by the sessions list
endpoint when using a refresh token to inform a client of the sessions
that have been deleted since the last request. We delete sessions in
bulk via a controller job to delete sessions that have been terminated
over an hour ago, which results in the trigger running a large number of
separate insert statements while processing the delete statement.

This changes the trigger to run once for the delete statement, instead
of for each row, resulting in a single bulk insert statement to the
session_deleted table.

This new trigger function also avoids the use of `on conflict`. When
testing this function, while the single statement was still faster than
running multiple inserts, the `on conflict` still added significant
overhead, even when there were no conflicts. It should be safe to
perform the insert without the `on conflict`, since the same ID should
never be deleted more than once if it is successfully deleted.
pull/5126/head
Timothy Messier 1 year ago
parent 5577b3c358
commit 3569b36c6e
No known key found for this signature in database
GPG Key ID: EFD2F184F7600572

@ -0,0 +1,25 @@
-- Copyright (c) HashiCorp, Inc.
-- SPDX-License-Identifier: BUSL-1.1
begin;
create function bulk_insert_deleted_ids() returns trigger
as $$
begin
execute format('insert into %I (public_id, delete_time)
select o.public_id, now()
from old_table o;',
tg_argv[0]);
return null;
end;
$$ language plpgsql;
comment on function bulk_insert_deleted_ids is
'bulk_insert_deleted_ids is a function that inserts records into the table '
'specified by the first trigger argument. It takes the public IDs from the '
'set of rows that where deleted and the current timestamp.';
drop trigger insert_deleted_id on session;
create trigger bulk_insert_deleted_ids
after delete on session
referencing old table as old_table
for each statement execute function bulk_insert_deleted_ids('session_deleted');
commit;
Loading…
Cancel
Save