Skip to content

fix: prevent goroutine leaks in SSE implementation #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Napat
Copy link

@Napat Napat commented Apr 15, 2025

The SSE implementation had potential goroutine leaks when clients disconnect
unexpectedly. This commit addresses these issues by:

  1. Using context.WithCancel to properly control goroutine lifecycle
  2. Adding a WaitGroup to ensure all goroutines complete before returning
  3. Implementing a cleanup function that closes all resources properly
  4. Adding error checking when writing to client connections
  5. Adding timeout when sending to eventQueue channels

This prevents resource exhaustion in long-running servers with many
client connections.

Summary by CodeRabbit

  • Bug Fixes

    • Improved stability of live updates by ensuring proper cleanup of background processes when connections close.
    • Enhanced error handling for client disconnections during live event streams.
    • Added protection against potential delays or hangs when sending messages if the system is busy.
  • Refactor

    • Improved internal handling of live update sessions for better reliability and resource management.

Copy link
Contributor

coderabbitai bot commented Apr 15, 2025

Walkthrough

This change refactors the server's SSE (Server-Sent Events) connection handler to use explicit context cancellation and goroutine synchronization. It introduces a cancellable context for each SSE session, ensuring that all spawned goroutines are properly signaled to exit when the session ends. A sync.WaitGroup is used to track and wait for goroutine completion. The handler now checks for write errors to the client and returns early if the client disconnects. In message handling, event queuing is protected by a context with a timeout to prevent goroutine leaks. Formatting changes to struct declarations are also included.

Changes

Files/Paths Change Summary
server/sse.go Refactored SSE handler to use explicit context cancellation and sync.WaitGroup for goroutine lifecycle management; added error handling for client disconnects; wrapped event queuing in a timeout context; included minor struct formatting changes.

Possibly related PRs

  • Expose SSE server as HttpHandler #29: Adds a ServeHTTP method that routes HTTP requests to the existing SSE handlers, relating to this PR's changes in internal SSE connection and goroutine management.

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08ed317 and 78c4c7b.

📒 Files selected for processing (1)
  • server/sse.go (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/sse.go

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
server/sse.go (2)

236-238: Redundant cancel() call could be clarified.
You call cancel() here and also within the cleanup() function (line 321). Although canceling a context more than once is safe, you might consider removing the second call for clarity.

 func (s *SSEServer) handleSSE(w http.ResponseWriter, r *http.Request) {
     ...
-    ctx, cancel := context.WithCancel(r.Context())
-    defer cancel()
+    ctx, outerCancel := context.WithCancel(r.Context())
+    // Defer outerCancel only once if desired, or rely purely on cleanup().
     ...
 }

288-312: Keep-alive goroutine likewise uses WaitGroup and handles cancellation gracefully.
One suggestion: sending pings into session.eventQueue can block if the channel reaches capacity, potentially causing a deadlock. Consider using a timeout or selective send, similar to the message handler, to avoid blocking the keep-alive loop if the queue is full.

 for {
     select {
     case <-ticker.C:
-        session.eventQueue <- fmt.Sprintf(":ping - %s\n\n", time.Now().Format(time.RFC3339))
+        ctxPing, cancelPing := context.WithTimeout(ctx, 2*time.Second)
+        select {
+        case session.eventQueue <- fmt.Sprintf(":ping - %s\n\n", time.Now().Format(time.RFC3339)):
+            // Ping sent
+        case <-ctxPing.Done():
+            // Avoid blocking indefinitely
+        case <-session.done:
+            cancelPing()
+            return
+        }
+        cancelPing()
     case <-session.done:
         return
     case <-ctx.Done():
         return
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8cdb6c6 and 738e27d.

📒 Files selected for processing (1)
  • server/sse.go (6 hunks)
🔇 Additional comments (8)
server/sse.go (8)

56-64: New fields in SSEServer struct look good for configuration and concurrency.
All added fields facilitate flexible configuration of the SSE server. Using sync.Map for storing sessions is valid for concurrent read/writes. No immediate concerns here.


161-167: Initialization of default settings is appropriate.
Defining sensible defaults for sseEndpoint, messageEndpoint, and keepAliveInterval is a good practice. This helps ensure that the server functions with minimal user configuration.


252-255: Session registration error handling is correct.
Early return on registration failure prevents partially initialized sessions from persisting. No immediate concurrency concerns here.


258-259: Introduction of a WaitGroup for concurrency synchronization is beneficial.
This allows proper coordination of goroutines to avoid leaks. Great choice to avoid leftover goroutines when the connection ends.


261-285: Notification handler goroutine cancellation logic is well-structured.
The select statement cleanly handles session.done and ctx.Done(). This ensures each branch properly terminates the goroutine without blocking.


318-325: Cleanup function efficiently terminates all goroutines.
Calling close(session.done), cancel(), then wg.Wait() ensures no goroutine remains. Just watch out for the duplicate cancel() call at line 237.


331-337: Immediate return on write failure prevents stuck writes.
Exiting on err != nil is a good approach to handle client disconnections promptly. This prevents wasted effort sending data to a dead connection.


394-405: Timed context for event queue insertion prevents deadlocks.
Applying a 5-second timeout here is a solid strategy to avoid blocking the goroutine if the queue is full.

Napat added 2 commits April 20, 2025 10:02
   The SSE implementation had potential goroutine leaks when clients disconnect
   unexpectedly. This commit addresses these issues by:

   1. Using context.WithCancel to properly control goroutine lifecycle
   2. Adding a WaitGroup to ensure all goroutines complete before returning
   3. Implementing a cleanup function that closes all resources properly
   4. Adding error checking when writing to client connections
   5. Adding timeout when sending to eventQueue channels

   This prevents resource exhaustion in long-running servers with many
   client connections.
- Move cancel() to cleanup function as final step
- Add clear comments explaining cleanup order
- Move cleanup defer immediately after context creation
- Ensure context cancellation happens on all return paths
- Remove redundant context cancellation
@Napat Napat force-pushed the fix/sse-goroutine-leaks branch from 08ed317 to 78c4c7b Compare April 20, 2025 03:07
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.

1 participant