ASP.NET Core là framework hiện đại, open-source, cross-platform được thiết kế để xây dựng high-performance và scalable web applications. Từ microservices đến enterprise-grade APIs, kiến trúc của nó đảm bảo developers có thể đạt throughput xuất sắc, latency tối thiểu, và resource utilization hiệu quả.
Trong bài viết này, chúng ta sẽ khám phá các key strategies, configuration tips, và code snippets để maximize performance và scalability trong ASP.NET Core applications của bạn.
🚀 Hiểu Performance và Scalability
Trước khi đi vào implementation, định nghĩa hai concepts quan trọng:
Performance: Ứng dụng phản hồi một request nhanh như thế nào.
(Ví dụ: Giảm response time từ 300ms xuống 100ms).Scalability: Ứng dụng xử lý increased load tốt như thế nào.
(Ví dụ: Xử lý 10,000 concurrent users mà không crash).
ASP.NET Core đạt được cả hai thông qua efficient memory management, asynchronous programming, dependency injection, caching, và built-in support cho distributed systems.

⚙️ Sử dụng Asynchronous Programming
ASP.NET Core runtime được tối ưu cho asynchronous I/O operations. Bằng cách dùng async và await keywords, bạn có thể free up threads để handle nhiều requests concurrently.
✅ Ví dụ: Asynchronous Controller Action
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
private readonly IProductService _productService;
public ProductsController(IProductService productService) {
_productService = productService;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProductById(int id) {
var product = await _productService.GetProductAsync(id);
if (product == null) return NotFound();
return Ok(product);
}
}
Bằng cách dùng Task<IActionResult> , thread không block khi chờ I/O-bound operations như database queries hoặc API calls. Điều này dramatically improves scalability under heavy load.
🧩 Optimize Middleware Pipeline
Middleware components handle mỗi request sequentially. Giữ middleware lightweight và tránh unnecessary processing.
✅ Ví dụ: Custom Lightweight Middleware
public class RequestTimingMiddleware {
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger) {
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context) {
var start = DateTime.UtcNow;
await _next(context);
var elapsed = DateTime.UtcNow - start;
_logger.LogInformation($"Request took {elapsed.TotalMilliseconds} ms");
}
}
// Registration in Program.cs
app.UseMiddleware<RequestTimingMiddleware>();
👉 Tip :
Đặt lightweight middleware ở top (như routing hoặc compression), và heavy middleware (như authentication) thấp hơn trong pipeline.
⚡ Enable Response Caching
Caching giảm nhu cầu recompute results hoặc hit database liên tục. ASP.NET Core cung cấp built-in Response Caching Middleware .
✅ Ví dụ: Enable Response Caching
// In Program.cs
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseResponseCaching();
app.MapGet("/time", (HttpContext context) => {
context.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue() {
Public = true,
MaxAge = TimeSpan.FromSeconds(30)
};
return DateTime.UtcNow.ToString("T");
});
Bây giờ, subsequent requests trong 30 giây sẽ được served từ cache — drastically improving performance.
🧠 Optimize Data Access với EF Core
Database access thường là bottleneck chính. Dùng Entity Framework Core hiệu quả bằng cách áp dụng:
AsNoTracking() cho read-only queries
Compiled queries cho repeated access
Connection pooling
✅ Ví dụ: Sử dụng AsNoTracking()
public async Task<IEnumerable<Product>> GetAllProductsAsync() {
return await _context.Products
.AsNoTracking() // Cải thiện performance
.ToListAsync();
}
Nếu bạn thường chạy similar queries, cân nhắc compiled queries :
private static readonly Func<AppDbContext, int, Task<Product?>> _getProductById = EF.CompileAsyncQuery((AppDbContext context, int id) => context.Products.FirstOrDefault(p => p.Id == id));
public Task<Product?> GetProductAsync(int id) => _getProductById(_context, id);
🧰 Sử dụng Output Compression
Nén responses trước khi gửi đến client giảm bandwidth usage và tăng tốc delivery.
✅ Ví dụ: Enable Response Compression
// In Program.cs
builder.Services.AddResponseCompression(options => {
options.EnableForHttps = true;
options.MimeTypes = new[] { "text/plain", "application/json" };
});
var app = builder.Build();
app.UseResponseCompression();
Bây giờ tất cả application/json responses sẽ tự động GZIP-compressed.
🌍 Scaling Out với Load Balancing
Performance tuning không đủ khi traffic grows. Scalability thường liên quan đến distribute load across multiple servers sử dụng:
Horizontal Scaling : Thêm servers
Load Balancers : NGINX, Azure Front Door, AWS ELB, etc.
Trong distributed systems, session state và caching nên externalized (ví dụ: Redis).
✅ Ví dụ: Cấu hình Distributed Cache (Redis)
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = "localhost:6379";
});
public class CacheService {
private readonly IDistributedCache _cache;
public CacheService(IDistributedCache cache) {
_cache = cache;
}
public async Task SetCacheAsync(string key, string value) {
await _cache.SetStringAsync(key, value, new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
});
}
public Task<string?> GetCacheAsync(string key) => _cache.GetStringAsync(key);
}
Điều này làm app của bạn stateless, essential cho load balancing.
🧩 Cấu hình Kestrel và Hosting cho High Throughput
Kestrel, built-in ASP.NET Core web server, có thể handle hundreds of thousands requests per second khi cấu hình đúng.
✅ Ví dụ: Optimize Kestrel Configuration
builder.WebHost.ConfigureKestrel(options => {
options.Limits.MaxConcurrentConnections = 10000;
options.Limits.MaxConcurrentUpgradedConnections = 1000;
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
});
Thêm vào đó:
- Dùng reverse proxy servers (như NGINX hoặc IIS) cho static file handling và TLS termination.
- Deploy trong containerized environments cho auto-scaling (ví dụ: Kubernetes).
🧮 Sử dụng Memory và Object Pooling
Để tránh frequent object allocations và garbage collection, ASP.NET Core hỗ trợ object pooling .
✅ Ví dụ: Sử dụng ArrayPool<T>
using System.Buffers;
public class BufferService {
public void ProcessData() {
var pool = ArrayPool<byte>.Shared;
var buffer = pool.Rent(1024); // Rent 1KB buffer
try {
// Use the buffer
} finally {
pool.Return(buffer);
}
}
}
Cách này minimize heap allocations và giảm GC pressure — crucial cho performance-sensitive applications.
🧱 Minimize Startup Time và Memory Footprint
Tránh unnecessary services trong
Program.cs.Dùng AddSingleton thay vì AddTransient khi appropriate.
Trim dependencies trong
*.csprojfiles.
✅ Ví dụ: Minimal API Setup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IProductService, ProductService>();
var app = builder.Build();
app.MapGet("/products", async (IProductService service) => await service.GetAllProductsAsync());
app.Run();
Minimal APIs giảm boilerplate và cải thiện startup performance.
📊 Monitoring và Benchmarking
Bạn không thể improve what you don't measure. Dùng tools như:
dotnet-trace và dotnet-counters
Application Insights
BenchmarkDotNet
✅ Ví dụ: Sử dụng BenchmarkDotNet
[MemoryDiagnoser]
public class PerformanceTests {
private readonly ProductService _service = new();
[Benchmark]
public async Task FetchProducts() {
await _service.GetAllProductsAsync();
}
}
Chạy benchmark này để identify bottlenecks và memory inefficiencies.
🧩 Additional Optimization Tips
- Enable HTTP/2 or HTTP/3 cho better parallelism.
- Dùng CDNs cho static assets.
- Employ connection pooling cho database và HTTP clients.
- Dùng
IHttpClientFactoryđể prevent socket exhaustion.
builder.Services.AddHttpClient("MyClient")
.SetHandlerLifetime(TimeSpan.FromMinutes(5));
🏁 Kết luận
High performance và scalability trong ASP.NET Core đạt được qua kết hợp asynchronous design , caching , efficient data access , và smart infrastructure choices.
Bằng cách áp dụng các strategies đã thảo luận — từ optimizing middleware và Kestrel configuration đến leveraging Redis và compression — ASP.NET Core application của bạn có thể handle massive workloads với low latency và high reliability.