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

📚 Interview question

The frontend team says the site is slow, but your API responds in 80 ms. As the backend engineer, what can you actually change to improve frontend performance? Talk about payload size, compression, HTTP caching headers and ETags, CDNs, HTTP/2 and HTTP/3, and how Core Web Vitals (LCP, INP, CLS) tell you whether it worked.

Backend levers for frontend performance: response size and shape, Brotli/gzip compression, Cache-Control, ETag and immutable hashed assets, output caching, CDNs such as Azure Front Door, HTTP/2 and HTTP/3, early hints and preload, and measuring with Core Web Vitals (LCP, INP, CLS) and real-user monitoring.

Mid-Level Theory Intermediate cdn core-web-vitals frontend http-caching response-compression web-performance

🎯 Key points

  • Server time is a fraction of page time: round trips, bytes, parse and render dominate, worst on variable mobile networks (60-100+ ms RTT)
  • Projection = return only the fields the screen renders (DTO via Select), plus pagination; JSON compresses 70-90% with Brotli/gzip
  • Hashed static assets: Cache-Control: public, max-age=31536000, immutable; HTML: no-cache; user data: private/no-store
  • ETag / If-None-Match gives 304s for revalidation; output caching for shared responses
  • CDN (Azure Front Door) near users: Australian edge sites cut RTT; cache static and public responses
  • HTTP/2 multiplexing and HTTP/3 (QUIC) reduce connection and head-of-line costs; fewer sequential calls per screen
  • Core Web Vitals at p75: LCP ≤ 2.5 s, INP ≤ 200 ms (INP replaced FID in March 2024), CLS ≤ 0.1; TTFB feeds LCP
  • Measure with real-user monitoring segmented by mobile vs desktop (Application Insights browser SDK, CrUX), not only Lighthouse

⏱ 30-second answer

The API's 80 ms is usually a small part of what users feel: round trips, bytes and browser work dominate. A backend engineer controls a lot of that. Shrink payloads with projection and pagination, and turn on Brotli/gzip (JSON shrinks 70–90%). Use HTTP caching properly: content-hashed JS/CSS get Cache-Control: public, max-age=31536000, immutable, HTML gets no-cache so deploys show up, and API GETs get ETags for cheap 304s. Put static and public content on a CDN like Azure Front Door with Australian points of presence. Enable HTTP/2 and HTTP/3, reduce chatty call sequences, and send preload or 103 Early Hints for critical assets. Then measure with Core Web Vitals at the 75th percentile from real users: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1. Trade-off: aggressive caching is fast but needs versioned URLs or you'll serve stale code.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I'd say is that 80 ms of server time doesn't mean an 80 ms experience. A page load is DNS, TLS, the HTML, CSS and JavaScript downloads, maybe a waterfall of API calls the SPA makes only after its bundle runs, then parsing and rendering on a phone that's much slower than my laptop. On a 4G connection in regional Queensland, every round trip might be 60–100 ms, so three sequential API calls after a 600 KB bundle easily become three seconds. I'd start by opening the Network panel's waterfall and a Lighthouse report, and checking field data, before changing anything.

Then the levers I own. Bytes: return what the screen needs, not entire entity graphs; paginate; enable response compression or let the CDN do Brotli. Caching: build tools like Vite emit content-hashed file names, so I serve those with a one-year immutable cache and give the HTML no-cache, which means 'revalidate every time', so a deploy is picked up immediately but nothing is downloaded twice. API GETs that rarely change get an ETag; the browser sends If-None-Match and I answer 304 with no body. Shared, non-personal responses can use ASP.NET Core output caching or the CDN. Distance: Azure Front Door terminates TLS close to the user and serves cached assets from Sydney or Melbourne edge locations. Protocol: HTTP/2 multiplexes requests on one connection, HTTP/3 over QUIC avoids TCP head-of-line blocking on lossy mobile links. Round trips: one aggregate endpoint for a screen instead of five sequential calls.

The mistake I see is optimising server microseconds while shipping uncompressed 2 MB JSON with no-store on everything. And I'd prove the gain with Core Web Vitals from real users: LCP for loading, INP for responsiveness, CLS for layout stability, all at the 75th percentile."


Lever → metric it moves

Lever Mostly improves ASP.NET Core / Azure feature
Smaller JSON (projection, paging) LCP, INP (less parsing) Select to DTOs, Take
Brotli/gzip LCP, TTFB to last byte AddResponseCompression, Front Door compression
Immutable hashed assets Repeat-visit LCP UseStaticFiles with OnPrepareResponse, MapStaticAssets
ETag + 304 Bandwidth, LCP on revisits EntityTagHeaderValue, output caching
CDN TTFB, LCP Azure Front Door, Azure CDN
HTTP/2, HTTP/3 Connection overhead Kestrel Protocols, Front Door
Fewer sequential calls LCP Aggregate/BFF endpoint
Server-rendered first view LCP Razor, Blazor static SSR, streaming
Reserve space for late content CLS Width/height on images, skeletons

Core Web Vitals (good thresholds, p75)

Metric Measures Good
LCP (Largest Contentful Paint) Loading of main content ≤ 2.5 s
INP (Interaction to Next Paint) Responsiveness to input (replaced FID in March 2024) ≤ 200 ms
CLS (Cumulative Layout Shift) Visual stability ≤ 0.1
TTFB (supporting) Server + network to first byte ≤ 0.8 s

Cache-Control recipes

Resource Header
app.3f9a1c.js, site.88b2.css public, max-age=31536000, immutable
index.html no-cache
Public reference data API public, max-age=300 + ETag
User-specific API private, no-cache or no-store

Production example

A product catalogue SPA served a 1.8 MB uncompressed JSON list and its bundle with no-store. Enabling Brotli at Front Door, paging to 50 items, and giving hashed assets a one-year immutable cache cut transferred bytes on repeat visits by 92% and moved p75 LCP from 4.3 s to 2.1 s for mobile users, measured with the Application Insights browser SDK over two weeks.

🔍 What the interviewer is checking

Checks that a backend engineer understands their influence on user-perceived performance and can measure it with the right metrics.

Green flags

  • Separates server time from page time and reads a waterfall
  • Gives correct Cache-Control recipes for hashed assets vs HTML vs user data
  • Mentions compression, ETags, CDN and fewer round trips
  • Knows LCP, INP, CLS thresholds and uses field data

Red flags

  • Only talks about server CPU or database tuning
  • Caches personalised data publicly
  • Mentions FID as current or measures only in Lighthouse

📚 Learn in depth

1. Where the time goes

[DNS][TCP][TLS][ HTML ]                     <- TTFB + download
                [ CSS ][   JS bundle   ]    <- render-blocking / parse
                                      [API 1][API 2][API 3]  <- waterfall after JS runs
                                                          [render] <- LCP

Each bracket is at least one round trip. Server processing is inside HTML and each API bar. The cheapest wins remove whole bars (caching, fewer sequential calls) or shrink them (compression, CDN proximity).

2. HTTP caching mechanics

  • Freshness: max-age lets the browser reuse without asking. immutable tells it not to revalidate even on reload.
  • Validation: when stale, the browser sends If-None-Match: "etag" (or If-Modified-Since). A 304 has no body.
  • no-cache means "store but revalidate before use"; no-store means "don't store at all". They're often confused.
  • private forbids shared caches (CDN, proxies) from storing it; essential for user data.
  • Vary tells caches which request headers change the response (Accept-Encoding, Origin).

3. Compression

Brotli at quality 4–5 for dynamic responses gives better ratios than gzip at similar CPU; static assets can be pre-compressed at maximum quality at build time (MapStaticAssets in .NET 9+ serves pre-compressed, fingerprinted files with correct ETags). Don't compress already-compressed formats (JPEG, PNG, WOFF2). Response compression over HTTPS is off by default in ASP.NET Core because of BREACH-style attacks when secrets and attacker-controlled input appear in the same compressed body; enable it deliberately, and avoid reflecting user input next to secrets.

4. CDNs and protocols

A CDN shortens the TLS handshake (terminated at the edge) and serves cached content locally. Azure Front Door has edge sites in Sydney, Melbourne, Brisbane and Perth. HTTP/2 multiplexes many requests on one TCP connection; HTTP/3 runs over QUIC on UDP, so one lost packet doesn't stall every stream, which helps on mobile. Kestrel supports HTTP/3 on .NET 10 where the OS has QUIC support.

5. Measuring

  • Lab: Lighthouse, WebPageTest, DevTools throttling: repeatable, good for regressions.
  • Field (RUM): Chrome UX Report (CrUX), the web-vitals JS library sending to Application Insights: what real users experience. Decide with field p75.

Try it yourself

  1. Run Lighthouse on your app with mobile throttling and note LCP and the largest network requests.
  2. Enable AddResponseCompression with Brotli and compare transferred vs resource size in the Network panel.
  3. Add an ETag to a GET endpoint and confirm a 304 on the second request (with cache enabled).
  4. Serve a hashed JS file with immutable and verify reloads show (memory cache).
  5. Add the web-vitals library and log LCP, INP and CLS to the console for your own pages.

💻 Code

Compression, immutable static assets, ETags and HTTP/3 in one ASP.NET Core app, plus field measurement.

// Program.cs (.NET 10)
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(k => k.ConfigureEndpointDefaults(
    l => l.Protocols = HttpProtocols.Http1AndHttp2AndHttp3)); // HTTP/3 where QUIC is available

builder.Services.AddResponseCompression(o =>
{
    o.EnableForHttps = true; // deliberate: don't mix secrets with reflected input in one body
    o.Providers.Add<BrotliCompressionProvider>();
    o.Providers.Add<GzipCompressionProvider>();
});
builder.Services.Configure<BrotliCompressionProviderOptions>(o => o.Level = CompressionLevel.Fastest);
builder.Services.AddOutputCache();

var app = builder.Build();
app.UseResponseCompression();

// Fingerprinted Vite output (app.3f9a1c.js): cache for a year
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        var isHtml = ctx.File.Name.EndsWith(".html", StringComparison.OrdinalIgnoreCase);
        ctx.Context.Response.Headers.CacheControl = isHtml ? "no-cache" : "public, max-age=31536000, immutable";
    }
});
app.UseOutputCache();

// Public reference data: small, shared, ETag for cheap revalidation
app.MapGet("/api/categories", (HttpContext http) =>
{
    Category[] data = [new(1, "Cables"), new(2, "Chargers")];
    var bytes = JsonSerializer.SerializeToUtf8Bytes(data, JsonSerializerOptions.Web);
    var etag = $"\"{Convert.ToHexString(SHA256.HashData(bytes))[..16]}\"";

    http.Response.Headers.ETag = etag;
    http.Response.Headers.CacheControl = "public, max-age=300";
    if (http.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
    return Results.Bytes(bytes, "application/json");
}).CacheOutput(p => p.Expire(TimeSpan.FromMinutes(5)));

app.MapFallbackToFile("index.html"); // SPA entry point, served with no-cache
app.Run();

public sealed record Category(int Id, string Name);
// main.ts: send real-user Core Web Vitals to Application Insights
import { onLCP, onINP, onCLS } from 'web-vitals';
import { appInsights } from './telemetry';

for (const report of [onLCP, onINP, onCLS]) {
  report((m) => appInsights.trackMetric({ name: m.name, average: m.value }, { rating: m.rating, page: location.pathname }));
}

⚠ Common mistakes

  • Mistake: Judging frontend speed by server response time. Why it is wrong: Round trips, bytes and rendering dominate the user's wait. Instead: Look at the waterfall and Core Web Vitals.
  • Mistake: no-store on every response. Why it is wrong: Hashed assets are downloaded on every visit. Instead: immutable for fingerprinted files, no-cache for HTML.
  • Mistake: Long max-age on index.html. Why it is wrong: Users keep old HTML pointing at deleted bundles after a deploy. Instead: no-cache on HTML; version assets by hash.
  • Mistake: Caching user-specific responses as public. Why it is wrong: A CDN can serve one user's data to another: a notifiable data breach. Instead: private or no-store for personalised data.
  • Mistake: Returning whole entity graphs. Why it is wrong: Megabytes to parse on a phone hurt LCP and INP. Instead: Purpose-built DTOs and paging.
  • Mistake: Compressing images and WOFF2 again. Why it is wrong: CPU for no gain. Instead: Compress text types only.
  • Mistake: Optimising only for Lighthouse on a desktop. Why it is wrong: Field users on mid-range phones see far worse. Instead: Use RUM p75 by device type.
  • Mistake: Still targeting FID. Why it is wrong: INP replaced it in March 2024. Instead: Track INP.

🏛 Senior insight: trade-offs

The backend's biggest frontend lever is usually removing round trips and bytes rather than shaving server milliseconds: an aggregate endpoint per screen, sensible caching, compression and a CDN. Server-rendering the first view (Razor, Blazor static SSR or framework SSR) is the next step when LCP is dominated by a JS bundle that has to run before data is fetched.

Option When it fits Cost When not to
Compression + caching headers Always Config only Never skip
CDN (Front Door) Public or static content, spread-out users Monthly cost, cache invalidation Purely internal apps on a LAN
Aggregate / BFF endpoint Screens making 4+ calls Endpoint per screen to maintain Generic public APIs
Server-side rendering of first view Poor LCP due to JS-then-fetch Server CPU, hydration complexity Highly interactive tools behind login where LCP matters less

Measure before and after with field data: Application Insights browser telemetry or CrUX at p75, segmented by mobile vs desktop and by region, plus bytes transferred per page view.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions payload size and compression Why: Checks deeper knowledge of response size, pagination and projection
    How to answer

    Every response pays twice: serialisation time on the server and transfer time on the wire. On a phone over 4G with 60–100 ms RTT, a 2 MB JSON payload needs many TCP slow-start round trips, so it can take seconds even when the server answered in 40 ms. I shrink responses three ways:

    • Pagination with a capped page size, so no endpoint returns "everything".
    • Projection to a purpose-built DTO (Select in EF Core), so only the fields the screen uses are read and sent.
    • Compression (Brotli or Gzip), which cuts JSON by 5–10×.

    I prove it with response bytes and client-side p95, not server time. The trade-off: compression costs CPU and needs care over HTTPS, and smaller pages mean more requests if the client really needs all the data.

  2. When: Candidate mentions Cache-Control and ETag Why: Checks HTTP header knowledge and what breaks when they're wrong
    How to answer

    A handful of headers carry most of an API's contract:

    • Content-Type / Accept: what the body is and what the client wants back; mismatches give 415 or 406.
    • Authorization: the credential, usually Bearer tokens; never in the URL.
    • Cache-Control / ETag: who may cache and for how long, and a version tag for conditional requests (304, 412).
    • Location on 201/202, Retry-After on 429/503.
    • traceparent: the W3C trace context that stitches a request across services.
    • X-Forwarded-For/Proto/Host: the original client details behind a proxy, which you must only trust from known proxies.

    The trade-off: headers are invisible in most client code, so anything important must be documented in OpenAPI and handled by the framework, not by hand.

  3. When: Candidate mentions HTTP/2 or HTTP/3 Why: Checks multiplexing and head-of-line blocking details
    How to answer

    HTTP/2 sends many requests as multiplexed streams over one TCP connection, with binary framing and HPACK header compression, so you stop paying for extra connections and HTTP/1.1's one-request-at-a-time queue. But it still runs on TCP, so one lost packet stalls every stream: TCP head-of-line blocking.

    HTTP/3 moves to QUIC over UDP with TLS 1.3 built in: each stream recovers from loss on its own, the handshake is faster (1-RTT, 0-RTT on resume), and connections survive a network change.

    In .NET 10, Kestrel serves HTTP/1.1 and HTTP/2 by default. HTTP/3 is a one-line opt-in: MsQuic ships with .NET on Windows, and on Linux you install the libmsquic package. The gain is real on high-latency, lossy mobile networks with many parallel requests and for gRPC; for a single big response inside one Azure region it is usually noise. Measure per protocol before you claim it.

🛠 Real-world problems: how you handle them

Catalogue page slow on mobile despite a fast API
Situation
A [retail product catalogue] React SPA on [Azure App Service in Australia East], API p95 under [100 ms], but [marketing] reported mobile bounce rates of [X]% and poor search rankings.
Signals
CrUX and Application Insights browser telemetry showed p75 LCP of [4.3 s] on mobile; Lighthouse flagged 'Serve static assets with an efficient cache policy' and 'Enable text compression'; the Network panel showed a [1.8 MB] uncompressed JSON response and assets served with `no-store`.
Investigation
Recorded a throttled Lighthouse run and a WebPageTest waterfall from Sydney on a mid-range mobile profile; found three sequential API calls after a 600 KB bundle; confirmed in DevTools the transferred size equalled resource size (no compression) and repeat visits re-downloaded everything.
Resolution
Immediate: enabled Brotli compression at Azure Front Door and set `immutable` caching on hashed assets with `no-cache` on `index.html`. Then paged the catalogue to 50 items with a projected DTO, merged the three calls into one screen endpoint, and added an ETag to category data.
Prevention
Lighthouse CI budget in the pipeline (LCP and total bytes), a web-vitals RUM dashboard with an alert when p75 LCP exceeds 2.5 s, and a review checklist for Cache-Control on new endpoints.

How to tell it (STAR)

**S:** Our [catalogue] API answered in under 100 ms, but mobile users found the page slow and [marketing] saw high bounce rates. **T:** I was asked to find out why from the backend side. **A:** I looked at field data and a throttled waterfall instead of server metrics, and found uncompressed megabyte-sized JSON, no caching on hashed bundles and three sequential API calls. I enabled Brotli at Front Door, set immutable caching on fingerprinted assets, paged and projected the catalogue response and merged the calls into one endpoint, then added Lighthouse CI budgets. **R:** Repeat-visit bytes fell by [about 90%] and p75 mobile LCP went from [4.3 s] to [2.1 s] over [two weeks], and [bounce rate improved by X].

↩ Usually asked after

More in Web Basics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me