An end-to-end scenario for fixing a slow reporting endpoint across EF Core and Azure SQL: measuring, server-side aggregation, columnstore and covering indexes, plan analysis, read replicas, pre-aggregated tables and caching, with evidence at each step.
First I note that 30 seconds is SqlClient's default command timeout, so the timeouts are the query hitting that limit. Raising the limit buys time but fixes nothing. I measure: the Application Insights timeline, the generated SQL, the actual plan, logical reads and Query Store CPU and waits. Then I fix in order of leverage. I push aggregation into SQL with a projected GroupBy and no tracked entities. I add a nonclustered columnstore index so the scan-and-aggregate runs in batch mode over compressed data. I pre-aggregate closed periods into a daily summary table so only today's rows are aggregated live. I move the read to a read replica if the business accepts slight staleness. Finally I cache the result with HybridCache. Each step is proved with reads, CPU and p95. The trade-off is freshness and extra storage and write cost in exchange for sub-second dashboards.
"The 30 seconds is a clue in itself: it's SqlClient's default
CommandTimeout, so the 'sometimes times out' is the query crossing that line on busy days. I'd raise the timeout for this one command as a short-term mitigation and tell the team that's what it is. Then I'd measure. I'd open a slow request in Application Insights, check it's one long SQL call and not a loop, grab the SQL through itsTagWithcomment, and look at the actual plan and Query Store. Typically I'd see a clustered index scan over tens of millions of rows, a hash aggregate spilling to tempdb, and parallelism waits.Then I fix in order of leverage. First, make sure the aggregation runs in SQL: a projected
GroupBywithSum, not entities pulled into memory. Second, an index that suits analytics. For scan-and-aggregate over millions of rows that's a nonclustered columnstore index: batch-mode execution and around 10x compression, so the same query reads far less. Third, stop recomputing history. Three years of closed months don't change, so a nightly job writes a daily summary table and the endpoint aggregates the summary plus today's raw rows. For example, at [company] a [regional sales dashboard] went from [28 s] to [1.1 s] with the columnstore index, and to [80 ms] with the summary table. Logical reads fell from [6 million] to [2,000]. Then caching with HybridCache for [5 minutes] took the database out of the hot path.The mistake I see is going straight to Redis. The first request after expiry still takes 30 seconds, and a stampede of those can take the primary down. Make the query cheap first, then cache it."
| Step | What I check | Typical change | Evidence |
|---|---|---|---|
| 0. Mitigate | Timeout errors in App Insights | Command-specific timeout, limit date range in the UI | Error rate drops |
| 1. Measure | Timeline, SQL text, actual plan, Query Store | None yet | Baseline: p95, reads, CPU |
| 2. Query shape | Is aggregation in SQL? Tracking? Over-fetching? | Projected GroupBy, AsNoTracking |
Rows returned: millions → hundreds |
| 3. Index | Scans, spills, row-mode aggregates | Nonclustered columnstore, or covering rowstore for narrow filters | Reads and CPU per execution |
| 4. Isolation | Report competing with OLTP | Read scale-out replica (ApplicationIntent=ReadOnly) |
Primary CPU during reports |
| 5. Precompute | Recomputing immutable history | Daily summary table or indexed view | Rows scanned per request |
| 6. Cache | Same filters requested repeatedly | HybridCache with a freshness-based TTL | DB calls per minute, p95 |
| Rowstore B-tree | Nonclustered columnstore | |
|---|---|---|
| Best for | Seeks, narrow ranges, OLTP | Scanning and aggregating many rows |
| Execution | Row mode (batch mode on rowstore exists from SQL Server 2019 but is less effective) | Batch mode, segment elimination, compression |
| Write cost | Per index per row | Delta store, tuple mover; heavier on update-heavy tables |
A [finance dashboard] over [45 million] order lines was [30 s] at p95 with [7%] of calls timing out. Projection plus a nonclustered columnstore index took it to [1.4 s]. A nightly daily-summary table took it to [120 ms]. A 10-minute HybridCache entry took steady-state p95 to [15 ms], and primary CPU during business hours fell by [35%].
Checks whether the candidate can take a slow reporting query through a structured, evidence-based fix across application and database, and recognise when the data shape is the real problem.
Green flags
Red flags
ToList()Aggregating three years of order lines is an analytical query on an OLTP schema:
Clustered index scan (OrderLines, 45M rows, row mode)
└─ Hash match (aggregate) ← memory grant too small → spill to tempdb
└─ Parallelism (gather streams)
Row-mode operators handle one row at a time through each operator. With a rowstore table, every column of every row is read even if only three columns are needed.
A columnstore index stores each column separately in row groups of up to about 1 million rows, compressed (often around 10x). Queries read only the columns they need, skip row groups whose min/max metadata excludes the filter (segment elimination), and process about 900 rows per batch in batch mode. That combination is why aggregates often get 10–100x faster. New rows land in a delta store (rowstore) until the tuple mover compresses them, so a busy OLTP table can carry a nonclustered columnstore index with acceptable write overhead. Measure that overhead on your own workload.
OrderLines (raw, hot) ──nightly job──► DailySales(Date, RegionId, ProductCategoryId, Revenue, Units)
│
Dashboard query = SUM(DailySales WHERE Date < today) + SUM(OrderLines WHERE Date = today)
An indexed view maintains the aggregate synchronously on every write, which gives exact freshness but adds cost and restrictions (schema binding, COUNT_BIG(*), deterministic expressions). A summary table refreshed by a job is cheaper on writes but stale between runs.
Azure SQL Premium and Business Critical tiers include a readable secondary (read scale-out), and Hyperscale supports named and HA replicas. Adding ApplicationIntent=ReadOnly to a separate connection string routes queries there. Replicas lag slightly behind the primary, so only use them where the business accepts that.
Once the query takes 100 ms, caching is an optimisation, not a crutch. HybridCache (.NET 9+) gives a local L1 cache, an optional distributed L2 cache and protection against concurrent recomputation for the same key. The cache key must include every filter (date range, region, user's permitted regions) so one user never sees another's slice.
For each step, record logical reads and CPU per execution (Query Store or SET STATISTICS IO, TIME ON), the endpoint's p95 and timeout rate, and primary CPU during business hours.
DailySales summary table and rewrite the query as summary plus today.GroupBy and check with ToQueryString() that the aggregation happens in SQL.Aggregate in SQL from the summary table plus today's raw rows, read from the replica, and cache with HybridCache.
namespace Shop.Reporting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Hybrid;
public sealed record RegionMonthRevenue(int RegionId, int Year, int Month, decimal Revenue);
// ReportingDbContext uses a connection string with ApplicationIntent=ReadOnly (read scale-out replica).
public sealed class SalesDashboard(ReportingDbContext db, HybridCache cache, TimeProvider clock)
{
public async Task<IReadOnlyList<RegionMonthRevenue>> Get(DateOnly from, DateOnly to, int[] regionIds, CancellationToken ct)
{
// The key carries every filter, including the caller's permitted regions.
var key = $"dashboard:{from:yyyyMMdd}:{to:yyyyMMdd}:{string.Join(',', regionIds.Order())}";
return await cache.GetOrCreateAsync(key, async token => await Query(from, to, regionIds, token),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10) }, cancellationToken: ct);
}
private async Task<IReadOnlyList<RegionMonthRevenue>> Query(DateOnly from, DateOnly to, int[] regionIds, CancellationToken ct)
{
var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
var start = from.ToDateTime(TimeOnly.MinValue);
// Closed days: small pre-aggregated table (nightly job).
var history = await db.DailySales
.TagWith("SalesDashboard.History")
.Where(d => d.Date >= from && d.Date <= to && d.Date < today && regionIds.Contains(d.RegionId))
.GroupBy(d => new { d.RegionId, d.Date.Year, d.Date.Month })
.Select(g => new RegionMonthRevenue(g.Key.RegionId, g.Key.Year, g.Key.Month, g.Sum(d => d.Revenue)))
.ToListAsync(ct);
if (to < today) return history;
// Today only: raw rows, SARGable range predicate, aggregated in SQL.
var todayStart = today.ToDateTime(TimeOnly.MinValue);
var live = await db.OrderLines
.TagWith("SalesDashboard.Today")
.Where(l => l.Order.CreatedAt >= todayStart && regionIds.Contains(l.Order.RegionId))
.GroupBy(l => l.Order.RegionId)
.Select(g => new RegionMonthRevenue(g.Key, today.Year, today.Month, g.Sum(l => l.Quantity * l.UnitPrice)))
.ToListAsync(ct);
return [.. history.Concat(live)
.GroupBy(r => (r.RegionId, r.Year, r.Month))
.Select(g => new RegionMonthRevenue(g.Key.RegionId, g.Key.Year, g.Key.Month, g.Sum(r => r.Revenue)))];
}
}
The index and summary table, created in a migration with migrationBuilder.Sql:
CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_OrderLines_Analytics
ON dbo.OrderLines (OrderId, ProductId, Quantity, UnitPrice);
CREATE TABLE dbo.DailySales (
[Date] date NOT NULL, RegionId int NOT NULL, Revenue decimal(19,4) NOT NULL,
CONSTRAINT PK_DailySales PRIMARY KEY CLUSTERED ([Date], RegionId));
CommandTimeout to 300 seconds and closing the ticket. Why it is wrong: The query still burns CPU and memory grants on the primary, and users still wait. Instead: Treat the timeout as a short-term mitigation with a follow-up fix.GroupBy/Sum so SQL returns a few hundred rows.The senior insight is recognising a workload mismatch: an analytical query on a transactional schema. The durable fixes change the shape of the data (columnstore, pre-aggregation) or where the work runs (replica, warehouse), not just the query text. I also ask the business how fresh the dashboard really needs to be. 'Up to yesterday plus today live' or '10 minutes old' is usually fine and unlocks the cheap options.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Nonclustered columnstore | Large scans and aggregates on an OLTP table | Write overhead, index maintenance | Small tables, seek-only workloads |
| Summary table (nightly) | Immutable history, tolerance for daily refresh | Job to run and monitor, staleness | Needs real-time exactness |
| Indexed view | Exact, always current aggregates | Write cost on every change, many restrictions | Very write-heavy tables |
| Read replica | Report load hurting OLTP | Tier cost, replica lag | Read-your-writes needed |
| Cache | Same filters requested repeatedly | Invalidation, key design | Query still slow cold |
When reporting needs keep growing, the next step is moving analytics out of the OLTP database entirely (Microsoft Fabric, Synapse, or a warehouse fed by change data capture). I'd write that up as an ADR rather than keep stretching Azure SQL.
I denormalise only when a measured read cost cannot be fixed with an index or query rewrite, and only with a named owner that keeps the copy consistent. SQL Server gives three levels:
LineTotal = Quantity * UnitPrice), always consistent and indexable.The trade-off: reads get cheaper, but writes get slower and lock more, data flows get more complex, and every copy needs reconciliation.
Operators like sort and hash match need workspace memory, and SQL Server reserves it as a memory grant before the query starts, sized from the estimated rows × estimated row width.
Memory grant feedback (row mode since 2019, percentile and persistence in 2022) adjusts grants on repeated executions. I diagnose with the actual plan's MemoryGrantInfo, sys.dm_exec_query_memory_grants and Query Store, then fix the cause: bad estimates, SELECT * with wide nvarchar(max) columns, or sorts an index could avoid. Hints are the last resort.
HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025, works on .NET 8+) replaces hand-written cache-aside code with one call: GetOrCreateAsync(key, factory, options, tags, ct).
MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).RemoveByTagAsync invalidates them as a group.I prove it by counting source calls and measuring p95 under a k6 load test before and after. The trade-off: protection and L1 invalidation are per process, so I keep L1 lifetimes short when data changes.
How to tell it (STAR)
**S:** At [company], our finance dashboard timed out at month end and dragged down the warehouse app on the same database. **T:** I led the fix with [our DBA]. **A:** I measured first and found one query reading [6 million] pages per call and spilling to tempdb. We mitigated with a targeted timeout and a narrower default range. Then we added a nonclustered columnstore index, pre-aggregated closed days into a summary table, moved reports to the read replica, and finally cached results keyed by filters and permissions. **R:** p95 went from [29 s] to [120 ms] uncached and [15 ms] cached, timeouts went to zero, and primary CPU at month end dropped by [about a third].
Last updated 23 Nov 2026.