High CPU usage is one of the most common performance problems in production .NET applications. When an ASP.NET Core application consumes more CPU than expected, API response times may increase, background jobs may take longer to complete, and the application may become unresponsive under heavy traffic.
The difficult part is identifying which part of the application is consuming CPU resources. A high CPU reading does not necessarily mean that the entire application is inefficient. One endpoint, background service, database-related operation, or frequently executed method may be responsible for most of the consumption.
For example, an API may normally respond within 100 milliseconds but suddenly take several seconds when multiple users access it. The application may also consume nearly all the CPU resources allocated to its container.
Restarting the application might temporarily improve performance, but it does not solve the underlying problem.
In this article, we will explore how to identify high CPU usage in a production .NET application, collect performance data, analyze CPU profiles, and optimize the code responsible for excessive CPU consumption.
Understanding High CPU Usage in .NET
CPU usage represents how much processing time an application consumes on the available processor resources.
A .NET application uses CPU resources for several operations, including:
- Executing business logic and calculations.
- Processing HTTP requests and responses.
- Serializing and deserializing JSON.
- Running LINQ queries and collection operations.
- Performing encryption and compression.
- Executing background jobs.
- Running garbage collection and runtime operations.
- Processing regular expressions and text transformations.
High CPU usage becomes a problem when the application continuously consumes most of its available CPU capacity or uses more processing resources than expected for its workload.
It is important to understand that high CPU usage is not always a sign of defective code. A sudden increase in incoming requests, a legitimate increase in background processing, or a change in workload can also increase CPU consumption.
The first objective is to determine whether the CPU usage is expected for the current workload. If it is not, the next step is to identify the methods responsible.
Common Causes of High CPU Usage
Several coding patterns and application behaviors can cause excessive CPU consumption.
Inefficient Loops and Repeated Calculations
Repeated calculations inside loops can waste CPU resources, especially when processing large collections.
Consider the following example:
public List<Order> GetActiveOrders(
List<Order> orders)
{
var result = new List<Order>();
foreach (var order in orders)
{
if (orders.Count(x => x.CustomerId == order.CustomerId) > 5
&& order.IsActive)
{
result.Add(order);
}
}
return result;
}
The Count operation runs repeatedly for each order. If the collection contains thousands of records, the application performs many unnecessary comparisons.
A better approach is to calculate the required counts once:
public List<Order> GetActiveOrders(
List<Order> orders)
{
var customerOrderCounts = orders
.GroupBy(x => x.CustomerId)
.ToDictionary(
group => group.Key,
group => group.Count());
return orders
.Where(order =>
order.IsActive &&
customerOrderCounts[order.CustomerId] > 5)
.ToList();
}
This avoids repeatedly scanning the complete collection. The grouping operation requires additional memory, so the best approach should still be evaluated against the actual data size and workload.
Expensive LINQ Operations
LINQ makes application code easier to read, but repeated filtering, sorting, grouping, and materialization can increase CPU consumption.
For example:
var activeCustomers = customers
.Where(x => x.IsActive)
.OrderBy(x => x.Name)
.ToList();
var customerNames = activeCustomers
.Select(x => x.Name.ToUpperInvariant())
.ToList();
This code performs several collection operations and creates intermediate data.
For small collections, this is generally acceptable. For large collections processed frequently, measure the cost and consider reducing unnecessary transformations.
Do not replace readable LINQ code with complicated loops without profiling. Optimization should be based on measured performance rather than assumptions.
Inefficient JSON Serialization
ASP.NET Core applications frequently serialize objects into JSON responses.
Large response objects, deeply nested structures, custom converters, and repeated serialization can consume significant CPU resources.
For example, returning an entire entity graph when an API needs only a few fields creates unnecessary processing.
Instead, select the required data:
public async Task<List<CustomerResponse>> GetCustomersAsync(
AppDbContext dbContext,
CancellationToken cancellationToken)
{
return await dbContext.Customers
.AsNoTracking()
.Select(customer => new CustomerResponse
{
Id = customer.Id,
Name = customer.Name,
Email = customer.Email
})
.ToListAsync(cancellationToken);
}
The application retrieves and serializes only the required fields.
This can reduce database materialization, object creation, and JSON serialization work.
Expensive Regular Expressions
Regular expressions can become expensive when patterns are complex or when they process large input strings repeatedly.
For example, a poorly designed pattern can cause excessive backtracking on certain inputs.
When using regular expressions:
- Avoid unnecessarily complex patterns.
- Set a timeout for patterns that process untrusted input.
- Reuse compiled or generated regular expressions when appropriate.
- Test patterns against large and unexpected input values.
For frequently used patterns in modern .NET applications, source-generated regular expressions can improve performance and provide compile-time validation.
using System.Text.RegularExpressions;
public partial class EmailValidator
{
[GeneratedRegex(
@"^[^@\s]+@[^@\s]+\.[^@\s]+$")]
private static partial Regex EmailPattern();
public bool IsValid(string email)
{
return EmailPattern().IsMatch(email);
}
}
This example demonstrates source-generated regular expressions. It is a basic validation pattern, not a complete implementation of every valid email address format.
Monitor CPU Usage With dotnet-counters
Before changing application code, collect runtime metrics to confirm that CPU consumption is actually increasing.
The dotnet-counters tool is useful for first-level performance monitoring.
Install it using the following command:
dotnet tool install --global dotnet-counters
Find the running .NET application:
dotnet-counters ps
Start monitoring the target process:
dotnet-counters monitor --process-id 12345
Replace 12345 with the actual process ID.
The tool displays runtime counters that help you understand application behavior.
Important metrics include:
| Metric | Purpose |
|---|
| dotnet.process.cpu.time | Measures CPU time consumed by the process |
| dotnet.cpu.time | Runtime CPU time metric where available |
| dotnet.gc.collections | Shows garbage collection activity |
| dotnet.gc.heap.total_allocated | Shows cumulative managed memory allocation |
| dotnet.thread_pool.thread.count | Shows the number of Thread Pool threads |
| dotnet.exceptions | Helps identify exception activity |
The exact counter names and available metrics can vary by .NET runtime and diagnostic tool version.
CPU time is a cumulative measurement, so compare its change over time rather than treating it as a percentage. Process CPU utilization and operating system or container CPU metrics provide additional context.
For example, if CPU usage increases whenever a particular API endpoint receives requests, investigate that endpoint and its dependencies.
If CPU consumption remains high even when request traffic is low, background services, scheduled jobs, or runtime activity may be responsible.
Find CPU-Intensive Methods With dotnet-trace
Runtime counters can confirm that CPU consumption is high, but they cannot reliably tell you which application method is responsible.
For that, use dotnet-trace.
Install the tool:
dotnet tool install --global dotnet-trace
Collect a trace from the running application:
dotnet-trace collect --process-id 12345
The command collects runtime events and CPU samples. It generates a .nettrace file that can be analyzed using supported performance tools.
For example, you can open the trace in Visual Studio or PerfView and inspect CPU usage call stacks.
The important areas to examine are:
- Methods with high CPU sample counts.
- Methods that repeatedly appear in hot call stacks.
- Expensive application-level loops.
- Serialization and deserialization operations.
- Regular expression processing.
- Garbage collection activity.
- Repeated execution of the same business logic.
A method that appears frequently in a CPU profile is worth investigating, but it is not automatically the root cause. Check how much CPU time it consumes and whether it is responsible for useful work or unnecessary repeated processing.
Understand Inclusive and Exclusive CPU Time
When analyzing a CPU profile, two concepts are particularly useful.
Inclusive CPU time represents the CPU time consumed by a method and the methods it calls.
Exclusive CPU time represents the CPU time spent executing the method itself, excluding its child methods.
For example, suppose an API endpoint calls a service, and the service calls a JSON serializer.
The endpoint may have high inclusive CPU time because its entire execution path is expensive. However, the serializer may have most of the exclusive CPU time.
This distinction helps identify whether the problem belongs to the API endpoint, a business service, or a lower-level operation.
Use Platform-Specific Profiling Tools
The profiling approach can vary depending on where the application runs.
Windows Applications
For applications running on Windows, Visual Studio Performance Profiler and PerfView can help analyze CPU usage.
Visual Studio provides a CPU Usage profiler that can identify methods consuming significant processing time.
You can also open a previously collected .nettrace file in Visual Studio and inspect the CPU usage call tree.
For production applications, collecting a trace from the affected process is often more practical than attaching a debugger.
Linux and Containerized Applications
For Linux applications, the Linux perf tool provides operating-system-level profiling capabilities.
For applications running on .NET 10 or later, dotnet-trace collect-linux can combine runtime events with Linux performance events to provide managed and native call stacks.
A typical collection command is:
sudo dotnet-trace collect-linux
This approach has additional system requirements, including suitable Linux kernel support, permissions, and configuration. Review the environment requirements before using it in production.
For containerized applications, also inspect the CPU limits configured for the container. An application may use a high percentage of its allocated CPU quota even when the underlying host has additional unused CPU capacity.
A Practical Example: Finding an Expensive Operation
Consider an ASP.NET Core API that calculates a summary for every customer.
app.MapGet("/customer-summary", (
AppDbContext dbContext) =>
{
var customers = dbContext.Customers.ToList();
var summaries = customers.Select(customer =>
{
var orders = dbContext.Orders
.Where(order =>
order.CustomerId == customer.Id)
.ToList();
return new
{
customer.Id,
customer.Name,
TotalOrders = orders.Count
};
});
return Results.Ok(summaries);
});
This example has two important problems.
First, it uses synchronous database operations in an API request. Second, it performs a separate database query for every customer.
When the number of customers increases, the application performs many database queries and repeatedly materializes collections.
The CPU profile may show significant time spent in query execution, object materialization, and response processing. Database monitoring may also reveal that the database is doing unnecessary work.
A better implementation calculates the order counts in a grouped query:
app.MapGet("/customer-summary", async (
AppDbContext dbContext,
CancellationToken cancellationToken) =>
{
var summaries = await dbContext.Customers
.Select(customer => new
{
customer.Id,
customer.Name,
TotalOrders = dbContext.Orders.Count(
order => order.CustomerId == customer.Id)
})
.ToListAsync(cancellationToken);
return Results.Ok(summaries);
});
Depending on the database provider and generated SQL, this can be translated into a database-side query instead of loading every customer's orders separately.
For very large datasets, inspect the generated SQL and execution plan, and consider grouping orders before joining them to customers.
This example also illustrates why CPU profiling should be combined with database performance analysis. A slow API may involve both application processing and database execution.
Distinguish High CPU Usage From Other Performance Problems
Not every slow API is caused by CPU consumption.
It is important to distinguish CPU saturation from other bottlenecks.
| Problem | Typical symptoms | What to investigate |
|---|
| High CPU usage | High processor utilization and expensive execution paths | CPU profiles and hot methods |
| Thread Pool starvation | Increasing latency, queued work, and blocked threads | Thread Pool counters and thread stacks |
| Slow database | Long database queries and increased request latency | Query plans and database metrics |
| Memory pressure | Frequent garbage collection and allocation activity | GC counters and memory profiles |
| Lock contention | Threads waiting for shared resources | Lock contention metrics and traces |
| External service delays | Requests waiting for HTTP or other dependencies | Dependency tracing and network timing |
For example, a slow database query may increase request latency without consuming much CPU in the ASP.NET Core process.
Similarly, Thread Pool starvation can occur when worker threads are blocked, even if CPU usage remains moderate.
Always correlate CPU measurements with request latency, dependency timings, Thread Pool metrics, and memory behavior.
Best Practices for Reducing CPU Consumption
After identifying the expensive methods, apply targeted optimizations.
- Profile before optimizing. Use actual production or production-like traces to identify expensive methods instead of guessing.
- Avoid unnecessary collection processing. Reduce repeated filtering, sorting, grouping, and materialization.
- Optimize database queries. Retrieve only required columns and avoid unnecessary data loading.
- Reduce serialization overhead. Return smaller response objects and avoid repeatedly serializing the same data.
- Review regular expressions. Avoid expensive patterns and use timeouts for untrusted input.
- Cache expensive calculations when the data and invalidation requirements allow it.
- Avoid unnecessary object creation. Excessive allocations can increase garbage collection work.
- Move independent long-running processing out of HTTP request execution when appropriate.
- Apply concurrency limits to protect CPU-intensive operations from overwhelming the application.
- Monitor CPU usage after deployment to confirm that the optimization improves the actual workload.
Moving work to a background service does not eliminate its CPU cost. It changes where and when the work executes. Background processing should still use bounded queues and suitable concurrency limits.
Common Mistakes During CPU Troubleshooting
Several approaches can make performance investigations less effective.
Restarting Without Collecting Diagnostics
Restarting an application may temporarily reduce CPU usage, but it also removes the opportunity to inspect the process while the problem is occurring.
Collect runtime counters and a short CPU trace before restarting whenever the operational situation allows it.
Optimizing Code Without Profiling
Developers sometimes rewrite loops, replace LINQ expressions, or introduce caching based on assumptions.
These changes may add complexity without improving performance.
Identify the methods consuming the most CPU time before modifying them.
Ignoring Container CPU Limits
A container configured with a small CPU quota can reach its limit even when the host machine has plenty of available resources.
Check container CPU limits and throttling metrics alongside application-level CPU measurements.
Increasing the Number of Threads
Increasing Thread Pool threads is not a general solution for high CPU usage.
If the application is already CPU-bound, additional concurrent work can increase contention and reduce overall throughput.
Thread Pool starvation and CPU saturation are different problems and require different diagnostic approaches.
Collecting Excessively Long Traces
Large trace files can consume storage and make analysis difficult.
Collect a focused trace during the period when CPU usage is high. Protect trace files because they may contain application metadata and other sensitive diagnostic information.
Summary
High CPU usage in a production .NET application can result from inefficient algorithms, repeated collection processing, expensive serialization, regular expressions, background workloads, or other CPU-intensive operations.
Start by confirming the issue with dotnet-counters. Once high CPU usage is established, use dotnet-trace to collect a performance profile and inspect the methods responsible for the highest CPU consumption.
Combine CPU profiling with database monitoring, Thread Pool metrics, memory counters, and distributed tracing to distinguish CPU saturation from other performance bottlenecks.
The most effective optimization is the one supported by profiling evidence. Identify the expensive operation, improve its implementation, and measure the result under a realistic workload before deploying the change to production.
Join the conversation! Your thoughts help the community grow.