Introduction
The performance of an API endpoint is not determined only by the database query. After a query completes, data must be materialized into objects, mapped to a response model, serialized into JSON, and transmitted over the network. For mobile clients, high-latency networks, and services handling many concurrent requests, even small payload differences can become significant.
In this lesson, we will design API responses with performance in mind. We will examine why returning entity objects directly can be risky, create response models containing only the fields clients need, configure System.Text.Json, and measure serialization costs with BenchmarkDotNet. The goal is not to make every endpoint artificially small, but to deliberately reduce unnecessary computation, memory usage, and network traffic.
1. Why response design is a performance concern
Consider the following processing chain for an API response:
- Rows are read from the database.
- EF Core materializes them into entity objects.
- The application prepares those objects or maps them to a response model.
System.Text.Jsonreads public properties and produces JSON.- The response body is sent to the client over HTTP.
If your entity contains 25 properties but the client uses only 6, the remaining properties can create unnecessary memory, CPU, and network costs. With large collections, that cost is repeated for every item and grows quickly.
The main principles of performance-oriented response design are:
- Return fields that the client actually uses.
- Use summary models for list endpoints and richer models for detail endpoints.
- Do not add unnecessary nested objects or collections to responses.
- Do not use entity classes as your public API contract.
- Measure serialization and payload size instead of assuming an optimization worked.
2. Problems with returning entities
The following approach may initially appear convenient:
[HttpGet("{id:int}")]
public async Task<ActionResult<Product>> Get(int id)
{
var product = await db.Products
.Include(x => x.Category)
.Include(x => x.Tags)
.SingleOrDefaultAsync(x => x.Id == id);
return product is null ? NotFound() : Ok(product);
}However, this design creates several problems. An entity may contain internal fields, cost information, or audit columns that should not be exposed to clients. Navigation properties can create circular reference graphs. In addition, adding a new public property to the entity can unintentionally change the API contract.
Over-fetching is another issue. A product page may need only a name, price, and category name, while the endpoint loads complete tag objects, inventory movements, or user relationships. This creates unnecessary database work and serialization work. JsonIgnore can help hide selected fields, but it does not remove the cost of loading and materializing unnecessary data. A response model that does not contain the field is usually the safer design.
3. Using response DTOs and projection
Separate the API contract from the entity by defining explicit response models:
public sealed record ProductListItemResponse(
int Id,
string Name,
decimal Price,
string CategoryName);
public sealed record ProductDetailResponse(
int Id,
string Name,
decimal Price,
string Description,
string CategoryName,
IReadOnlyList<string> Tags);The list endpoint can select only the required fields through projection:
[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductListItemResponse>>> GetList(
CancellationToken cancellationToken)
{
var products = await db.Products
.AsNoTracking()
.OrderBy(x => x.Name)
.Select(x => new ProductListItemResponse(
x.Id,
x.Name,
x.Price,
x.Category.Name))
.ToListAsync(cancellationToken);
return Ok(products);
}This combines projection and reduced tracking with API design. EF Core can generate SQL that selects only the columns used by the projection. This reduces both entity materialization and unnecessary property serialization.
The detail endpoint can include nested data, but it should still be limited:
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDetailResponse>> GetDetail(
int id,
CancellationToken cancellationToken)
{
var product = await db.Products
.AsNoTracking()
.Where(x => x.Id == id)
.Select(x => new ProductDetailResponse(
x.Id,
x.Name,
x.Price,
x.Description,
x.Category.Name,
x.Tags
.OrderBy(t => t.Name)
.Select(t => t.Name)
.ToList()))
.SingleOrDefaultAsync(cancellationToken);
return product is null ? NotFound() : Ok(product);
}You do not have to use the same model for list and detail endpoints. A short response for list screens and a richer but still controlled response for detail screens usually provides a better contract.
4. Configuring System.Text.Json
ASP.NET Core uses System.Text.Json as the JSON formatter for controller-based APIs by default. Global settings can be configured during application startup:
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy =
JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition =
JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.WriteIndented = false;
options.JsonSerializerOptions.MaxDepth = 16;
});WriteIndented = false is normally appropriate for production APIs. Pretty-printed JSON is easier for humans to read, but it increases payload size. WhenWritingNull can omit null properties from responses. Because this setting changes the client contract, use it only after confirming that all clients correctly handle missing fields.
You can conditionally omit an individual property with an attribute:
public sealed record ProductInternalResponse(
int Id,
string Name,
decimal Price,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
decimal DiscountAmount);This is useful for explicitly optional fields, but it should not be treated as the only security boundary. Sensitive fields should not be included in the response model at all.
5. Reducing nested objects and computed work
Not every nested object is harmful. The problem is nested data that the client does not use or that is expensive to calculate for every item. For example, a product list usually benefits from a simple categoryName field instead of a complete category object.
Likewise, calling another service for every item or performing expensive calculations repeatedly before serialization can create a bottleneck. A response model should carry the result the client needs:
public sealed record OrderListItemResponse(
int Id,
DateTime CreatedAt,
decimal Total,
int ItemCount,
string Status);If ItemCount or Total can be expressed in a database-translatable projection, prefer that approach over loading all order items and calculating them in application memory. A custom method that cannot be translated to SQL may cause the application to retrieve more data than necessary.
6. Source generation and serialization
For services that perform substantial serialization, the System.Text.Json source-generation approach can move metadata generation to build time. A simple context might look like this:
[JsonSerializable(typeof(ProductListItemResponse[]))]
[JsonSerializable(typeof(ProductDetailResponse))]
public partial class ApiJsonContext : JsonSerializerContext
{
}This approach is particularly useful for frequently used response types with predictable shapes. However, adding source generation to every endpoint does not automatically solve performance problems. If the payload is too large, the response contains unnecessary properties, or data access is inefficient, metadata optimization may affect only a small part of the total cost.
When using source generation, verify the supported members and options for the selected mode. Some converters and advanced serialization settings have limitations. First reduce unnecessary data; then optimize the serialization strategy.
7. Measuring payload size and time
Before and after a change, compare at least the following measurements:
- Response body size in bytes.
- Server-side serialization time.
- Total endpoint duration.
- Allocated memory and Gen 0 collections.
- Compressed and uncompressed size when compression is enabled.
Browser developer tools, HTTP clients, or application logs can help you observe the real endpoint. For microbenchmarks, use a separate console benchmark project rather than embedding BenchmarkDotNet directly into an ASP.NET Core web project:
[MemoryDiagnoser]
public class SerializationBenchmarks
{
private readonly ProductListItemResponse[] products =
Enumerable.Range(1, 1000)
.Select(id => new ProductListItemResponse(
id, "Product " + id, 19.99m, "Hardware"))
.ToArray();
[Benchmark]
public byte[] SerializeDefault() =>
JsonSerializer.SerializeToUtf8Bytes(products);
[Benchmark]
public byte[] SerializeIndented() =>
JsonSerializer.SerializeToUtf8Bytes(
products,
new JsonSerializerOptions { WriteIndented = true });
}Run BenchmarkDotNet in Release mode. A single first-call measurement, a Debug build, or a very small data set can lead to misleading conclusions. BenchmarkDotNet measures the selected serialization operation; it does not represent the complete behavior of a real endpoint with database access, middleware, network latency, and compression. Use microbenchmarks and real HTTP measurements together.
Common mistakes
- Returning entities directly: This couples the API contract to the database model and can expose more data than intended.
- Including every relationship: Large nested graphs increase payload and serialization costs.
- Confusing JsonIgnore with query optimization: A property may be excluded from JSON even though it was loaded and materialized.
- Leaving WriteIndented enabled in production: Readability improves, but the response becomes larger.
- Treating source generation as a magic solution: Poor queries and unnecessary data transfer still dominate the total cost.
- Compressing every response: For very small payloads, compression CPU cost may exceed the network savings.
Practice exercise
Inspect an existing product list endpoint and complete the following steps:
- List every property currently returned by the endpoint.
- Identify the fields that the client actually uses.
- Create a separate
ProductListItemResponsemodel. - Use projection to select only the required columns.
- Configure null handling and indented JSON deliberately.
- Measure payload size for 100, 1,000, and 10,000 records.
- Compare total duration and allocated memory before and after the change.
As an extension, replace a complete category object in the detail response with only the category name. Evaluate the result using response bytes and p95 latency, not only average duration.
Conclusion
API performance is not achieved by writing fast SQL alone. The shape of the data sent to clients, the boundaries of response models, nested relationships, and JSON serialization settings all contribute to the total cost. Replacing direct entity responses with purpose-built DTOs, filtering unnecessary data at the database layer through projection, and configuring System.Text.Json deliberately produces APIs that are smaller, safer, and easier to maintain.
The most important rule is to measure. Comparing payload size, serialization time, allocations, and real endpoint latency turns an assumption into evidence. In the next stage, these measurements can be evaluated together with caching and response compression to understand end-to-end API performance.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting
- https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/ignore-properties
- https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation
- https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation-modes
- https://github.com/dotnet/BenchmarkDotNet
- https://learn.microsoft.com/en-us/aspnet/core/performance/response-compression