Performance is critical for modern APIs. A slow API leads to poor user experience and scalability issues. In this article, we will explore proven techniques to improve API performance in ASP.NET Core with real examples.
1. Use Asynchronous Programming
Always use async/await for I/O operations to avoid blocking threads.
[HttpGet]
public async Task GetUsers()
{
var users = await _context.Users.ToListAsync();
return Ok(users);
}
Benefit: Improves scalability and thread utilization.
2. Enable Response Caching
Caching reduces repeated processing and database calls.
[HttpGet]
[ResponseCache(Duration = 60)]
public IActionResult GetData()
{
return Ok("Cached Data");
}
Also enable in Program.cs:
builder.Services.AddResponseCaching();
app.UseResponseCaching();
3. Use In-Memory Caching
public class UserService
{
private readonly IMemoryCache _cache;
public UserService(IMemoryCache cache)
{
_cache = cache;
}
public async Task> GetUsers()
{
if (!_cache.TryGetValue("users", out List users))
{
users = await _context.Users.ToListAsync();
_cache.Set("users", users, TimeSpan.FromMinutes(5));
}
return users;
}
}
4. Optimize Database Queries
Use projection instead of fetching full entities.
var users = await _context.Users
.Select(u => new { u.Id, u.Name })
.ToListAsync();
Use AsNoTracking() for read-only queries:
var users = await _context.Users
.AsNoTracking()
.ToListAsync();
5. Use Pagination
[HttpGet]
public async Task GetUsers(int page = 1, int pageSize = 10)
{
var users = await _context.Users
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return Ok(users);
}
6. Enable Compression
Reduces response size.
builder.Services.AddResponseCompression();
app.UseResponseCompression();
7. Use Minimal APIs (Faster Execution)
app.MapGet("/users", async (AppDbContext db) =>
{
return await db.Users.ToListAsync();
});
8. Avoid Blocking Calls
❌ Bad Practice:
var data = _service.GetData().Result;✅ Good Practice:
var data = await _service.GetData();9. Use Connection Pooling
Configured automatically in EF Core, but ensure proper DB connection string usage.
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=TestDb;Trusted_Connection=True;Pooling=true;"
}
10. Use Logging & Monitoring
Use tools like Application Insights or Serilog.
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
11. Use Rate Limiting
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 100;
opt.Window = TimeSpan.FromMinutes(1);
});
});
app.UseRateLimiter();
12. Use Background Tasks for Heavy Work
Offload heavy tasks using background services.
public class BackgroundJob : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Background work
await Task.Delay(1000);
}
}
}
📌 Conclusion
Improving API performance in ASP.NET Core requires a combination of best practices:
- Use async programming
- Apply caching strategies
- Optimize database queries
- Enable compression
- Avoid unnecessary data processing
By applying these techniques, you can significantly improve your API speed, scalability, and user experience.
No comments:
Post a Comment