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.
Join the conversation! Your thoughts help the community grow.