diff --git a/.changeset/gold-crabs-agree.md b/.changeset/gold-crabs-agree.md new file mode 100644 index 0000000000..1f345a8c10 --- /dev/null +++ b/.changeset/gold-crabs-agree.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Use a faster count method on pg when computing some metrics diff --git a/plugins/catalog-backend/src/database/metrics.ts b/plugins/catalog-backend/src/database/metrics.ts index d8cd87558f..809405d69f 100644 --- a/plugins/catalog-backend/src/database/metrics.ts +++ b/plugins/catalog-backend/src/database/metrics.ts @@ -98,20 +98,40 @@ export function initDatabaseMetrics(knex: Knex) { description: 'Total amount of registered locations in the catalog', }) .addCallback(async gauge => { - const total = await knex('locations').count({ - count: '*', - }); - gauge.observe(Number(total[0].count)); + if (knex.client.config.client === 'pg') { + // https://stackoverflow.com/questions/7943233/fast-way-to-discover-the-row-count-of-a-table-in-postgresql + const total = await knex.raw(` + SELECT reltuples::bigint AS estimate + FROM pg_class + WHERE oid = 'locations'::regclass; + `); + gauge.observe(Number(total.rows[0].estimate)); + } else { + const total = await knex('locations').count({ + count: '*', + }); + gauge.observe(Number(total[0].count)); + } }), relations: meter .createObservableGauge('catalog_relations_count', { description: 'Total amount of relations between entities', }) .addCallback(async gauge => { - const total = await knex('relations').count({ - count: '*', - }); - gauge.observe(Number(total[0].count)); + if (knex.client.config.client === 'pg') { + // https://stackoverflow.com/questions/7943233/fast-way-to-discover-the-row-count-of-a-table-in-postgresql + const total = await knex.raw(` + SELECT reltuples::bigint AS estimate + FROM pg_class + WHERE oid = 'relations'::regclass; + `); + gauge.observe(Number(total.rows[0].estimate)); + } else { + const total = await knex('relations').count({ + count: '*', + }); + gauge.observe(Number(total[0].count)); + } }), }; }