Skip to content

chore(perf): Dedupe charge filter preload#5945

Open
jdenquin wants to merge 1 commit into
mainfrom
perf-dedupe-charge-filter-load
Open

chore(perf): Dedupe charge filter preload#5945
jdenquin wants to merge 1 commit into
mainfrom
perf-dedupe-charge-filter-load

Conversation

@jdenquin

Copy link
Copy Markdown
Contributor

Context

When computing customer usage, the plan's charges and their filter tree (charge_filters + charge_filter_values with their large properties jsonb) are
loaded from PostgreSQL twice per computation:

  1. Invoices::CustomerUsageService#charges preloads them for the fee loop
  2. Events::BillingPeriodFilterService#non_recurring_charges_with_events re-loads the exact same associations for the same plan

On large plans (~1,600 charge filters) each load costs seconds, and RefreshWalletsService pays this per subscription.

Description

Load the charge/filter set once and share it:

  • Events::BillingPeriodFilterService accepts an optional charges: argument (pre-loaded charges with billable_metric and filters: {values: :billable_metric_filter}). When provided, non_recurring_charges_with_events, recurring_event_charges_and_filters and current_recurring_charges are
    resolved in memory instead of re-querying. Without it, behavior is unchanged, so CalculateFeesService and ProgressiveBillingService are unaffected.
  • Invoices::CustomerUsageService passes its memoized charges relation to the service; since it is the same object, the fee loop then reuses the loaded
    records.
  • find_each is replaced by each in the fee loop: find_each always re-queries in batches, which would have triggered the preload a second time.
  • The usage preload now includes billable_metric: :filters, required by ChargeFilters::EventMatchingService to stay query-free on pre-loaded charges.

@jdenquin jdenquin self-assigned this Jul 15, 2026
@jdenquin

Copy link
Copy Markdown
Contributor Author

with #5882, we can again win around 50ms per subscription during a customer usage computation.
QA confirm it.

@jdenquin jdenquin marked this pull request as ready for review July 15, 2026 13:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant