Skip to content

fix: snapshot invoice quantities in parallel - #3034

Merged
turip merged 1 commit into
mainfrom
fix/snapshot-invoice-quantities-in-parallel
Jun 25, 2025
Merged

turip merged 1 commit into
mainfrom
fix/snapshot-invoice-quantities-in-parallel

Conversation

@turip

@turip turip commented Jun 24, 2025 •

Copy link
Copy Markdown
Member

Overview

Given invoices with a lot of events we can have quite slow queries, let's add an option to fetch the invoice quantities parallel. This will speed up invoice creation and gathering the invoice listing in such cases.

Summary by CodeRabbit

  • New Features

    • Introduced a configurable limit for the maximum number of parallel quantity snapshots during invoice processing, improving performance and flexibility.
  • Refactor

    • Updated invoice line quantity snapshotting to run in parallel, enhancing efficiency for larger invoices.
    • Adjusted configuration and service initialization to support the new parallel snapshotting feature.
    • Modified snapshotting method signatures to use subject keys instead of full invoice objects.
  • Tests

    • Added and updated test configurations to validate the parallel snapshotting functionality.

@coderabbitai

coderabbitai Bot commented Jun 24, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change introduces a new configuration parameter, MaxParallelQuantitySnapshots, to control the level of concurrency when snapshotting invoice line quantities in the billing service. The parameter is propagated through configuration structs, constructor functions, and service methods, refactoring snapshotting logic to support parallel processing using worker goroutines.

Changes

Files/Paths Change Summary
app/config/billing.go, app/config/config_test.go Added MaxParallelQuantitySnapshots to BillingConfiguration and updated tests to include this field.
app/common/billing.go Updated BillingService function signature to accept BillingConfiguration and pass new config to billing service.
cmd/billing-worker/wire_gen.go, cmd/jobs/internal/wire_gen.go, cmd/server/wire_gen.go Modified wiring to pass full billingConfiguration instead of just AdvancementStrategy to BillingService.
openmeter/billing/service/service.go Added maxParallelQuantitySnapshots to Service and config structs; enforced validation and initialization.
openmeter/billing/service/invoice.go, openmeter/billing/service/invoicestate.go Refactored invoice snapshotting to use new parallel snapshotting method; removed sequential snapshot method.
openmeter/billing/service/invoiceline.go Introduced snapshotLineQuantitiesInParallel for concurrent line snapshotting; updated related calls and error handling.
openmeter/billing/service/lineservice/service.go, .../feeline.go, .../usagebasedline.go, .../usagebasedlineflat.go Changed Line interface and implementations: SnapshotQuantity now takes []string subjectKeys instead of invoice ptr.
test/app/testenv.go, test/billing/suite.go, test/subscription/framework_test.go Updated test setups to include MaxParallelQuantitySnapshots in billing service configuration.

Possibly related PRs

  • openmeterio/openmeter#2768: Modifies the billing service initialization to accept a feature switches configuration, affecting the same BillingService function signature as this PR, though focused on different configuration aspects.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f6af73b and 71847f4.

📒 Files selected for processing (17)
  • app/common/billing.go (1 hunks)
  • app/config/billing.go (2 hunks)
  • app/config/config_test.go (1 hunks)
  • cmd/billing-worker/wire_gen.go (1 hunks)
  • cmd/jobs/internal/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/billing/service/invoice.go (2 hunks)
  • openmeter/billing/service/invoiceline.go (4 hunks)
  • openmeter/billing/service/invoicestate.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline.go (1 hunks)
  • openmeter/billing/service/lineservice/service.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedlineflat.go (1 hunks)
  • openmeter/billing/service/service.go (3 hunks)
  • test/app/testenv.go (1 hunks)
  • test/billing/suite.go (1 hunks)
  • test/subscription/framework_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/subscription/framework_test.go
🚧 Files skipped from review as they are similar to previous changes (16)
  • app/config/config_test.go
  • test/billing/suite.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • app/config/billing.go
  • cmd/billing-worker/wire_gen.go
  • test/app/testenv.go
  • openmeter/billing/service/lineservice/feeline.go
  • openmeter/billing/service/lineservice/service.go
  • openmeter/billing/service/lineservice/usagebasedlineflat.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • openmeter/billing/service/invoice.go
  • app/common/billing.go
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/service/service.go
  • openmeter/billing/service/invoicestate.go
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Quickstart
  • GitHub Check: CI
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Jun 24, 2025
@turip
turip force-pushed the fix/snapshot-invoice-quantities-in-parallel branch from 5f69ded to f6af73b Compare June 24, 2025 15:57
@turip
turip marked this pull request as ready for review June 24, 2025 16:07
@turip
turip requested a review from a team as a code owner June 24, 2025 16:07
@turip
turip requested review from chrisgacsal and tothandras June 24, 2025 16:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
app/config/billing.go (1)

19-34: Add validation for MaxParallelQuantitySnapshots.

The new configuration field should be validated to ensure it has a reasonable value.

 func (c BillingConfiguration) Validate() error {
 	var errs []error
+	
+	if c.MaxParallelQuantitySnapshots <= 0 {
+		errs = append(errs, errors.New("MaxParallelQuantitySnapshots must be greater than 0"))
+	}
+	
 	if err := c.Worker.Validate(); err != nil {
 		errs = append(errs, err)
 	}
🧹 Nitpick comments (2)
openmeter/billing/service/service.go (1)

92-95: Consider adding an upper bound validation.

While validating that MaxParallelQuantitySnapshots is greater than zero is good, consider adding an upper bound (e.g., 100) to prevent potential resource exhaustion from extremely high concurrency values.

 if c.MaxParallelQuantitySnapshots < 1 {
 	return errors.New("max parallel snapshots must be greater than 0")
 }
+if c.MaxParallelQuantitySnapshots > 100 {
+	return errors.New("max parallel snapshots must not exceed 100")
+}
openmeter/billing/service/invoiceline.go (1)

299-348: Well-implemented parallel processing with comprehensive error handling.

The parallel implementation includes several good practices:

  • Proper context cancellation handling
  • Panic recovery in goroutines
  • Comprehensive error collection and joining
  • Appropriate channel management and synchronization

However, there's one potential improvement for robustness:

Consider adding validation for the maxParallelQuantitySnapshots configuration to ensure it's greater than zero:

+	if s.maxParallelQuantitySnapshots <= 0 {
+		return fmt.Errorf("maxParallelQuantitySnapshots must be greater than zero")
+	}

This would prevent potential issues if misconfigured.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e48bdfe and f6af73b.

📒 Files selected for processing (17)
  • app/common/billing.go (1 hunks)
  • app/config/billing.go (2 hunks)
  • app/config/config_test.go (1 hunks)
  • cmd/billing-worker/wire_gen.go (1 hunks)
  • cmd/jobs/internal/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/billing/service/invoice.go (2 hunks)
  • openmeter/billing/service/invoiceline.go (4 hunks)
  • openmeter/billing/service/invoicestate.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline.go (1 hunks)
  • openmeter/billing/service/lineservice/service.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (2 hunks)
  • openmeter/billing/service/lineservice/usagebasedlineflat.go (1 hunks)
  • openmeter/billing/service/service.go (3 hunks)
  • test/app/testenv.go (1 hunks)
  • test/billing/suite.go (1 hunks)
  • test/subscription/framework_test.go (1 hunks)
🔇 Additional comments (22)
app/config/billing.go (2)

14-14: LGTM: New configuration field added correctly.

The MaxParallelQuantitySnapshots field is properly integrated into the configuration struct.


53-53: LGTM: Appropriate default value set.

The default value of 4 for parallel quantity snapshots seems reasonable for performance optimization without overwhelming the system.

app/config/config_test.go (1)

144-145: LGTM: Test configuration updated correctly.

The test configuration properly includes the new MaxParallelQuantitySnapshots field with the correct default value of 4.

test/billing/suite.go (1)

186-186: LGTM: Test uses appropriate concurrency level.

Setting MaxParallelQuantitySnapshots to 2 in tests is reasonable to avoid resource contention while still testing the parallel functionality.

test/app/testenv.go (1)

283-283: LGTM: Consistent test configuration.

The test environment correctly includes the new configuration parameter with a value of 2, consistent with other test files.

test/subscription/framework_test.go (1)

93-93: LGTM: Subscription test configuration updated correctly.

The subscription framework test properly includes the new MaxParallelQuantitySnapshots parameter with a value of 2, maintaining consistency with other test configurations.

cmd/jobs/internal/wire_gen.go (1)

289-289: LGTM! Configuration parameter update aligns with parallel snapshotting feature.

The change correctly passes the full billingConfiguration to enable access to the new MaxParallelQuantitySnapshots field instead of just the advancement strategy.

cmd/server/wire_gen.go (1)

283-283: LGTM! Consistent configuration parameter update.

The change aligns with the parallel snapshotting refactor by passing the complete billing configuration.

openmeter/billing/service/lineservice/feeline.go (1)

31-31: LGTM! Method signature updated for parallel snapshotting.

The parameter change from *billing.Invoice to []string correctly implements the interface update to support subject-key-based parallel quantity snapshotting.

openmeter/billing/service/lineservice/usagebasedlineflat.go (1)

91-91: LGTM! Consistent method signature update for parallel processing.

The parameter change from *billing.Invoice to []string aligns with the parallel snapshotting refactor while maintaining existing functionality.

cmd/billing-worker/wire_gen.go (1)

281-281: LGTM! Completes the consistent configuration refactor across wire files.

The change correctly passes the full billing configuration to support the new parallel snapshotting feature.

openmeter/billing/service/lineservice/service.go (1)

216-216: LGTM: Interface refactored to support parallel processing.

The method signature change from accepting the full invoice to just subject keys is well-designed. This reduces coupling and enables efficient parallel processing where each line service only needs the relevant subject keys for snapshotting.

openmeter/billing/service/lineservice/usagebasedline.go (1)

149-173: LGTM: Implementation correctly updated to match interface change.

The method implementation properly follows the new interface signature, directly using the provided subject keys instead of extracting them from the invoice object. The core snapshotting logic remains intact and correct.

openmeter/billing/service/service.go (1)

38-38: LGTM: Configuration field properly integrated.

The maxParallelQuantitySnapshots field is correctly added to both Service and Config structs with proper initialization in the constructor.

Also applies to: 52-52, 115-115

openmeter/billing/service/invoice.go (3)

143-146: LGTM: Customer profile expansion properly configured.

The customer profile is correctly fetched with expanded customer data to ensure UsageAttribution.SubjectKeys are available for the parallel snapshotting operation.


178-178: LGTM: Timestamp correctly updated after successful snapshot.

The QuantitySnapshotedAt timestamp is properly set after the parallel snapshotting operation completes successfully.


160-162: ```shell
#!/bin/bash

Locate the Service struct definition across the repo

rg -n "type Service struct" -A20 .

Find where maxParallelQuantitySnapshots is declared and its type

rg -n "maxParallelQuantitySnapshots" -C3 .


</details>
<details>
<summary>openmeter/billing/service/invoicestate.go (1)</summary>

`725-738`: **LGTM: State machine properly updated for parallel snapshotting.**

The `snapshotQuantityAsNeeded` method has been correctly refactored to:
1. Convert invoice lines to line services
2. Use the new parallel snapshotting approach with customer subject keys
3. Update the timestamp after successful completion

This change is consistent with the overall refactoring and maintains the same logical flow.

</details>
<details>
<summary>openmeter/billing/service/invoiceline.go (2)</summary>

`289-291`: **LGTM! Parallel processing implementation looks correct.**

The refactoring to use parallel snapshotting is well-implemented and should provide the performance improvements mentioned in the PR objectives.

---

`374-374`: **Interface change correctly implemented.**

The change from passing the entire invoice to just the subject keys is a good refactoring that reduces coupling and makes the interface cleaner.

</details>
<details>
<summary>app/common/billing.go (2)</summary>

`51-51`: **Configuration parameter change is well-structured.**

The change from passing just the advancement strategy to the full billing configuration provides better flexibility and maintains clean separation of concerns.

---

`65-67`: **Service initialization correctly updated.**

The initialization properly extracts both the advancement strategy and the new parallel snapshots configuration from the billing config, maintaining backward compatibility while adding the new feature.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Given for long sending invoices we can have quite slow queries, let's
add an option to parallely fetch the invoice quantities. This will
speed up invoice creation and gathering invoice listing in such cases.
@turip
turip force-pushed the fix/snapshot-invoice-quantities-in-parallel branch from f6af73b to 71847f4 Compare June 25, 2025 08:17
@turip
turip enabled auto-merge (squash) June 25, 2025 08:19
@turip
turip merged commit 1c62942 into main Jun 25, 2025
@turip
turip deleted the fix/snapshot-invoice-quantities-in-parallel branch June 25, 2025 08:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants