Skip to content

[Bugfix #580] Fix SSE connection leak — server never cleans up disconnected clients - #581

Merged
waleedkadous merged 2 commits into
mainfrom
builder/bugfix-580-bug-sse-connections-leak-serve
Feb 28, 2026
Merged

waleedkadous merged 2 commits into
mainfrom
builder/bugfix-580-bug-sse-connections-leak-serve

Conversation

@waleedkadous

Copy link
Copy Markdown
Contributor

Summary

Fixes #580

Root Cause

SSE connections leaked because:

  1. Only req.on('close') was listened to — res.on('close') and res.on('error') were not, so some disconnect signals were missed
  2. No heartbeat — half-open TCP connections (browser tab close, network change, OS suspend) were never detected because nothing was written to test liveness
  3. broadcastNotification swallowed write errors — the catch block caught exceptions but never removed the dead client from the sseClients array

Fix

Three changes, all in the SSE server infrastructure:

1. Heartbeat interval (tower-server.ts)

  • Added a 30-second heartbeat that writes :heartbeat\n\n (SSE comment) to every client
  • Failed writes or destroyed responses trigger immediate client removal
  • Logs active client count for monitoring
  • Cleaned up during graceful shutdown

2. Dead client cleanup in broadcastNotification (tower-server.ts)

  • Checks res.destroyed and res.writableEnded before writing
  • Collects dead clients during the broadcast loop and removes them after
  • Replaces the old silent catch-and-ignore pattern

3. Multi-event cleanup in handleSSEEvents (tower-routes.ts)

  • Now listens on req.on('close'), res.on('close'), AND res.on('error')
  • Deduplication guard (cleaned flag) ensures cleanup runs exactly once even if multiple events fire

Test Plan

  • Added 3 regression tests:
    • removes SSE client on res close — validates res.on('close') cleanup
    • removes SSE client on res error — validates res.on('error') cleanup
    • only cleans up once even if multiple close events fire — validates deduplication
  • All 62 unit tests pass (59 existing + 3 new)
  • TypeScript compilation clean
  • Build succeeds

@waleedkadous

Copy link
Copy Markdown
Contributor Author

Architect Review

Low-risk server-side bugfix. Three-layer approach is solid: event listeners with dedup guard, heartbeat sweep, and dead-client detection during broadcast. Codex's Playwright E2E ask is overkill for this — unit tests cover the logic.

Approved — please merge.


Architect review

@waleedkadous
waleedkadous merged commit 46c36bc into main Feb 28, 2026
6 checks passed
@waleedkadous
waleedkadous deleted the builder/bugfix-580-bug-sse-connections-leak-serve branch February 28, 2026 14:37
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.

[Bug] SSE connections leak — server never cleans up disconnected clients

1 participant