Diagnoses the common breakages after putting a reverse proxy in front of ASP.NET Core: WebSocket upgrade and idle timeouts for SignalR, sticky sessions, body size limits at each layer, layered request timeouts that cause 502/504, and forwarded headers for client IPs.
First find which hop failed: a 413, 502 or 504 is usually generated by the proxy, so it never shows in app logs. Then fix each symptom at the right layer. WebSockets need HTTP/1.1 and the Upgrade / Connection headers forwarded (Nginx defaults to HTTP/1.0), idle timeouts longer than SignalR's 15-second keep-alive, and sticky sessions or Azure SignalR Service when there are several instances. Uploads hit the smallest body limit anywhere in the path: Nginx (1 MB default), Application Gateway WAF, IIS (30 MB), Kestrel (~28.6 MB). 502/504 come from a proxy timeout shorter than the endpoint (Nginx 60 s, Application Gateway 20 s); move long work to a background job. Rate limiting needs UseForwardedHeaders trusting only the proxy, then partitions keyed by user or API key. The trade-off: raising limits is quick; fixing the design (async jobs, direct-to-Blob uploads) is what lasts.
"I start by working out which hop produced each error, because behind a proxy there are two connections with separate limits. If the app's request log in Application Insights has no failed request but the client got a 413 or 504, the proxy generated it. Nginx error logs, Application Gateway access logs or Front Door logs tell me which rule fired.
Then I go symptom by symptom. SignalR falling back to long polling means the WebSocket upgrade isn't getting through: Nginx speaks HTTP/1.0 to the backend by default and drops the
UpgradeandConnectionheaders, so I setproxy_http_version 1.1and forward them. If connections drop after a minute, an idle timeout is shorter than the traffic gap, so I raiseproxy_read_timeoutand keep SignalR's keep-alive pings flowing. With several instances, negotiate and connect can land on different servers, so I enable cookie affinity or, better, use Azure SignalR Service. For the 413, I check every layer's body limit and fix the smallest one, usually Nginx's 1 MB default. For the 502 or 504 on the report, Application Gateway's default request timeout is 20 seconds and Nginx waits 60; for example at [company] we [raised the timeout first and then moved report generation to a queue with a 202 and a status URL], which [took the endpoint from 90 seconds to under 200 ms]. And for rate limiting, the app sees the proxy's IP for everyone, so I configure forwarded headers trusting only the proxy's subnet and partition limits by user or API key.The mistake I see is raising every timeout and limit to huge values. That just moves the failure: threads, sockets and SNAT ports get held open. The proxy's defaults are a hint that the design should change."
| Symptom | Likely layer | Cause | Fix |
|---|---|---|---|
| SignalR uses long polling | Proxy | Upgrade headers dropped, HTTP/1.0 | proxy_http_version 1.1, forward Upgrade and Connection |
| WebSocket drops after ~60 s | Proxy or LB | Idle timeout | Raise idle timeout, keep-alive pings |
| SignalR "No connection with that ID" | Proxy | No affinity across instances | Sticky sessions or Azure SignalR Service |
| 413 Payload Too Large | Proxy | Body limit (Nginx 1 MB) | Raise at every layer or upload direct to Blob |
| 502 / 504 on slow endpoint | Proxy | Request timeout shorter than endpoint | Background job + 202, or align timeouts |
| Everyone shares one rate-limit bucket | App | No forwarded headers | UseForwardedHeaders, partition by user |
| Layer | Body size | Request timeout |
|---|---|---|
| Nginx | 1 MB (client_max_body_size) |
60 s (proxy_read_timeout) |
| Application Gateway v2 | Configurable, WAF body limits apply | 20 s backend request timeout |
| Azure Front Door | Large; WAF inspection limits apply | 60 s origin response timeout |
| App Service | IIS 30 MB on Windows | 230 s front-end timeout |
| Container Apps ingress | Large | 240 s |
| Kestrel | 30,000,000 bytes (~28.6 MB) | No request timeout by default |
After moving a dashboard app behind Application Gateway, [30%] of SignalR clients fell back to long polling and nightly exports failed with 504. Enabling cookie-based affinity, raising the backend timeout for the hub path only, and moving exports to a queued job brought WebSocket usage back to [over 95%] and export failures to zero.
Checks that the candidate can localise failures to a hop in the request chain and fix the cause at the right layer, rather than raising every limit.
Green flags
Red flags
Browser ──(conn A)──▶ Proxy ──(conn B)──▶ Kestrel
client timeouts proxy limits: Kestrel limits:
body size, MaxRequestBodySize,
read timeout, MinRequestBodyDataRate,
idle timeout, KeepAliveTimeout
affinity
A status code produced by the proxy never reaches Kestrel, so it is missing from app telemetry. Always compare the proxy's log with the app's.
traceparent through the proxy (YARP, Application Gateway and Front Door pass it through) so proxy and app spans join up.Failed Requests and Backend Response Status, Front Door Origin Latency, Nginx $upstream_status vs $status and $upstream_response_time in the access log format.AzureDiagnostics | where Category == "ApplicationGatewayAccessLog" | summarize count() by httpStatus_d, serverStatus_s separates gateway-generated errors (no server status) from backend errors.A WebSocket starts as an HTTP/1.1 GET with Upgrade: websocket and Connection: Upgrade. These are hop-by-hop headers: a proxy strips them unless told to forward. Nginx needs:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
Application Gateway and Container Apps ingress support WebSockets natively. IIS needs the WebSocket Protocol feature installed. SignalR sends keep-alive pings every 15 seconds and the client times out after 30, so any idle timeout below that drops connections. Azure Load Balancer's default TCP idle timeout is 4 minutes.
SignalR first calls /hub/negotiate, then connects with the returned connection id. If the second request lands on another instance, it fails. Options: sticky sessions (cookie affinity at the proxy), WebSockets-only with SkipNegotiation = true, or Azure SignalR Service, which takes the persistent connections off your servers entirely.
The effective limit is the smallest anywhere in the path, and every layer's value is configurable: Nginx client_max_body_size (1 MB default), Application Gateway WAF request body and file upload limits, IIS maxAllowedContentLength (30,000,000 bytes), Kestrel MaxRequestBodySize (30,000,000 bytes) and per-endpoint [RequestSizeLimit]. Raising Kestrel's limit does nothing if an outer layer rejects first. For large files, the better design is a SAS URL so the browser uploads straight to Blob Storage and the API only records metadata.
Each outer layer must wait at least as long as the inner one, or the outer gives up while work continues inside: wasted work and a confusing 502/504. Example of a consistent chain: client 100 s > Front Door 60 s > Application Gateway 55 s > app's own HttpClient calls 30 s. If an endpoint genuinely needs longer than the outermost limit you control, no amount of tuning helps; change the design. A 202 Accepted with a Location status URL and a background worker keeps every request short.
The proxy adds X-Forwarded-For. UseForwardedHeaders replaces RemoteIpAddress only when the immediate peer is in KnownProxies or KnownIPNetworks (the latter replaces the obsolete KnownNetworks in .NET 10). ForwardLimit (default 1) controls how many hops are processed when there are two proxies, such as Front Door then Application Gateway. Then the rate limiter partitions correctly: RateLimitPartition.GetTokenBucketLimiter(key, ...) keyed by the authenticated user id or API key first, and the real client IP only for anonymous traffic.
RemoteIpAddress before and after configuring forwarded headers, then confirm two users get separate rate-limit buckets.The app side: forwarded headers, per-endpoint body limit, Azure SignalR Service, and a long report turned into a background job.
// Program.cs (.NET 10)
using System.Net;
using System.Threading.Channels;
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(o =>
{
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
o.KnownIPNetworks.Add(IPNetwork.Parse("10.0.2.0/24")); // proxy subnet only
});
// Azure SignalR Service removes the need for sticky sessions across instances.
builder.Services.AddSignalR().AddAzureSignalR();
builder.Services.AddSingleton(Channel.CreateBounded<ReportRequest>(100));
builder.Services.AddHostedService<ReportWorker>();
var app = builder.Build();
app.UseForwardedHeaders();
app.MapHub<DashboardHub>("/hubs/dashboard");
// Raise the limit only where needed, not globally.
app.MapPost("/files", async (IFormFile file, CancellationToken ct) =>
{
await using var s = file.OpenReadStream();
return Results.Ok(new { file.FileName, file.Length });
}).WithMetadata(new RequestSizeLimitAttribute(50 * 1024 * 1024)).DisableAntiforgery();
// Long work returns 202 immediately instead of fighting proxy timeouts.
app.MapPost("/reports", async (Channel<ReportRequest> queue, CancellationToken ct) =>
{
var id = Guid.NewGuid();
await queue.Writer.WriteAsync(new ReportRequest(id), ct);
return Results.Accepted($"/reports/{id}", new { id });
});
app.Run();
public sealed record ReportRequest(Guid Id);
public sealed class DashboardHub : Microsoft.AspNetCore.SignalR.Hub;
public sealed class ReportWorker(Channel<ReportRequest> queue, ILogger<ReportWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var req in queue.Reader.ReadAllAsync(stoppingToken))
{
log.LogInformation("Generating report {ReportId}", req.Id);
await Task.Delay(TimeSpan.FromSeconds(90), stoppingToken); // stand-in for real work
}
}
}
The proxy side for Nginx:
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
upstream app { ip_hash; server 10.0.3.4:8080; server 10.0.3.5:8080; } # affinity if not using Azure SignalR
server {
listen 443 ssl;
client_max_body_size 50m;
location /hubs/ {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 300s; # longer than SignalR keep-alive gaps
}
location / {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
proxy_http_version 1.1 and the Upgrade headers. Why it is wrong: WebSockets silently fail and SignalR falls back to long polling, multiplying requests. Instead: Forward Upgrade and Connection on hub paths.KnownProxies to make client IPs appear. Why it is wrong: Clients can spoof their IP and dodge rate limits. Instead: Trust only the proxy's address range and set ForwardLimit for multiple hops.ip_hash affinity behind another proxy. Why it is wrong: Every request shares the outer proxy's IP, so all traffic lands on one instance. Instead: Cookie-based affinity or Azure SignalR Service.Every one of these symptoms is the proxy telling you the design assumed a direct connection. The quick fix is to align limits; the durable fix is to change the shape of the work: uploads go straight to Blob Storage, long jobs become 202 plus polling or a SignalR notification, persistent connections move to Azure SignalR Service. I'd also check the whole chain, not just one proxy: Front Door, Application Gateway, ingress and Kestrel each have their own number.
Each fix has a knock-on effect. Sticky sessions make autoscaling uneven and drop sessions on scale-in. Longer timeouts hold connections and SNAT ports, which caps how far one instance can scale before outbound calls start failing. Moving to Azure SignalR Service or a queue adds a managed dependency to monitor. I pick the change that keeps requests short and instances stateless, then confirm it under load before calling it fixed.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Raise proxy timeout | Endpoint is legitimately 30–60 s and rare | Holds connections longer | Work can run for minutes or grows with data |
| 202 + background job | Reports, exports, imports | Queue and status endpoint | Truly interactive calls |
| Direct-to-Blob upload (SAS) | Files over a few MB | SAS issuing and validation | Small form posts |
| Azure SignalR Service | More than one instance, many connections | Per-unit monthly cost | Single instance, low connection count |
| Sticky sessions | Few instances, short-term | Uneven load, lost sessions on scale-in | Autoscaling at volume |
Measure with proxy logs ($upstream_status vs $status in Nginx, serverStatus in Application Gateway), Application Insights failed requests and the SignalR transport mix reported by clients.
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.
Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.
A reverse proxy sits between clients and Kestrel. Clients connect to the proxy; it forwards each request to one of your app instances over an internal connection. It typically does TLS termination (owns the certificate), routing by host or path, load balancing across instances, buffering of slow uploads and downloads, and enforces limits like body size, timeouts and rate limits.
Kestrel has been supported at the edge since ASP.NET Core 2.0, and in .NET 10 it serves HTTP/1.1, HTTP/2 and HTTP/3 (QUIC) with TLS 1.3, so a proxy is not mandatory. You add one when you need several apps on one IP and port 443, central certificates, a WAF, or zero-downtime instance swaps. In Azure you rarely run one yourself: App Service, Front Door, Application Gateway and Kubernetes ingress are reverse proxies. The trade-off is one more hop and one more set of timeouts, headers and error responses you must configure to agree with Kestrel.
SignalR keeps each client's persistent connection on one server. With several instances you need sticky sessions (negotiate and connect must hit the same server, unless clients use WebSockets only with SkipNegotiation) and a backplane so a message sent from one server reaches clients connected to the others. A Redis backplane (AddStackExchangeRedis) relays messages through Redis pub/sub; it is cheap, but each server still holds its own clients' connections, you still need affinity, and Redis becomes a dependency to run. Azure SignalR Service (AddAzureSignalR) takes client connections off your servers: clients connect to the service, your app keeps a few server connections to it, and no affinity is needed. Choose the service for many connections or autoscaling; Redis when you must self-host or have few connections.
How to tell it (STAR)
**S:** At [company] we put our dispatch dashboard behind Application Gateway for a security uplift, and the next morning CPU was up [40%] and exports were failing. **T:** I [owned the platform migration], so I needed to find what the gateway changed. **A:** Gateway logs showed 504s that never reached the app, and client telemetry showed SignalR on long polling because negotiate and connect hit different instances. I turned on cookie affinity as a stop-gap, then moved the hubs to Azure SignalR Service, turned exports into a queued job with a completion notification, and fixed forwarded headers so rate limits applied per user. **R:** WebSocket usage went back above [95%], CPU dropped below the pre-migration level, and export failures went to zero.
Last updated 23 Nov 2026.