ASP.NET Core

ASP.NET Core Backend & Web API Performance Optimization (.NET 8):
20 C# and SQL Techniques

Practical guidance for Kestrel, async code, SQL Server, caching, memory allocation, serialization and diagnostics.

June 2026 • 20 min read • By Kshitij Mehta

ASP.NET Core performance work starts by measuring the request path and finding the component that consumes the most time or resources. For a .NET 8 Web API, examine application code, SQL Server, network calls, serialization, memory allocation and hosting behavior before changing implementation details.

Performance problems can come from inefficient database access, blocking work, excessive allocations, unnecessary network calls or cache behavior. The techniques below are investigation and design patterns; the appropriate result depends on the application and its measured workload.

The guide focuses on backend engineering for APIs and business systems. It contains 20 distinct techniques and does not report measured performance results for a customer deployment.

Key Takeaways
  • Identify performance bottlenecks before optimizing code.
  • Reduce SQL Server round trips and optimize database queries.
  • Use Dapper strategically for high-performance read operations.
  • Implement effective caching and asynchronous programming.
  • Validate every optimization against representative measurements.

1. Measure Before You Optimize

One of the biggest mistakes developers make is optimizing code without first identifying where the actual bottleneck exists. Performance tuning should always begin with measurement rather than assumptions.

A profiler may show that a request spends most of its time waiting on SQL Server or an external API rather than executing C# code. Measure the dependency and application spans before optimizing a loop or LINQ query.

Before making any code changes, collect performance data using tools such as:

  • Visual Studio Performance Profiler
  • BenchmarkDotNet
  • dotnet-counters
  • dotnet-trace
  • Application Insights
  • SQL Server Query Store
Pro Tip

Always optimize the slowest component first. Improving a small in-process method will not compensate for a database or network dependency that dominates the request duration.


2. Reduce Database Round Trips

In many enterprise ASP.NET Core applications, SQL Server is the primary contributor to request latency. Inefficient queries, unnecessary database round trips, missing indexes, and poor execution plans often have a far greater impact on performance than the application code itself. Every additional database call increases network overhead, connection usage, serialization time, and overall response time.

Consider an API that displays customer information.

Get Customer
                    ↓
                    Get Orders
                    ↓
                    Get Address
                    ↓
                    Get Payments
                    ↓
                    Get Shipment History
                

This approach requires five separate database calls for a single request.

A better approach is to retrieve the required information using one optimized query or a small number of carefully designed queries.

Real World Experience

If a request loads related data through several sequential queries, inspect the execution plan and consider a join, projection, batch or small number of carefully designed queries. Compare query count, database duration, returned rows and application allocations before and after; this article does not claim a measured customer result.


3. Use Dapper for High-Performance Read Operations

Entity Framework Core can simplify entity-oriented application work. Dapper offers explicit SQL and direct mapping with a smaller ORM feature surface. Which approach performs better depends on the query, database plan, result shape and application code; measure before switching.

Dapper maps result rows to C# objects without EF Core’s change tracker. Mapping work and allocations still depend on the query and result size.

using (var connection = new SqlConnection(connectionString))
                {
                    var orders = await connection.QueryAsync<Order>(
                "SELECT Id, CustomerName, Status FROM Orders");
                }

Many successful enterprise systems use a hybrid approach:

  • Entity Framework Core for complex write operations.
  • Dapper for reporting and high-performance read APIs.
Recommendation

Some applications use EF Core for domain workflows and Dapper for specific queries that benefit from explicit SQL. Keep both behind clear boundaries and select based on maintainability and measurements for the workload.


4. Select Only the Columns You Need

One of the simplest ways to improve application performance is to avoid using SELECT *.

Retrieving unnecessary columns increases:

  • Database I/O
  • Network traffic
  • Memory usage
  • JSON serialization time
-- Avoid
                SELECT *
                FROM Orders
                
-- Better
                SELECT
                        OrderId,
                        CustomerName,
                        Status,
                        CreatedDate
                FROM Orders
                

Returning only required fields reduces unnecessary database, network and serialization work, especially when the same endpoint is called often.


5. Database Indexing Matters More Than Most Code Changes

Many developers immediately begin optimizing C# code while ignoring the execution plan generated by SQL Server.

A missing index can turn a query that executes in milliseconds into one that takes several seconds.

Regularly review:

  • Execution Plans
  • Missing Index Recommendations
  • Table Scans
  • Index Fragmentation
  • Query Store Reports
Important

Never add indexes blindly. Every index improves reads but also adds overhead to INSERT, UPDATE, and DELETE operations. Always evaluate indexes using production-like workloads.


6. Use Asynchronous Programming Correctly

ASP.NET Core was designed around asynchronous I/O. Every request that waits on SQL Server, a REST API, cloud storage, or the file system should be asynchronous.

Synchronous database calls block valuable thread pool threads. Under heavy traffic, this leads to thread starvation, increased response times, and reduced throughput.

public async Task<Order> GetOrder(int id)
                {
                return await _repository.GetOrderAsync(id);
                }

Avoid using .Result or .Wait() inside ASP.NET Core applications. They can reduce scalability and may introduce deadlocks in certain environments.

When blocking calls accumulate, ThreadPool starvation can appear as rising thread counts and queued work while CPU usage stays below full utilization. Check runtime counters and traces before changing thread pool settings; see Microsoft’s thread-pool starvation diagnostics.


7. Cache Data That Rarely Changes

A cache can avoid repeating an expensive lookup when the data remains valid for a defined period.

Reference data and configuration may change less often than the transactions that consume them, but the appropriate expiration depends on the business freshness requirement.

Examples include:

  • Countries
  • States
  • Shipping carriers
  • Tax rates
  • Configuration settings
  • Product categories
var countries = await _memoryCache.GetOrCreateAsync(
                "Countries",
                async entry =>
                    {
                        entry.AbsoluteExpirationRelativeToNow =
                TimeSpan.FromHours(12);

                return await repository.GetCountriesAsync();
                    });

Define freshness and invalidation behavior before adding a cache. IMemoryCache is local to a process; use a distributed cache such as Redis when application instances must share entries. HybridCache was introduced in .NET 9, so .NET 8 projects need a compatible package or another abstraction rather than assuming it is built into the runtime. See the official .NET caching guidance.


8. Enable Response Compression

APIs often return large JSON payloads. Compressing these responses reduces bandwidth consumption and improves page load times.

ASP.NET Core supports both Gzip and Brotli compression.

The amount of compression depends on the payload and content type. Measure representative responses before estimating bandwidth or latency changes.

Enterprise Tip

Smaller responses not only improve user experience but also lower bandwidth costs for cloud-hosted applications.


9. Reduce JSON Serialization Overhead

Returning an entire Entity Framework entity often sends significantly more data than the client actually requires.

Instead, create lightweight DTOs containing only the required properties.

public class OrderSummaryDto
                {
                public int OrderId { get; set; }
                public string CustomerName { get; set; }
                public string Status { get; set; }
                }

Smaller JSON objects reduce:

  • Serialization time
  • Memory allocation
  • Network traffic
  • Browser parsing time

10. Let SQL Connection Pooling Work for You

Opening SQL Server connections is relatively expensive. Fortunately, ADO.NET automatically manages a connection pool for each unique connection string.

Always create connections as late as possible and dispose them as soon as you're finished.

using var connection =
                new SqlConnection(connectionString);

                await connection.OpenAsync();

Never keep connections open longer than necessary.


11. Move Long Running Work to Background Services

Users should never wait while your application generates PDFs, sends emails, synchronizes shipments, or processes large imports.

Instead, return a response immediately and process heavy workloads using background services.

Good candidates include:

  • Email notifications
  • Invoice generation
  • Shipping label creation
  • Import/export processing
  • Scheduled maintenance jobs
Real-World Benefit

Moving long-running tasks to background services improves perceived application speed while increasing the number of requests your API can process concurrently.


12. Reduce Memory Allocations

Profile allocation hot spots before introducing lower-level memory code. For synchronous parsing or buffer operations, Span<T> and ReadOnlySpan<T> can process slices without creating intermediate arrays or strings; use Memory<T> when a buffer must cross an asynchronous boundary. Keep lifetime and ownership rules in view.

Common improvements include:

  • Reuse objects where practical.
  • Avoid unnecessary string concatenation.
  • Use StringBuilder for repeated string operations.
  • Return lightweight DTOs instead of large entity graphs.
  • Avoid loading unnecessary collections into memory.

Compare allocated bytes, garbage-collection activity and latency under the same workload before and after a memory change. See Microsoft’s Memory<T> and Span<T> usage guidance.


13. Optimize LINQ Queries

LINQ is one of the most productive features of C#, but poorly written queries can become expensive when working with large collections or databases.

Keep LINQ expressions simple and allow Entity Framework Core to translate them into efficient SQL. Avoid loading unnecessary records into memory before filtering.

// Less efficient
                    var activeCustomers = context.Customers
                        .ToList()
                        .Where(c => c.IsActive);

                // Better
                    var activeCustomers = await context.Customers
                        .Where(c => c.IsActive)
                        .ToListAsync();
Best Practice

Always filter data inside SQL Server whenever possible rather than retrieving all records and filtering them in memory.

For a frequently executed, fixed EF Core query shape, a compiled query can skip part of the normal query-cache lookup. It is a targeted option for a measured hot path, not a replacement for efficient SQL, suitable indexes or projection.

private static readonly Func<AppDbContext, int, IAsyncEnumerable<OrderSummary>> OrdersForCustomer =
    EF.CompileAsyncQuery((AppDbContext db, int customerId) =>
        db.Orders
            .AsNoTracking()
            .Where(order => order.CustomerId == customerId)
            .OrderBy(order => order.Id)
            .Select(order => new OrderSummary(order.Id, order.Status)));

await foreach (var order in OrdersForCustomer(context, customerId))
{
    Process(order);
}

Keep parameters scalar and the query shape stable, then benchmark it with the application's actual provider and database workload. See the official EF Core compiled-query guidance for its limitations and measurement examples.


14. Optimize SQL Queries

The fastest ASP.NET Core API cannot compensate for slow SQL queries. SQL Server should always be included in your performance optimization strategy.

Review execution plans regularly and identify expensive operations such as table scans, missing indexes, implicit conversions, and key lookups.

  • Review execution plans.
  • Keep statistics updated.
  • Avoid unnecessary SELECT * statements.
  • Index frequently filtered columns.
  • Return only required data.

15. Implement Server-Side Pagination

Returning thousands of rows to a web browser wastes memory, bandwidth, and processing time.

Every large data grid should support:

  • Pagination
  • Sorting
  • Searching
  • Filtering
var orders = await context.Orders
                    .OrderByDescending(x => x.OrderDate)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

Server-side pagination dramatically reduces response sizes and keeps applications responsive as databases grow.


16. Design Lightweight APIs

Modern APIs should return only the information the client actually needs. Avoid exposing entire entity graphs or deeply nested objects.

Smaller payloads improve:

  • Serialization speed
  • Network transfer
  • Browser rendering
  • Mobile performance

17. Log Smartly, Not Excessively

Logging is essential for diagnosing production issues, but excessive logging can reduce performance and generate unnecessary storage costs.

Follow these guidelines:

  • Use Information logs for important business events.
  • Use Warning logs for recoverable issues.
  • Use Error logs for failures.
  • Avoid logging every successful database call.
  • Never log sensitive customer information.

18. Monitor Production Continuously

Performance tuning doesn't stop after deployment. Production monitoring helps identify slow endpoints, SQL bottlenecks, memory leaks, and unexpected spikes in traffic before they affect users.

Useful metrics include:

  • Average response time
  • 95th percentile response time
  • Error rate
  • SQL execution time
  • CPU utilization
  • Memory usage

19. Load Test Before Production

A low-concurrency test can miss bottlenecks that appear under the expected production concurrency. Define a realistic workload and increase concurrency gradually while monitoring queueing, failures and resource use.

Simulate realistic workloads using tools such as:

  • k6
  • Apache JMeter
  • Azure Load Testing

Load testing reveals scalability issues long before customers discover them.


20. Review Kestrel and hosting limits

Kestrel settings affect request handling, connection timeouts, request body limits and synchronous I/O. Keep defaults unless measurements or a documented requirement justify a change; overly permissive limits can create resource and security risks.

  • Prefer asynchronous request and response I/O; avoid blocking calls that can starve the thread pool.
  • Set request size, connection and timeout policies to match the API contract.
  • Check whether compression and caching are handled by the reverse proxy or application.
  • Test under representative load and inspect Kestrel, thread-pool and dependency metrics before tuning.

Review the official Kestrel options and ASP.NET Core performance guidance for the hosting version in use.


These 20 techniques form the foundation of high-performance ASP.NET Core applications. Start with measurement, address the biggest bottlenecks first, and iterate.

About the Author

Kshitij Mehta writes about ASP.NET Core, C#, SQL Server and enterprise application development.

For related implementation work, see ERP integration services and shipping software development. For a workload example involving manufacturing orders, production planning and inventory, see the Enerlux ERP case study.