An ASP.NET Core API can execute database queries quickly and still return responses more slowly than expected. In many applications, developers investigate database performance first because database queries are often responsible for API delays. However, the time required to convert application objects into JSON can also become a significant part of request processing.
Consider an API that returns thousands of customer records along with order details, addresses, payment information, and account statistics. The database query may finish quickly, but the application still needs to convert the resulting objects into JSON before sending the response.
When response objects become large or contain deeply nested structures, serialization can consume CPU time and memory. This becomes more noticeable when several clients request large responses simultaneously.
The challenge is that serialization delays are not always obvious. A developer may see that the database query is fast and assume that the API should also be fast. Without measuring individual stages of request processing, it can be difficult to identify where the remaining time is being spent.
ASP.NET Core provides several ways to investigate response serialization, including logging, diagnostic tools, middleware instrumentation, profiling, and serializer configuration.
In this article, we will explore how JSON serialization works in ASP.NET Core, identify common causes of slow serialization, measure its impact, and improve response performance without unnecessarily changing the API contract.
Understanding JSON Serialization in ASP.NET Core
When a controller returns an object using Ok(), ASP.NET Core does not normally send the C# object directly to the client.
The framework uses an output formatter to convert the object into an HTTP response format. For JSON responses, System.Text.Json is commonly used by default.
Consider this endpoint:
[HttpGet("customers")]
public IActionResult GetCustomers()
{
var customers = new List<Customer>
{
new Customer
{
Id = 1,
Name = "Rahul",
Email = "[email protected]"
},
new Customer
{
Id = 2,
Name = "Priya",
Email = "[email protected]"
}
};
return Ok(customers);
}The application creates a collection of Customer objects. ASP.NET Core then serializes that collection into JSON.
The resulting response looks like this:
[
{
"id": 1,
"name": "Rahul",
"email": "[email protected]"
},
{
"id": 2,
"name": "Priya",
"email": "[email protected]"
}
]For a small collection, serialization is usually not a concern.
However, consider an API that returns 50,000 records, each containing several nested objects and collections. The serialization process now has to inspect many properties, convert values, handle nested structures, and write a much larger response.
The total API response time can be understood as several stages:
Incoming HTTP Request
|
v
Authentication and Middleware
|
v
Controller Execution
|
v
Database and External Service Calls
|
v
Object Mapping and Response Preparation
|
v
JSON Serialization
|
v
HTTP Response TransmissionMeasuring these stages separately helps identify whether serialization is actually the source of the delay.
Common Causes of Slow JSON Serialization
Before changing serializer settings, it is important to understand why serialization is taking longer than expected.
Large Response Objects
The most common reason is returning more information than the client needs.
For example, an order endpoint may return complete customer information, product details, payment records, shipment history, and audit information.
If the client only displays the order number, status, and total amount, serializing all the additional information wastes processing time and increases network traffic.
A smaller response model is often the simplest improvement.
Deeply Nested Object Structures
Nested objects increase the amount of work required to serialize a response.
Consider the following model:
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; }
public List<OrderItem> Items { get; set; }
public Payment Payment { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}A collection of these objects may contain many nested properties.
The serializer needs to process each object and its associated properties.
Nested structures are not automatically a problem, but unnecessarily complex response models can increase serialization work and make responses harder to maintain.
Circular Object References
Entity models sometimes contain navigation properties that reference each other.
For example, an Order contains a Customer, while the Customer also contains a collection of Orders.
public class Customer
{
public int Id { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; }
}This creates a circular reference.
Depending on the serializer configuration, circular references can result in serialization exceptions or require reference-handling behavior that changes the response representation.
Returning dedicated response models instead of directly exposing entity relationships helps avoid this problem.
Expensive Custom Converters
Custom JSON converters are useful when an application needs to control how specific data types are represented.
However, a converter that performs expensive calculations, repeated lookups, or unnecessary string operations can increase serialization time.
For example, a converter should not make a database call every time it serializes a property.
Serialization should generally transform already available data rather than perform additional business operations.
Repeated Serialization of the Same Data
Some applications serialize the same object multiple times.
This may happen when generating logs, creating cache entries, producing audit records, and returning the final API response.
If a large object is serialized independently for each operation, the application performs repeated work.
Reviewing these paths can reveal opportunities to reuse suitable representations or avoid unnecessary serialization.
Measuring Serialization Time in ASP.NET Core
The first step in improving serialization performance is measurement.
Do not assume that System.Text.Json is slow simply because the API response is large.
The delay may come from database execution, object mapping, compression, network transmission, or another middleware component.
A useful approach is to measure the time spent preparing the response separately from the time spent writing it.
Measuring Serialization Outside the Controller
For an isolated benchmark, you can measure serialization directly using Stopwatch.
using System.Diagnostics;
using System.Text.Json;
var customers = GetLargeCustomerCollection();
var stopwatch = Stopwatch.StartNew();
var json = JsonSerializer.Serialize(customers);
stopwatch.Stop();
Console.WriteLine(
$"Serialization time: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine(
$"JSON size: {System.Text.Encoding.UTF8.GetByteCount(json)} bytes");This example measures the time required to convert the object collection into a JSON string.
It is useful for comparing different response models and serializer configurations.
However, it does not represent the complete ASP.NET Core response pipeline. It also creates a string containing the entire JSON response, which may introduce additional memory usage.
Use this type of measurement for controlled investigations rather than adding it to every production request.
Measuring Serialization During an API Request
For a more realistic measurement, you can instrument an output formatter or use application diagnostics.
The following example demonstrates a simplified custom middleware that measures how long the downstream request pipeline takes:
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
_logger.LogInformation(
"Request {Method} {Path} completed in {ElapsedMs} ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds);
}
}Register the middleware:
app.UseMiddleware<RequestTimingMiddleware>();This provides the total time spent in the downstream pipeline.
It does not isolate serialization time. The measurement may include controller execution, database operations, output formatting, and response writing.
To identify serialization specifically, use a profiler or instrument the JSON output formatter.
Measuring the JSON Output Formatter
ASP.NET Core MVC uses output formatters to produce response content.
You can wrap the existing System.Text.Json output formatter with a custom formatter that measures the time spent writing JSON.
The following example demonstrates the general approach:
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
public class TimedJsonOutputFormatter : IOutputFormatter
{
private readonly SystemTextJsonOutputFormatter _inner;
private readonly ILogger<TimedJsonOutputFormatter> _logger;
public TimedJsonOutputFormatter(
SystemTextJsonOutputFormatter inner,
ILogger<TimedJsonOutputFormatter> logger)
{
_inner = inner;
_logger = logger;
}
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return _inner.CanWriteResult(context);
}
public async Task WriteAsync(
OutputFormatterWriteContext context)
{
var stopwatch = Stopwatch.StartNew();
await _inner.WriteAsync(context);
stopwatch.Stop();
_logger.LogInformation(
"JSON output formatting completed in {ElapsedMs} ms",
stopwatch.ElapsedMilliseconds);
}
}This example illustrates the instrumentation concept, but it is not a drop-in registration for the default MVC formatter.
A production implementation must account for how the framework creates and registers formatter instances, including the available serializer options and dependency injection requirements.
For most applications, a profiler or supported diagnostic instrumentation is a better starting point than replacing the default formatter.
Also remember that formatter execution can include writing the response stream. Its elapsed time is not necessarily pure CPU serialization time.
Improving Serialization Performance With Better Response Models
One of the most effective improvements is reducing the amount of data returned by an endpoint.
Consider an API that returns complete order information:
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; }
public List<OrderItem> Items { get; set; }
public Payment Payment { get; set; }
public List<OrderAudit> AuditHistory { get; set; }
}If a mobile screen only needs the order number, customer name, status, and total amount, there is no reason to serialize the complete object graph.
Create a smaller response model:
public class OrderSummaryResponse
{
public int Id { get; set; }
public string CustomerName { get; set; }
public string Status { get; set; }
public decimal TotalAmount { get; set; }
}Map the required information:
[HttpGet("summary")]
public IActionResult GetOrderSummary()
{
var orders = _orderService.GetOrders();
var response = orders.Select(order =>
new OrderSummaryResponse
{
Id = order.Id,
CustomerName = order.Customer.Name,
Status = order.Status,
TotalAmount = order.TotalAmount
});
return Ok(response);
}The resulting response contains only the fields required by the client.
This reduces serialization work and network payload size. It can also reduce database work when the query is designed to retrieve only the required columns.
For larger collections, use pagination rather than returning every record in a single response.
Choosing the Right JSON Serializer Settings
System.Text.Json provides several options that influence serialization behavior.
These settings should be selected according to the API contract rather than changed blindly for performance.
Avoid Unnecessary Property Processing
If a response model contains properties that should never be returned, remove them from the response model instead of relying on runtime conditions to hide them.
For example:
public class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string InternalNotes { get; set; }
= string.Empty;
}If InternalNotes is never part of the public API contract, it should not be included in the response model.
Using dedicated DTOs makes the intended response structure clear.
Configure Naming Policies Once
ASP.NET Core applications commonly use camel-case JSON property names.
You can configure JSON options centrally:
builder.Services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy =
JsonNamingPolicy.CamelCase;
});Avoid creating different serializer configurations for every request unless the API genuinely needs different output formats.
Use Reference Handling Only When Required
System.Text.Json supports reference-handling options such as ReferenceHandler.Preserve.
However, enabling reference preservation changes the JSON representation by introducing reference metadata.
It should not be enabled simply to hide object-model design problems.
For public APIs, explicit response models are often easier for clients to consume.
Understanding the Impact of Response Compression
Serialization and network transmission are separate stages, but they can influence each other.
A large JSON response may consume significant network bandwidth.
ASP.NET Core supports response compression through middleware.
For example:
builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
app.MapControllers();Response compression can reduce the amount of data transferred over the network.
However, compression requires additional CPU processing.
For a large response, the application may spend time serializing the JSON and then compressing the resulting data.
Compression should therefore be evaluated using actual response sizes and application workload.
It is not automatically beneficial for every endpoint or every response size.
Using BenchmarkDotNet to Compare Serialization Approaches
When comparing serializer configurations or response models, a benchmark is more reliable than measuring a single request.
BenchmarkDotNet can help compare execution time and memory allocation under controlled conditions.
Install the package:
dotnet add package BenchmarkDotNetCreate a benchmark:
using BenchmarkDotNet.Attributes;
using System.Text.Json;
[MemoryDiagnoser]
public class SerializationBenchmark
{
private List<CustomerResponse> _customers;
[GlobalSetup]
public void Setup()
{
_customers = Enumerable.Range(1, 10000)
.Select(id => new CustomerResponse
{
Id = id,
Name = $"Customer {id}",
Email = $"customer{id}@example.com"
})
.ToList();
}
[Benchmark]
public string SerializeCustomers()
{
return JsonSerializer.Serialize(_customers);
}
}
public class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}Run the benchmark using:
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<SerializationBenchmark>();BenchmarkDotNet executes the benchmark multiple times and reports measurements such as execution time and memory allocation.
This can help identify whether a smaller response model or a different serialization configuration produces a meaningful improvement.
Do not treat a microbenchmark as a substitute for testing the complete API under realistic traffic. Actual performance also depends on database access, network conditions, concurrency, compression, and hosting infrastructure.
Common Mistakes That Make Serialization Slower
Mistake | Why It Causes Problems | Recommended Approach |
|---|---|---|
Returning complete database entities | Serializes unnecessary properties and relationships | Use dedicated response DTOs |
Returning thousands of records at once | Increases memory usage and response size | Use pagination or streaming |
Performing database calls inside custom converters | Adds external work during serialization | Prepare data before serialization |
Serializing the same object repeatedly | Performs unnecessary conversion work | Review logging, caching, and response generation |
Enabling reference preservation unnecessarily | Changes response structure and adds metadata | Use explicit response models |
Assuming all API delay is database-related | Can hide serialization and network bottlenecks | Measure individual request stages |
Adding compression without measurement | May increase CPU usage | Benchmark compression with real payloads |
A Practical Troubleshooting Approach
When an API response is slower than expected, follow a structured investigation rather than immediately changing serializer settings.
Measure total API request duration and identify the slow endpoints.
Measure database execution time separately.
Measure object mapping and response preparation time.
Inspect the response size and the number of serialized objects.
Profile CPU usage and memory allocations during response generation.
Review custom converters, nested object relationships, and repeated serialization.
Compare the existing response model with a smaller DTO.
Test changes using realistic data and concurrent requests.
This process helps identify whether serialization is the actual bottleneck and prevents unnecessary changes to otherwise healthy API code.
Summary
Slow JSON serialization can affect ASP.NET Core API performance even when database queries execute quickly. Large response models, deeply nested objects, circular references, custom converters, and repeated serialization can increase CPU usage, memory allocation, and response preparation time.
The first step should always be measurement. Use request instrumentation, profiling, and controlled benchmarks to understand where the application spends its time. Then reduce unnecessary response data, use dedicated DTOs, avoid expensive serialization logic, and consider pagination or streaming for large collections.
System.Text.Json provides useful configuration options, but changing serializer settings without measuring their impact can introduce complexity without solving the real problem.
A well-designed API returns only the information clients need, measures expensive processing stages, and keeps serialization separate from database and business operations. This makes response performance easier to understand and maintain as application traffic and data volumes grow.


Join the conversation! Your thoughts help the community grow.