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

๐Ÿ“š Interview question

Why does response size matter so much for API latency? Explain how pagination, projection and compression shrink a response, why payload size hurts most on mobile networks, and how you would measure the gain.

Covers how payload size drives API latency, and reducing it with pagination, projection (purpose-built DTOs), compression and omitting nulls, with measurement on real networks.

Intermediate Theory Intermediate api-performance aspnet-core pagination performance projection response-compression

๐ŸŽฏ Key points

  • Latency = round trips × RTT + bytes ÷ bandwidth + server time; on mobile (4G and even 5G, where signal and RTT vary widely) bytes and round trips dominate
  • TCP slow start: a new connection sends only ~14 KB in the first round trip and ramps up, so large payloads cost extra round trips
  • Pagination with a hard maximum page size (e.g. 100) and keyset paging for deep lists
  • Projection to a purpose-built DTO with an async Select (ToListAsync), never serialising entities or full object graphs
  • Efficient serialisation: System.Text.Json source generation, omitting nulls; Protobuf/gRPC for internal traffic
  • Brotli/Gzip via AddResponseCompression (CompressionLevel.Fastest) or at the gateway/CDN; JSON compresses 5–10×
  • Measure response bytes (Content-Length, App Insights) and p95 by client network, not just server duration
  • Compression costs CPU and EnableForHttps is off by default because of BREACH-style attacks on secrets in compressed responses

โฑ 30-second 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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"Server duration is only part of what the user waits for. The rest is the network: round trips times RTT, plus bytes divided by bandwidth. TCP doesn't send at full speed straight away: a new connection starts by sending about 14 KB, then ramps up each round trip. So a 20 KB response arrives in one or two round trips, but a 2 MB response needs many more, and on a mobile network, whether 4G or 5G with a weak signal, RTT and bandwidth swing a lot, so that is the difference between 150 ms and two seconds. Big payloads also cost the server: reading more columns, materialising more objects, serialising more JSON, and allocating large buffers that end up on the large object heap.

In ASP.NET Core I attack size in four places. First, pagination with a hard maximum, so a list endpoint can never return 50,000 rows; for deep lists I use keyset paging. Second, projection: the handler runs an async EF Core query that selects into a DTO shaped for the screen instead of serialising an entity with its navigation properties. That shrinks the SQL, the memory and the JSON at once. Third, serialisation: System.Text.Json with source generation and nulls omitted for public JSON, and Protobuf over gRPC for internal service-to-service calls. Fourth, compression: Brotli or Gzip through the response compression middleware, or better at the gateway or CDN, because JSON is repetitive and usually compresses five to ten times.

The mistake I see is measuring only server duration in Application Insights and declaring the endpoint fast. I look at response size per endpoint and at p95 from the client's side, ideally split by network type. Shrink the bytes before you tune the CPU."


Where the time goes

Part of latency Driven by Fix
Server time Query, mapping, serialisation Async projection, indexes, caching, source-generated JSON
Round trips TCP/TLS setup, slow start, chatty calls Keep-alive, HTTP/2, fewer calls
Transfer Bytes รท bandwidth Pagination, projection, compression

The levers

Lever What it does When not to use it
Pagination Caps rows per response (e.g. default 25, max 100) Exports: stream a file instead
Projection Sends only the fields the client needs Never skip it for public APIs
Serialisation format STJ source generation cuts CPU and allocations; Protobuf is typically 3โ€“10ร— smaller than JSON Protobuf for browsers or third parties who expect JSON
Compression Brotli/Gzip, 5โ€“10ร— smaller JSON Already-compressed content (images, zip), tiny responses under ~1 KB, responses mixing secrets with attacker-controlled input over HTTPS

Async all the way

The data access behind a list endpoint should be ToListAsync/await foreach, never .Result or synchronous ToList() on I/O. Blocking a ThreadPool thread while the database or network works caps throughput, and large responses make each request hold that thread longer.

How to measure

  • Log or chart response size per endpoint (Application Insights request telemetry, gateway logs, Content-Length).
  • Compare client p95 (Real User Monitoring, mobile SDK telemetry) before and after, not only server duration.
  • Use Chrome DevTools network throttling ("Fast 4G") to see the user's view locally.

Production example

A mobile app's order history endpoint returned the full order entity with lines, addresses and audit fields: 1.8 MB for a typical customer. Projecting to a 9-field DTO, capping pages at 50 and enabling Brotli at the gateway brought it to 22 KB. Server p95 fell from 310 ms to 90 ms, and app-side p95 on 4G from 2.6 s to 420 ms.

๐Ÿ” What the interviewer is checking

Checks that the candidate sees latency end to end, including the network, and knows the concrete levers to make responses smaller and how to prove it.

Green flags

  • Explains RTT, TCP slow start or bandwidth as part of latency
  • Projects to DTOs and caps page size on the server
  • Knows compression trade-offs (CPU, BREACH, double compression)
  • Measures bytes and client-side p95, not only server duration

Red flags

  • "Just add caching" without looking at what is returned
  • Returns entities directly from controllers
  • Unlimited page size or "return everything and filter on the client"

๐Ÿ“š Learn in depth

1. Latency is more than server time

client                      server
  |--- DNS / TCP / TLS -----> |   1-3 RTT (once per connection)
  |--- request ------------> |
  |                          |   server time (query + serialise)
  |<-- first ~14 KB -------- |   1 RTT
  |<-- next ~28 KB --------- |   1 RTT  (sender ramps up)
  |<-- next ~56 KB --------- |   1 RTT
  |<-- ...                   |

In plain terms: TCP slow start means a new connection begins cautiously, sending about 10 segments (roughly 14 KB, RFC 6928), and roughly doubles what it sends each round trip until it detects loss. So the bigger the payload, the more round trips it needs. On a 100 ms RTT link, a response that needs six round trips costs 600 ms before bandwidth even matters. Packet loss on mobile networks (4G, and 5G at the cell edge or indoors) makes the sender back off again, which is why big payloads have a long tail at p95 and p99. Faster networks raise bandwidth but don't remove RTT or slow start.

2. What big payloads cost the server

  • SQL: more columns and joins, wider rows, less chance of a covering index.
  • Memory: EF Core materialises full entities (and tracks them unless AsNoTracking). Any single buffer or array of 85,000 bytes or more, such as the byte array behind a large serialised response, is allocated on the large object heap. The LOH is only collected with Gen 2 and is not compacted by default, so frequent large allocations cause expensive full collections and fragmentation. Streaming the response and pooled buffers avoid it.
  • Serialisation: System.Text.Json cost grows with bytes written; deep graphs can also hit reference cycles. Source-generated JsonSerializerContext removes reflection and is required for Native AOT.

3. Pagination

Offset paging (Skip/Take) is simple but gets slower on deep pages because the database still reads the skipped rows. Keyset (seek) paging uses WHERE (CreatedAt, Id) < (@lastCreatedAt, @lastId) with a matching index, so every page costs the same. Always enforce a server-side maximum page size: the client's pageSize=100000 is a denial-of-service vector.

4. Projection, asynchronously

await query.Select(o => new OrderSummaryDto(o.Id, o.Number, o.Total, o.Status)).ToListAsync(ct) makes EF Core generate SQL for exactly those columns and frees the request thread while SQL Server works. Synchronous ToList() blocks a ThreadPool thread for the whole query, which under load leads to ThreadPool starvation. Projection also keeps sensitive fields from leaking by accident, which matters under the Privacy Act 1988 when the entity holds personal information.

5. Serialisation formats

Format Size CPU Fits
JSON (STJ, reflection) Baseline Baseline Public APIs
JSON (STJ source-generated) Same Lower, fewer allocations Public APIs, Native AOT
Protobuf (gRPC) Typically 3โ€“10ร— smaller Lower Internal service-to-service

6. Compression internals

AddResponseCompression wraps the response body stream in a Brotli or Gzip stream when the request's Accept-Encoding allows it and the MIME type is in the list. Key settings:

  • EnableForHttps is false by default. Compressing secrets alongside attacker-controlled input over TLS enables BREACH/CRIME-style attacks, so enable it only after considering that.
  • CompressionLevel.Fastest is usually right for dynamic responses; Optimal/SmallestSize costs much more CPU for a few percent.
  • If a reverse proxy, Azure Front Door or API Management already compresses, do it there and not in the app.

7. Other size levers

  • JsonIgnoreCondition.WhenWritingNull and short property names.
  • Sparse fieldsets (?fields=id,total) for APIs with many consumers.
  • HTTP caching (ETag, Cache-Control) so the best response is no response.

Try it yourself

  1. Return a list endpoint as full entities and as a projected DTO; compare Content-Length and the SQL in the EF Core log.
  2. Add AddResponseCompression with Brotli and compare sizes with curl -H "Accept-Encoding: br" -so /dev/null -w '%{size_download}'.
  3. Throttle Chrome DevTools to "Fast 4G" and compare load time of a 20 KB vs 2 MB response.
  4. Benchmark serialising 1,000 entities vs 1,000 DTOs, reflection vs source-generated STJ, with BenchmarkDotNet and [MemoryDiagnoser].
  5. Try pageSize=100000 against your API and make sure the server caps it.

๐Ÿ’ป Code

A list endpoint that pages with a hard cap, projects to a DTO and serves compressed JSON:

// Program.cs
using System.IO.Compression;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShopDb>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));

// Compress in the app only if no gateway/CDN does it already.
builder.Services.AddResponseCompression(o =>
{
    o.EnableForHttps = true; // reviewed: responses don't mix secrets with reflected input
    o.Providers.Add<BrotliCompressionProvider>();
    o.Providers.Add<GzipCompressionProvider>();
});
builder.Services.Configure<BrotliCompressionProviderOptions>(o => o.Level = CompressionLevel.Fastest);

// Smaller JSON: skip nulls.
builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull);

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

app.MapGet("/customers/{customerId:int}/orders", async (
    int customerId, DateTime? before, int? beforeId, int? pageSize,
    ShopDb db, CancellationToken ct) =>
{
    var size = Math.Clamp(pageSize ?? 25, 1, 100); // never trust the client's page size

    var query = db.Orders.AsNoTracking().Where(o => o.CustomerId == customerId);

    if (before is not null && beforeId is not null) // keyset: same cost on every page
        query = query.Where(o => o.CreatedAt < before ||
                                 (o.CreatedAt == before && o.Id < beforeId));

    var items = await query
        .OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id)
        .Take(size)
        .Select(o => new OrderSummary(o.Id, o.Number, o.Total, o.Status, o.CreatedAt)) // projection
        .ToListAsync(ct);

    return Results.Ok(new Page<OrderSummary>(items, items.Count == size));
});

app.Run();

public sealed record OrderSummary(int Id, string Number, decimal Total, string Status, DateTime CreatedAt);
public sealed record Page<T>(IReadOnlyList<T> Items, bool HasMore);
# Measure what actually crosses the wire
curl -s -o /dev/null -w 'bytes=%{size_download} time=%{time_total}\n' \
  -H 'Accept-Encoding: br' https://localhost:5001/customers/42/orders

โš  Common mistakes

  • Mistake: Optimising without measuring, e.g. switching serialisers before checking the payload size. Why it is wrong: you may spend days on 5% of server time while 90% of user latency is transfer. Instead: chart response bytes and client p95 per endpoint first.
  • Mistake: Micro-optimising a cold admin endpoint called ten times a day. Why it is wrong: the effort never pays back. Instead: rank endpoints by calls ร— bytes and fix the top few.
  • Mistake: Returning EF Core entities from controllers. Why it is wrong: it over-fetches columns, risks cycles and lazy-loading storms, and leaks fields the client shouldn't see. Instead: project to purpose-built DTOs.
  • Mistake: Letting the client choose any page size. Why it is wrong: pageSize=100000 becomes a self-inflicted denial of service. Instead: clamp to a server maximum.
  • Mistake: Turning on EnableForHttps everywhere without thought. Why it is wrong: compressed responses that mix secrets with attacker-controlled input leak through length (BREACH). Instead: compress at the edge, or exclude sensitive responses.
  • Mistake: Compressing twice, in the app and at the gateway, or compressing images. Why it is wrong: wasted CPU for no gain. Instead: pick one layer and limit MIME types.
  • Mistake: Using CompressionLevel.Optimal or SmallestSize for dynamic JSON. Why it is wrong: much more CPU for a few percent of size. Instead: Fastest for dynamic responses, pre-compress static assets.

๐Ÿ› Senior insight: trade-offs

Payload size is the cheapest performance win in most APIs because it improves the database, the server and the network at once, and it reduces data exposure. Seniors start by asking what the screen actually needs, and treat the page size cap and DTO as part of the API contract, not an afterthought. They also know where compression belongs: usually at the edge (Azure Front Door, API Management or the ingress) so the app spends its CPU on business work.

Option When it fits Cost When not to
Projection to DTO Every endpoint Mapping code Never skip it
Offset pagination Shallow lists, admin grids Slows on deep pages Infinite scroll over big tables
Keyset pagination Feeds, deep lists No "jump to page 40" When users really need page numbers
App-level compression No gateway/CDN in front CPU per response A proxy already compresses
Edge compression Front Door, APIM, nginx Config only Rarely a reason not to

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions keyset or deep-page pagination Why: Checks they can implement keyset paging in EF Core and explain why offset paging slows down.
    How to answer

    Skip(n) becomes OFFSET n ROWS, so SQL Server reads and discards n rows every time; page 5,000 reads 100,000 rows to return 20, and cost grows linearly with depth. Keyset paging remembers the last row's sort key and filters WHERE Price > @lastPrice OR (Price = @lastPrice AND Id > @lastId) with the same ORDER BY Price, Id, which seeks an index and reads only the rows it returns, so every page costs the same. It is also stable when rows are inserted. The trade-off: no jumping to page N, so it suits infinite scroll, APIs and exports, while offset stays fine for shallow, numbered pages in admin screens. The sort key needs a matching index and a unique tiebreaker.

  2. When: Candidate mentions response compression or caching middleware Why: Checks they know what response compression, output caching and response caching each do in ASP.NET Core.
    How to answer

    They solve different problems:

    • Response compression makes responses smaller (Brotli or Gzip). It helps large text payloads on slow networks but costs CPU per response. Over HTTPS it's off by default because of BREACH-style attacks, and is often better done at a proxy or CDN.
    • Output caching (AddOutputCache, .NET 7+) stores the whole response on the server and replays it without running the endpoint. The app controls the policy: expiry, vary-by, tags for eviction, and stampede-preventing locking.
    • Response caching middleware follows HTTP Cache-Control rules, so clients can bypass it; its headers mainly matter for browser and CDN caching.

    For server-side caching of API responses I choose output caching. The trade-off is freshness: anything cached can be stale until it expires or is evicted.

  3. When: Candidate talks about round trips or RTT Why: Checks their grasp of latency, bandwidth and throughput, and how chatty calls multiply RTT.
    How to answer
    • Latency: how long one thing takes, such as one round trip or one request (ms). Bounded by distance (light in fibre travels roughly 200 km per ms) plus queuing and processing.
    • Bandwidth: the maximum data rate of a link (Mbit/s, Gbit/s). The width of the pipe.
    • Throughput: what you actually achieve (requests/s or MB/s). Limited by bandwidth, latency, windows, concurrency and the slowest component.

    For most APIs, latency ร— number of round trips dominates, not bandwidth. A request that makes 50 sequential database calls at 2 ms RTT spends 100 ms on the network; move the database to another region at 30 ms RTT and it spends 1.5 s. Fix it by reducing round trips (batching, joins, fewer chatty calls), moving compute near data, caching, and parallelising independent calls.

โ†ฉ Usually asked after

More in API Performance

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me