Sunday, November 9, 2025

Dotnet Core - Performance Tuning of Applications

 🚀 How to Improve Performance in ASP.NET Core Applications

Performance optimization in .NET Core is multi-layered, covering areas from code-level tuning to infrastructure scaling.
Here’s a structured breakdown:





🧱 1. Use Built-in Caching

🔹 Memory Cache (for small-scale, single-server)

builder.Services.AddMemoryCache(); public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) => _cache = cache; public Product GetProduct(int id) { return _cache.GetOrCreate($"product_{id}", entry => { entry.SlidingExpiration = TimeSpan.FromMinutes(5); return LoadProductFromDb(id); }); } }

🔹 Distributed Cache (for load-balanced apps)

Use Redis, SQL Server, or AWS ElastiCache.

builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; });

✅ Benefit: Reduces DB hits and speeds up responses.


⚙️ 2. Enable Response Caching

Cache HTTP responses for static or infrequently changing data.

builder.Services.AddResponseCaching(); app.UseResponseCaching();
[ResponseCache(Duration = 60)] public IActionResult GetWeather() => Ok("Sunny");

✅ Benefit: Reuses responses instead of regenerating data.


⚡ 3. Use Asynchronous Code

ASP.NET Core is non-blocking. Always use async/await for I/O operations:

public async Task<IActionResult> GetProductsAsync() => Ok(await _db.Products.ToListAsync());

✅ Benefit: Frees up threads → handles more concurrent requests.


🧰 4. Optimize Entity Framework Core

  • Use AsNoTracking() for read-only queries.
  • Fetch only needed columns via Select().
  • Use compiled queries for hot paths.
  • Use connection pooling.

Example:

var products = await _context.Products .AsNoTracking() .Select(p => new { p.Id, p.Name }) .ToListAsync();

✅ Benefit: Reduces EF overhead and memory allocations.


🧩 5. Compression & Minification

Enable Response Compression middleware:

builder.Services.AddResponseCompression(); app.UseResponseCompression();

Compresses JSON, HTML, CSS, etc., reducing network load.


💾 6. Use Data Transfer Optimization

  • Use DTOs to avoid over fetching large models.
  • Paginate results.
  • Use gzip/brotli compression and HTTP/2.

🌐 7. Use CDN & Static File Optimization

Host static assets (JS, CSS, images) on a CDN like CloudFront.
Also, use cache headers:

app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=604800"); } });

🧮 8. Connection & Pooling

Use IHttpClientFactory for efficient, pooled HTTP calls:

builder.Services.AddHttpClient("MyClient");

Avoids socket exhaustion caused by frequent new HttpClient instances.


🧠 9. Reduce Middleware Overhead

Register only necessary middleware, and put frequently used ones first (e.g., authentication before routing).


🧩 10. Use Output Caching (ASP.NET Core 7+)

Output caching stores full HTTP responses:

builder.Services.AddOutputCache(); app.UseOutputCache();
[OutputCache(Duration = 60)] public IActionResult GetProducts() => Ok(Products);

✅ Much faster than recomputing each request.


☁️ 11. Use Cloud & Deployment Optimization (AWS Context)

On AWS, you can:

  • Use Elastic Beanstalk or ECS/EKS for autoscaling.
  • Add AWS ElastiCache for distributed caching.
  • Use AWS CloudFront CDN.
  • Add Application Load Balancer for traffic balancing.
  • Store assets in S3 instead of app server.

✅ You can also enable AOT (Ahead-of-Time Compilation) for startup performance improvements.


🧪 12. Profiling & Diagnostics

Use tools like:

  • dotnet-trace, dotnet-counters
  • Application Insights
  • MiniProfiler
  • AWS X-Ray (for distributed tracing)

✅ Identify slow methods, DB queries, or excessive GC pressure.


🧠 13. Memory Management

  • Use Span<T>, Memory<T> for high-performance code.
  • Avoid large object allocations.
  • Prefer pooled objects (ArrayPool<T>).
  • Release disposable resources properly.

✅ Summary Table

AreaTechniqueBenefit
CachingMemory, Redis, Output CacheReduce recomputation
Async I/Oasync/awaitHandle more requests
EF CoreAsNoTracking, ProjectionOptimize DB performance
CompressionGzip, BrotliReduce payload
MiddlewareOptimize pipelineReduce latency
CDN/StaticCache headersReduce load
DiagnosticsProfilers, LogsIdentify bottlenecks

💡Summary (Short Answer)

"In ASP.NET Core, I improve performance using multi-level caching (in-memory, distributed, and output), async programming, optimized EF Core queries, response compression, and CDN-based static content delivery. I also use IHttpClientFactory for efficient HTTP calls, limit middleware overhead, and profile apps with Application Insights or AWS X-Ray to find hot spots. In cloud deployments, I leverage autoscaling and caching via AWS ElastiCache and CloudFront."

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...