← Back to Blog

Pre-Flight Compliance & Guardrail Checks

Running ordered schema, signature, KYC, velocity, and balance gates in our Fiat & Crypto Settlement Hub without burying the happy path under nested conditionals.

REQ AUTH KYC BAL OK

In Milestone 3, we made sure a TransferInstruction cannot even exist in memory unless its own fields are internally consistent. Internal consistency is only half the battle, though. Before the hub locks a cent or touches a blockchain node, an incoming transfer request still has to pass external business and compliance guardrails.

Every transfer request arriving at the Settlement Hub passes through five ordered gates before it reaches the ledger:

  1. Schema check: verify the tenant ID, currency format, and positive amount.
  2. Signature auth: confirm the partner's HMAC signature matches the request payload.
  3. KYC and sanctions screening: block sanctioned counterparties and cap unverified BASIC accounts at $500.
  4. Daily velocity limit: verify that dailyUsed + amount stays inside the tenant's daily cap.
  5. Available balance check: verify the source wallet actually holds enough unlocked funds.

Why Order and Early Exit Matter

Ordering and early exits matter just as much as the checks themselves. If a request carries a forged signature, we must reject it immediately at gate 2 without wasting a paid sanctions API call or hitting the wallet balance table. At the same time, every rejection needs an explicit machine-readable reason code and human-readable explanation so the partner's API client knows whether to fix a payload, refresh credentials, or fund a wallet.

Tilted black-and-white 1950s Polaroid photograph of a stern security inspector at a checkpoint booth inspecting an envelope with a magnifying glass and rubber stamp
Gate 2 stops a forged signature before Gate 3 ever dials a paid sanctions API.

The hasty shortcut is a 90-line validation method built from nested if / else pyramids or early-return clutter stuffed with database clients, HMAC helpers, and sanctions rules all in one class. Every time a new compliance rule arrives, the method grows deeper, harder to reason about, and riskier to edit. A compliance officer asking to insert a geo-fencing gate between KYC and velocity limits, or to run a lighter check list for internal wallet sweeps, forces changes straight into the heart of a monolithic validator.

Notice also what happens when checks throw exceptions for ordinary rejections: stack traces pile up in logs for normal business outcomes like an expired daily cap or a missing signature, and callers have to parse exception messages instead of inspecting structured data.

Building Independent Checkpoints

Think of each guardrail as a checkpoint booth along a single road. A car drives up to booth 1. If something is wrong, booth 1 hands back a ticket explaining exactly why and sends the car straight home. Otherwise, booth 1 waves the car onward to whatever booth sits next down the road, without even needing to know which booth is next. From the outside, the road looks like a single entry point, while internally each booth owns just one rule.

First, let's model the incoming TransferRequest and a sealed CheckResult. Using a Java 21 sealed interface with two records (Approved and Rejected) lets every caller switch exhaustively on the result and extract the exact checkName, reasonCode, and detail without catching exceptions.

import java.math.BigDecimal;
import java.util.List;

record TransferRequest(
        String tenantId,
        String signature,
        String payload,
        BigDecimal amount,
        String currency,
        String kycTier,
        boolean sanctionedMatch,
        BigDecimal dailyUsed,
        BigDecimal dailyLimit,
        BigDecimal availableBalance
) {}

sealed interface CheckResult permits CheckResult.Approved, CheckResult.Rejected {
    record Approved() implements CheckResult {}
    record Rejected(String checkName, String reasonCode, String detail) implements CheckResult {}
}

Now let's define the contract for each booth. A PreFlightCheck receives the TransferRequest plus a continuation callback, NextCheck. Notice how clean this makes short-circuiting: to reject, return CheckResult.Rejected right away; to pass, return next.proceed(request).

@FunctionalInterface
interface NextCheck {
    CheckResult proceed(TransferRequest request);
}

interface PreFlightCheck {
    CheckResult evaluate(TransferRequest request, NextCheck next);
}

With that tiny contract in place, each of our five guardrails becomes a focused, independent class with a single reason to change:

static class SchemaValidationCheck implements PreFlightCheck {
    @Override
    public CheckResult evaluate(TransferRequest req, NextCheck next) {
        System.out.println("  -> running SchemaValidationCheck");
        if (req.tenantId() == null || req.tenantId().isBlank()) {
            return new CheckResult.Rejected("SchemaValidation", "INVALID_TENANT", "tenantId is missing");
        }
        if (req.currency() == null || !req.currency().matches("[A-Z]{3,5}")) {
            return new CheckResult.Rejected("SchemaValidation", "INVALID_CURRENCY", "Unsupported currency code");
        }
        if (req.amount() == null || req.amount().compareTo(BigDecimal.ZERO) <= 0) {
            return new CheckResult.Rejected("SchemaValidation", "INVALID_AMOUNT", "Amount must be positive");
        }
        return next.proceed(req);
    }
}

static class SignatureAuthCheck implements PreFlightCheck {
    @Override
    public CheckResult evaluate(TransferRequest req, NextCheck next) {
        System.out.println("  -> running SignatureAuthCheck");
        String expected = "sig_" + req.tenantId() + "_" + req.payload().hashCode();
        if (!expected.equals(req.signature())) {
            return new CheckResult.Rejected("SignatureAuth", "BAD_SIGNATURE", "HMAC signature mismatch");
        }
        return next.proceed(req);
    }
}

static class KycSanctionsCheck implements PreFlightCheck {
    private static final BigDecimal UNVERIFIED_CAP = new BigDecimal("500.00");

    @Override
    public CheckResult evaluate(TransferRequest req, NextCheck next) {
        System.out.println("  -> running KycSanctionsCheck");
        if (req.sanctionedMatch()) {
            return new CheckResult.Rejected("KycSanctions", "SANCTIONS_HIT", "Counterparty matched sanctions list");
        }
        if ("BASIC".equals(req.kycTier()) && req.amount().compareTo(UNVERIFIED_CAP) > 0) {
            return new CheckResult.Rejected("KycSanctions", "KYC_UPGRADE_REQUIRED", "BASIC tier capped at 500.00");
        }
        return next.proceed(req);
    }
}

static class VelocityLimitCheck implements PreFlightCheck {
    @Override
    public CheckResult evaluate(TransferRequest req, NextCheck next) {
        System.out.println("  -> running VelocityLimitCheck");
        BigDecimal projected = req.dailyUsed().add(req.amount());
        if (projected.compareTo(req.dailyLimit()) > 0) {
            return new CheckResult.Rejected("VelocityLimit", "DAILY_LIMIT_EXCEEDED",
                    "Projected " + projected + " exceeds limit " + req.dailyLimit());
        }
        return next.proceed(req);
    }
}

static class AvailableBalanceCheck implements PreFlightCheck {
    @Override
    public CheckResult evaluate(TransferRequest req, NextCheck next) {
        System.out.println("  -> running AvailableBalanceCheck");
        if (req.availableBalance().compareTo(req.amount()) < 0) {
            return new CheckResult.Rejected("AvailableBalance", "INSUFFICIENT_FUNDS",
                    "Available " + req.availableBalance() + " is below " + req.amount());
        }
        return next.proceed(req);
    }
}

Finally, GuardrailPipeline stitches any ordered list of checks together from back to front, ending at a terminal step that returns new CheckResult.Approved(). Reordering, removing, or inserting a sixth check is now a one-line list edit at startup.

static class GuardrailPipeline {
    private final NextCheck head;

    GuardrailPipeline(List<PreFlightCheck> checks) {
        NextCheck terminal = req -> new CheckResult.Approved();
        for (int i = checks.size() - 1; i >= 0; i--) {
            PreFlightCheck check = checks.get(i);
            NextCheck next = terminal;
            terminal = req -> check.evaluate(req, next);
        }
        this.head = terminal;
    }

    public CheckResult run(TransferRequest request) {
        return head.proceed(request);
    }
}

Let's run four realistic cases through Main and watch exactly where each rejection short-circuits:

public static void main(String[] args) {
    var pipeline = new GuardrailPipeline(List.of(
            new SchemaValidationCheck(),
            new SignatureAuthCheck(),
            new KycSanctionsCheck(),
            new VelocityLimitCheck(),
            new AvailableBalanceCheck()
    ));

    String payload = "tx-8801:1200.00:USD";
    String validSig = "sig_tenant-acme_" + payload.hashCode();

    var approvedReq = new TransferRequest(
            "tenant-acme", validSig, payload, new BigDecimal("1200.00"), "USD",
            "VERIFIED", false, new BigDecimal("3000.00"), new BigDecimal("10000.00"), new BigDecimal("5000.00")
    );
    var badSigReq = new TransferRequest(
            "tenant-acme", "sig_tampered", payload, new BigDecimal("1200.00"), "USD",
            "VERIFIED", false, new BigDecimal("3000.00"), new BigDecimal("10000.00"), new BigDecimal("5000.00")
    );
    var sanctionsReq = new TransferRequest(
            "tenant-acme", validSig, payload, new BigDecimal("1200.00"), "USD",
            "VERIFIED", true, new BigDecimal("3000.00"), new BigDecimal("10000.00"), new BigDecimal("5000.00")
    );
    var lowBalanceReq = new TransferRequest(
            "tenant-acme", validSig, payload, new BigDecimal("1200.00"), "USD",
            "VERIFIED", false, new BigDecimal("3000.00"), new BigDecimal("10000.00"), new BigDecimal("400.00")
    );

    runCase("Case 1 (Approved)", pipeline, approvedReq);
    runCase("Case 2 (Bad Signature)", pipeline, badSigReq);
    runCase("Case 3 (Sanctions Hit)", pipeline, sanctionsReq);
    runCase("Case 4 (Low Balance)", pipeline, lowBalanceReq);
}

Observed output from Java 21:

Case 1 (Approved):
  -> running SchemaValidationCheck
  -> running SignatureAuthCheck
  -> running KycSanctionsCheck
  -> running VelocityLimitCheck
  -> running AvailableBalanceCheck
  Result: Approved[]
Case 2 (Bad Signature):
  -> running SchemaValidationCheck
  -> running SignatureAuthCheck
  Result: Rejected[checkName=SignatureAuth, reasonCode=BAD_SIGNATURE, detail=HMAC signature mismatch]
Case 3 (Sanctions Hit):
  -> running SchemaValidationCheck
  -> running SignatureAuthCheck
  -> running KycSanctionsCheck
  Result: Rejected[checkName=KycSanctions, reasonCode=SANCTIONS_HIT, detail=Counterparty matched sanctions list]
Case 4 (Low Balance):
  -> running SchemaValidationCheck
  -> running SignatureAuthCheck
  -> running KycSanctionsCheck
  -> running VelocityLimitCheck
  -> running AvailableBalanceCheck
  Result: Rejected[checkName=AvailableBalance, reasonCode=INSUFFICIENT_FUNDS, detail=Available 400.00 is below 1200.00]

Spot the Pattern

Pause and notice how the control flow behaves. Look at Case 2: SignatureAuthCheck failed, so KYC, velocity, and balance never ran. Each handler makes a local decision: either handle (reject) the request right here, or pass it along to the next link via next.proceed(req).

That linked sequence of handlers is the Chain of Responsibility pattern. Each link owns one focused check and decides whether processing stops or continues downstream.

1. Schema fields > 0 2. Signature HMAC auth 3. KYC / AML sanctions 4. Velocity daily cap 5. Balance next -> Approved Short-Circuit Exit: CheckResult.Rejected Stops immediately at the first failing check; later gates do not run
Chain of Responsibility: each PreFlightCheck either short-circuits with Rejected or delegates to next.proceed(req).

When NOT to Use It

Avoid this pattern when you want to collect all validation errors at once (such as highlighting every invalid input field in a web form). Short-circuiting stops at the first failure by design. For form-style multi-error reporting, a plain loop over independent predicates collecting into a List<ValidationError> is simpler and gives users all errors in one round trip. Likewise, for 2 tiny fixed checks, two guard clauses at the top of a method beat extra interfaces.

Cost & Trade-offs

  • Order sensitivity: Putting AvailableBalanceCheck before SignatureAuthCheck would leak account-balance information to unauthenticated callers. The assembly list order is a security invariant and deserves explicit integration tests.
  • Longer stack traces: Wrapping links through lambdas adds one stack frame per check, though 5 to 10 frames is negligible in Java.
  • No guarantee of reaching the end: Any link can return early, which is great for fast failure, provided no check assumes an earlier or later check already ran unless ordering is documented.

Real-World Appearances

  • Java Servlet & Web APIs: jakarta.servlet.FilterChain (doFilter(req, res)) and Netty's ChannelPipeline.
  • Spring Framework: HandlerInterceptor chains in Spring MVC and SecurityFilterChain in Spring Security.
  • Fintech & Payments: Risk and fraud rule engines, API gateway auth/rate-limit filters, and pre-trade compliance checks on exchanges.