Skip to content

Nomey: Dev Test Solution#116

Open
ahmed563 wants to merge 1 commit intonomeyy:mainfrom
ahmed563:dev-test-solution
Open

Nomey: Dev Test Solution#116
ahmed563 wants to merge 1 commit intonomeyy:mainfrom
ahmed563:dev-test-solution

Conversation

@ahmed563
Copy link

@ahmed563 ahmed563 commented Aug 12, 2025

This PR implements a reusable Server-Sent Events (SSE) layer for real-time, server-to-client communication across the application. The solution provides a clean abstraction for managing client connections, broadcasting events, and sending targeted messages.

Key Changes:

  • SSEManager Service: Added a centralized SSEManager class to manage SSE clients. Supports adding/removing clients by userId, sending targeted events to specific users, and broadcasting events to all connected clients. Handles client connection cleanup on write failure.
  • API Endpoints:
    • GET /api/sse: Establishes an SSE connection for the given userId, sends an initial connected event, includes a heartbeat (ping every 15s), and cleans up on disconnect.
    • POST /api/sse: Allows sending a specific event and payload to a given userId.
  • Connection Stability Improvements: Added retry: 10000 for reconnection attempts, implemented ping events to keep connections alive, and gracefully removed disconnected clients to prevent memory leaks.

Benefits

  • Decouples SSE logic from API routes, allowing easy reuse across the app.
  • Enables both targeted user messaging and global broadcasts.
  • Improves scalability by managing connections efficiently.
  • Maintains connection reliability with heartbeats and retry intervals.

Testing

  • Verified that clients receive initial connected event, regular ping events, and targeted events via POST /api/sse.
  • Tested disconnection and reconnection scenarios.
  • Confirmed no memory leaks after client disconnections.

Loom of changes in action:
https://www.loom.com/share/3e51861dffe64da3958ac4759e347b38

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