Repository navigation
perf(billing): optimize credit balance and history queries - #5425
Conversation
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Scope grouping and query construction openmeter/ledger/historical/adapter/balancesatboundaries_query.go |
The query groups requests by filters, builds movements capped at each scope’s latest boundary, and adds a marker for each requested boundary. It selects shared running balances or independent sums based on scope overlap. |
Boundary query validation openmeter/ledger/historical/adapter/balancesatboundaries_query_test.go, openmeter/ledger/historical/adapter/balancesatboundaries_test.go |
SQL-template tests check generated queries and arguments, including a 500-row page. A repository test compares results with independent sums across cursor, timestamp, duplicate, missing, and filtered boundaries. |
Charge realization namespace filtering
| Layer / File(s) | Summary |
|---|---|
Namespace-scoped realization reads openmeter/billing/charges/usagebased/adapter/charge.go, openmeter/billing/charges/usagebased/adapter/charge_query_test.go |
Single and batch charge reads pass the namespace to realization expansion. The runs query filters by namespace and retains its deleted-run behavior. Tests check namespace filtering for both read paths. |
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Refactor
Possibly related PRs
- openmeterio/openmeter#5316: Uses
GetBalancesAtBoundariesto resolve credit transaction balances. This change modifies how that query calculates balances. - openmeterio/openmeter#5199: Adds plan predicates to historical ledger movement queries used by the balance-boundary query.
Suggested labels: kind/refactor, area/billing
Suggested reviewers: borosr
Merge Risk: 
Minimal · up to 00c2c
-
The shared balance scans and namespace-scoped realization reads have no identified merge-blocking issue, subject to normal checks.
Pre-merge checks: 
4
-
Full details: Title check
-
Explanation
The title is concise and describes query optimization work present in the changeset. It is partially related because the main performance change is in ledger balance-boundary history queries, while the title labels the work as billing.
-
Finishing Touches
-
Generate docstrings
-
- Commit to this branch
- Create a new PR
Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Credit transaction history currently calculates each row's booked balances with separate aggregate branches. A 500-row page can repeat the same account history scans 1,000 times.
This switches the production
GetBalancesAtBoundariesquery to scan each distinct filter scope once and calculate balances with a running total at timestamp/cursor markers. Transaction history already calls this method, so it uses the new calculation directly. When no scopes can be shared, the query keeps the existing independent sums to avoid an unnecessary sort.Per-row booked balances, same-time transaction ordering, filters, and pagination semantics are unchanged. No schema or API changes.
Usage-based realization loading also omitted namespace from the child run query, despite the existing index being
(namespace, charge_id). Both single-charge and batch lookups now pass the parent namespace into that query. This preserves run expansion and soft-delete behavior while avoiding broad index/table scans; no new index or migration is needed.On a separate local PostgreSQL 14.20 fixture with one million synthetic runs, adding namespace reduced median server execution from 6.47 ms to 0.055 ms for one charge, and 45.94 ms to 0.326 ms for 50 charges (five runs each). Including planning, those medians were 7.01 to 0.61 ms and 46.51 to 0.91 ms. These are query measurements, not endpoint or production speedup claims.
Local PostgreSQL 14.20 results with 1,000 historical transactions, median of three runs of eight queries:
These measure query execution and result decoding on synthetic data, not full endpoint latency. Benchmark code is kept outside the PR.
Validation:
Usage-based adapter tests verify namespace binding in the emitted run queries for single and batch lookups, including deleted-run expansion.
PostgreSQL-backed historical ledger, customer-balance, and credit API tests pass.
Regression coverage compares results with independent ledger sums, including tied timestamps, multiple entries per transaction, duplicate/out-of-order boundaries, empty scopes, and additional filters.
SQL template and bound-argument assertions cover the full query, multiple scopes, filtered movements, duplicate/mixed boundary markers, and the independent-sum fallback. Page-size scan-count assertions pass; focused lint reports no issues.
The optimized 10,000-transaction/500-row case also passes benchmarks with 1, 8, and 24 concurrent readers. The previous query's 500-row concurrent benchmark exhausted local PostgreSQL shared memory, so no comparative concurrent throughput claim is made.
Summary by CodeRabbit


Confidence Score: 5/5
The PR appears safe to merge; no actionable issues were found.Summary
Shares ledger history scans across balance requests with matching filters. Requests without shared filters keep independent sums.
No actionable issues were found in the changes since the previous review or the full-PR rules check. Validation was limited to source review; tests were not run.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart TD A[Balance requests] --> B[Group matching filters] B --> C{Any shared groups?} C -->|No| D[Sum each request separately] C -->|Yes| E[Scan each group once] E --> F[Add zero-value boundary markers] F --> G[Calculate running totals] G --> H[Return totals at markers]Reviews (2) · Last reviewed commit: "test(ledger): expand balance boundary qu..." · Reviewed by Greptile