-
Notifications
You must be signed in to change notification settings - Fork 22
perf(dashboard): optimize financial log queries (load 5-15s -> <500ms) #3725
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TaprootFreak
wants to merge
7
commits into
develop
Choose a base branch
from
perf/dashboard-financial-log-optimization
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0511e4f
perf(dashboard): add composite index on log table for financial queries
TaprootFreak 8a1c4be
perf(dashboard): denormalize aggregate columns on log entity
TaprootFreak 7aea13f
perf(dashboard): DB-side bucketing for sub-week financial log ranges
TaprootFreak 1ecb9ba
perf(dashboard): enable gzip compression for API responses
TaprootFreak 6cea047
perf(log): filter sampling subquery by 'from' to avoid full-table agg…
TaprootFreak dd591ef
refactor(log): route balancesByType JSON column through typed getter/…
TaprootFreak e311a78
refactor(log): move getSampleIntervalMinutes to log.util.ts
TaprootFreak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /** | ||
| * @typedef {import('typeorm').MigrationInterface} MigrationInterface | ||
| * @typedef {import('typeorm').QueryRunner} QueryRunner | ||
| */ | ||
|
|
||
| /** | ||
| * @class | ||
| * @implements {MigrationInterface} | ||
| */ | ||
| module.exports = class AddLogFinancialIndex1779221816705 { | ||
| name = 'AddLogFinancialIndex1779221816705'; | ||
|
|
||
| /** | ||
| * @param {QueryRunner} queryRunner | ||
| */ | ||
| async up(queryRunner) { | ||
| // Composite index to accelerate dashboard-financial queries: | ||
| // - getLatestFinancialLog (system/subsystem/severity, ORDER BY id DESC) | ||
| // - getFinancialLogs / getFinancialChangesLogs (range scans on created with daily/minute bucketing) | ||
| // - log-job.service.maxEntity lookups (every minute on the same predicates) | ||
| // The log table grows by ~525k rows/year (one cron entry per minute), so a non-covered scan is expensive. | ||
| await queryRunner.query( | ||
| `CREATE INDEX "IDX_7765c3f5f663a0c6d250d28255" ON "log" ("subsystem", "severity", "created")`, | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * @param {QueryRunner} queryRunner | ||
| */ | ||
| async down(queryRunner) { | ||
| await queryRunner.query(`DROP INDEX "IDX_7765c3f5f663a0c6d250d28255" ON "log"`); | ||
| } | ||
| }; |
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adapt to PSQL |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /** | ||
| * @typedef {import('typeorm').MigrationInterface} MigrationInterface | ||
| * @typedef {import('typeorm').QueryRunner} QueryRunner | ||
| */ | ||
|
|
||
| /** | ||
| * @class | ||
| * @implements {MigrationInterface} | ||
| */ | ||
| module.exports = class AddLogFinancialAggregates1779221847925 { | ||
| name = 'AddLogFinancialAggregates1779221847925'; | ||
|
|
||
| /** | ||
| * @param {QueryRunner} queryRunner | ||
| */ | ||
| async up(queryRunner) { | ||
| // Denormalised aggregates for the FinancialDataLog cron rows, consumed by the dashboard chart | ||
| // endpoint. Nullable so older rows continue to work via a JSON.parse fallback in the service. | ||
| await queryRunner.query(`ALTER TABLE "log" ADD "totalBalanceChf" float`); | ||
| await queryRunner.query(`ALTER TABLE "log" ADD "plusBalanceChf" float`); | ||
| await queryRunner.query(`ALTER TABLE "log" ADD "minusBalanceChf" float`); | ||
| await queryRunner.query(`ALTER TABLE "log" ADD "btcPriceChf" float`); | ||
| await queryRunner.query(`ALTER TABLE "log" ADD "balancesByTypeJson" nvarchar(4000)`); | ||
| } | ||
|
|
||
| /** | ||
| * @param {QueryRunner} queryRunner | ||
| */ | ||
| async down(queryRunner) { | ||
| await queryRunner.query(`ALTER TABLE "log" DROP COLUMN "balancesByTypeJson"`); | ||
| await queryRunner.query(`ALTER TABLE "log" DROP COLUMN "btcPriceChf"`); | ||
| await queryRunner.query(`ALTER TABLE "log" DROP COLUMN "minusBalanceChf"`); | ||
| await queryRunner.query(`ALTER TABLE "log" DROP COLUMN "plusBalanceChf"`); | ||
| await queryRunner.query(`ALTER TABLE "log" DROP COLUMN "totalBalanceChf"`); | ||
| } | ||
| }; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
135 changes: 135 additions & 0 deletions
135
src/subdomains/supporting/dashboard/__tests__/dashboard-financial.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { createMock } from '@golevelup/ts-jest'; | ||
| import { Test, TestingModule } from '@nestjs/testing'; | ||
| import { AssetService } from 'src/shared/models/asset/asset.service'; | ||
| import { RefRewardService } from 'src/subdomains/core/referral/reward/services/ref-reward.service'; | ||
| import { createCustomLog } from '../../log/__mocks__/log.entity.mock'; | ||
| import { LogService } from '../../log/log.service'; | ||
| import { DashboardFinancialService } from '../dashboard-financial.service'; | ||
|
|
||
| describe('DashboardFinancialService', () => { | ||
| let service: DashboardFinancialService; | ||
|
|
||
| let logService: LogService; | ||
| let assetService: AssetService; | ||
| let refRewardService: RefRewardService; | ||
|
|
||
| beforeEach(async () => { | ||
| logService = createMock<LogService>(); | ||
| assetService = createMock<AssetService>(); | ||
| refRewardService = createMock<RefRewardService>(); | ||
|
|
||
| const module: TestingModule = await Test.createTestingModule({ | ||
| providers: [ | ||
| DashboardFinancialService, | ||
| { provide: LogService, useValue: logService }, | ||
| { provide: AssetService, useValue: assetService }, | ||
| { provide: RefRewardService, useValue: refRewardService }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| service = module.get(DashboardFinancialService); | ||
| }); | ||
|
|
||
| describe('getFinancialLog (chart fast path)', () => { | ||
| it('uses denormalised aggregate columns without parsing the message JSON', async () => { | ||
| const log = createCustomLog({ | ||
| id: 42, | ||
| created: new Date('2026-05-19T12:00:00Z'), | ||
| message: '{"this":"must not be parsed"}', | ||
| totalBalanceChf: 1_000_000, | ||
| plusBalanceChf: 1_200_000, | ||
| minusBalanceChf: 200_000, | ||
| btcPriceChf: 90_000, | ||
| balancesByTypeJson: JSON.stringify({ EUR: { plusBalanceChf: 50, minusBalanceChf: 10 } }), | ||
| }); | ||
|
|
||
| jest.spyOn(logService, 'getFinancialLogs').mockResolvedValue([log]); | ||
| jest.spyOn(assetService, 'getBtcCoin').mockResolvedValue({ id: 1 } as never); | ||
|
|
||
| const result = await service.getFinancialLog(new Date(), false); | ||
|
|
||
| expect(result.entries).toHaveLength(1); | ||
| expect(result.entries[0]).toEqual({ | ||
| timestamp: log.created, | ||
| totalBalanceChf: 1_000_000, | ||
| plusBalanceChf: 1_200_000, | ||
| minusBalanceChf: 200_000, | ||
| btcPriceChf: 90_000, | ||
| balancesByType: { EUR: { plusBalanceChf: 50, minusBalanceChf: 10 } }, | ||
| }); | ||
| }); | ||
|
|
||
| it('falls back to JSON.parse for legacy rows without denormalised columns', async () => { | ||
| const message = JSON.stringify({ | ||
| balancesByFinancialType: { EUR: { plusBalanceChf: 100, minusBalanceChf: 20 } }, | ||
| balancesTotal: { plusBalanceChf: 100, minusBalanceChf: 20, totalBalanceChf: 80 }, | ||
| assets: { 1: { priceChf: 90_000 } }, | ||
| }); | ||
|
|
||
| const legacyLog = createCustomLog({ | ||
| id: 1, | ||
| created: new Date('2024-01-01T00:00:00Z'), | ||
| message, | ||
| totalBalanceChf: null, | ||
| plusBalanceChf: null, | ||
| minusBalanceChf: null, | ||
| btcPriceChf: null, | ||
| balancesByTypeJson: null, | ||
| }); | ||
|
|
||
| jest.spyOn(logService, 'getFinancialLogs').mockResolvedValue([legacyLog]); | ||
| jest.spyOn(assetService, 'getBtcCoin').mockResolvedValue({ id: 1 } as never); | ||
|
|
||
| const result = await service.getFinancialLog(new Date(), false); | ||
|
|
||
| expect(result.entries).toHaveLength(1); | ||
| expect(result.entries[0]).toMatchObject({ | ||
| totalBalanceChf: 80, | ||
| plusBalanceChf: 100, | ||
| minusBalanceChf: 20, | ||
| btcPriceChf: 90_000, | ||
| balancesByType: { EUR: { plusBalanceChf: 100, minusBalanceChf: 20 } }, | ||
| }); | ||
| }); | ||
|
|
||
| it('caches results within the TTL window', async () => { | ||
| const log = createCustomLog({ | ||
| id: 1, | ||
| created: new Date(), | ||
| totalBalanceChf: 1, | ||
| plusBalanceChf: 1, | ||
| minusBalanceChf: 0, | ||
| btcPriceChf: 0, | ||
| }); | ||
|
|
||
| const spy = jest.spyOn(logService, 'getFinancialLogs').mockResolvedValue([log]); | ||
| jest.spyOn(assetService, 'getBtcCoin').mockResolvedValue({ id: 1 } as never); | ||
|
|
||
| const from = new Date(); | ||
| await service.getFinancialLog(from, false); | ||
| await service.getFinancialLog(from, false); | ||
|
|
||
| expect(spy).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('uses different cache entries for different query parameters', async () => { | ||
| const log = createCustomLog({ | ||
| id: 1, | ||
| created: new Date(), | ||
| totalBalanceChf: 1, | ||
| plusBalanceChf: 1, | ||
| minusBalanceChf: 0, | ||
| btcPriceChf: 0, | ||
| }); | ||
|
|
||
| const spy = jest.spyOn(logService, 'getFinancialLogs').mockResolvedValue([log]); | ||
| jest.spyOn(assetService, 'getBtcCoin').mockResolvedValue({ id: 1 } as never); | ||
|
|
||
| await service.getFinancialLog(new Date('2026-01-01'), false); | ||
| await service.getFinancialLog(new Date('2026-01-02'), false); | ||
| await service.getFinancialLog(new Date('2026-01-01'), true); | ||
|
|
||
| expect(spy).toHaveBeenCalledTimes(3); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adapt to PSQL