📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you implement Server-Sent Events in an ASP.NET Core .NET 10 Minimal API. Stream events from an IAsyncEnumerable, support reconnection with Last-Event-ID, handle heartbeats and client disconnects, and tell me when SSE is a better choice than WebSockets or SignalR.

Implementing Server-Sent Events in .NET 10 with TypedResults.ServerSentEvents and SseItem<T>: the text/event-stream format, event ids and Last-Event-ID resume, heartbeats, cancellation on disconnect, proxy buffering, and when SSE beats WebSockets or SignalR.

Mid-Level Coding Intermediate aspnet-core dotnet-10 iasyncenumerable minimal-apis real-time server-sent-events

🎯 Key points

  • SSE is a single HTTP response with Content-Type text/event-stream; events are 'data:' lines ending with a blank line
  • .NET 10: TypedResults.ServerSentEvents(IAsyncEnumerable<SseItem<T>>) sets headers, serialises T as JSON and flushes per item
  • SseItem<T> carries EventType and EventId (and ReconnectionInterval); the browser resends Last-Event-ID on reconnect
  • Read Last-Event-ID from the request header and replay missed events from a store or buffer
  • Pass the CancellationToken ([EnumeratorCancellation]) so the stream stops when the client disconnects (RequestAborted)
  • Heartbeats shorter than the shortest proxy idle timeout; disable proxy buffering and response compression for the route
  • Auth: EventSource can't set headers, so use a same-site cookie or a short-lived single-use stream token, and authorise every subscription
  • SSE fits one-way feeds (notifications, progress, AI token streams); WebSockets fit custom two-way protocols; SignalR fits interactive features with groups

⏱ 30-second answer

Server-Sent Events is one long-lived HTTP response with Content-Type: text/event-stream. The server writes id:, event: and data: lines, and the browser's EventSource parses them and reconnects automatically, sending the last id in a Last-Event-ID header. In .NET 10 it is built in: return TypedResults.ServerSentEvents(stream), where stream is an IAsyncEnumerable<SseItem<T>>. The framework sets the headers, serialises T to JSON and flushes each item. You pass the request's CancellationToken so the loop ends when the client goes away, read Last-Event-ID to replay missed events, and send heartbeats so proxies don't cut idle streams.

SSE beats WebSockets when data flows one way: it is plain HTTP, so auth, HTTP/2, proxies and logging all just work. It is the wrong tool when the client must send a lot back.

🗣 Full answer (senior)

How I would answer this in an interview

"SSE is the simplest real-time option that still feels instant. It is just an HTTP GET whose response never ends: Content-Type: text/event-stream, and each event is a few lines, id:, event:, data:, ended by a blank line. The browser's EventSource handles parsing and reconnection, and when it reconnects it sends Last-Event-ID, so the server can resume where the client left off.

Before .NET 10 you wrote the headers and the data: lines yourself and flushed after each one. Now there is TypedResults.ServerSentEvents, which takes an IAsyncEnumerable<SseItem<T>>. SseItem<T> comes from System.Net.ServerSentEvents and carries the data, an event type and an event id. I write an async iterator that yields items, mark its token parameter with [EnumeratorCancellation], and bind the endpoint's CancellationToken, which is HttpContext.RequestAborted. When the browser tab closes, the token fires and the loop ends instead of leaking. For fan-out I keep a broadcaster that gives each subscriber its own bounded Channel<T>, so one slow client can't block the producer. On reconnect I read the Last-Event-ID header and replay from a small ring buffer or the database.

Two production details matter. First, heartbeats: proxies and load balancers close idle connections, so every 15–20 seconds I send a comment or a ping event. Second, buffering: nginx, IIS and the response compression middleware will hold events back unless you turn buffering off for that route. The mistake I see is people using SignalR for a one-way progress bar. SSE is less infrastructure, works over HTTP/2 and passes through ordinary auth and logging."


SSE vs WebSockets vs SignalR

SSE WebSockets SignalR
Direction Server → client Both Both
Protocol Plain HTTP response HTTP Upgrade, then frames Negotiated transport plus hub protocol
Reconnect and resume Built in (retry, Last-Event-ID) You build it Reconnect built in, no resume
Data UTF-8 text (JSON) Text or binary JSON or MessagePack
Auth Cookies or query string (EventSource can't set headers) Query string or cookies access_token query string
HTTP/2 Multiplexed, no 6-connection limit Needs RFC 8441 support Depends on transport
Good for Notifications, progress, dashboards, AI token streams Custom protocols, games Chat, collaboration, groups

Production checklist

Concern What to do
Disconnects Bind CancellationToken, use [EnumeratorCancellation]
Resume Set EventId; read Last-Event-ID; replay from a buffer or store
Idle timeouts Heartbeat every 15–20 s, below the shortest proxy timeout
Buffering X-Accel-Buffering: no for nginx; exclude text/event-stream from compression
Slow clients Per-subscriber bounded Channel with DropOldest or disconnect
HTTP/1.1 limit About 6 connections per origin per browser; serve over HTTP/2
Scale-out Each instance needs the events: feed the broadcaster from Redis pub/sub or Service Bus

Production example

For a [report generation] feature, we replaced a 1-second progress poll with an SSE endpoint. Requests to the status endpoint dropped by about [95%], progress showed within [100 ms] of each step, and the only infrastructure change was proxy_buffering off on the ingress route.

🔍 What the interviewer is checking

Checks that the candidate can build a correct, production-ready SSE endpoint in .NET 10 and knows when SSE is the right tool.

Green flags

  • Uses TypedResults.ServerSentEvents with SseItem<T> (or knows how to write the format by hand)
  • Handles cancellation with [EnumeratorCancellation] and RequestAborted
  • Implements event ids and Last-Event-ID replay
  • Mentions heartbeats, proxy buffering and the HTTP/1.1 connection limit
  • Explains when WebSockets or SignalR are better

Red flags

  • Writes an infinite loop with no cancellation
  • Thinks SSE is bidirectional or needs a special server
  • Never mentions what happens on reconnect

📚 Learn in depth

1. The wire format

GET /jobs/7/progress HTTP/1.1
Accept: text/event-stream
Last-Event-ID: 41            <- only on reconnect

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

retry: 3000

id: 42
event: progress
data: {"percent":60}

id: 43
event: progress
data: {"percent":80}

: keep-alive comment (ignored by EventSource)

Rules: lines are UTF-8, fields are id, event, data and retry, multiple data: lines are joined with newlines, and a blank line dispatches the event. A line starting with : is a comment, which makes a perfect heartbeat.

2. What .NET 10 does for you

endpoint returns ServerSentEventsResult<T>
   │
   ├─ sets Content-Type: text/event-stream, Cache-Control: no-cache
   ├─ disables response buffering (IHttpResponseBodyFeature.DisableBuffering)
   ├─ await foreach item in your IAsyncEnumerable<SseItem<T>>
   │     └─ SseFormatter writes id/event/data (T serialised with System.Text.Json; strings written as-is)
   │     └─ flush after each item
   └─ ends when the enumerable completes or RequestAborted fires

SseItem<T> and SseFormatter live in System.Net.ServerSentEvents. .NET 9 added SseParser for consuming SSE from HttpClient, and .NET 10 added the formatter and the ASP.NET Core result.

3. Fan-out design

producer (BackgroundService, Service Bus consumer)
   │ Publish(evt)
   ▼
Broadcaster (singleton)
   ├─ ring buffer of last N events (for Last-Event-ID replay)
   ├─ subscriber 1: Channel<T> bounded(100, DropOldest) ──▶ SSE response 1
   ├─ subscriber 2: Channel<T> bounded(100, DropOldest) ──▶ SSE response 2
   └─ ...

The producer never awaits a slow client: TryWrite into each bounded channel either succeeds or drops the oldest item. Each SSE response reads its own channel. With several instances, every instance runs its own broadcaster fed from a shared source such as Redis pub/sub.

4. Cancellation path

When the browser closes the tab, Kestrel notices the connection reset and cancels HttpContext.RequestAborted. If your iterator takes [EnumeratorCancellation] CancellationToken ct and you pass it to Task.Delay and ReadAllAsync, the await throws OperationCanceledException, the iterator's finally runs (unsubscribe here), and the framework treats it as a normal end. Without the token, the loop keeps running until the next write fails, which can be minutes if events are rare.

5. Proxies and buffering

SSE breaks silently when something in the path buffers the response: nginx proxy_buffering on (the default), IIS dynamic compression, the ASP.NET Core response compression middleware, or some API gateways. Symptoms: nothing arrives for a while, then a burst. Fix it per route, and test through the real ingress, not just Kestrel.

Try it yourself

  1. Build the code example and run curl -N http://localhost:5000/jobs/7/progress to see raw events stream in.
  2. Stop the server mid-stream and restart it; in DevTools watch the browser reconnect and send Last-Event-ID.
  3. Put nginx with default settings in front, observe the buffering, then add proxy_buffering off.
  4. Open 8 tabs over HTTP/1.1 and see the 7th hang; switch Kestrel to HTTPS with HTTP/2 and see it work.
  5. Close the tab and set a breakpoint in the iterator's finally to confirm cancellation reaches it.
  6. Load-test 5,000 SSE connections with k6 and watch dotnet-counters for memory and current-connections.

💻 Code

A .NET 10 SSE endpoint with a broadcaster, resume with Last-Event-ID, heartbeats, per-user authorisation and clean cancellation.

// Program.cs (.NET 10, nullable enabled)
using System.Collections.Concurrent;
using System.Net.ServerSentEvents;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Threading.Channels;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddCookie(); // EventSource sends cookies; it can't send headers
builder.Services.AddAuthorization();
builder.Services.AddSingleton<ProgressBroadcaster>();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/jobs/{jobId:int}/progress", (
    int jobId,
    ClaimsPrincipal user,
    ProgressBroadcaster broadcaster,
    HttpRequest request,
    CancellationToken ct) => // bound to HttpContext.RequestAborted
{
    // Authorise the subscription, not just the endpoint (real code checks job ownership in the database).
    if (!broadcaster.CanWatch(user, jobId)) return Results.Forbid();

    long? lastId = long.TryParse(request.Headers["Last-Event-ID"], out var id) ? id : null;
    return TypedResults.ServerSentEvents(broadcaster.Subscribe(jobId, lastId, ct));
}).RequireAuthorization();

app.Run();

public sealed record Progress(int JobId, int Percent);

public sealed class ProgressBroadcaster
{
    private static readonly TimeSpan HeartbeatInterval = TimeSpan.FromSeconds(15);
    private readonly ConcurrentDictionary<Guid, (int JobId, Channel<SseItem<Progress>> Channel)> _subscribers = new();
    private readonly ConcurrentQueue<(long Id, SseItem<Progress> Item)> _recent = new(); // small replay buffer
    private long _nextId;

    public bool CanWatch(ClaimsPrincipal user, int jobId) => user.Identity?.IsAuthenticated == true;

    public void Publish(Progress p)
    {
        var id = Interlocked.Increment(ref _nextId);
        var item = new SseItem<Progress>(p, eventType: "progress") { EventId = id.ToString() };
        _recent.Enqueue((id, item));
        while (_recent.Count > 500) _recent.TryDequeue(out _);

        foreach (var (_, sub) in _subscribers)
            if (sub.JobId == p.JobId)
                sub.Channel.Writer.TryWrite(item); // never blocks the producer; DropOldest handles slow clients
    }

    public async IAsyncEnumerable<SseItem<Progress>> Subscribe(
        int jobId, long? lastEventId, [EnumeratorCancellation] CancellationToken ct)
    {
        var channel = Channel.CreateBounded<SseItem<Progress>>(
            new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
        var key = Guid.NewGuid();
        _subscribers[key] = (jobId, channel);
        try
        {
            // Replay anything the client missed while it was disconnected.
            if (lastEventId is { } last)
                foreach (var (id, missed) in _recent)
                    if (id > last && missed.Data.JobId == jobId)
                        yield return missed;

            while (true)
            {
                // One wait at a time (SingleReader): wait for data, or time out to send a heartbeat.
                using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
                waitCts.CancelAfter(HeartbeatInterval);
                bool hasData;
                try
                {
                    hasData = await channel.Reader.WaitToReadAsync(waitCts.Token);
                }
                catch (OperationCanceledException) when (!ct.IsCancellationRequested)
                {
                    hasData = false; // heartbeat timeout, not a client disconnect
                }

                if (!hasData)
                {
                    // Keeps proxies with idle timeouts from closing the stream.
                    yield return new SseItem<Progress>(new Progress(jobId, -1), eventType: "ping");
                    continue;
                }
                while (channel.Reader.TryRead(out var item))
                    yield return item;
            }
        }
        finally
        {
            _subscribers.TryRemove(key, out _); // runs when the client disconnects (ct cancelled)
        }
    }
}
// Browser: EventSource reconnects and sends Last-Event-ID automatically; cookies go with it.
const es = new EventSource("/jobs/7/progress", { withCredentials: true });
es.addEventListener("progress", e => updateBar(JSON.parse(e.data).percent));
# Ingress or nginx: never buffer event streams
location /jobs/ {
    proxy_pass http://api;
    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_read_timeout 3600s;
}

⚠ Common mistakes

  • Mistake: Not passing the CancellationToken into the iterator. Why it is wrong: The loop keeps running after the client leaves, holding memory and subscriptions until a write eventually fails. Instead: Bind the endpoint's token and mark the iterator parameter [EnumeratorCancellation].
  • Mistake: No event ids. Why it is wrong: After a reconnect the client silently misses everything sent while it was away. Instead: Set EventId, read Last-Event-ID and replay from a buffer or store.
  • Mistake: Leaving buffering or compression on. Why it is wrong: Events arrive in bursts or only when the stream ends. Instead: Disable proxy buffering for the route and exclude text/event-stream from response compression. Each platform differs: nginx needs proxy_buffering off or X-Accel-Buffering: no; IIS needs dynamic compression off for the route; Azure Front Door, API Management and Application Gateway each have their own buffering and timeout settings. Test through the real path in every environment.
  • Mistake: No heartbeat. Why it is wrong: Load balancers and proxies close idle connections (Azure Load Balancer defaults to 4 minutes, many proxies 60 s), and the client sees random drops. Instead: Send a comment or ping event every 15–20 s.
  • Mistake: Writing to all subscribers synchronously from the producer. Why it is wrong: One slow client blocks every other client and the producer. Instead: Give each subscriber a bounded channel and use TryWrite.
  • Mistake: Serving SSE over HTTP/1.1 to users with several tabs. Why it is wrong: Browsers allow about 6 connections per origin, so extra tabs hang. Instead: Serve over HTTP/2, or share one stream between tabs.
  • Mistake: Putting a long-lived bearer token in the query string. Why it is wrong: EventSource can't set headers, and query strings end up in proxy and server logs, which is a credential leak and a Privacy Act concern. Instead: Prefer a Secure, HttpOnly, SameSite auth cookie on the same site. Otherwise call an authenticated POST that returns a single-use stream ticket valid for about 30–60 seconds, redeem it when the stream opens, and scrub it from logs. Because the token is only checked when the stream opens, cap stream lifetime (for example close after the access token expires) so the client reconnects and re-authenticates.
  • Mistake: Authorising the endpoint but not the subscription. Why it is wrong: Any signed-in user can stream another user's job progress by changing the id. Instead: Check the caller owns the resource before subscribing.
  • Mistake: Using SSE for chatty two-way interaction. Why it is wrong: Every client message becomes a separate POST. Instead: Use SignalR or WebSockets.

🏛 Senior insight: trade-offs

SSE is underrated because it looks too simple. For the very common "tell the user when something finished" feature, it gives you real-time behaviour with nothing new to operate: same auth, same logging, same load balancer, HTTP/2 multiplexing and a browser API that reconnects on its own. The parts you must own are resume (event ids and a replay source), fan-out across instances, and proxy configuration.

Option When it fits Cost When not to
SSE with in-memory broadcaster One instance or per-instance producers Lowest Several instances that must all see every event, without a shared feed
SSE fed by Redis pub/sub or Service Bus Multiple instances A shared feed and replay store Very high fan-out to public viewers (use a CDN-friendly or managed service)
SignalR Two-way, groups, users Connections plus backplane One-way notifications only
Polling Freshness of 30 s or more is fine Requests Sub-second needs

Measure it with current-connections and memory per connection under a k6 load test, the reconnect rate in your logs, and end-to-end latency from publish to browser.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses an async iterator to produce the stream. Why: Checks understanding of IAsyncEnumerable, await foreach and cancellation.
    How to answer

    IAsyncEnumerable<T> is a sequence whose items arrive asynchronously. You produce one with an async iterator method that uses both await and yield return, and consume it with await foreach, which awaits MoveNextAsync() for each item and disposes the enumerator asynchronously. Cancellation is passed with .WithCancellation(ct) and received in the iterator through a parameter marked [EnumeratorCancellation]. It lets you process large or slow data item by item instead of buffering everything, for example EF Core AsAsyncEnumerable() or streaming JSON responses from ASP.NET Core. .NET 10 includes LINQ operators for it in the base library (System.Linq.AsyncEnumerable).

  2. When: Candidate mentions bounded channels per subscriber. Why: Checks producer/consumer design and backpressure with Channels.
    How to answer

    System.Threading.Channels provides fast, async-friendly queues for passing data between producers and consumers. Channel.CreateBounded<T>(capacity) gives backpressure: when full, WriteAsync waits (or drops items, depending on BoundedChannelFullMode). Channel.CreateUnbounded<T>() never blocks writers but can grow without limit. Writers call Complete() when done; readers loop with await foreach (var x in reader.ReadAllAsync(ct)) and finish when the channel is completed and empty. Options such as SingleReader and SingleWriter enable faster internal implementations. Channels are the standard building block for in-process background queues and pipelines.

  3. When: Candidate compares SSE with WebSockets or polling. Why: Checks the broader choice between real-time techniques.
    How to answer

    There are five ways to get server changes to a client. Short polling asks on a timer: simple and cache-friendly, but wasteful, and data is up to one interval stale. It suits reports and KPIs. Long polling holds each request open until something happens, giving near real-time over plain HTTP when nothing else gets through a proxy. Server-Sent Events (SSE) keep one HTTP response open and stream text/event-stream messages one way, server to client, with automatic reconnect. They suit notifications, progress and AI token streams. WebSockets upgrade the connection to a full-duplex channel for low-latency two-way traffic such as chat or collaborative editing. SignalR sits on top: it negotiates WebSockets, falls back to SSE or long polling, and adds reconnects, groups and hub methods.

    The trade-off: polling costs requests, while push costs one held connection per client. Those connections need capacity planning, proxy idle-timeout settings and a scale-out story.

🛠 Real-world problems: how you handle them

SSE progress events arrive in one burst at the end behind the ingress
Situation
A [document export] feature streamed progress to the browser with SSE from an ASP.NET Core API on [AKS] behind ingress-nginx. Exports took [30–90 seconds] and users relied on the progress bar.
Signals
It worked locally, but in test and production the progress bar sat at 0% and jumped to 100% at the end. Some users saw the stream drop after exactly 60 seconds with no error. Support tickets said "export looks frozen" and users started duplicate exports.
Investigation
Used `curl -N` directly against the pod (port-forward) and saw events arrive steadily, then repeated it through the ingress and saw them arrive all at once, which isolated the problem to the proxy. Checked the ingress config: `proxy_buffering` was on by default and `proxy-read-timeout` was 60 s. Also found the app's response compression middleware was compressing `text/event-stream`, which added buffering inside the app.
Resolution
Immediate: added ingress annotations `nginx.ingress.kubernetes.io/proxy-buffering: "off"` and `proxy-read-timeout: "3600"` for the route. Real fix: excluded `text/event-stream` from response compression, moved to .NET 10's `TypedResults.ServerSentEvents` (which disables buffering for the response), added a 15-second heartbeat, and added event ids with `Last-Event-ID` replay so a dropped stream resumed without losing progress.
Prevention
An end-to-end test in the deployment pipeline that opens the SSE stream through the real ingress and asserts the first event arrives within 2 seconds. A platform checklist item for streaming endpoints (buffering, timeouts, compression). A dashboard of SSE reconnects per minute in Application Insights.

How to tell it (STAR)

**S:** Our [document export] showed progress through Server-Sent Events. It was fine locally, but in production the bar sat at 0% and then jumped to 100%, and some streams dropped at exactly 60 seconds. **T:** I owned the fix, because users were starting duplicate exports and [load was doubling]. **A:** I compared `curl -N` straight to the pod with the same call through the ingress and saw the buffering only through nginx. I turned off proxy buffering and raised the read timeout for that route, excluded event streams from compression, moved to .NET 10's ServerSentEvents result, and added heartbeats and Last-Event-ID resume. **R:** The first progress event now arrives in under [a second], duplicate exports dropped by [about 80%], and we added a pipeline test so the next streaming endpoint doesn't hit the same problem.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me