.NET 𝗦𝗲𝗿𝘃𝗲𝗿 𝗦𝗶𝗱𝗲 𝗘𝘃𝗲𝗻𝘁𝘀 𝘄𝗶𝘁𝗵 𝗠𝗼𝗻𝗴𝗼𝗗𝗕 𝗖𝗵𝗮𝗻𝗴𝗲 𝗦𝘁𝗿𝗲𝗮𝗺𝘀
You want real-time updates in ASP.NET Core. You might think of WebSockets first.
There is a simpler way for dashboards and feeds. You can use MongoDB Change Streams and Server-Sent Events (SSE).
This setup provides one-way streaming from your server to your client with very little code.
How it works:
- MongoDB Change Streams detect database changes instantly.
- SSE pushes those changes to the browser over a single HTTP connection.
- You avoid constant polling, which saves server resources.
SSE is a native browser API. It works through a long-lived HTTP response and supports automatic reconnects. It is perfect for:
- Live timelines
- Notifications
- Activity feeds
- Admin dashboards
In ASP.NET Core Minimal APIs, you can implement this using TypedResults.ServerSentEvents.
The code flow follows these steps:
- Your app opens a change stream cursor in MongoDB.
- MongoDB emits events when data changes.
- Your app maps these changes to the client.
One major advantage is the ability to resume streams. MongoDB provides a resume token for every change. You can pass this token through the Last-Event-ID header. When a browser reconnects, it sends the last ID it saw. Your app reads this ID and tells MongoDB to start exactly where it left off.
When should you use SSE versus SignalR?
Use SSE if:
- You only need server-to-client updates.
- You want a lightweight, text-based setup.
- You want to use native browser APIs.
Use SignalR if:
- You need two-way (bi-directional) communication.
- You need complex features like groups or hubs.
- You need automatic transport negotiation (WebSockets, Long Polling).
Start with SSE for simple live feeds. Move to SignalR only when your app requires richer interaction.
Note: MongoDB Change Streams require a replica set or a sharded cluster. They do not work on a standalone server.
Source: https://dev.to/mongodb/net-server-side-events-with-mongodb-change-streams-5dfb
Optional learning community: https://t.me/GyaanSetuAi