Add periodic ping support to SseFormatter for keeping SSE connections alive
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Is your feature request related to a problem? Please describe the problem.
Currently, the `SseFormatter` in **ASP.NET 10** supports writing `IAsyncEnumerable>` to a `Stream` via the following API:
```csharp
class SseFormatter
{
Task WriteAsync(IAsyncEnumerable> items, Stream stream, CancellationToken cancellationToken);
}
```
However, there is no built-in mechanism to send periodic ping events to the client.
This can cause issues when the underlying HTTP connection or proxy times out due to inactivity — especially in long-lived streams where messages may not be sent frequently.
For example, when no data is being emitted for a while, clients may get disconnected because intermediaries (load balancers, proxies, or browsers) assume the connection is idle.
### Describe the solution you'd like
Add **ping (heartbeat) support** to `SseFormatter`, allowing the server to send periodic keep-alive messages to prevent connection timeouts.
### Example design proposal
```csharp
class SseFormatter
{
Task WriteAsync(
IAsyncEnumerable> items,
Stream stream,
CancellationToken cancellationToken,
TimeSpan? pingInterval = null,
string pingComment = ": ping\n\n" // default ping format
);
}
```
---
## Expected Behavior
When `pingInterval` is set (e.g., `TimeSpan.FromSeconds(15)`), the server should send a comment-based keep-alive message (`: ping\n\n`) periodically if no data is being emitted.
This would ensure:
* Connections remain open behind proxies/load balancers
* Clients (e.g., browsers) do not close idle `EventSource` connections
* Developers have configurable control over heartbeat frequency
### Additional context
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.