Database performance has a direct impact on the responsiveness of an ASP.NET Core application. An API endpoint that normally responds in a few milliseconds may become noticeably slower when database queries take longer than expected. This can happen because of missing indexes, database resource pressure, network latency, connection pool limitations, or large queries.

Developers often test database operations using a local database that responds quickly. These tests confirm that the application returns the expected data, but they do not always reveal how the application behaves when database operations become slow.

For example, an API might wait several seconds for a database query and continue processing requests without any timeout or cancellation strategy. Under normal development conditions, this problem may remain hidden until the application receives real production traffic.

One practical way to test this behavior is to introduce artificial delays during database command execution. Entity Framework Core provides database interceptors that allow developers to observe and influence database operations. These interceptors can be used in ASP.NET Core integration tests to simulate slow database responses without changing the application's production code.

In this article, we will explore how to introduce database delays, configure them through WebApplicationFactory, and test how an ASP.NET Core application behaves when database queries take longer than expected.

Why Simulating Slow Database Operations Matters

Consider an ASP.NET Core API that retrieves customer information from SQL Server.

Under normal conditions, the database responds in approximately 20 milliseconds. The API processes the result and returns a successful response.

Now imagine that the same query takes three seconds because the database is under heavy load.

Several problems may appear:

  • API response times increase.
  • HTTP requests remain active for longer periods.
  • Database connections stay occupied.
  • More requests wait for available database connections.
  • Application-level timeouts may occur.
  • Users may retry requests and increase the load further.

These problems are difficult to identify through tests that always use a fast database.

Simulating database delays helps developers verify timeout behavior, request cancellation, response handling, logging, and application resilience before deploying changes to production.

Understanding EF Core Database Interceptors

Entity Framework Core provides interception APIs that allow applications to observe database operations before and after execution.

The DbCommandInterceptor base class is particularly useful when testing database performance.

It provides methods for intercepting different types of database commands:

MethodPurpose
ReaderExecutingAsyncCalled before a query that returns rows
ScalarExecutingAsyncCalled before a query that returns a single value
NonQueryExecutingAsyncCalled before commands such as INSERT, UPDATE, and DELETE
ReaderExecutedAsyncCalled after a query returning rows completes
ScalarExecutedAsyncCalled after a scalar command completes
NonQueryExecutedAsyncCalled after a non-query command completes

For example, when Entity Framework Core executes a LINQ query that retrieves a collection of customers, it generally uses the reader execution methods.

By overriding ReaderExecutingAsync, we can introduce a delay before the database command is executed.

This is useful because the delay happens inside the EF Core database pipeline. The application continues using its normal DbContext and database provider.

Creating a Database Delay Interceptor

Start by creating a class named SlowDatabaseInterceptor.

The interceptor will accept a delay duration and wait before allowing a database query to execute.

C#
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Data.Common;

public class SlowDatabaseInterceptor : DbCommandInterceptor
{
    private readonly TimeSpan _delay;

    public SlowDatabaseInterceptor(TimeSpan delay)
    {
        _delay = delay;
    }

    public override async ValueTask<InterceptionResult<DbDataReader>>
        ReaderExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<DbDataReader> result,
            CancellationToken cancellationToken = default)
    {
        await Task.Delay(_delay, cancellationToken);

        return result;
    }
}

The interceptor receives the database command and waits for the configured duration.

For example, if the delay is three seconds, every intercepted reader command waits three seconds before EF Core executes it.

The cancellation token is passed to Task.Delay. This is important because a canceled request should not continue waiting unnecessarily.

This implementation affects only commands that use ReaderExecutingAsync. It does not automatically delay scalar commands or non-query commands. Those operations require their corresponding interceptor methods if they also need to be simulated.

Creating a Testable ASP.NET Core Application

Consider a simple ASP.NET Core application that retrieves customer information using Entity Framework Core.

The application contains a Customer entity:

C#
public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Email { get; set; } = string.Empty;
}

Create a database context:

C#
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Customer> Customers => Set<Customer>();
}

Next, create an API endpoint that retrieves customers.

C#
app.MapGet(
    "/customers",
    async (
        ApplicationDbContext dbContext,
        CancellationToken cancellationToken) =>
    {
        var customers = await dbContext.Customers
            .AsNoTracking()
            .ToListAsync(cancellationToken);

        return Results.Ok(customers);
    });

The endpoint accepts a cancellation token and passes it to ToListAsync.

This allows database operations to respond to request cancellation rather than continuing indefinitely after the caller disconnects.

The endpoint is intentionally simple. It provides a clear place to test how the application behaves when database execution becomes slower.

Registering the Interceptor in Integration Tests

ASP.NET Core provides WebApplicationFactory through the Microsoft.AspNetCore.Mvc.Testing package.

It allows integration tests to start the application in a test host and replace selected services without changing the production configuration.

For database testing, the test project can replace the application's database registration and add the delay interceptor.

The following example uses SQLite in-memory mode.

First, install the required packages:

Bash
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package xunit

Next, create a custom WebApplicationFactory.

C#
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

public class SlowDatabaseWebApplicationFactory
    : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(
        IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            services.RemoveAll<ApplicationDbContext>();
            services.RemoveAll<DbContextOptions<ApplicationDbContext>>();

            var connection = new Microsoft.Data.Sqlite.SqliteConnection(
                "Data Source=:memory:");

            connection.Open();

            services.AddSingleton(connection);

            services.AddDbContext<ApplicationDbContext>(
                (serviceProvider, options) =>
                {
                    options.UseSqlite(connection);

                    options.AddInterceptors(
                        new SlowDatabaseInterceptor(
                            TimeSpan.FromSeconds(3)));
                });
        });
    }
}

The factory removes the original database context registration and replaces it with SQLite.

It also registers the SlowDatabaseInterceptor with a three-second delay.

The SQLite connection is kept open for the lifetime of the test factory because an in-memory SQLite database exists only while its connection remains open.

For a production-like integration test, the same approach can be used with a real database provider running in a test container.

One important detail is that this example assumes the application has an accessible Program class. For applications using top-level statements, add a public partial Program declaration to the application project:

C#
public partial class Program
{
}

Measuring the Delayed API Response

Now create an integration test that sends a request to the customers endpoint and measures how long it takes.

C#
using System.Diagnostics;
using Xunit;

public class SlowDatabaseTests
    : IClassFixture<SlowDatabaseWebApplicationFactory>
{
    private readonly HttpClient _client;

    public SlowDatabaseTests(
        SlowDatabaseWebApplicationFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetCustomers_ShouldIncludeDatabaseDelay()
    {
        var stopwatch = Stopwatch.StartNew();

        var response = await _client.GetAsync("/customers");

        stopwatch.Stop();

        Assert.True(response.IsSuccessStatusCode);

        Assert.True(
            stopwatch.Elapsed >= TimeSpan.FromSeconds(3),
            $"Expected at least 3 seconds but took " +
            $"{stopwatch.ElapsedMilliseconds} ms.");
    }
}

The test sends a real HTTP request through the ASP.NET Core test server.

The request reaches the endpoint, Entity Framework Core executes the query, and the interceptor introduces the configured delay.

The test then verifies that the response took at least three seconds.

This confirms that the delay is being applied to the database operation rather than simply delaying the test before sending the request.

In a real application, the total response time may be slightly longer because it also includes request processing, database execution, and response serialization.

Avoid asserting an exact duration. Test environments have different execution speeds, and timing measurements can vary between machines.

Testing Request Cancellation

Introducing a delay also makes it possible to test whether an API correctly handles cancellation.

Suppose the application receives a request but the caller cancels it after one second. The database interceptor should observe the cancellation token and stop waiting.

The following test sends a request with a cancellation token.

C#
[Fact]
public async Task GetCustomers_ShouldStopWhenRequestIsCanceled()
{
    using var cancellationSource =
        new CancellationTokenSource(
            TimeSpan.FromSeconds(1));

    await Assert.ThrowsAnyAsync<OperationCanceledException>(
        async () =>
        {
            await _client.GetAsync(
                "/customers",
                cancellationSource.Token);
        });
}

The interceptor is configured to wait three seconds, but the request is canceled after one second.

Because the cancellation token is passed into Task.Delay, the delay stops when cancellation is requested.

This test is useful for verifying that cancellation is passed through the ASP.NET Core endpoint and the EF Core query pipeline.

However, cancellation behavior depends on the database provider. Canceling the delay in the interceptor does not prove that every real database provider will immediately stop an already-running SQL command. That behavior should be tested separately with the actual provider when it matters.

Simulating Delays for Different Database Operations

The previous interceptor delays only queries that return rows. Some applications also need to test slow database writes or scalar operations.

For example, SaveChangesAsync may execute INSERT, UPDATE, or DELETE statements. EF Core generally uses non-query execution for these operations.

You can extend the interceptor to cover non-query and scalar commands.

C#
public class SlowDatabaseInterceptor : DbCommandInterceptor
{
    private readonly TimeSpan _delay;

    public SlowDatabaseInterceptor(TimeSpan delay)
    {
        _delay = delay;
    }

    private Task AddDelayAsync(
        CancellationToken cancellationToken)
    {
        return Task.Delay(_delay, cancellationToken);
    }

    public override async ValueTask<InterceptionResult<DbDataReader>>
        ReaderExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<DbDataReader> result,
            CancellationToken cancellationToken = default)
    {
        await AddDelayAsync(cancellationToken);

        return result;
    }

    public override async ValueTask<InterceptionResult<int>>
        NonQueryExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<int> result,
            CancellationToken cancellationToken = default)
    {
        await AddDelayAsync(cancellationToken);

        return result;
    }

    public override async ValueTask<InterceptionResult<object?>>
        ScalarExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<object?> result,
            CancellationToken cancellationToken = default)
    {
        await AddDelayAsync(cancellationToken);

        return result;
    }
}

This version applies the same delay to all three asynchronous command types.

Use this approach only when the test needs to simulate delays across different database operations. Otherwise, delaying every command can make tests unnecessarily slow.

Also, synchronous database operations are not delayed by these asynchronous overrides. If the application uses synchronous database APIs, the corresponding synchronous interceptor methods must be implemented separately.

Using a Real Database Instead of SQLite

SQLite in-memory mode is convenient for fast tests, but it does not reproduce every behavior of SQL Server or PostgreSQL.

For example, query translation, data types, locking, transaction behavior, and execution plans can differ between database providers.

If the application uses SQL Server in production, a stronger integration test can run SQL Server inside a Docker container using Testcontainers for .NET.

The database interceptor can still be registered in the same way. The only difference is the database provider and connection string.

This approach allows developers to test application behavior against the actual database engine while introducing controlled delays at the EF Core command level.

It is especially useful when testing provider-specific behavior or database operations that behave differently across engines.

Common Mistakes When Simulating Slow Databases

One common mistake is using Thread.Sleep inside an interceptor. This blocks a thread instead of waiting asynchronously. Use Task.Delay with the provided cancellation token to avoid unnecessary thread blocking.

Another mistake is assuming that delaying one interceptor method covers every database operation. Reader, scalar, and non-query commands use different execution methods. Implement only the methods required by the test scenario.

Developers should also avoid adding artificial delays to the production service registration. The delay interceptor should be registered only in the test environment.

A further mistake is treating an EF Core interceptor delay as a complete simulation of database slowness. It delays the application before command execution, but it does not reproduce slow SQL execution, lock contention, network packet loss, or connection pool exhaustion.

Finally, avoid exact timing assertions. Verify that the expected delay was introduced while allowing reasonable variation for test execution overhead.

Best Practices for Reliable Integration Tests

Keep the delay configurable so different tests can simulate different conditions. A short delay is usually sufficient to test cancellation and timeout behavior without making the entire test suite slow.

Use a separate test factory for slow-database scenarios. This prevents ordinary integration tests from receiving unexpected delays.

Test both read and write operations when the application depends on them. Also verify that cancellation tokens reach EF Core methods and that exceptions are handled appropriately by the API.

For production-like testing, use the same database provider as the application. SQLite is useful for lightweight tests, while Testcontainers can provide a real database engine in an isolated environment.

Finally, combine artificial delays with database command logging and performance measurements. This helps distinguish time spent waiting in application code from time spent executing SQL.

Summary

Slow database operations can affect API response times, connection usage, and the overall stability of an ASP.NET Core application. Testing only against a fast local database does not reveal how the application behaves when queries take longer than expected.

Entity Framework Core's DbCommandInterceptor provides a practical way to introduce controlled delays into database operations. By registering the interceptor through WebApplicationFactory, developers can test the complete ASP.NET Core request pipeline without modifying production code.

For more realistic database behavior, combine interceptor-based delay tests with integration tests using the same database provider as production.

This approach helps developers identify timeout, cancellation, and performance-handling problems before they become production incidents.