From 5577b3c358e9d45cd7ec02fc951e45d52e50595e Mon Sep 17 00:00:00 2001 From: Timothy Messier Date: Mon, 16 Sep 2024 13:43:32 +0000 Subject: [PATCH] perf(db): Reorder index columns for primary keys When processing a controller API request, system uses a query to fetch the grants for the requesting user. This query requires pulling together information from several tables, and is currently performing many sequential scans to do so. For a number of the tables involved, there are indexes from multi-column primary keys, however, due to the order of the columns in the index, the postgres planner would need to do a full scan of the index, which can be less efficient than a sequential scan, so instead it will perform a sequential scan of the table. This recreates the primary keys while swapping the order of the columns in the primary key definition, and thus the order in the index. By doing so, the planner will not need to perform a full index scan, and will be more likely to use the index when executing the grants query. --- .../91/03_indexes_grants_query.up.sql | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 internal/db/schema/migrations/oss/postgres/91/03_indexes_grants_query.up.sql diff --git a/internal/db/schema/migrations/oss/postgres/91/03_indexes_grants_query.up.sql b/internal/db/schema/migrations/oss/postgres/91/03_indexes_grants_query.up.sql new file mode 100644 index 0000000000..97c779dbdd --- /dev/null +++ b/internal/db/schema/migrations/oss/postgres/91/03_indexes_grants_query.up.sql @@ -0,0 +1,39 @@ +-- Copyright (c) HashiCorp, Inc. +-- SPDX-License-Identifier: BUSL-1.1 + +begin; + -- For each of these tables, swap the ordering of the + -- columns in the index for the primary key. + -- This helps the grants query that contains + -- several where clauses on what is currently the second + -- column in these indexes. By swapping the order, this + -- will make it more likely that the query planner will + -- choose to use the index. + -- See: https://www.postgresql.org/docs/current/indexes-multicolumn.html + + alter table auth_oidc_managed_group_member_account + drop constraint auth_oidc_managed_group_member_account_pkey, + add primary key (member_id, managed_group_id); + + alter table iam_managed_group_role + drop constraint iam_managed_group_role_pkey, + add primary key (principal_id, role_id); + + alter table iam_group_member_user + drop constraint iam_group_member_user_pkey, + add primary key (member_id, group_id); + + alter table iam_group_role + drop constraint iam_group_role_pkey, + add primary key (principal_id, role_id); + + alter table iam_user_role + drop constraint iam_user_role_pkey, + add primary key (principal_id, role_id); + + analyze auth_oidc_managed_group_member_account, + iam_managed_group_role, + iam_group_member_user, + iam_group_role, + iam_user_role; +commit;