Scalable outbox: dedicated connection pool, keyset pagination, dedup - #25
Merged
Conversation
This log fires for every outbox record that was already processed by another pod or goroutine, which is expected behavior in multi-replica deployments. At INFO level it produces thousands of noisy log lines that obscure meaningful output. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The getRecordIDs loop used defer inside a for-loop, accumulating unclosed rows and uncancelled contexts across pages — exhausting the connection pool and causing context deadline exceeded errors. This extracts a fetchPage method so defer scopes correctly per page. Also replaces LIMIT/OFFSET pagination with keyset pagination (WHERE id > $1 ORDER BY id) which is O(1) per page and stable under concurrent modifications. Increases the channel buffer from 1 to 100 to reduce backpressure blocking. Adds configurable WithPageSize and WithChannelBufferSize store options. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Split fetchPage into queryPage (DB-scoped) and fetchPage (channel send) so that channel backpressure cannot trigger the 15s context timeout. This was causing "pq: canceling statement due to user request" errors every 15s under load when the consumer couldn't drain the channel fast enough. Reduce defaults to chanBufferSize=5, pageSize=6 so the producer blocks on the 6th item of each page. This keeps the consumer saturated (5 items of runway while the next page is fetched) while minimizing the window where another pod could read the same buffered-but-unprocessed items. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add sync.Map-based in-flight tracking in dispatch() to skip IDs already being processed. Without this, getRecordIDs rescans return records still being processed, sending duplicate IDs to the channel. Each duplicate spawns a goroutine that acquires a pool connection via BeginTx, saturating the pool and causing 30s context timeouts across the system — including spilling into the sites-api connection pool. Use defer tx.Rollback() in ProcessTx (idiomatic Go pattern) so that when context cancellation auto-rolls back the tx, the deferred Rollback is a silent no-op instead of returning "sql: transaction has already been committed or rolled back". Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…pressure The outbox consumer (queryPage, ProcessTx) shared the same *sql.DB pool as the API resolvers. Long-running GraphQL mutations exhausted the pool, starving the consumer and triggering 15s context timeouts. Open a dedicated consumer pool from the existing connStr with a small MaxOpenConns (default 8). queryPage and ProcessTx.BeginTx now use this isolated pool, so API traffic cannot block outbox processing. Also adds: - WithMaxConsumerConns option to configure the pool size - Close() method with done channel for graceful shutdown of the Listen goroutine and consumer pool - Cancellable channel sends via done channel to prevent goroutine leaks Fixes test connStr to point at the correct database (outbox_test). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Set s.db = consumerDB on the parent store so init(), Delete, and Update bypass the caller's shared pool entirely. The db parameter in NewStore is kept for backward compatibility but no longer used. Also removes redundant pre-check select on done channel in Listen loop. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
gjarmstrong
approved these changes
Mar 16, 2026
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.
Problem
At scale, the outbox consumer was experiencing
context deadline exceedederrors and blocking behavior. Root cause analysis identified three compounding issues:Connection pool starvation — The outbox consumer shared a
*sql.DBpool with the API resolvers. Long-running mutations (e.g.createServiceableAddresses) would exhaust the pool, starving the outbox consumer'sSELECTandFOR UPDATEqueries until the mutation completed or timed out.Unbounded table scan —
SELECT id FROM outboxloaded every row into memory in a single query, causing context deadline timeouts as the table grew.Changes
Dedicated consumer connection pool (
store/pg/pg.go)*sql.DBfromconnStrwith configurableMaxOpenConns(default 8)queryPage,ProcessTx,GetWithLock,Delete) run on this isolated pooldbparameter is accepted for backward compatibility but no longer storedClose()method anddonechannel for clean shutdown and goroutine lifecycleWithMaxConsumerConns(n)optionKeyset pagination (
store/pg/pg.go)SELECT id FROM outboxwithSELECT id FROM outbox WHERE id > $1 ORDER BY id LIMIT NqueryPage(DB-scoped context) andfetchPage(channel sends) so backpressure cannot trigger context timeoutsWithPageSize(n)andWithChannelBufferSize(n)optionschanBufferSize=5,pageSize=6— producer blocks on the 6th item, keeping the consumer saturated while minimizing duplicate-read windows across podsIn-flight deduplication (
outbox.go)sync.Mapto track IDs currently being processedLoadOrStore/Deletearound process)ProcessTx rollback safety (
store/pg/pg.go)defer tx.Rollback()to handle context cancellation gracefully (no-op after commit)sql: transaction has already been committed or rolled backerrorsListener lifecycle (
store/pg/pg.go)defer l.Close()in Listen goroutinel.Ping()back into thetime.Afterselect case (only needed when idle)selectondonechannelrows.Err()check after row iterationTests (
store/pg/pg_test.go,store/pg/pg_suite_test.go)WithMaxConsumerConns, andClose()defer subject.Close()to all test casesconnStrinitialization in test suite setupTest plan
go test ./store/pg/...passes🤖 Generated with Claude Code