Skip to content

perf(billing): optimize credit balance and history queries - #5425

Merged
GAlexIHU merged 3 commits into
mainfrom
codex/credit-history-balance-performance
Nov 2, 2026
Merged

GAlexIHU merged 3 commits into
mainfrom
codex/credit-history-balance-performance

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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 GetBalancesAtBoundaries query 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:

Page size Previous query New query
50 36.3 ms 3.3 ms
500 396.1 ms 5.8 ms

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

  • New Features
    • Retrieve historical balances at requested timestamps and transaction boundaries, including scopes with no ledger entries at the boundary.
  • Bug Fixes
    • Balance results account for matching ledger activity through each scope’s latest requested boundary and remain consistent across repeated, out-of-order, and filtered requests.
    • Charge reads now limit related realization data to the charge’s namespace.
  • Tests
    • Added coverage for boundary queries, multiple scopes, tied timestamps, large pages, and namespace filtering.

RetriggerView in GreptileConfidence 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.

  • Credit history calculates many row balances from shared ledger scans.

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]
Loading

Reviews (2) · Last reviewed commit: "test(ledger): expand balance boundary qu..." · Reviewed by Greptile

@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Nov 2, 2026
@GAlexIHU
GAlexIHU requested a review from a team as a code owner November 2, 2026 16:12
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between a9b23d1 and 00c2c04.

Files selected for processing: 2
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/charge_query_test.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

Walkthrough

The balance-boundary query groups requests by filters and selects shared running balances or independent sums. Charge realization reads now apply namespace filtering. Tests cover generated SQL and returned balance results.

Changes: Balance-boundary query

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 GetBalancesAtBoundaries to 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: Passed 4
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 th…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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.

Share

turip
turip previously approved these changes Nov 2, 2026
@GAlexIHU GAlexIHU changed the title perf(ledger): share history scans across balance boundaries perf(billing): optimize credit balance and history queries Nov 2, 2026
@GAlexIHU
GAlexIHU enabled auto-merge (squash) November 2, 2026 16:48
@GAlexIHU
GAlexIHU merged commit 676f3f4 into main Nov 2, 2026
31 checks passed
@GAlexIHU
GAlexIHU deleted the codex/credit-history-balance-performance branch November 2, 2026 16:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants