fix(ai-gateway): shed usage writes when the pool is full - #5115
Open
jrf0110 wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Follow-up to #5034, #5098, and #5105. The shared Sentry event for
insertUsageRecord failed (code=unknown constraint=none)shows the failure originates atpg-poolacquisition inside Drizzle, beforeBEGINor any usage SQL. The pairedusage record handoff to primary region failedevent is the caller reporting that failed Frankfurt delivery.Production diagnostics already show the local pool at
idle=0on 96-98% of sampled requests, with as many as 245 waiters againstmax=10. Letting every handoff join that queue causes connection-acquisition timeouts and keeps unrelated work on the same Fluid instance under pressure.This change adds admission control to
POST /api/internal/usage/record: after authentication, it returns a retryable 503 before reading the body or starting a write when the primary pool has no idle connection and is already at its configured maximum. The existing client retries 503 because this response proves no write began, preserving idempotency. Requests are still admitted when an idle connection exists or the pool can grow. If the pool maximum is unavailable, the check fails open.The third linked event,
TRPCError: Usage data temporarily unavailable, is a separate Snowflake query exceeding its 5-second timeout. Its stack does not touch this PostgreSQL path, so this PR does not claim to fix it.Verification
pnpm --filter web test -- --runInBand src/lib/ai-gateway/usage-record-diagnostics.test.ts src/lib/ai-gateway/usage-record-client.test.ts(53 tests passed)pnpm --filter web typecheckpnpm --filter web lint(0 warnings, 0 errors)pnpm formatgit diff --checkVisual Changes
N/A