From 3569b36c6eb2bee7a4e36e7584fcc6bbf1124f95 Mon Sep 17 00:00:00 2001 From: Timothy Messier Date: Mon, 16 Sep 2024 13:52:37 +0000 Subject: [PATCH] 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. --- ..._insert_session_delete_on_statement.up.sql | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 internal/db/schema/migrations/oss/postgres/91/04_insert_session_delete_on_statement.up.sql diff --git a/internal/db/schema/migrations/oss/postgres/91/04_insert_session_delete_on_statement.up.sql b/internal/db/schema/migrations/oss/postgres/91/04_insert_session_delete_on_statement.up.sql new file mode 100644 index 0000000000..99e8eebad2 --- /dev/null +++ b/internal/db/schema/migrations/oss/postgres/91/04_insert_session_delete_on_statement.up.sql @@ -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;