Skip to content

Commit 66725f8

Browse files
authored
perf: improve metrics query performance (#1052)
The current query is not using any indices due to the CASE statement. Using `UNION`, we're now able to take advantage of tables indices, and have a more faster query
1 parent f0c6345 commit 66725f8

File tree

2 files changed

+14
-16
lines changed

2 files changed

+14
-16
lines changed

src/helpers/metrics.ts

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -96,23 +96,19 @@ new client.Gauge({
9696
labelNames: ['status'],
9797
async collect() {
9898
const statusResults = await db.queryAsync(`
99-
SELECT
100-
SUM(CASE WHEN verified > 0 THEN 1 ELSE 0 END) AS verified,
101-
SUM(CASE WHEN flagged > 0 THEN 1 ELSE 0 END) AS flagged,
102-
SUM(CASE WHEN hibernated > 0 THEN 1 ELSE 0 END) AS hibernated,
103-
SUM(CASE WHEN turbo_expiration > UNIX_TIMESTAMP() THEN 1 ELSE 0 END) AS active_turbo,
104-
SUM(CASE WHEN turbo_expiration > 0 AND turbo_expiration <= UNIX_TIMESTAMP() THEN 1 ELSE 0 END) AS expired_turbo
105-
FROM spaces
99+
SELECT 'verified' as status, COUNT(*) as count FROM spaces WHERE verified > 0
100+
UNION ALL
101+
SELECT 'flagged' as status, COUNT(*) as count FROM spaces WHERE flagged > 0
102+
UNION ALL
103+
SELECT 'hibernated' as status, COUNT(*) as count FROM spaces WHERE hibernated > 0
104+
UNION ALL
105+
SELECT 'active_turbo' as status, COUNT(*) as count FROM spaces WHERE turbo_expiration > UNIX_TIMESTAMP()
106+
UNION ALL
107+
SELECT 'expired_turbo' as status, COUNT(*) as count FROM spaces WHERE turbo_expiration > 0 AND turbo_expiration <= UNIX_TIMESTAMP()
106108
`);
107109

108-
[
109-
'verified',
110-
'flagged',
111-
'hibernated',
112-
'active_turbo',
113-
'expired_turbo'
114-
].forEach(status => {
115-
this.set({ status }, statusResults[0][status]);
110+
statusResults.forEach((row: any) => {
111+
this.set({ status: row.status }, row.count);
116112
});
117113
}
118114
});

src/helpers/mysql.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ sequencerConfig.connectTimeout = 60e3;
3434
sequencerConfig.acquireTimeout = 60e3;
3535
sequencerConfig.timeout = 60e3;
3636
sequencerConfig.charset = 'utf8mb4';
37-
sequencerConfig.ssl = { rejectUnauthorized: sequencerConfig.host !== 'localhost' };
37+
sequencerConfig.ssl = {
38+
rejectUnauthorized: sequencerConfig.host !== 'localhost'
39+
};
3840

3941
const sequencerDB = mysql.createPool(sequencerConfig);
4042

0 commit comments

Comments
 (0)