Skip to content

fix(billing): avoid long-lived invoice sequence locks - #4681

Merged
turip merged 1 commit into
mainfrom
feat/billing-sequence-allocation
Jul 10, 2026
Merged

turip merged 1 commit into
mainfrom
feat/billing-sequence-allocation

Conversation

@turip

@turip turip commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add an explicit commit mode to billing sequence definitions so allocations can either follow the caller transaction or commit independently.
  • Allocate sequence values with one atomic PostgreSQL upsert and keep gathering/draft allocations independent while custom-invoicing and sandbox allocations remain caller-bound.
  • Add allocation latency metrics, transaction safety documentation, and service-level coverage for rollback, commit, and concurrent uniqueness behavior.

Why

Previously, sequence allocation participated in the surrounding invoice transaction. The sequence row for a namespace and scope could therefore remain locked for the full invoice operation, serializing otherwise independent invoice work.

Independent allocation keeps contention limited to the allocation itself. The deliberate tradeoff is that invoice numbers are not guaranteed to be contiguous: a caller rollback can leave a gap, but an allocated number is not reused.

This is a follow-up to #4676.

Transaction considerations

transaction.RunInNewTransaction is intentionally exceptional. For Ent-backed adapters it starts a separate transaction on another pooled database connection. The callback cannot observe caller-uncommitted writes, and concurrent callers can add connection-pool pressure. The sequence callback only uses in-memory inputs and touches the sequence table, so it does not depend on caller-held customer or invoice locks.

A local OpenMeter Cloud dual-schema harness verified caller commit/rollback behavior and concurrent uniqueness using Cloud's shared Cloud/OpenMeter Ent driver. It also confirmed the additional pooled-connection requirement.

Validation

  • nix develop --impure .#ci -c make lint
  • nix develop --impure .#ci -c make test-nocache

Greptile Summary

This PR changes billing sequence allocation to reduce long-lived invoice sequence locks. The main changes are:

  • Adds explicit commit modes for billing sequence definitions.
  • Moves gathering and draft invoice number allocation into independent transactions.
  • Replaces sequence allocation with one atomic PostgreSQL upsert.
  • Adds allocation duration metrics and updates DI wiring.
  • Adds tests for rollback, commit, and concurrent allocation behavior.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.
  • The highest-risk transaction and allocation paths have targeted coverage for rollback, commit, and concurrent uniqueness.

Important Files Changed

Filename Overview
openmeter/billing/sequence/adapter/seq.go Replaces the sequence row lock/read/update flow with an atomic upsert that returns the allocated number.
openmeter/billing/sequence/service/service.go Adds commit-mode dispatch, allocation metrics, and constructor validation for the sequence service.
pkg/framework/transaction/transaction.go Adds a helper for starting a transaction that shadows any transaction already on the caller context.
openmeter/billing/sequence/sequence.go Adds required sequence commit modes and sets the built-in gathering and draft definitions to independent allocation.
app/common/billing.go Threads the metric meter into billing sequence service construction and billing registry wiring.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Generate invoice sequence number] --> B[Validate sequence definition]
    B --> C{Commit mode}
    C -->|with_caller| D[Allocate in caller transaction]
    C -->|independent| E[Start independent transaction]
    E --> F[Allocate sequence number]
    D --> G[Atomic upsert returns next value]
    F --> G
    G --> H[Render invoice number]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[Generate invoice sequence number] --> B[Validate sequence definition]
    B --> C{Commit mode}
    C -->|with_caller| D[Allocate in caller transaction]
    C -->|independent| E[Start independent transaction]
    E --> F[Allocate sequence number]
    D --> G[Atomic upsert returns next value]
    F --> G
    G --> H[Render invoice number]
Loading

Reviews (1): Last reviewed commit: "fix(billing): allocate invoice sequences..." | Re-trigger Greptile

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)
  • Context used - api/spec/AGENTS.md (source)

Summary by CodeRabbit

  • New Features

    • Added configurable sequence commit modes for caller-bound or independent commits.
    • Added independent transaction support for sequence allocation.
    • Added OpenTelemetry metrics for tracking allocation duration.
  • Bug Fixes

    • Improved concurrent sequence allocation to ensure unique numbers.
    • Preserved expected sequence behavior across transaction commits and rollbacks.
  • Tests

    • Added coverage for commit modes, rollback behavior, concurrency, and transaction isolation.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f9259c74-36c5-4c9c-ac64-11e2e774157d

📥 Commits

Reviewing files that changed from the base of the PR and between 7d6a4f7 and 9d37487.

📒 Files selected for processing (19)
  • .agents/skills/service/SKILL.md
  • app/common/billing.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/app/custominvoicing/app.go
  • openmeter/app/sandbox/app.go
  • openmeter/billing/sequence/adapter/seq.go
  • openmeter/billing/sequence/sequence.go
  • openmeter/billing/sequence/sequence_test.go
  • openmeter/billing/sequence/service/service.go
  • openmeter/billing/sequence/service/service_test.go
  • pkg/framework/transaction/context.go
  • pkg/framework/transaction/context_test.go
  • pkg/framework/transaction/transaction.go
  • test/app/testenv.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go

📝 Walkthrough

Walkthrough

Sequence definitions now require explicit commit modes. Allocation supports caller-bound or independent transactions, uses an atomic SQL upsert, records allocation metrics, and receives meters through application and test wiring.

Changes

Sequence allocation and transaction flow

Layer / File(s) Summary
Commit-mode contracts and definitions
openmeter/billing/sequence/sequence.go, openmeter/billing/sequence/sequence_test.go, openmeter/app/...
Sequence definitions validate with_caller and independent commit modes; built-in, custom invoicing, and sandbox definitions set explicit modes.
Independent transaction execution
pkg/framework/transaction/*, .agents/skills/service/SKILL.md
RunInNewTransaction creates a fresh transaction context, with tests covering driver shadowing and documentation describing its usage constraints.
Atomic sequence persistence
openmeter/billing/sequence/adapter/seq.go
Sequence allocation uses an insert-on-conflict upsert that increments and returns the stored sequence value.
Mode-aware sequence service
openmeter/billing/sequence/service/*
The service accepts a meter, records allocation duration, routes allocations by commit mode, and tests rollback, commit, and concurrent uniqueness behavior.
Meter injection and integration updates
app/common/billing.go, cmd/*/wire_gen.go, test/app/*, test/billing/*, test/customer/*, test/subscription/*
Billing constructors, generated wiring, and test environments pass explicit meters to the configurable sequence service constructor.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant SequenceService
  participant Transaction
  participant SequenceAdapter
  participant Database
  Caller->>SequenceService: Generate invoice sequence number
  alt Caller-bound mode
    SequenceService->>SequenceAdapter: Allocate using caller transaction
  else Independent mode
    SequenceService->>Transaction: Run allocation in new transaction
    Transaction->>SequenceAdapter: Allocate using fresh transaction
  end
  SequenceAdapter->>Database: Upsert and return next sequence
  Database-->>SequenceAdapter: Next sequence value
  SequenceAdapter-->>SequenceService: Sequence value
  SequenceService-->>Caller: Invoice sequence number
Loading

Possibly related PRs

  • openmeterio/openmeter#4395: Updates the same billing registry constructor and generated wiring surfaces with an additional dependency.

Suggested labels: kind/feature

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: reducing long-lived invoice sequence locks in billing.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/billing-sequence-allocation

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

Comment @coderabbitai help to get the list of available commands.

@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels Jul 10, 2026
@turip
turip marked this pull request as ready for review July 10, 2026 09:18
@turip
turip requested a review from a team as a code owner July 10, 2026 09:18
@turip
turip requested a review from tothandras July 10, 2026 11:31
@turip
turip merged commit 49b2f18 into main Jul 10, 2026
28 of 31 checks passed
@turip
turip deleted the feat/billing-sequence-allocation branch July 10, 2026 12:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants