Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Start storing congestion per minute #598

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

neekolas
Copy link
Contributor

@neekolas neekolas commented Mar 7, 2025

TL;DR

Added originator congestion tracking to measure message volume per originator over time.

What changed?

  • Created new originator_congestion table to track message counts per originator
  • Added SQL queries to increment and retrieve congestion metrics
  • Modified gateway envelope insertion to concurrently update both usage and congestion metrics
  • Added corresponding test coverage for congestion tracking

Other ideas

I thought about including message counts on the unsettled_usage table. I decided against because I'm worried that the lifecycle of the rows might be different. If we get a payer report, we will delete all unsettled_usage for that payer from before the report. That could be in the last 5 minutes, where we would still need the congestion information.

It would also mean we would need to store congestion per-payer, instead of a single value per originator.

How to test?

  • Run existing test suite which includes new congestion tracking tests
  • Verify that TestInsertAndIncrement and TestInsertAndIncrementParallel pass
  • Confirm congestion metrics increment correctly when messages are processed

Why make this change?

This change enables tracking message volume per originator, which is essential for implementing rate limiting and preventing potential abuse of the system. The concurrent updates ensure efficient processing while maintaining accurate metrics for both usage and congestion.

Copy link

coderabbitai bot commented Mar 7, 2025

Walkthrough

This pull request introduces concurrent execution within the InsertGatewayEnvelopeAndIncrementUnsettledUsage function by running the increment operations for unsettled usage and originator congestion simultaneously using goroutines and a sync.WaitGroup. New SQL queries and corresponding Go methods have been added to manage originator congestion, along with a new Go struct to represent congestion metrics. In addition, migration scripts are introduced to create and drop the originator_congestion table. Test cases have been updated to assert the expected originator congestion state following these operations.

Changes

File(s) Change Summary
pkg/db/gatewayEnvelope.go
pkg/db/gatewayEnvelope_test.go
Modified InsertGatewayEnvelopeAndIncrementUnsettledUsage to execute increment operations concurrently using goroutines; test cases updated to validate the originator congestion value.
pkg/db/queries.sql
pkg/db/queries/queries.sql.go
Reformatted existing SQL queries for clarity; added new queries (IncrementOriginatorCongestion, GetOriginatorCongestion) and implemented corresponding Go methods and parameter types to manage originator congestion.
pkg/db/queries/models.go Added new struct OriginatorCongestion with fields for OriginatorID, NumMessages, and MinutesSinceEpoch to track congestion metrics.
pkg/migrations/00009_originator-congestion.up.sql
pkg/migrations/00009_originator-congestion.down.sql
Introduced migration files to create the originator_congestion table with a composite primary key and default settings, and to drop the table if necessary.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Function as InsertGatewayEnvelopeAndIncrementUnsettledUsage
    participant TxQueries

    Client->>Function: Call InsertGatewayEnvelopeAndIncrementUnsettledUsage
    par Concurrent Operations
        Function->>TxQueries: IncrementUnsettledUsage
        Function->>TxQueries: IncrementOriginatorCongestion
    end
    TxQueries-->>Function: Return increment results (unsettled usage & congestion)
    Function->>Client: Return inserted rows or error based on results
Loading

Possibly related PRs

  • Track unsettled usage #549: Involves modifications to unsettled usage tracking and introduces new functions and SQL commands related to usage metrics.

Suggested reviewers

  • mkysel
  • fbac

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.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

Copy link
Contributor Author

neekolas commented Mar 7, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/db/gatewayEnvelope_test.go (2)

69-74: Consider additional test cases for congestion metrics

The test verifies that congestion is tracked, but it doesn't explicitly verify that the minutes_since_epoch is stored correctly or how multiple messages in the same minute are handled.

Consider adding tests that:

  1. Verify the correct minute is used (matching incrementParams.MinutesSinceEpoch)
  2. Test multiple insertions within the same minute to ensure num_messages increments correctly

143-148: Verify congestion behavior with multiple insertions

While this parallel test checks for race conditions, it only verifies a single successful insertion. Consider extending this test to verify how congestion is tracked when multiple insertions succeed.

Since totalInserted is 1 (due to sequence ID uniqueness constraint), but you're making multiple insertion attempts, it would be valuable to test a scenario where multiple distinct messages are successfully inserted to verify congestion increments correctly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82dfd87 and a681451.

📒 Files selected for processing (7)
  • pkg/db/gatewayEnvelope.go (2 hunks)
  • pkg/db/gatewayEnvelope_test.go (3 hunks)
  • pkg/db/queries.sql (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/queries.sql.go (5 hunks)
  • pkg/migrations/00009_originator-congestion.down.sql (1 hunks)
  • pkg/migrations/00009_originator-congestion.up.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test (Node)
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (10)
pkg/migrations/00009_originator-congestion.down.sql (1)

1-2: SQL migration looks good!

This down migration correctly drops the originator_congestion table to revert the changes made by the up migration.

pkg/db/queries/models.go (1)

53-57: Data model looks good for tracking congestion metrics

The OriginatorCongestion struct is well-structured and matches the schema defined in the migration files, with appropriate types for each field.

pkg/migrations/00009_originator-congestion.up.sql (1)

1-6: Table schema looks good!

The table design with a composite primary key on (originator_id, minutes_since_epoch) is appropriate for tracking congestion per minute. The default value of 0 for num_messages is also a sensible choice.

pkg/db/gatewayEnvelope_test.go (1)

9-10: Appropriate import alias added

Adding the explicit xmtpd_db alias makes it clear where the functions are coming from.

pkg/db/gatewayEnvelope.go (1)

34-63: Great implementation of concurrent operations!

The introduction of concurrent execution for incrementing unsettled usage and originator congestion using goroutines and WaitGroup is a good performance improvement. The implementation correctly:

  1. Uses sync.WaitGroup to coordinate both operations
  2. Captures errors from each goroutine individually
  3. Properly handles error cases in sequence after both operations complete
pkg/db/queries.sql (2)

234-251: SQL queries for originator congestion look good.

The new SQL queries for tracking and retrieving originator congestion are well structured and follow the same patterns as existing queries. The implementation will correctly:

  1. Insert or update congestion metrics in the originator_congestion table
  2. Retrieve congestion metrics with appropriate filtering based on time range

203-232: Formatting improvements enhance readability.

The formatting adjustments to the SQL queries improve code readability while maintaining the same functionality.

pkg/db/queries/queries.sql.go (3)

292-316: Well-implemented function for retrieving originator congestion.

The implementation follows the established pattern for database query functions and correctly handles parameter passing and result processing.


344-360: Correctly implemented function for incrementing originator congestion.

The function correctly passes the parameters to the SQL query and properly handles errors.


274-282: Formatting enhancements to SQL queries improve readability.

The formatting changes to the constant SQL strings align with the changes in the queries.sql file and improve readability without changing functionality.

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