📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A sales dashboard endpoint takes about 30 seconds and sometimes times out. It aggregates three years of orders (tens of millions of order lines) in Azure SQL through EF Core. Walk me through how you would make it fast: projection and pushing work to SQL, indexes (including columnstore), plan analysis, pre-aggregation and caching, and how you would prove each step.

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.

Senior RealWorldScenario Advanced azure-sql caching columnstore ef-core performance reporting

🎯 Key points

  • ~30 s matches SqlClient's default CommandTimeout: a clue that the query is being cut off, not the cause; raising it is mitigation only
  • Measure first: Application Insights timeline, the generated SQL, actual plan, logical reads, Query Store runtime and wait stats (SQL Server 2017+ / Azure SQL)
  • Push aggregation to SQL: projected GroupBy/Sum checked with ToQueryString(), no tracked entities, no LINQ to Objects over millions of rows
  • Analytics index: nonclustered columnstore index for scan-and-aggregate (batch mode, compression); rowstore covering index for narrow filters
  • Move heavy reads off the primary: Azure SQL read scale-out with ApplicationIntent=ReadOnly where staleness is acceptable
  • Pre-aggregate history (daily summary table or indexed view) and query raw rows only for the current period
  • Cache the result (HybridCache, key includes every filter and permission scope) only after the query is good
  • Prove each step in a production-sized test environment (reads, CPU, plan), then confirm with production p95

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 its TagWith comment, 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 GroupBy with Sum, 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."


The path, step by step

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

Columnstore vs rowstore for this workload

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

Production example

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%].

🔍 What the interviewer is checking

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

  • Spots the 30-second default timeout and treats raising it as mitigation only
  • Pushes aggregation to SQL and knows columnstore and batch mode for analytics
  • Proposes pre-aggregation or a replica after asking how fresh the data must be
  • Puts caching last, with a correct key and stampede awareness, and proves each step with reads and p95

Red flags

  • "Add Redis" or "increase the timeout" as the whole answer
  • Aggregating in memory after ToList()
  • No measurement or no thought for the OLTP workload sharing the database

📚 Learn in depth

1. Why the query is slow

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.

2. Columnstore and batch mode

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.

3. Pre-aggregation

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.

4. Read replicas

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.

5. Caching last

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.

6. Proving it

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.

Try it yourself

  1. Generate 10 million synthetic order lines in SQL Server in Docker, run a monthly revenue-by-region query and record reads and duration.
  2. Add a nonclustered columnstore index on the needed columns; rerun and check for batch mode in the plan.
  3. Build a DailySales summary table and rewrite the query as summary plus today.
  4. Write the EF Core projection with GroupBy and check with ToQueryString() that the aggregation happens in SQL.
  5. Wrap the result in HybridCache and load test with k6 to compare p95 and database calls.

💻 Code

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));

⚠ Common mistakes

  • Mistake: Optimising without measuring, for example adding Redis or indexes before looking at the plan. Why it is wrong: You can't tell which step helped, and the cold path stays 30 seconds. Instead: Baseline p95, reads and CPU, then change one thing at a time.
  • Mistake: Raising 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.
  • Mistake: Loading entities and aggregating in LINQ to Objects. Why it is wrong: Millions of rows are transferred, materialised and tracked. Instead: Project with GroupBy/Sum so SQL returns a few hundred rows.
  • Mistake: Adding a wide rowstore covering index for an analytical scan. Why it is wrong: It is nearly as big as the table and adds write cost without making the aggregate cheaper. Instead: Use a nonclustered columnstore index for scan-and-aggregate workloads.
  • Mistake: Caching with a key that omits filters or the user's permitted regions. Why it is wrong: Users see wrong or unauthorised data, which can be a Notifiable Data Breach if personal information is involved. Instead: Include every filter and authorisation scope in the key.
  • Mistake: Running heavy reports against the OLTP primary at peak. Why it is wrong: Reports steal CPU, memory grants and I/O from transactional traffic. Instead: Use a read replica, off-peak exports or precomputed tables.
  • Mistake: Micro-optimising cold paths, such as tuning a yearly export someone runs once. Why it is wrong: Effort goes where users don't feel it. Instead: Prioritise by frequency × cost from Query Store and Application Insights.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions summary tables or indexed views Why: Checks they understand denormalisation options and their write and consistency costs.
    How to answer

    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:

    • Persisted computed column: a derived value from the same row (e.g. LineTotal = Quantity * UnitPrice), always consistent and indexable.
    • Indexed view: a pre-joined or pre-aggregated result with a unique clustered index, maintained synchronously on every write, which can create lock hot spots on popular groups.
    • Summary / reporting table or read model: refreshed by a job or events, cheapest to read but can be stale.

    The trade-off: reads get cheaper, but writes get slower and lock more, data flows get more complex, and every copy needs reconciliation.

  2. When: Candidate mentions hash aggregate spills or memory grants Why: Checks depth on memory grants, spills and RESOURCE_SEMAPHORE waits.
    How to answer

    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.

    • Too small and the operator spills to tempdb: a warning triangle in the actual plan and often 10× slower.
    • Too large and memory sits idle while other queries queue on RESOURCE_SEMAPHORE.

    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.

  3. When: Candidate proposes caching the dashboard result Why: Checks they can use HybridCache correctly, including stampede protection and tags.
    How to answer

    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).

    • Two levels: an in-process L1 (MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).
    • Stampede protection: concurrent misses for the same key in one process share a single factory call.
    • Tags: entries can carry tags, and 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.

🛠 Real-world problems: how you handle them

Finance dashboard timing out at month end
Situation
[Wholesale distributor] with a finance dashboard in an ASP.NET Core API on Azure SQL [General Purpose 8 vCore], [45 million] order lines over three years. At month end, [~200] finance users opened the dashboard at once.
Signals
Application Insights showed `SqlException` timeouts ("Execution Timeout Expired") at about 30 s on the dashboard endpoint, p95 at [29 s], Azure SQL CPU at 100%, and order-entry latency rising for the warehouse app sharing the database.
Investigation
The end-to-end view showed one long SQL call. The tagged query in Query Store had [6 million] logical reads per execution, a clustered index scan, a hash aggregate spilling to tempdb, and high CXPACKET/CXCONSUMER waits. The EF Core query was already aggregating in SQL, so the problem was the data shape and how often it was recomputed.
Resolution
Immediate: set a 90 s command timeout for this query only and limited the default date range to 12 months. Real fix: nonclustered columnstore index on OrderLines (p95 [1.4 s]); nightly DailySales summary table with only today's rows queried live ([120 ms]); moved to Business Critical with read scale-out for reports; 10-minute HybridCache entry keyed by filters and permitted regions ([15 ms] steady state).
Prevention
ADR on reporting workload placement; Query Store alert on reads per execution for tagged report queries; monitoring on summary job success and freshness; load test of month-end concurrency in Azure Load Testing before each quarter close.

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].

More in EF and SQL Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me