JSON serialization is an important part of almost every ASP.NET Core API. When a client sends a request, the application may deserialize JSON into a C# object. When the API returns a response, the application serializes that object into JSON before sending it to the client.
For small responses, this process is usually fast enough that developers rarely think about it. However, when an API returns thousands of records, deeply nested objects, or large collections, JSON serialization can become a noticeable performance bottleneck.
The challenge is identifying whether serialization is actually responsible for the delay. A slow API response can also be caused by database queries, object mapping, network transfer, response compression, or application logic.
In this article, we will explore how to identify slow JSON serialization in ASP.NET Core APIs and improve performance using practical techniques.
Understanding JSON Serialization in ASP.NET Core
ASP.NET Core uses System.Text.Json as its default JSON serializer in typical API scenarios. It converts C# objects into JSON when an API returns a response and converts incoming JSON into C# objects during request processing.
Consider a simple API endpoint:
app.MapGet("/customers", async (AppDbContext db) =>
{
var customers = await db.Customers.ToListAsync();
return Results.Ok(customers);
});
When this endpoint executes, several operations take place:
The application executes a database query.
Entity Framework Core materializes the returned records.
ASP.NET Core processes the response.
System.Text.Json serializes the objects into JSON.
The server sends the response to the client.
If the endpoint takes two seconds to respond, it does not automatically mean JSON serialization takes two seconds. The database query might be responsible for most of the delay.
Understanding these individual stages is the first step toward finding the actual bottleneck.
Common Causes of Slow JSON Serialization
JSON serialization performance depends on the size and structure of the response, the serializer configuration, and the types being serialized.
Returning Large Object Graphs
One common problem is returning complete Entity Framework Core entities directly from an API.
An entity might contain navigation properties for orders, addresses, payments, and other related records. Serializing the entire object graph can produce a much larger response than the client actually needs.
For example, a customer response might include hundreds of orders, and every order might contain additional product and payment information. Even when the client only needs a customer's name and email address, the serializer may have to process all those additional properties.
This increases memory usage, serialization work, and response size.
Circular References
Entity relationships can create circular references. For example, a customer can contain a collection of orders, while every order contains a reference back to its customer.
This creates a cycle:
Customer → Orders → Customer
System.Text.Json does not automatically serialize circular references as an unlimited object graph. Depending on the configuration, serialization can fail when a cycle is detected.
Developers sometimes configure reference handling to work around this issue. However, the better solution for most API responses is to avoid returning unnecessary entity relationships.
Expensive Custom Converters
Custom JSON converters allow developers to control how specific types are serialized and deserialized.
However, a converter that performs database lookups, complex calculations, repeated string operations, or unnecessary object creation can increase serialization time.
A converter should focus on converting values. Business operations and database access should remain outside the serialization process.
Repeated Serializer Configuration
Creating new JsonSerializerOptions instances for every request can introduce unnecessary overhead, especially when an application repeatedly performs manual serialization.
JsonSerializerOptions caches metadata and should generally be reused after configuration. ASP.NET Core's built-in JSON configuration also manages serializer options for the application.
Large Response Payloads
A response containing thousands of records or large text fields requires more serialization work than a small response.
Large payloads also take longer to transfer over the network. These are separate performance costs, even though they can appear together as a slow API response.
Measure Serialization Performance Before Optimizing
Before changing the application, identify where the time is being spent.
A useful performance investigation should measure the following areas:
Area | What to measure | Possible problem |
|---|
Database | Query execution duration | Slow SQL query or missing index |
Object mapping | Time required to create response objects | Expensive mapping logic |
Serialization | Time required to generate JSON | Large object graph or expensive converter |
Response size | Number of bytes returned | Oversized payload |
Network | Client-observed transfer duration | Bandwidth or network latency |
You can use the Visual Studio profiler, dotnet-counters, and dotnet-trace to investigate runtime behavior.
For example, dotnet-trace can collect runtime traces from a running application:
dotnet-trace collect --process-id <PID>
Replace PID with the process ID of the ASP.NET Core application.
When analyzing CPU call stacks, look for System.Text.Json methods and related serialization activity. If serialization methods consume a significant amount of CPU during a representative workload, investigate the response models and serializer configuration.
You should also compare API response sizes and request durations using an HTTP client or browser developer tools.
Measure Serialization in an Isolated Test
For a focused diagnostic test, you can measure serialization separately from database operations and network transfer.
var customers = await db.Customers
.AsNoTracking()
.ToListAsync();
var stopwatch = Stopwatch.StartNew();
var json = JsonSerializer.Serialize(customers);
stopwatch.Stop();
Console.WriteLine(
$"Serialization time: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine(
$"JSON size: {Encoding.UTF8.GetByteCount(json)} bytes");
This example measures serialization after the database query has completed. It is useful for comparing different response models with the same data.
However, it is not a complete measurement of ASP.NET Core response processing. It creates a JSON string in memory, whereas the framework normally writes response data through its HTTP output pipeline.
Use this approach in a controlled diagnostic environment rather than adding Stopwatch measurements to every production request.
Use DTOs Instead of Returning Complete Entities
One of the most effective ways to reduce serialization overhead is to return only the data required by the client.
Instead of returning an entire database entity, define a response DTO.
public sealed record CustomerResponse(
int Id,
string Name,
string Email);
Now project the database records directly into the response type.
app.MapGet("/customers", async (
AppDbContext db,
CancellationToken ct) =>
{
var customers = await db.Customers
.AsNoTracking()
.Select(c => new CustomerResponse(
c.Id,
c.Name,
c.Email))
.ToListAsync(ct);
return Results.Ok(customers);
});
This approach provides several benefits.
First, the API returns only the properties needed by the client. Second, Entity Framework Core can generate a query that selects only the required columns. Third, the serializer processes a smaller and simpler object structure.
It also prevents accidental exposure of internal database properties.
DTO projection is especially useful for APIs that return related entities, such as customer dashboards, order histories, and administrative reports.
Reuse JsonSerializerOptions
When an application manually serializes JSON, avoid creating new serializer options for every operation.
For example, this pattern introduces unnecessary repeated configuration:
public string ConvertToJson(CustomerResponse customer)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy =
JsonNamingPolicy.CamelCase
};
return JsonSerializer.Serialize(customer, options);
}
A better approach is to configure the options once and reuse them.
public static class JsonConfiguration
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNamingPolicy =
JsonNamingPolicy.CamelCase
};
}
Then use the shared options:
var json = JsonSerializer.Serialize(
customer,
JsonConfiguration.Options);
For ASP.NET Core applications, configure the framework's JSON options during application startup instead of manually serializing every response.
For Minimal APIs, use ConfigureHttpJsonOptions:
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.PropertyNamingPolicy =
JsonNamingPolicy.CamelCase;
});
For MVC controllers, use AddJsonOptions:
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy =
JsonNamingPolicy.CamelCase;
});
These are different configuration entry points. Choose the one that matches the API programming model used by your application.
Use System.Text.Json Source Generation
System.Text.Json normally collects serialization metadata at runtime using reflection. This metadata is cached, but the initial collection still requires time and memory.
Source generation moves metadata collection to compile time. It can reduce runtime reflection work, improve startup characteristics, and support applications with trimming or Native AOT requirements.
Create a source-generated JSON context:
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(List<CustomerResponse>))]
internal partial class ApiJsonContext : JsonSerializerContext
{
}
For a Minimal API application, register the generated context with the HTTP JSON options:
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(
0,
ApiJsonContext.Default);
});
You can also use the generated type information directly when performing manual serialization:
var json = JsonSerializer.Serialize(
customer,
ApiJsonContext.Default.CustomerResponse);
Source generation supports metadata-based serialization and an optimized serialization mode. The optimized mode can improve serialization throughput for supported types and configurations, but it does not support every serializer feature.
For example, custom converters and some advanced options can prevent the optimized path from being used. Test the generated configuration with your actual response models before expecting a performance improvement.
Source generation is particularly useful for applications with known response types, high serialization workloads, or Native AOT requirements. It does not solve problems caused by unnecessarily large response payloads.
Handle Circular References Carefully
System.Text.Json provides reference-handling options for dealing with object graphs containing cycles.
For example:
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.ReferenceHandler =
ReferenceHandler.IgnoreCycles;
});
IgnoreCycles prevents circular references from causing serialization failures by writing null for properties that would create a cycle.
Another option is ReferenceHandler.Preserve. It maintains object references using additional JSON metadata such as $id and $ref.
However, Preserve changes the JSON response structure, which can affect clients expecting a conventional JSON contract.
Neither option should be the default solution for poorly designed API response models. DTOs with explicit properties provide better control over the response structure and usually avoid the need for reference handling.
Reduce Network Transfer With Response Compression
Sometimes an API appears slow because it returns a large JSON response over a limited network connection.
ASP.NET Core supports response compression using middleware. JSON responses can benefit from Brotli or Gzip compression when the client supports the corresponding encoding.
Register the middleware:
builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
The middleware should be placed early enough in the request pipeline to compress responses produced by later middleware and endpoints.
Compression can reduce the number of bytes transferred, but it does not make the JSON serializer itself faster. In fact, compression requires additional CPU resources.
For CPU-bound applications, measure the cost of compression before enabling aggressive compression settings. Also consider whether compression is already handled by your reverse proxy or hosting platform.
Common Mistakes to Avoid
Several implementation mistakes can make JSON serialization slower or make performance investigations misleading.
Mistake | Why it causes problems | Better approach |
|---|
Returning complete EF entities | Serializes unnecessary properties and relationships | Use DTO projection |
Returning unlimited collections | Creates large payloads | Add pagination and filtering |
Creating serializer options repeatedly | Repeats configuration work | Configure once and reuse |
Using expensive converters | Adds unnecessary CPU work | Keep converters lightweight |
Enabling Preserve without checking clients | Changes the JSON contract | Prefer explicit response models |
Using compression to fix CPU overhead | Adds compression work | Optimize serialization first |
Benchmarking only small objects | Does not represent production workloads | Test realistic response sizes |
Best Practices for Production ASP.NET Core APIs
For production applications, JSON serialization should be treated as one part of the complete API response pipeline.
Use DTOs to control response size and avoid exposing database entities directly. Apply pagination to endpoints that return large collections, and select only the database columns required by the client.
Configure JSON options once during application startup. Consider source generation when the application has stable response types or needs to reduce runtime reflection.
Keep custom converters simple and avoid performing database queries or business operations during serialization. Review nested properties carefully because a seemingly small response model can include a large object graph.
Finally, monitor request duration, response size, database execution time, and CPU usage together. A performance improvement in one area should be verified against the complete request lifecycle.
Advantages and Disadvantages of Serialization Optimization
Optimizing JSON serialization can improve API throughput, reduce CPU usage, lower memory pressure, and decrease response sizes when unnecessary properties are removed.
However, optimization also involves trade-offs. DTOs require additional response models and mapping decisions. Source generation introduces configuration and build-time requirements. Compression consumes CPU, while aggressive response changes can affect existing clients.
The best approach is to make improvements based on measurements rather than applying every available optimization.
Troubleshooting Slow JSON Serialization
When an API continues to return slow responses after basic optimization, investigate the following areas:
Check whether the response contains unexpected navigation properties or nested collections.
Compare the database query duration with the time required to generate the response.
Inspect custom converters, computed properties, and getters that perform expensive operations.
Check whether the first request is slower than subsequent requests because of metadata initialization.
Compare uncompressed and compressed response sizes and CPU usage.
Test the endpoint with realistic data volumes rather than a few sample records.
Review CPU profiles for System.Text.Json activity under representative load.
If serialization is not responsible for the delay, move the investigation to database execution, object mapping, middleware, or network transfer.
Summary
Slow JSON serialization can affect the performance of ASP.NET Core APIs, particularly when endpoints return large collections, complex object graphs, or unnecessary database relationships.
The first step is to measure the complete request pipeline and identify how much time is actually spent serializing JSON. Once the bottleneck is confirmed, use DTO projection, reusable serializer configuration, source generation, and appropriate response compression to improve performance.
Avoid returning complete Entity Framework Core entities, keep custom converters lightweight, and use pagination for large collections.
Most importantly, do not assume every slow API response is caused by JSON serialization. Measure database queries, serialization work, response size, and network transfer separately. This approach helps developers fix the actual problem instead of introducing optimizations that add complexity without improving application performance.
Join the conversation! Your thoughts help the community grow.