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

📚 Interview question

You move an ASP.NET Core 10 app behind Nginx or Application Gateway. Now SignalR connections drop and fall back to long polling, file uploads over 1 MB fail with 413, a slow report endpoint returns 502 or 504, and rate limiting treats every user as one client. How do you diagnose and fix each?

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.

Mid-Level Debugging Intermediate debugging devops reverse-proxy signalr timeouts websockets

🎯 Key points

  • Work out which hop produced the error: proxy logs vs app logs vs Application Insights end-to-end traces
  • WebSockets need HTTP/1.1 plus Upgrade and Connection headers through every hop (Nginx proxy_http_version 1.1)
  • SignalR on several instances needs sticky sessions or Azure SignalR Service
  • Effective body limit = smallest across all layers (Nginx 1 MB default, App Gateway WAF, IIS 30 MB, Kestrel ~28.6 MB), each configurable
  • Timeouts layered outer > inner: Nginx proxy_read_timeout 60 s, Application Gateway 20 s, App Service 230 s, Container Apps 240 s
  • Long work moves to a background job with 202 Accepted and polling instead of raising timeouts forever
  • UseForwardedHeaders with KnownProxies / KnownIPNetworks, then AddRateLimiter partitioned by user id or API key

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 Upgrade and Connection headers, so I set proxy_http_version 1.1 and forward them. If connections drop after a minute, an idle timeout is shorter than the traffic gap, so I raise proxy_read_timeout and 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 to cause

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

Default limits to know

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts by asking which hop generated the error and compares proxy and app logs
  • Knows the WebSocket upgrade headers and the SignalR affinity requirement
  • Knows that the smallest body limit and the shortest timeout in the chain win
  • Proposes design fixes: 202 + background job, SAS uploads, Azure SignalR Service

Red flags

  • "Increase all timeouts to 10 minutes"
  • Debugs only in app code for a proxy-generated status
  • Trusts all forwarded headers to fix client IPs

📚 Learn in depth

1. Two connections, two sets of rules

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.

2. Diagnosing with telemetry, not just logs

  • Application Insights end-to-end transaction view: if the client-side (browser SDK) request failed but there is no server request with that operation id, the proxy answered.
  • Distributed tracing: propagate traceparent through the proxy (YARP, Application Gateway and Front Door pass it through) so proxy and app spans join up.
  • Proxy metrics: Application Gateway Failed Requests and Backend Response Status, Front Door Origin Latency, Nginx $upstream_status vs $status and $upstream_response_time in the access log format.
  • KQL: AzureDiagnostics | where Category == "ApplicationGatewayAccessLog" | summarize count() by httpStatus_d, serverStatus_s separates gateway-generated errors (no server status) from backend errors.

3. WebSockets through a proxy

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.

4. SignalR negotiation and affinity

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.

5. Body limits stack

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.

6. Timeouts stack the other way

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.

7. Client IP, forwarded headers and rate limiting

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.

Try it yourself

  1. Put Nginx with defaults in front of a SignalR sample and watch the browser fall back to long polling in dev tools; then fix the headers.
  2. Run two app instances behind Nginx without affinity and reproduce the negotiate failure.
  3. Upload 2 MB, 40 MB and 100 MB files and record which layer rejects each.
  4. Add an endpoint that sleeps 70 seconds and find which layer returns 504, using the end-to-end transaction view.
  5. Log RemoteIpAddress before and after configuring forwarded headers, then confirm two users get separate rate-limit buckets.

💻 Code

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;
    }
}

⚠ Common mistakes

  • Mistake: Searching app logs for a 504 the proxy generated. Why it is wrong: The request may never have finished in the app, or the app logged a 200 after the proxy gave up. Instead: Read the proxy's access and error logs and correlate by time and trace id.
  • Mistake: Raising Kestrel's body limit to fix a 413. Why it is wrong: The smallest limit in the chain wins, usually Nginx's 1 MB. Instead: Fix the layer that rejected it, or upload directly to Blob Storage with a SAS URL.
  • Mistake: Forgetting 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.
  • Mistake: Scaling SignalR to several instances without affinity or a backplane. Why it is wrong: Negotiate and connect hit different servers; messages miss clients on other instances. Instead: Sticky sessions plus a backplane, or Azure SignalR Service.
  • Mistake: Setting every timeout to 10 minutes. Why it is wrong: Connections, threads and SNAT ports are held, and the next layer out still times out. Instead: Keep requests short and move long work to background jobs.
  • Mistake: Clearing 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.
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions X-Forwarded-For, wrong client IPs or HTTPS redirect loops Why: Checks safe forwarded headers configuration and redirect loop diagnosis in depth
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    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.

  2. When: Candidate is unsure why a proxy is there at all Why: Checks the basics of what a reverse proxy does in front of Kestrel
    How to answer

    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.

  3. When: Candidate mentions sticky sessions for SignalR Why: Checks understanding of SignalR scale-out: affinity, backplanes and the managed service
    How to answer

    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.

🛠 Real-world problems: how you handle them

SignalR fell back to long polling behind Application Gateway
Situation
[Logistics] dispatch dashboard on [three] App Service instances in Australia East, moved behind Application Gateway WAF v2 for a security uplift; about [2,000] concurrent dispatchers.
Signals
CPU up [40%] after the move; Application Insights showed a flood of short `/hubs/dispatch` requests; client telemetry reported `LongPolling` transport; nightly export endpoint returned 504; rate limiter blocked whole depots at once.
Investigation
Application Gateway access logs showed 504s with no matching app requests (gateway timeout of 20 s), and WebSocket upgrades succeeding but connections reset on scale-out. Browser dev tools confirmed negotiate and connect landing on different instances. App logs showed every request from the gateway's private IP.
Resolution
Short term: enabled cookie-based affinity and raised the backend timeout only for the export path. Real fix: moved hubs to Azure SignalR Service, changed exports to a queued job with 202 and a SignalR notification on completion, and configured forwarded headers trusting only the gateway subnet so rate limits partitioned by user.
Prevention
A smoke test in the pipeline that asserts the WebSocket transport; dashboards for SignalR transport mix and gateway-generated 5xx; a checklist for any new proxy layer (body size, timeouts, upgrade headers, forwarded headers, affinity).

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.

More in Reverse Proxy and Gateway

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me