Repository navigation
perf(bot): keep database connections open and trace the listeners - #419
Conversation
The pool closed a connection after 30 seconds unused, shorter than the gap between most commands and between the runs of the tasks polling every minute, so they kept opening new ones (32ms at the median, 336ms at p95 on Sentry). Also traces every listener of the client with an OpenTelemetry span, so the events of Discord and the bot's own events can be measured. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016cicF5gGPhXEZDzNK5gmLi
Architecture Data flow Review 1 finding · reviewed
|
There was a problem hiding this comment.
ℹ️ No critical issues — two small follow-ups, nothing blocking.
Approach: sound. The pool change targets the measured cost of reopening connections, and wrapping the listener store's onLoad is the narrowest place to trace every client listener, including the ones the @wolfstar/plugin-gateway decorators wrap.
Reviewed changes
I read the full diff and checked the wrapping against @wolfstar/http-framework 6.6.0, @wolfstar/plugin-gateway and the @prisma/orm-postgres runtime.
- Pool idle timeout:
projects/database/src/index.tssetspoolOptions.idleTimeoutMillisto 10 minutes. The runtime reads it (options.poolOptions?.idleTimeoutMillis ?? 3e4). Shutdown exits explicitly (closeLoggerOnShutdowncallsprocess.exit), so the longer idle timers cannot delay it. - Listener spans:
listenerTracing.tsreplacespiece._listenerfor pieces oncontainer.clientbefore the store registers it. The framework'sonUnloadreads the same field, sooffstill removes the wrapped function, and theWeakSetstops a double wrap. - Wiring and tests:
createClient()callstraceClientListeners()before the pieces load. The new test covers sync, async, throwing and rejecting listeners, and that only listeners of the client are wrapped.
ℹ️ AGENTS.md Tracing paragraph is now out of date
The paragraph says the Redis commands made for a dispatch are not traced, and that the module only opens spans for commands, components and modals. Both stop being true here: a listener now runs in its own span, and ioredis, pg and undici spans nest under it. This repo keeps AGENTS.md current with every behavior change, so the next agent will read the old claim.
Technical details
# Update the Tracing paragraph of AGENTS.md
## Affected sites
- `AGENTS.md`, **Tracing** bullet: "The commands of Redis made for a dispatch are not traced (`ioredis` only traces a command under a span, and a dispatch has none), and its queries are traces of their own."
## Required outcome
- Describe `traceClientListeners()` (`lib/utilities/listenerTracing.ts`, called in `createClient()`): the `listener <event> <name>` span, its `wolfstar.listener.*` attributes, and that the Redis and database spans of a listener now sit under it.
- Mention `PoolIdleTimeout` (10 minutes) next to the `pg` instrumentation note, or in **Database**, since it explains the connection spans.ℹ️ Each listener run is its own trace, so ratio sampling cuts a message into pieces
A dispatch has no parent span, so every listener of one messageCreate opens a separate root span with its own trace ID. This differs from the PR's note that parentbased_traceidratio "samples whole traces". It samples each listener run independently, so a sampled message shows some of its listeners and not others. The raw listeners (rawDebug) also add a span for every dispatch the gateway receives. If volume turns out to matter, the options are to skip high-frequency, low-value events such as raw, or to open one parent span per dispatch.
Technical details
# Sampling and volume of listener spans
## Affected sites
- `projects/bot/src/lib/utilities/listenerTracing.ts:91` — `tracer.startActiveSpan` has no parent for a dispatch, so each listener is a root span.
- `projects/bot/src/listeners/debug/rawDebug.ts` — runs on every dispatch.
## Required outcome
- Either correct the sampling note in the PR description, or decide whether `raw` (and similar per-dispatch debug listeners) should be left untraced.
## Open questions for the human
- Is one trace per listener acceptable for the Sentry quota, or should dispatches get a shared parent span?claude-sonnet-5-5 | 𝕏
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #419 +/- ##
==========================================
+ Coverage 62.53% 62.66% +0.12%
==========================================
Files 269 270 +1
Lines 9447 9493 +46
Branches 2246 2253 +7
==========================================
+ Hits 5908 5949 +41
- Misses 3161 3162 +1
- Partials 378 382 +4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
A span for each listener of raw and dispatch added a trace to every dispatch the gateway receives. AGENTS.md now describes the listener spans and the pool idle timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016cicF5gGPhXEZDzNK5gmLi
There was a problem hiding this comment.
✅ No new issues found.
Approach: unchanged and still sound; the new commit settles both follow-ups of the previous review.
Reviewed changes
I read the incremental delta since the prior pullfrog review and the pieces of the full diff it touches.
rawanddispatchleft untraced:listenerTracing.tsskips pieces whose event is inUntracedEvents, sorawDebugand the other per-dispatch listeners no longer add a trace to every dispatch. The new test checks that such a piece keeps its original_listenerthroughonLoadandonUnload.AGENTS.mdTracing updated: the stale claim that the Redis commands of a dispatch are untraced is replaced by thelistener <event> <name>span and itswolfstar.listener.*attributes, the per-listener trace and its effect on ratio sampling, theraw/dispatchexclusion, andPoolIdleTimeout.
claude-sonnet-5-5 | 𝕏
Runs the traced listeners under the OpenTelemetry SDK with the AsyncLocalStorage context manager, so a lost parent span fails the tests. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016cicF5gGPhXEZDzNK5gmLi
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
I read the incremental delta since the prior pullfrog review (cae4d80).
- Context propagation test:
listenerTracing.context.test.tsrunscreateTracedListenerunder a realTracerProviderwith anAsyncLocalStorageContextManager. It checks that a span started after anawaitis a child of the listener span, and that a nested listener's span is parented to the outer one. This closes the gap in the mocked-tracer test, which could not catch a lost parent span. - Dev dependencies:
@opentelemetry/sdk-traceand@opentelemetry/context-async-hooks(^3.0.0) are added to the bot'sdevDependencies. The test's imports (TracerProvider,InMemorySpanExporter,SimpleSpanProcessor) are exported by@opentelemetry/sdk-trace3.0.0.
claude-sonnet-5-5 | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
I read the incremental delta since my previous review (4d4849d).
- Span ends when reading
thenthrows:createTracedListenernow evaluatesisPromiseLike(result)inside thetry, so a result whosethengetter throws ends the span as an error and rethrows, instead of leaving it open. Thependingflag is assigned on every path that reaches the code after thetry, because thecatchalways throws. - Test for the getter case:
listenerTracing.test.tsadds a case with a throwingthengetter and checks the span hasERRORstatus, records the exception and is ended.
claude-sonnet-5-5 | 𝕏

Requested by RedStar · project thread
What
Database pool (
projects/database/src/index.ts):poolOptions.idleTimeoutMillisgoes from the runtime's default of 30 s to 10 minutes.In Sentry (project
wolfstar, last 14 days), 7.7% of the 48k connection checkouts opened a new connection.pg.connecttook 32 ms at p50 and 336 ms at p95, while a query on an open connection takes about 2 ms. Most commands came more than 30 s apart, so each one paid for a new connection. A settings cache miss runs 14 parallel SELECTs, and on a cold pool it opened about 9 connections at once: 35 ms of the 308 ms in one/commandstrace. The tasks that poll every minute also reopened a connection on each run.Listener spans (
src/lib/utilities/listenerTracing.ts): every listener oncontainer.clientnow runs in an OpenTelemetry span namedlistener <event> <piece>.This covers Discord events (
messageCreate,guildMemberAdd…) and the bot's own events (userMessage…). Until now these listeners had no span, so theirpg,ioredisandundicispans were orphan roots and the listeners' own time was not measured.How it works:
traceClientListeners()wraps the listener store'sonLoadbefore the pieces load, and wraps each piece's_listeneronce.rawanddispatchare left out: they would add a trace to every dispatch.AGENTS.md(Tracing) now describes both changes.Notes
OTEL_TRACES_SAMPLER=parentbased_traceidratiowithOTEL_TRACES_SAMPLER_ARGsamples each listener run on its own, so a sampled message can show some of its listeners and not others. Giving each dispatch a shared parent span would be a follow-up.BROKER_ENABLED, the gateway process also opens short empty spans for dispatch listeners that only run on the workers.type Listener as ListenerPiecebecause the build's auto-imports otherwise add a value import ofListener.@opentelemetry/sdk-traceand@opentelemetry/context-async-hooks(both already in the lockfile through the plugin) let a test check under the real SDK that the listener span stays the parent acrossawaits.Checks
golar typecheck,oxlint,oxfmtandstars buildpass.vitest run: 2103 tests passed.🤖 Generated with Claude Code
https://claude.ai/code/session_016cicF5gGPhXEZDzNK5gmLi


Confidence Score: 5/5
The PR appears safe to merge.Reviews (3) · Last reviewed commit: "fix(bot): end the listener span when rea..." · Reviewed by Greptile