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.
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:
Select in EF Core), so only the fields the screen uses are read and sent.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.
"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."
| 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 |
| 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 |
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.
Content-Length).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.
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
Red flags
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.
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.JsonSerializerContext removes reflection and is required for Native AOT.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.
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.
| 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 |
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.JsonIgnoreCondition.WhenWritingNull and short property names.?fields=id,total) for APIs with many consumers.ETag, Cache-Control) so the best response is no response.Content-Length and the SQL in the EF Core log.AddResponseCompression with Brotli and compare sizes with curl -H "Accept-Encoding: br" -so /dev/null -w '%{size_download}'.[MemoryDiagnoser].pageSize=100000 against your API and make sure the server caps it.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
pageSize=100000 becomes a self-inflicted denial of service. Instead: clamp to a server maximum.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.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.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 |
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.
They solve different problems:
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.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.
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.
Last updated 23 Nov 2026.