The short version

  • .NET 11 lets a Data Annotations rule await a database call. Think of checks like "is this email already taken?".
  • It keeps that rule on the model. It doesn't make validation faster, and I want to be clear about that from the start.
  • What it changes is how many requests my test server handles when the database is slow and requests arrive together. At a 10 ms lookup and 256 concurrent requests, the five-run medians put the awaited attribute on .NET 11 at about five times the throughput of the blocking handler on .NET 11, and the hand-written awaited handler at about six and a half times. The ranges didn't overlap. The attribute gave up some of that: on the same runtime it completed about 18 per cent fewer requests than the hand-written awaited handler. A single-run sweep showed a smaller gap at the same lookup time, and I haven't explained the difference.
  • The database delay was simulated with pg_sleep, not a production workload. These results come from one two-core sandbox, so read them as a comparison on that setup, not as a general law.

Background: what Data Annotations are and what was missing

Picture a sign-up form for a small online service. A visitor types an email address and presses submit. Before the form can continue, it has to answer one question: is this address already in use? The answer lives in a database.

Data Annotations are the attributes you put on a model's properties, such as [Required], [StringLength] and [EmailAddress]. The framework checks them before your code runs. Those checks are synchronous. Each one returns a result straight away.

That worked fine for "this field is required". It didn't work well for "is this email taken?" The answer comes from a database. Before .NET 11 you had two choices:

  1. Wait for the database inside the check, which blocks the thread. This causes trouble under load, as you'll see below.
  2. Move the check into the endpoint. It works, but the rule leaves the model, and it's easy to forget.

FluentValidation is the usual alternative. It supports asynchronous rules, but it's one more library to learn and maintain.

Background: what await does for threads

A web server handles requests with a limited pool of threads, called the thread pool. The pool can grow. But not instantly, and not without limit.

When a request waits on a database, what happens to its thread depends on the code:

  • A blocking thread waits and does nothing else until the answer arrives. Other requests that need a thread have to queue.
  • An awaiting thread returns to the pool while the database works. When the answer arrives, the request carries on, possibly on a different thread.

Picture a restaurant with a fixed number of waiters. A blocking waiter stands at the kitchen door until the food is ready. An awaiting waiter takes orders from other tables in the meantime. Both serve the same food at the same speed. But the second one seats more guests.

What .NET 11 adds

Three new pieces fit the existing model. Microsoft's What's new in .NET 11 page confirms that .NET 11 is generally available.

The first is AsyncValidationAttribute. It's an abstract base class with one method to override. You write the check, and the framework awaits it. The method takes the value, a ValidationContext and a CancellationToken, and returns a Task<ValidationResult?>. The framework can cancel that token when another rule fails, and the documentation says your implementation must observe it. I test that in the cancellation section below. The attribute also has to be thread-safe, so keep it free of shared mutable state.

The second is IAsyncValidatableObject, for rules that look at several properties at once. It's the asynchronous version of IValidatableObject.

The third is Validator.ValidateObjectAsync. It lives in System.ComponentModel.Annotations, so it works in a console application or a background worker, not only in ASP.NET Core.

The ASP.NET Core validation documentation says asynchronous validation operations can run in parallel, and that their completion order isn't guaranteed. So your rules mustn't depend on order or share mutable state.

Example: a unique email address

The attribute and endpoint below are close to the code I ran in the tests. The store is an interface you implement with your own data access. In the tests it was backed by Postgres, and the code shown here leaves out the test's artificial delay.

First, the store interface. The synchronous method exists only for the blocking baseline further down:

public interface IUserStore
{
    Task<bool> EmailExistsAsync(string email, CancellationToken ct);
    bool EmailExists(string email);
}

Next, the attribute. The base class declares the synchronous IsValid method abstract, so the attribute has to override it. The snippet throws InvalidOperationException from it, so a synchronous call fails loudly instead of returning a wrong answer. Minimal API validation always takes the asynchronous path, so the synchronous method is never called on that route:

using System.ComponentModel.DataAnnotations;

public sealed class UniqueEmailAttribute : AsyncValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        => throw new InvalidOperationException("UniqueEmail needs an asynchronous validation entry point.");

    protected override async Task<ValidationResult?> IsValidAsync(
        object? value, ValidationContext validationContext, CancellationToken cancellationToken)
    {
        if (value is not string email) return ValidationResult.Success;

        var store = (IUserStore)validationContext.GetService(typeof(IUserStore))!;

        return await store.EmailExistsAsync(email, cancellationToken)
            ? new ValidationResult("This email address is already registered.", [validationContext.MemberName!])
            : ValidationResult.Success;
    }
}

The attribute goes on the request model, next to the attributes you already use:

using System.ComponentModel.DataAnnotations;

public sealed class UniqueRequest
{
    [Required, EmailAddress, StringLength(254), UniqueEmail]
    public string Email { get; set; } = "";
}

Finally, register the store and validation, and map the endpoint:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IUserStore>(/* your implementation */);
builder.Services.AddValidation();

var app = builder.Build();

app.MapPost("/users", (UniqueRequest body) => Results.Created("/users", body));

app.Run();

Results.Created puts /users in the Location header, so personal data stays out of the URL. In a real project, point the header at a resource that exists.

In the tests, a taken address returned 400 with the message under Email, and a new address returned 201. The framework produced the 400 response with a ProblemDetails body. I checked the response, but I didn't separately confirm that the handler is skipped.

A check like this isn't enough on its own. Two requests can both see an address as free, and both save it. The fix is a unique index on the column, with the duplicate-key error mapped to the same 400 response. The check gives the user a friendly message, and the index keeps the data correct. The store should also be cheap to call. A uniqueness check on an indexed column is fine. A full table scan on every request isn't.

The trap: don't validate these models synchronously

A model with an asynchronous attribute must be validated asynchronously. The synchronous Validator methods call the synchronous IsValid, and in our attribute that method throws on purpose, so a synchronous call fails.

If you have a helper that validates objects synchronously, switch it to Validator.ValidateObjectAsync before you add an async attribute to the model. Check the overload you pick. By default, ValidateObjectAsync checks the [Required] attributes on the properties and the type-level attributes. It doesn't check the other property attributes unless you pass validateAllProperties: true. Passing true is the safe choice when a model mixes both kinds.

Cancellation: what happens when another rule fails

The framework can stop the other rules when one fails, and it cancels the token it gives them. To see what that does in practice, I wrote a small test project. One model has two properties. Name fails at once, and Email has a rule that takes two seconds and is still running when Name fails. I ran each case in two modes, one where the rule honours the token and one where it ignores it.

Calling Validator.TryValidateObjectAsync with a null results collection stops at the first error, and the token given to the slow rule is cancelled. A rule that honours the token returned a 400 in 1 to 45 ms over three runs. A rule that ignores it took about two seconds, because the request waited for it to finish even though its token had already been cancelled.

Minimal API validation behaved differently. With the attribute registered through AddValidation, the 400 took about two seconds in both modes, three runs each, and the slow rule was never cancelled, whichever property came first. The framework collected the errors and waited for every rule. I didn't find a way to get the short-circuit through Minimal API validation. So if a slow rule must not hold up the response, call Validator.TryValidateObjectAsync with a null results collection, and check the behaviour in your own project before you rely on it.

Why waiting matters

Imagine a sign-up endpoint on a launch day, with many people submitting at once. Each submission runs the uniqueness check, and that check waits for the database.

Both snippets use a request model without the uniqueness attribute:

public sealed class PlainRequest
{
    [Required, EmailAddress, StringLength(254)]
    public string Email { get; set; } = "";
}

Both handlers first run Valid, a small helper that calls Validator.TryValidateObject with validateAllProperties: true:

static bool Valid(object model) =>
    Validator.TryValidateObject(model, new ValidationContext(model), new List<ValidationResult>(), validateAllProperties: true);

Here are two ways to write the endpoint. The blocking version calls the synchronous data access method, so the thread waits for the database and does nothing else:

// Blocking: the thread waits for the database and does nothing else.
app.MapPost("/users", (PlainRequest body, IUserStore store) =>
    !Valid(body) ? Results.BadRequest("invalid")
    : store.EmailExists(body.Email)
        ? Results.BadRequest("This email address is already registered.")
        : Results.Created("/users", body));

Wrapping the asynchronous method with GetAwaiter().GetResult() blocks in the same way, and the documentation discourages both. I measured only the synchronous version.

The awaited version gives the thread back during the wait:

// Awaited: the thread is released while the database works.
app.MapPost("/users", async (PlainRequest body, IUserStore store, CancellationToken ct) =>
    !Valid(body) ? Results.BadRequest("invalid")
    : await store.EmailExistsAsync(body.Email, ct)
        ? Results.BadRequest("This email address is already registered.")
        : Results.Created("/users", body));

Both versions validate the request first, then run the same check and return the same responses. What differs is what happens to the thread during the wait.

What I measured

I measured the variants at 256 concurrent requests, with a Postgres lookup that takes 10 ms. Each variant ran five times on each runtime. Each row shows the median of those five runs, with the throughput range in brackets.

ApproachThroughput, requests per second (median, range)Median response time (p50)99th percentile (p99)
.NET 10 blocking570 (503 to 631)435 ms834 ms
.NET 10 awaited handler3,798 (3,654 to 4,579)65 ms111 ms
.NET 11 blocking632 (616 to 2,052)382 ms1,002 ms
.NET 11 awaited handler4,127 (3,416 to 4,565)61 ms94 ms
.NET 11 awaited attribute3,383 (3,159 to 4,178)72 ms122 ms

The attribute only exists on .NET 11, so it has no .NET 10 row. Its comparison to the blocking handler is the useful one for this article.

A few terms, in case they're new to you:

  • Throughput is how many requests the server completes per second.
  • The median (p50) is the time that half the requests beat.
  • The 99th percentile (p99) is the time that 99 in 100 requests beat. It shows how bad the slowest requests get.
  • Concurrency is how many requests are in progress at the same time.

At 10 ms the ranges don't overlap on either runtime. The two-core machine varies from run to run, so the ranges matter more than any single number.

Why the difference appears

My reading is that blocking code holds a thread for each waiting request. The pool is limited, so requests queue. Users would then wait for the queue as well as for the database. I didn't measure queue times directly, but the pattern fits the results. With awaiting, the threads can serve other requests, so the queue should not form.

The thread pool also has runtime settings for how quickly it adds threads when work blocks. From .NET 6 they are System.Threading.ThreadPool.Blocking.ThreadsToAddWithoutDelay_ProcCountFactor, System.Threading.ThreadPool.Blocking.ThreadsPerDelayStep_ProcCountFactor, System.Threading.ThreadPool.Blocking.DelayStepMs and System.Threading.ThreadPool.Blocking.MaxDelayMs. The documentation ties them to waits on other tasks. My blocking handler doesn't wait on a task. It makes a synchronous call, so these settings may not affect it at all, and they may not explain the gap. I used the defaults for those settings and for the Npgsql connection pool, which I capped at 100. Changing them might narrow the gap, but that's untested.

When the benefit appears

By "sweep" I mean one run of each variant at each lookup time, 0, 2 and 10 ms, all at 256 concurrent requests. Here's the throughput from that sweep:

Lookup timeBlocking, .NET 10Blocking, .NET 11Awaited handler, .NET 10Awaited handler, .NET 11
0 ms8,2319,47712,69112,336
2 ms4,8476,0278,1227,389
10 ms2,2232,4157,5547,200

Each cell is one run, so the sweep is noisier than the five-run table. Its absolute figures also differ from the repeated runs by up to about four times, and I haven't found out why. So I rely on comparisons between variants within the same sweep, not on the absolute numbers.

I then ran the 5 ms point with the final settings, five times for each variant on each runtime:

ApproachThroughput, requests per second (median, range)
.NET 10 blocking1,014 (899 to 1,140)
.NET 10 awaited handler4,083 (3,451 to 4,548)
.NET 11 blocking939 (359 to 1,163)
.NET 11 awaited handler3,677 (3,243 to 4,210)
.NET 11 awaited attribute3,573 (3,145 to 4,077)

At 5 ms the ranges don't overlap on either runtime. The .NET 11 blocking runs spread much wider than the others, from 359 to 1,163, so the median says more than any single run.

The gap grows with the wait, but the sources differ, so I read them separately. The single sweep runs gave about 1.3 to 1.5 times at 0 ms and about 1.2 to 1.7 times at 2 ms, for the awaited handler against blocking. The five-run medians gave about four times at 5 ms and about six and a half times at 10 ms. The sweep's 10 ms gap was only about three times, and I can't yet explain why the two sets differ that much. With so few runs per point, I can't say how the gap grows beyond 10 ms.

What it doesn't change, and what the attribute costs

The benefit comes from releasing the thread during the wait, and the validation itself doesn't get faster. The same pattern applies to a hand-written endpoint, and I measured that on both .NET 10 and .NET 11 at 5 ms and 10 ms.

I also measured the CPU cost of validation alone with BenchmarkDotNet, the common .NET benchmarking tool, with no waiting and an in-memory store. That benchmark isn't part of the code in this article, so treat its figures as unverified here. The attribute costs about 370 ns and about 850 bytes more per request than the same check written inline, which is small next to a 10 ms wait. On .NET 11, though, the attribute ran about 10 to 20 per cent slower than the hand-written await at 10 ms, and about 3 per cent slower at 5 ms. The CPU cost predicts only about 370 ns of extra work per request, far too little to explain the gap at 10 ms, so I treat that gap as unresolved. The attribute's advantage is that it keeps the rule on the model. It is not a speed gain.

How to reproduce these numbers

Everything in this article came from one setup: a Linux sandbox with two cores, running .NET 10.0.15 and .NET 11.0.0 (generally available). The load generator shared those cores with the server and the database, so the absolute numbers carry its overhead. Postgres 16 ran in the same sandbox and was reached over TCP on the loopback interface, not over a real network. The delay is pg_sleep on the database server, not a client-side timer. The load generator sends real HTTP requests over keep-alive connections, and each measured run lasts five seconds after a two-second warm-up. That's short for a 99th percentile, so the spread between runs is the best guide to precision.

You need Linux with two cores, Postgres 16, and the .NET 10 and .NET 11 SDKs. The code below is the code I ran. Your figures will differ, so compare the variants with each other rather than matching my numbers.

Create a folder called repro with three subfolders, api, loadgen and cancel, and save the files from the listings at the end of this section into them.

  1. Prepare Postgres. Set max_connections to 200, then restart the server, because the setting only takes effect after a restart:
ALTER SYSTEM SET max_connections = 200;
sudo systemctl restart postgresql   # or: sudo service postgresql restart

Create the database and the table, and fill it with 10,001 rows:

CREATE DATABASE users;
\c users
CREATE TABLE users (id bigserial PRIMARY KEY, email text NOT NULL);
INSERT INTO users (email) SELECT 'user' || g || '@example.com' FROM generate_series(1, 10001) g;
CREATE INDEX users_email_idx ON users (email);
ANALYZE users;

Before each run, check that Postgres accepts connections. If it's stopped, every request returns 500, and the load generator reports them as non-201.

  1. Build the three projects:
cd repro/api && dotnet build -c Release
cd ../loadgen && dotnet build -c Release
cd ../cancel && dotnet build -c Release
  1. Start one variant from repro/api. The connection string keeps the Npgsql pool at 100:
cd repro/api
export PG_CONN="Host=127.0.0.1;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=users;Maximum Pool Size=100"
VARIANT=blocking DB_DELAY_MS=10 dotnet bin/Release/net11.0/api.dll

The variants are blocking, manual-async (the awaited handler) and attribute-async. The attribute variant only compiles for net11.0, so use bin/Release/net10.0/api.dll for the .NET 10 runs of the other two.

  1. In a second terminal, check the server is up. /health reports the variant, the runtime and the pool size:
curl -s http://127.0.0.1:5080/health
  1. From repro, send 256 concurrent requests for 5 seconds, after a 2-second warm-up:
cd repro
dotnet loadgen/bin/Release/net11.0/loadgen.dll http://127.0.0.1:5080/users 256 5 2

It prints requests per second, the p50 and p99 response times, and the number of non-201 responses. That last number should be 0.

  1. Stop the API, switch the variant or the runtime, and repeat. Run each combination five times and use the medians.

On the final code, one run at 10 ms gave 579 requests a second for the blocking handler, 4,846 for the awaited handler and 4,135 for the attribute. The blocking figure sits just below its five-run range, and the awaited handler just above its range. One run can land outside a range, so compare medians.

The cancellation test needs no database. Start it from repro/cancel, which listens on port 5090:

cd repro/cancel
CANCEL_MODE=observe dotnet bin/Release/net11.0/cancel.dll

In another terminal, send a request whose name is bad:

curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" -X POST http://127.0.0.1:5090/try-null-email-first -H "Content-Type: application/json" -d '{"email":"a@b.c","name":"bad"}'

Repeat with CANCEL_MODE=ignore. The observe run should return in milliseconds, and the ignore run should take about two seconds.

The Minimal API route in the same program shows the other behaviour. Post to /minimal-email-first with the same body:

curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" -X POST http://127.0.0.1:5090/minimal-email-first -H "Content-Type: application/json" -d '{"email":"a@b.c","name":"bad"}'

In both modes it takes about two seconds, because AddValidation waits for every rule.

The files:

api/api.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFrameworks>net10.0;net11.0</TargetFrameworks>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Npgsql" Version="9.0.3" />
  </ItemGroup>
</Project>

api/Program.cs

using System.ComponentModel.DataAnnotations;
using Npgsql;

var variant = Environment.GetEnvironmentVariable("VARIANT") ?? "manual-async";
var delayMs = int.Parse(Environment.GetEnvironmentVariable("DB_DELAY_MS") ?? "0");
var pg = Environment.GetEnvironmentVariable("PG_CONN")!;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://127.0.0.1:5080");
builder.Services.AddSingleton<IUserStore>(new Db(pg, delayMs));
#if NET11_0_OR_GREATER
if (variant == "attribute-async") builder.Services.AddValidation();
#endif

var app = builder.Build();

app.MapGet("/health", () => Results.Json(new
{
    variant,
    runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription,
    maxPoolSize = new NpgsqlConnectionStringBuilder(pg).MaxPoolSize,
}));

switch (variant)
{
    case "blocking":
        app.MapPost("/users", (PlainRequest body, IUserStore store) =>
            !Valid(body) ? Results.BadRequest("invalid")
            : store.EmailExists(body.Email)
                ? Results.BadRequest("This email address is already registered.")
                : Results.Created("/users", body));
        break;

    case "manual-async":
        app.MapPost("/users", async (PlainRequest body, IUserStore store, CancellationToken ct) =>
            !Valid(body) ? Results.BadRequest("invalid")
            : await store.EmailExistsAsync(body.Email, ct)
                ? Results.BadRequest("This email address is already registered.")
                : Results.Created("/users", body));
        break;

#if NET11_0_OR_GREATER
    case "attribute-async":
        app.MapPost("/users", (UniqueRequest body) => Results.Created("/users", body));
        break;
#endif

    default:
        throw new InvalidOperationException($"Unknown VARIANT '{variant}'.");
}

app.Run();

static bool Valid(object model) =>
    Validator.TryValidateObject(model, new ValidationContext(model), new List<ValidationResult>(), validateAllProperties: true);

public sealed class PlainRequest
{
    [Required, EmailAddress, StringLength(254)]
    public string Email { get; set; } = "";
}

public interface IUserStore
{
    Task<bool> EmailExistsAsync(string email, CancellationToken ct);
    bool EmailExists(string email);
}

// Real Postgres over TCP. pg_sleep makes the server itself take the chosen time per lookup.
public sealed class Db(string connectionString, int delayMs) : IUserStore
{
    private readonly NpgsqlDataSource _ds = NpgsqlDataSource.Create(connectionString);
    private readonly double _delaySec = delayMs / 1000.0;
    private const string Sql = "SELECT EXISTS(SELECT 1 FROM users WHERE email = $1) FROM pg_sleep($2)";

    public async Task<bool> EmailExistsAsync(string email, CancellationToken ct)
    {
        await using var c = await _ds.OpenConnectionAsync(ct);
        await using var cmd = new NpgsqlCommand(Sql, c);
        cmd.Parameters.AddWithValue(email);
        cmd.Parameters.AddWithValue(_delaySec);
        return (bool)(await cmd.ExecuteScalarAsync(ct))!;
    }

    public bool EmailExists(string email)
    {
        using var c = _ds.OpenConnection();
        using var cmd = new NpgsqlCommand(Sql, c);
        cmd.Parameters.AddWithValue(email);
        cmd.Parameters.AddWithValue(_delaySec);
        return (bool)cmd.ExecuteScalar()!;
    }
}

#if NET11_0_OR_GREATER
public sealed class UniqueEmailAttribute : AsyncValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        => throw new InvalidOperationException("UniqueEmail needs an asynchronous validation entry point.");

    protected override async Task<ValidationResult?> IsValidAsync(
        object? value, ValidationContext validationContext, CancellationToken cancellationToken)
    {
        if (value is not string email) return ValidationResult.Success;
        var store = (IUserStore)validationContext.GetService(typeof(IUserStore))!;
        return await store.EmailExistsAsync(email, cancellationToken)
            ? new ValidationResult("This email address is already registered.", [validationContext.MemberName!])
            : ValidationResult.Success;
    }
}

public sealed class UniqueRequest
{
    [Required, EmailAddress, StringLength(254), UniqueEmail]
    public string Email { get; set; } = "";
}
#endif

loadgen/loadgen.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

loadgen/Program.cs

// usage: loadgen <url> <concurrency> <measureSeconds> <warmupSeconds>
using System.Diagnostics;
using System.Net;
using System.Text;

var url = args[0];
int concurrency = int.Parse(args[1]);
double measureSeconds = double.Parse(args[2]);
double warmupSeconds = double.Parse(args[3]);

// Keep-alive connections, one per concurrent worker.
using var http = new HttpClient(new SocketsHttpHandler { MaxConnectionsPerServer = 1024 })
{
    Timeout = TimeSpan.FromSeconds(30),
};

async Task<(int Status, double Ms)> Post()
{
    // An address that is not in the table, so every request is a successful insert.
    using var content = new StringContent("{\"email\":\"brand.new@example.com\"}", Encoding.UTF8, "application/json");
    long start = Stopwatch.GetTimestamp();
    using var response = await http.PostAsync(url, content);
    return ((int)response.StatusCode, Stopwatch.GetElapsedTime(start).TotalMilliseconds);
}

async Task<List<(int Status, double Ms)>> Phase(double seconds)
{
    var results = new System.Collections.Concurrent.ConcurrentBag<(int Status, double Ms)>();
    var end = DateTime.UtcNow.AddSeconds(seconds);
    var workers = Enumerable.Range(0, concurrency).Select(_ => Task.Run(async () =>
    {
        while (DateTime.UtcNow < end)
        {
            try { results.Add(await Post()); }
            catch (Exception) { results.Add((0, 0)); }
        }
    })).ToArray();
    await Task.WhenAll(workers);
    return results.ToList();
}

static double Percentile(List<double> sorted, double p) =>
    sorted.Count == 0 ? double.NaN : sorted[(int)Math.Min(sorted.Count - 1, Math.Floor(p * sorted.Count))];

await Phase(warmupSeconds);
var done = await Phase(measureSeconds);
var created = done.Where(r => r.Status == 201).Select(r => r.Ms).OrderBy(ms => ms).ToList();
int notCreated = done.Count - created.Count;
Console.WriteLine($"requests/s={created.Count / measureSeconds:F0} p50={Percentile(created, 0.50):F1} ms p99={Percentile(created, 0.99):F1} ms non-201={notCreated}");

cancel/cancel.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

cancel/Program.cs

using System.ComponentModel.DataAnnotations;

// CANCEL_MODE=observe: the slow rule honours the token. CANCEL_MODE=ignore: it ignores it.
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://127.0.0.1:5090");
builder.Services.AddValidation();
var app = builder.Build();

// Email is declared first, so its slow rule is still running when Name fails.
app.MapPost("/try-null-email-first", async (HttpContext http, CancellationToken ct) =>
{
    var body = await http.Request.ReadFromJsonAsync<CancelRequest>(ct);
    var ok = await Validator.TryValidateObjectAsync(body!, new ValidationContext(body!), null, validateAllProperties: true, ct);
    return ok ? Results.Ok() : Results.BadRequest("invalid");
});

// Minimal API route: AddValidation validates the body before the handler runs.
app.MapPost("/minimal-email-first", (CancelRequest body) => Results.Ok());
app.Run();

public sealed class CancelRequest
{
    [SlowRule, EmailAddress]
    public string Email { get; set; } = "";

    [FailsFast]
    public string Name { get; set; } = "";
}

public sealed class FailsFastAttribute : AsyncValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        => throw new InvalidOperationException("async only");

    protected override async Task<ValidationResult?> IsValidAsync(object? value, ValidationContext ctx, CancellationToken ct)
    {
        await Task.Yield();
        return value as string == "bad" ? new ValidationResult("bad name", [ctx.MemberName!]) : ValidationResult.Success;
    }
}

public sealed class SlowRuleAttribute : AsyncValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        => throw new InvalidOperationException("async only");

    protected override async Task<ValidationResult?> IsValidAsync(object? value, ValidationContext ctx, CancellationToken ct)
    {
        var mode = Environment.GetEnvironmentVariable("CANCEL_MODE") ?? "observe";
        if (mode == "ignore") await Task.Delay(TimeSpan.FromSeconds(2));
        else await Task.Delay(TimeSpan.FromSeconds(2), ct);
        return ValidationResult.Success;
    }
}

Pitfalls and limits

  • The documentation confirms that Minimal API validation always takes the asynchronous path, which matches my tests. The validation documentation also says Blazor form validation calls the asynchronous path when the form is submitted, so async rules work there without extra setup. I haven't tested Blazor myself.
  • I haven't tested MVC, and I didn't confirm its behaviour in the documentation. Check before you plan around it.
  • The documentation says asynchronous validation operations can run in parallel, with no guaranteed order. I haven't measured that.

Which tool, and is it worth it?

Built-in validation is the right default for rules that depend only on the request. Required fields, lengths, ranges and formats belong there, with the attributes you already know, the 400 response and no extra library.

FluentValidation still earns its place for complex rules that span several properties, or for validation you want to keep out of your domain models. The async attribute sits in between: it covers a single rule that needs one database call, such as a uniqueness check. If your model needs five such checks and several cross-field rules, a validator class is probably cleaner.

Is it worth it? Yes, but more narrowly than I first hoped. Use an async rule when the check waits on a database and many requests can overlap, because that's when awaiting increases capacity. In my runs the gain was there at 0, 2, 5 and 10 milliseconds, and it was largest at the longer waits. Choose the attribute for the way it keeps the rule on the model, not for speed.

Do you already validate with FluentValidation? If so, is one more library worth removing for this one feature? I'd like to hear how you handle it.