Why Performance Matters
API performance directly impacts user experience and business metrics. Studies show that every 100ms of latency costs 1% in sales. This guide covers advanced techniques to make your .NET Core APIs blazingly fast.
Baseline: Measuring Performance
Before optimizing, establish baselines. Key metrics to track:
- Response Time: P50, P95, P99 latencies
- Throughput: Requests per second
- Resource Usage: CPU, memory, database connections
Database Optimization
1. Use Async/Await Correctly
// Bad - blocks thread
var data = dbContext.Users.ToList();
// Good - frees thread during I/O
var data = await dbContext.Users.ToListAsync();2. Optimize Queries
- Use
AsNoTracking()for read-only queries - Select only needed columns with projections
- Avoid N+1 queries with proper includes
- Use compiled queries for repeated operations
3. Connection Pooling
Ensure proper connection pool configuration. Default of 100 connections may be too low for high-traffic applications.
Caching Strategies
In-Memory Caching
Use IMemoryCache for frequently accessed, small datasets:
public async Task<User> GetUserAsync(int id)
{
return await _cache.GetOrCreateAsync($"user_{id}", async entry => {
entry.SlidingExpiration = TimeSpan.FromMinutes(5);
return await _dbContext.Users.FindAsync(id);
});
}Distributed Caching
For multi-instance deployments, use Redis or SQL Server distributed cache.
Response Caching
Use response caching middleware for GET requests that don't change frequently.
Serialization Optimization
System.Text.Json is faster than Newtonsoft.Json. Further optimize with source generators:
[JsonSerializable(typeof(User))]
public partial class UserContext : JsonSerializerContext { }Compression
Enable response compression for text-based content. Brotli offers better compression than gzip with modern clients.
HTTP/2 and Connection Reuse
Enable HTTP/2 for multiplexing. Use HttpClientFactory for proper connection management with external services.
Results
Applying these techniques to a real-world API achieved:
- P95 latency reduced from 450ms to 45ms (10x improvement)
- Throughput increased from 500 to 3000 requests/second
- Server count reduced from 8 to 3 instances
Conclusion
Performance optimization is about making informed decisions based on profiling data. Start with the biggest bottlenecks (usually database queries) and work your way through systematic improvements.