Skip to content

Build the usage insert once, not on every message (CHOO-3667) - #1262

Closed
abeldantas wants to merge 1 commit into
mainfrom
usage-insert-once
Closed

abeldantas wants to merge 1 commit into
mainfrom
usage-insert-once

Conversation

@abeldantas

@abeldantas abeldantas commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Every message an agent sends records its usage, and UsageStore.record built its INSERT ... ON CONFLICT for each one. In this PR we build it once and run it with bind parameters, as #1250 does for the budget standings.

Locally (400 agents, 20 messages a second), this and #1263 take CPU per message from 13.2 to 12.7 ms.

Every message an agent sends records its usage, and UsageStore.record
built its INSERT ... ON CONFLICT statement each time, which cost more
than running it. It is built once and run with bind parameters, as the
budget standings statement is.

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

🟢 Approval recommended

The review identifies no active issues, with the change focused on reusing a parameterized usage upsert while preserving the existing aggregation and conflict-update behavior.

No open issues 🎉

What changed in this PR

This pull request improves usage-recording performance by constructing the PostgreSQL upsert once and reusing it with bind parameters, while preserving hourly aggregation and conflict-update behavior.

Changes:

  • Adds a reusable, parameterized usage upsert statement.
  • Updates UsageStore.record to execute the shared statement.
  • Documents the optimization in the changelog.
File Summary
core/​switch_core/​db/​stores/​usage_store.py Reuses the module-level usage upsert with runtime bind parameters. A regression test covering statement reuse would be beneficial.
CHANGELOG.md Documents the usage-statement construction optimization.

This pull request is ready to be approved.

Review effort: Lite

@abeldantas

Copy link
Copy Markdown
Collaborator Author

Combined into #1307 with the other scaling PRs.

@abeldantas abeldantas closed this Nov 2, 2026
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.

2 participants