Validation is an important part of building reliable ASP.NET Core applications. Before saving a customer, creating an account, or processing an order, applications need to verify that the incoming data meets the required business rules.

Some validation rules are simple. Checking whether an email address is empty or whether an age falls within an acceptable range does not require a database call. However, other rules need to communicate with external systems or query a database.

For example, when registering a new user, an application may need to check whether the email address already exists. Similarly, creating an order may require checking product availability or verifying whether a customer has an active subscription.

These checks can become expensive when they are performed repeatedly or without proper asynchronous execution. Even when developers use async and await, validation can still introduce unnecessary database queries and increase API response times.

In this article, we will explore how asynchronous validation works in ASP.NET Core, why database calls can make validation slow, and how to improve validation performance using Entity Framework Core and FluentValidation.

Why Database Calls During Validation Can Become Slow

Consider a user registration API that checks whether an email address already exists before creating a new account.

A simple implementation might look like this:

C#
public async Task<bool> IsEmailExistsAsync(string email)
{
    return await _context.Users
        .AnyAsync(x => x.Email == email);
}

This method uses AnyAsync, which checks whether a matching record exists without loading the complete user entity.

Although this is better than retrieving an entire record, database validation can still become a performance problem in certain situations.

Common reasons include:

  • Multiple validation rules execute separate database queries.
  • The same database condition is checked more than once.
  • Database columns used for validation do not have appropriate indexes.
  • Validation queries retrieve more information than necessary.
  • Database calls are executed sequentially when independent checks could run concurrently.
  • The application performs synchronous database operations inside an asynchronous request pipeline.

For example, a registration request might check email availability, phone number availability, and username availability. If each check makes a separate database call, the total validation time can increase.

The solution is not simply to add async and await everywhere. Developers also need to examine how many queries are executed and whether each query is necessary.

Understanding Asynchronous Validation in ASP.NET Core

Asynchronous validation allows an application to perform operations that involve waiting for external resources without unnecessarily blocking a thread.

Consider the difference between synchronous and asynchronous database calls.

A synchronous query:

C#
bool exists = _context.Users
    .Any(x => x.Email == email);

An asynchronous query:

C#
bool exists = await _context.Users
    .AnyAsync(x => x.Email == email);

The asynchronous version allows the request thread to return to the thread pool while the database operation is waiting for a response.

When the database operation completes, the application continues processing the request.

This is particularly useful in ASP.NET Core applications that handle multiple concurrent requests.

However, asynchronous execution does not make the database query itself faster. It improves how application threads are used while waiting for I/O operations.

Microsoft recommends using asynchronous APIs for database and other I/O operations in ASP.NET Core applications.

Implementing Async Validation With FluentValidation

FluentValidation is a popular library for defining validation rules separately from application models.

It supports asynchronous validation through methods such as MustAsync and CustomAsync.

Let's implement a practical registration example.

Step 1. Create the Registration Model

First, define a model containing the information required to register a user.

C#
public sealed class RegisterUserRequest
{
    public string Name { get; set; } = string.Empty;

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

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

Step 2. Create a User Repository

Instead of writing database queries directly inside the validator, keep database access in a separate service.

C#
public interface IUserRepository
{
    Task<bool> EmailExistsAsync(
        string email,
        CancellationToken cancellationToken);

    Task<bool> PhoneExistsAsync(
        string phoneNumber,
        CancellationToken cancellationToken);
}

Now implement the repository using Entity Framework Core.

C#
public sealed class UserRepository : IUserRepository
{
    private readonly AppDbContext _context;

    public UserRepository(AppDbContext context)
    {
        _context = context;
    }

    public Task<bool> EmailExistsAsync(
        string email,
        CancellationToken cancellationToken)
    {
        return _context.Users
            .AnyAsync(
                x => x.Email == email,
                cancellationToken);
    }

    public Task<bool> PhoneExistsAsync(
        string phoneNumber,
        CancellationToken cancellationToken)
    {
        return _context.Users
            .AnyAsync(
                x => x.PhoneNumber == phoneNumber,
                cancellationToken);
    }
}

Using AnyAsync avoids loading complete user records when the application only needs to know whether a matching record exists.

The cancellation token also allows the database operation to be cancelled when the request is no longer needed.

Step 3. Create an Asynchronous Validator

Now define the registration validator.

C#
public sealed class RegisterUserValidator
    : AbstractValidator<RegisterUserRequest>
{
    public RegisterUserValidator(IUserRepository repository)
    {
        RuleFor(x => x.Name)
            .NotEmpty()
            .MaximumLength(100);

        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress()
            .MustAsync(async (email, cancellationToken) =>
            {
                return !await repository.EmailExistsAsync(
                    email,
                    cancellationToken);
            })
            .WithMessage("Email address is already registered.");

        RuleFor(x => x.PhoneNumber)
            .NotEmpty()
            .MustAsync(async (phone, cancellationToken) =>
            {
                return !await repository.PhoneExistsAsync(
                    phone,
                    cancellationToken);
            })
            .WithMessage("Phone number is already registered.");
    }
}

The validator separates business validation rules from the controller.

The Name rule performs local validation, while the Email and PhoneNumber rules execute asynchronous database checks.

Passing the cancellation token is important because it allows the underlying database operation to respond to cancellation requests.

Step 4. Register Dependencies

Register the repository and validator in the application's dependency injection container.

C#
builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddScoped<
    IValidator<RegisterUserRequest>,
    RegisterUserValidator>();

The scoped lifetime is appropriate because the repository uses an Entity Framework Core DbContext, which is normally registered with a scoped lifetime.

Step 5. Execute Validation Asynchronously in the Controller

One important detail is how the validator is executed.

For asynchronous rules, call ValidateAsync rather than Validate.

C#
[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
    private readonly IValidator<RegisterUserRequest> _validator;

    public UsersController(
        IValidator<RegisterUserRequest> validator)
    {
        _validator = validator;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(
        RegisterUserRequest request,
        CancellationToken cancellationToken)
    {
        var validationResult = await _validator.ValidateAsync(
            request,
            cancellationToken);

        if (!validationResult.IsValid)
        {
            return BadRequest(
                validationResult.Errors.Select(x => new
                {
                    x.PropertyName,
                    x.ErrorMessage
                }));
        }

        return Ok(new
        {
            Message = "User registration validation completed."
        });
    }
}

The controller explicitly executes asynchronous validation before continuing with the registration operation.

There is an important distinction here. FluentValidation's traditional automatic integration with the ASP.NET Core MVC validation pipeline is synchronous. Asynchronous validation rules should not be placed in that automatic pipeline.

For this reason, manually calling ValidateAsync is a straightforward approach when using FluentValidation with MVC controllers.

Running Independent Validation Queries Concurrently

Another way to reduce validation time is to execute independent database checks concurrently.

Consider the email and phone number checks from the previous example.

If both checks are independent, they do not necessarily need to wait for each other.

You can execute them using Task.WhenAll.

C#
public async Task<bool> HasDuplicateDetailsAsync(
    string email,
    string phoneNumber,
    CancellationToken cancellationToken)
{
    var emailTask = _repository.EmailExistsAsync(
        email,
        cancellationToken);

    var phoneTask = _repository.PhoneExistsAsync(
        phoneNumber,
        cancellationToken);

    await Task.WhenAll(emailTask, phoneTask);

    return await emailTask || await phoneTask;
}

Both operations start before the application waits for their completion.

However, there is an important Entity Framework Core limitation.

A single DbContext does not support multiple concurrent operations. Therefore, the two repository calls must not execute simultaneously against the same DbContext instance.

The previous example is appropriate only when the repository implementation uses independent DbContext instances or another data-access approach that supports concurrent operations.

If both checks use the same scoped DbContext, execute them sequentially or combine them into a single database query.

Reducing Database Calls With a Single Query

Sometimes the best optimization is to avoid multiple database calls altogether.

Instead of checking email and phone availability separately, you can combine both conditions into one query.

C#
public async Task<bool> HasDuplicateDetailsAsync(
    string email,
    string phoneNumber,
    CancellationToken cancellationToken)
{
    return await _context.Users.AnyAsync(
        x => x.Email == email ||
             x.PhoneNumber == phoneNumber,
        cancellationToken);
}

This query checks both conditions in one database round trip.

However, the application only receives a Boolean result. If it needs to display separate error messages for email and phone number, it must identify which condition matched.

A single query is not automatically the best option for every scenario. Choose the query structure based on the information the application needs and the database execution plan.

Advantages and Disadvantages of Async Validation

Advantages

  1. Better thread utilization: Asynchronous database operations avoid blocking request threads while waiting for database responses.
  2. Cleaner separation of concerns: Validation rules can remain separate from controller and repository implementations.
  3. Better cancellation support: Cancellation tokens can stop unnecessary database operations when a request is cancelled.
  4. Flexible validation logic: Developers can validate data using databases, external APIs, and other asynchronous services.
  5. Better scalability: Proper asynchronous I/O helps ASP.NET Core applications handle concurrent requests more efficiently.

Disadvantages

  1. Additional implementation complexity: Asynchronous validators require proper execution and dependency management.
  2. Database dependency: Validation can become unavailable or slow when the database experiences connectivity problems.
  3. More complex concurrency: Running independent checks concurrently requires careful DbContext management.
  4. Additional database traffic: Every external validation rule can introduce another database query.
  5. Race conditions: A successful validation does not guarantee that the data will remain unique when the record is eventually inserted.

Best Practices for Improving Async Validation Performance

Use AnyAsync Instead of Loading Complete Records

When checking whether a record exists, use AnyAsync instead of retrieving the complete entity.

This avoids unnecessary data retrieval and tracking.

Create Indexes for Frequently Validated Columns

If email and phone number are frequently checked, ensure that the corresponding database columns have appropriate indexes.

For uniqueness requirements, consider unique database constraints as well.

Avoid Duplicate Validation Queries

Do not perform the same database check in multiple validators, services, and controllers during one request unless there is a clear reason.

Keep validation responsibilities organized.

Pass Cancellation Tokens

Always pass the request cancellation token to asynchronous database operations.

This prevents unnecessary work when a client disconnects or the request is cancelled.

Do Not Run Multiple Queries on the Same DbContext Concurrently

Entity Framework Core does not support parallel operations on one DbContext instance.

Use sequential queries or separate DbContext instances when concurrent execution is necessary.

Keep Business Rules and Database Constraints Consistent

An email availability check is useful for providing an immediate validation message, but it cannot guarantee uniqueness.

Two requests can pass validation at almost the same time and attempt to insert the same email address.

A unique database constraint is the final protection against duplicate records. Handle the resulting database constraint violation appropriately in the application.

Common Mistakes and Troubleshooting

Problem

Possible reason

Recommended solution

Async validator throws an exception

Validate was called instead of ValidateAsync

Always use ValidateAsync for asynchronous rules

API requests become slow

Too many separate database queries

Combine independent checks where appropriate

DbContext concurrency exception

Multiple operations run simultaneously on one context

Execute sequentially or use separate contexts

Database query takes too long

Missing indexes or inefficient query conditions

Review indexes and database execution plans

Validation continues after request cancellation

Cancellation token is not passed to database operations

Pass the request cancellation token

Duplicate records are inserted

Validation and insertion are separate operations

Enforce uniqueness with database constraints

Automatic validation fails with async rules

Synchronous MVC validation pipeline is being used

Invoke the validator manually using ValidateAsync

Summary

Asynchronous validation is important when ASP.NET Core applications need to verify information using databases or external services.

Using async and await prevents request threads from remaining blocked while waiting for I/O operations. However, asynchronous execution alone does not guarantee fast validation. Developers must also reduce unnecessary database queries, use efficient existence checks, and understand the limitations of Entity Framework Core.

FluentValidation provides a convenient way to organize asynchronous validation rules through MustAsync and ValidateAsync. Combining these rules with cancellation tokens, appropriate database indexes, and unique constraints helps build more reliable registration and business workflows.

The most important point is to treat validation as part of the application's performance design. A well-designed validator should perform only the checks it needs, avoid unnecessary database calls, and leave final data integrity enforcement to the database.