← All writing
/writing

Design Preconditions That Can't Become an N+1

Give a precondition check a DbContext and you've written a performance bug with a delayed fuse.

The problem

A rule like "the response must already be on file" needs data. The obvious move is to inject a repository:

// Tempting, and a trap.
public sealed class ResponseFiledGuard(IResponseRepository repo) : IGuard
{
    public bool IsSatisfied(Order order) => repo.ExistsFor(order.Id);  // a query, per guard
}

Five rules on one transition is five round trips. Evaluate that transition for twenty rows to render a list, and you have a hundred.

Gather once, then evaluate

Make the engine collect everything the rules could need, once, and pass it in:

public sealed record GuardContext(
    Order Order,
    IReadOnlySet<string> ActorPermissions,
    IReadOnlyDictionary<string, string> Facts)
{
    public bool FactIsTrue(string key) =>
        Facts.TryGetValue(key, out var v) && bool.TryParse(v, out var b) && b;
}

Rules become pure functions over that record. They cannot query, because they have nothing to query with.

Why it matters

Purity here buys two things at once. Performance is bounded by construction — one fact-gathering trip per transition, no matter how many rules run. And every rule becomes trivially testable: build a context, assert the outcome, no database, no mocks.

Keeping facts as a string dictionary looks crude next to a typed context object. It's deliberate: a new rule needs a new fact, not a new context type and a change to every call site.

← All writing