
In high-concurrency enterprise B2B software—such as multi-facility safety platforms or real-time restaurant POS systems—the primary performance bottleneck is almost never CPU math inside C#. Instead, 95% of production slowdowns originate in **poorly structured Entity Framework Core queries and unindexed PostgreSQL table scans**.
A query that runs in 3 milliseconds against 50 rows on a developer laptop can easily take 14 seconds against 20 million rows in production, exhausting the Npgsql connection pool. In this deep-dive guide, we walk through the exact Infrastructure/Persistence folder structure and the **7 production engineering patterns** we use at Digital HAT to keep .NET 9 and PostgreSQL queries in single-digit milliseconds.
What You Will Master in This Guide:
1. CompleteInfrastructure/Persistence/directory structure for high-throughput .NET 9 solutions.
2. Eliminating EF Core Change Tracker overhead withAsNoTracking()and direct.Select()DTO projections.
3. Designing PostgreSQL Composite & Covering Indexes (INCLUDE) for Index-Only Scans.
4. Building an automatedSlowQueryDetectionInterceptorin EF Core.
5. Set-based bulk operations withExecuteUpdateAsyncandExecuteDeleteAsync.
6. Npgsql Connection Pooling and Redis Cache-Aside patterns.
1. Production Persistence Layer Directory Structure
src/DigitalHat.Enterprise.Infrastructure/
└── Persistence/
├── AppDbContext.cs # Core EF Core DbContext
├── Configurations/ # Dedicated IEntityTypeConfiguration per aggregate
│ ├── OrderConfiguration.cs # Composite & Covering Index definitions
│ └── AuditLogConfiguration.cs # JSONB & GIN Index definitions
├── Interceptors/
│ └── SlowQueryDetectionInterceptor.cs # Automatically logs SQL queries exceeding 150ms
├── CompiledQueries/
│ └── OrderCompiledQueries.cs # Pre-compiled EF.CompileAsyncQuery delegates
└── Caching/
└── RedisCacheService.cs # Distributed Cache-Aside implementation
2. Rule 1: Never Load Full Entities for Read-Only Queries
By default, EF Core allocates a memory snapshot for every loaded entity to track property mutations. For read-only API endpoints, combine AsNoTracking() with a direct .Select() projection so PostgreSQL only transmits the exact columns needed:
// ❌ SLOW & MEMORY-HEAVY (Fetches all 40 columns + allocates Change Tracker snapshots):
public async Task<List<Order>> GetRecentOrdersSlowAsync(Guid companyId, CancellationToken ct)
{
return await _dbContext.Orders
.Include(o => o.Customer)
.Include(o => o.Items)
.Where(o => o.CompanyId == companyId)
.OrderByDescending(o => o.CreatedAt)
.Take(50)
.ToListAsync(ct);
}
// ✅ ULTRA-FAST PRODUCTION QUERY (AsNoTracking + Direct SQL Projection):
public async Task<IReadOnlyList<OrderSummaryDto>> GetRecentOrdersFastAsync(Guid companyId, CancellationToken ct)
{
return await _dbContext.Orders
.AsNoTracking()
.Where(o => o.CompanyId == companyId)
.OrderByDescending(o => o.CreatedAt)
.Take(50)
.Select(o => new OrderSummaryDto(
o.Id,
o.OrderNumber,
o.Customer.CompanyName,
o.GrandTotal,
o.CreatedAt
))
.ToListAsync(ct);
}
3. Rule 2: PostgreSQL Composite & Covering Indexes (OrderConfiguration.cs)
When querying a 50-million-row Orders table by CompanyId, Status, and CreatedAt, a covering index with IncludeProperties allows PostgreSQL to satisfy the query entirely from the B-Tree leaf nodes (Index-Only Scan in <1ms) without touching the heap table:
// File: Persistence/Configurations/OrderConfiguration.cs
using DigitalHat.Enterprise.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ToTable("Orders");
builder.HasKey(o => o.Id);
builder.Property(o => o.OrderNumber).IsRequired().HasMaxLength(32);
builder.Property(o => o.GrandTotal).HasPrecision(18, 2);
builder.HasIndex(o => o.OrderNumber).IsUnique();
// Composite + Covering Index for sub-millisecond Index-Only Scans:
builder.HasIndex(o => new { o.CompanyId, o.Status, o.CreatedAt })
.IncludeProperties(o => new { o.OrderNumber, o.GrandTotal })
.HasDatabaseName("IX_Orders_Company_Status_CreatedAt_Covering");
}
}
4. Rule 3: Automated Slow Query Detection with DbCommandInterceptor
// File: Persistence/Interceptors/SlowQueryDetectionInterceptor.cs
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
public class SlowQueryDetectionInterceptor : DbCommandInterceptor
{
private readonly ILogger<SlowQueryDetectionInterceptor> _logger;
private const int SlowQueryThresholdMs = 150;
public SlowQueryDetectionInterceptor(ILogger<SlowQueryDetectionInterceptor> logger)
{
_logger = logger;
}
public override ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result,
CancellationToken cancellationToken = default)
{
if (eventData.Duration.TotalMilliseconds > SlowQueryThresholdMs)
{
_logger.LogWarning(
"[SLOW SQL ALERT - {DurationMs:N1} ms] Query: {CommandText}",
eventData.Duration.TotalMilliseconds,
command.CommandText);
}
return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
}
}
5. Rule 4: Zero-Allocation Bulk Updates with ExecuteUpdateAsync
int affectedRows = await _dbContext.Notifications
.Where(n => !n.IsRead && n.CreatedAt < DateTimeOffset.UtcNow.AddDays(-30))
.ExecuteUpdateAsync(setters => setters
.SetProperty(n => n.IsArchived, true)
.SetProperty(n => n.UpdatedAt, DateTimeOffset.UtcNow), ct);
Did you find this engineering guide helpful?
Give it a like or share it with your team and network.