LESSON 18 OF 20

18. Performance, Caching, and Database Optimization

Learn how to measure slow content pages, improve EF Core queries with async, projection, and AsNoTracking, and use output caching and database indexes effectively.

45 dk 32

Introduction

In a content management application, a page must be fast as well as correct. A content page may load an article, category name, tags, and related content from the database. Problems that are invisible with a small development database often become obvious when the application contains realistic data.

In this lesson, we will first measure a slow page. Then we will simplify Entity Framework Core queries with asynchronous methods, projections, and AsNoTracking. Finally, we will configure ASP.NET Core output caching and create SQL Server indexes for frequently used queries.

The most important rule is simple: measure before optimizing. Changing code based only on assumptions can make the application more complex without solving the actual bottleneck.

1. Measuring a performance problem

Slow responses can be caused by controller logic, a database query, network latency, Razor view rendering, or an unnecessarily large result set. For that reason, performance should be examined at several levels.

  1. Check the total response time in the browser developer tools.
  2. Review request duration and error rates in application logs.
  3. Inspect the SQL generated by Entity Framework Core.
  4. Examine the query plan and index usage in SQL Server.

You can increase EF Core SQL logging in a development environment:

builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information);

Do not log every SQL parameter indiscriminately in production. Parameters may contain personal or sensitive data. Detailed SQL logging should be limited to development or controlled test environments.

2. Using asynchronous queries

When database access is performed synchronously during an ASP.NET Core request, a ThreadPool thread may remain occupied while waiting for the database. EF Core methods such as ToListAsync, SingleOrDefaultAsync, and CountAsync allow I/O waits to be handled more efficiently.

A content details action can be written as follows:

public sealed class ContentsController : Controller
{
    private readonly ApplicationDbContext _db;

    public ContentsController(ApplicationDbContext db)
    {
        _db = db;
    }

    public async Task<IActionResult> Details(string slug,
        CancellationToken cancellationToken)
    {
        var content = await _db.Contents
            .Where(x => x.Slug == slug && x.IsPublished)
            .Select(x => new ContentDetailsViewModel
            {
                Id = x.Id,
                Title = x.Title,
                Slug = x.Slug,
                Summary = x.Summary,
                Body = x.Body,
                PublishedAt = x.PublishedAt,
                CategoryName = x.Category.Name
            })
            .SingleOrDefaultAsync(cancellationToken);

        if (content is null)
        {
            return NotFound();
        }

        return View(content);
    }
}

Asynchronous code does not automatically make a poor query fast. If the query still returns thousands of unnecessary rows, the page can remain slow. Async methods improve the handling of database waits; filtering, projection, and indexes optimize the query itself.

3. Selecting only required columns with projection

Projection means selecting only the properties required by the view instead of loading a complete Entity object. In EF Core, projection is commonly expressed with Select.

Compare these two approaches:

// May load more data than the page needs
var entity = await _db.Contents
    .Include(x => x.Category)
    .SingleOrDefaultAsync(x => x.Slug == slug);

// Selects the fields required by the view
var model = await _db.Contents
    .Where(x => x.Slug == slug)
    .Select(x => new ContentDetailsViewModel
    {
        Title = x.Title,
        Summary = x.Summary,
        Body = x.Body,
        CategoryName = x.Category.Name
    })
    .SingleOrDefaultAsync();

Projection is particularly useful when an Entity contains a large body, image data, SEO fields, or related objects. The Select expression can be translated into SQL, which is often more efficient than loading a complete Entity and transforming it afterward.

Use the same approach on list pages:

var items = await _db.Contents
    .Where(x => x.IsPublished)
    .OrderByDescending(x => x.PublishedAt)
    .Select(x => new ContentListItemViewModel
    {
        Title = x.Title,
        Slug = x.Slug,
        Summary = x.Summary,
        PublishedAt = x.PublishedAt
    })
    .Take(20)
    .ToListAsync(cancellationToken);

Pagination, covered earlier in the course, is also essential here. Fetching every content record without a limit increases response time and memory usage as the data grows.

4. Using AsNoTracking for read-only queries

By default, EF Core tracks Entity instances returned from queries. This allows changes to be detected and persisted later. For read-only lists and details pages, that tracking work may be unnecessary. Use AsNoTracking when the returned Entity will not be updated.

var latestContents = await _db.Contents
    .AsNoTracking()
    .Where(x => x.IsPublished)
    .OrderByDescending(x => x.PublishedAt)
    .Select(x => new ContentListItemViewModel
    {
        Title = x.Title,
        Slug = x.Slug,
        PublishedAt = x.PublishedAt
    })
    .Take(10)
    .ToListAsync(cancellationToken);

AsNoTracking is appropriate for read-only operations. If you plan to modify the Entity and call SaveChangesAsync, tracking is normally required, or you must explicitly attach the Entity and set its state before updating it.

When projection directly creates a ViewModel, an Entity instance may not be materialized at all. Adding AsNoTracking can still communicate that the query is intentionally read-only.

5. Applying output caching

For public content pages that change infrequently, executing the same database query and Razor view for every request may be unnecessary. ASP.NET Core output caching, available in .NET 8, can store suitable responses on the server.

Register the service and middleware:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddOutputCache();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseOutputCache();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

The middleware should be placed after authentication and authorization. This helps prevent a response generated for an authorized user from being served incorrectly to an anonymous user.

You can define a policy on a controller action:

using Microsoft.AspNetCore.OutputCaching;

public sealed class ContentsController : Controller
{
    [OutputCache(Duration = 60, VaryByRouteValueNames = new[] { "slug" })]
    public async Task<IActionResult> Details(
        string slug,
        CancellationToken cancellationToken)
    {
        // The projection-based query goes here.
        // ...
        return View();
    }
}

Cache only public GET pages that do not depend on the current user. Do not use output caching when the response includes a username, role, shopping cart, personal permission, or other user-specific data. If old content must disappear immediately after an administrator edits it, use an invalidation strategy or a suitable expiration policy.

6. Response caching versus output caching

Response caching is based on HTTP cache headers. Clients and intermediary proxies may follow those headers. For example, adding a ResponseCache attribute can tell clients or proxies that a response may be cached.

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
public IActionResult About()
{
    return View();
}

Output caching provides more direct server-side control over which responses are stored. For many MVC user-interface pages, output caching is the more practical choice. Both approaches require caution for authenticated or user-specific pages.

7. Creating database indexes

Appropriate indexes can reduce query time for columns used in filtering and sorting, especially as a table grows. In our content application, common operations include looking up a content item by slug, filtering by publication status, and sorting by publication date.

Configure indexes in the EF Core model:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Content>()
        .HasIndex(x => x.Slug)
        .IsUnique();

    modelBuilder.Entity<Content>()
        .HasIndex(x => new { x.IsPublished, x.PublishedAt });
}

If Slug must be unique, a unique index supports both data integrity and lookup performance. The order of columns matters in a composite index. An index on IsPublished, PublishedAt can help a query that filters by publication status and orders by publication date.

Indexes also have a cost. Each index consumes storage and must be maintained during inserts and updates. Do not create indexes on every column automatically. Inspect real queries and verify index usage in the SQL Server query plan.

After changing the model, create and apply a migration:

dotnet ef migrations add AddContentPerformanceIndexes
dotnet ef database update

8. Common mistakes

  • Adding caching without measurement: A cache can preserve incorrect or user-specific data. Confirm that the response is public before caching it.
  • Loading complete Entities: If a view uses five properties, do not load twenty properties and large relationships unnecessarily.
  • Using synchronous queries in async actions: Prefer ToListAsync and other async methods where appropriate.
  • Using AsNoTracking everywhere: Do not forget that update operations may require tracked Entities.
  • Creating too many indexes: Indexes can improve reads but increase write and storage costs.
  • No cache invalidation plan: Decide how long an old response may remain visible after an administrator edits content.
  • Testing with too little data: A query that is fast with a few rows may be slow with thousands of content items.

9. Practice exercise

Task: Improve the performance of your content listing page.

  1. Measure the response time before making changes.
  2. Add filtering with Where(x => x.IsPublished), ordering, and pagination.
  3. Use a ViewModel projection to select only required fields.
  4. Add AsNoTracking and ToListAsync.
  5. Create the IsPublished, PublishedAt composite index through a migration.
  6. If the page is public, test output caching with a duration of 30 or 60 seconds.
  7. Compare the response time and generated SQL again after the changes.

Record the total request time, number of returned rows, query duration, and generated HTML size. This makes it easier to determine whether the optimization produced a real improvement.

Conclusion

Performance optimization is not a single configuration switch. A fast content page usually requires measurement, well-designed queries, limited result sets, projections, AsNoTracking where appropriate, output caching, and carefully selected database indexes.

The techniques in this lesson also prepare the application for the deployment work in the next lesson. Before going live, test with realistic data, verify cache behavior, and confirm through query plans that the intended indexes are actually being used.

Sources