Search code examples
azureasp.net-coreserver-side

Server-Side Event Response Buffering Issues on Azure (ASP.net Core Web App)


To experiment with server-side events and asp.net core, I wrote a simple web application to make a rudimentary chat window. Posts to the server are done with a simple AJAX call using fetch, and data is received by clients using server-side events. Everything works perfectly on my local machine, but when I publish things to Azure, I find that responses arrive sporadically on the clients, often waiting for a second chat post before appearing.

After scratching my head over this for a while, I finally hypothesized that there was some additional response buffering being done on Azure that does not occur on my local machine. An experiment where I wrote a ton of dummy data after each post indeed fixed the problem, giving some support to my theory.

A bit of scouring of the web led me to several articles which confirmed my suspicions. For example: https://learn.microsoft.com/en-us/azure/api-management/how-to-server-sent-events. In particular it mentions: "Turn off response buffering on the forward-request policy so that events are immediately relayed to the clients."

I'm pretty ignorant about Azure and how anything beyond the very basics work. I'm trying to figure out if the above article (and others like it) are relevant to me. I've written a WebApp and published it, but these articles refer to an "API Management instance", which weren't created when I published my app.

So, at long last we reach the questions:

  1. Do I need to create a API Management instance event though my application doesn't really have an API?

  2. If I do turn off this buffering, can I turn it off just for the SSE stream and not the application as a whole?

OR

  1. Am I barking up the wrong tree and there's a better way to approach this problem?

Solution

  • I did figure this out myself eventually. And the answer was #3: I was barking up the wrong tree.

    The simple answer was to disable buffering in the server-side event middleware. That is, near the beginning my SSE middleware code I added this code:

    var responseBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
    if (responseBodyFeature != null) responseBodyFeature.DisableBuffering();
    

    While I can't explain things worked without these lines on my local machine but failed on the Azure App service... with this additional code, everything works correctly in both locations.