Structured Concurrency for Payment Orchestration
bankingNovember 23, 2026

Structured Concurrency for Payment Orchestration

Parallel checks, clean cancellation, no thread leaks

Before a payment is executed, a modern payment platform runs it past several independent checks: KYC status of the payer, sanctions screening of both parties, a fraud score and the customer's limits. Run one after another, their latencies add up. Under instant payment schemes, where the whole end-to-end flow has to complete within seconds, that sum quickly eats the budget. Run them in parallel and you have a different problem: what happens to the other three calls when one fails, hangs or comes back with a decline? 

The usual answer in Java codebases is CompletableFuture.allOf(...) with a thread pool. It works on the happy path, and it fails quietly on the unhappy ones. When the sanctions call throws, the fraud and limit calls keep running, holding threads and connections and putting load on downstream services, for a payment that has already been declined. Timeouts get bolted on per future and differ between them. Logging context is lost when work hops threads. And a thread dump during an incident shows a pool full of anonymous workers with no indication of which payment they belong to. 

Structured concurrency, combined with virtual threads, solves exactly this problem. On JDK 25 it is still a preview API, which means a deliberate decision for a regulated platform. This article covers both: how to build the parallel check stage, and how to decide whether and how to adopt the API before it is final. 


The shape of the solution 

The idea is simple. Concurrent subtasks live inside a scope tied to a block of code. They can't outlive that block, and the block can't exit until they've all finished or been cancelled. On JDK 25 (JEP 505, fifth preview) a parallel check stage looks like this: 

 1 record PaymentChecks(KycStatus kyc, SanctionsResult sanctions, 
 2                      FraudScore fraud, LimitDecision limits) {} 
 3  
 4 PaymentChecks runChecks(Payment payment) throws InterruptedException { 
 5     try (var scope = StructuredTaskScope.open( 
 6             Joiner.awaitAllSuccessfulOrThrow(), 
 7             cf -> cf.withTimeout(Duration.ofMillis(1200)) 
 8                     .withName("checks-" + payment.id()))) { 
 9  
10         Subtask       kyc       = scope.fork(() -> kycService.status(payment.payerId())); 
11         Subtask sanctions = scope.fork(() -> sanctionsService.screen(payment)); 
12         Subtask      fraud     = scope.fork(() -> fraudService.score(payment)); 
13         Subtask   limits    = scope.fork(() -> limitService.evaluate(payment)); 
14  
15         scope.join();   // waits for all four, or fails fast on the first failure / timeout 
16         return new PaymentChecks(kyc.get(), sanctions.get(), fraud.get(), limits.get()); 
17     } 
18 } 

Each fork runs on its own virtual thread, so four blocking HTTP or database calls cost four cheap threads, not four slots in a carefully sized pool. The guarantees that matter in production come from the scope, not from the threads: 

  • Fail fast with real cancellation. If any subtask throws, the scope cancels the others by interrupting their threads, and join() throws a FailedException carrying the original cause. The remaining calls stop instead of running on for a payment that's already lost. 
  • One deadline for the whole stage. The timeout covers the scope, not each call separately. When it expires, unfinished subtasks are cancelled and join() throws a TimeoutException. The stage has a single, auditable latency budget. 
  • No leaks, by construction. The try-with-resources block guarantees that when the method returns, by any path, no subtask is still running. That's the property CompletableFuture can't give you, and the one that matters most during an incident. 
  • Readable thread dumps. jcmd <pid> Thread.dump_to_file -format=json shows virtual threads grouped under their named scope, so checks-PAY-20261116-0042 points straight to the payment that's stuck. 


Decline early, not just fail early 

In payments, most negative outcomes aren't exceptions. A sanctions hit or a limit breach is a valid result that means "stop", and once you have one, there's no reason to wait for the fraud score. The allUntil joiner expresses this directly. It cancels the scope as soon as a completed subtask meets a condition: 

 1 try (var scope = StructuredTaskScope.open( 
 2         Joiner.allUntil(st -> 
 3             st.state() == Subtask.State.SUCCESS && st.get().isHardDecline()), 
 4         cf -> cf.withTimeout(Duration.ofMillis(1200)))) { 
 5  
 6     scope.fork(() -> sanctionsService.screen(payment)); 
 7     scope.fork(() -> limitService.evaluate(payment)); 
 8     scope.fork(() -> fraudService.score(payment)); 
 9     scope.fork(() -> kycService.status(payment.payerId())); 
10  
11     List completed = scope.join() 
12         .filter(st -> st.state() == Subtask.State.SUCCESS) 
13         .map(Subtask::get) 
14         .toList(); 
15     return decisionEngine.decide(payment, completed); 
16 } 

On JDK 25, join() returns a stream of subtasks here. On JDK 26 and later, the related allSuccessfulOrThrow joiner returns a List. That's one of several small API movements between previews, and we come back to why that matters below. The pattern itself is stable: model hard declines as results, cancel early on them, and let one decision engine weigh whatever came back. 


The decisions that matter more than the API 


The code is the easy part. These design decisions are what make the parallel stage safe on a payment platform. 

Only run read-only checks in parallel. Cancellation interrupts the local thread. It doesn't undo a request that has already reached another system. A limit check that reserves the amount, or a fraud call that records an attempt, is a side effect that cancellation won't roll back. Keep the parallel stage to evaluations with no side effects. Do reservations and other state changes afterwards, in sequence, with idempotency keys. If a check must have a side effect, make it compensable and record the compensation in the same audit trail. 


Define what a timeout means for each check, in business terms. A sanctions screening that doesn't return in time isn't a pass. The payment can't proceed, but it's usually not a reject either. It goes to a hold queue for manual review. A fraud score that times out might fall back to a conservative rule-based score. A limit service that times out might mean a soft decline with a retry message. These are business rules, and they should be explicit in the requirements, not left to whichever exception handler someone wrote first. Size the overall timeout against the end-to-end budget of the payment scheme, leaving room for everything that happens after the checks. 


Protect the services you're calling. Virtual threads make it trivially cheap to fan out four calls per payment. At peak, that's four times the request rate hitting the fraud and sanctions services. Cheap threads don't make downstream capacity cheap. Keep a bulkhead, such as a semaphore or Resilience4j bulkhead per downstream, around each call inside the subtasks, and keep the circuit breaker configuration from your existing integrations. Structured concurrency organises the concurrency. It doesn't limit it. 

Carry context with scoped values, not ThreadLocals. Correlation IDs, the payment ID and the authenticated channel need to reach every log line and audit record produced by the subtasks. ThreadLocal-based context, including the usual logging MDC, doesn't follow work onto new threads automatically. ScopedValue, final in JDK 25 (JEP 506), does: values bound around the scope are inherited by every forked subtask. Bind the request context once, and copy it into the MDC at the start of each subtask if your logging framework still relies on it. 


 1 static final ScopedValue CTX = ScopedValue.newInstance(); 
 2  
 3 ScopedValue.where(CTX, PaymentContext.of(payment)) 
 4            .call(() -> runChecks(payment));   // every forked subtask sees CTX.get() 

Know where pinning still bites, and where it no longer does. On JDK 21, a virtual thread blocking inside a synchronized block pinned its carrier thread. Under load, that could quietly reduce throughput, and several JDBC drivers and HTTP clients triggered it. JDK 24 removed that limitation (JEP 491), so on JDK 25 synchronized is no longer a reason to avoid virtual threads. Pinning still happens around native calls, for instance in some cryptographic or HSM client libraries. JFR's jdk.VirtualThreadPinned event tells you whether that applies to your stack, so record it under load before rollout. 


The preview decision 

Structured concurrency isn't final on JDK 25. Using it requires --enable-preview at compile time and at run time, and preview class files only run on the exact JDK release they were compiled for. The API has also moved between previews. JDK 26 renamed anySuccessfulResultOrThrow to anySuccessfulOrThrow, changed some return types to List and added a timeout callback to Joiner. JDK 27 previewed it a seventh time, and the API has now been finalised for JDK 28, due in March 2027, with no changes from JDK 27. The next LTS release to contain it as a final API is expected to be JDK 29. 

For a regulated payment platform on JDK 25 LTS, that leaves three realistic options: 

  • Wait. Use virtual threads (final since JDK 21) with ExecutorService and handle cancellation explicitly. You give up the structural guarantees until you move to a JDK with the final API. 
  • Adopt the preview behind a facade. Define a small internal interface for "run these checks in parallel with this deadline and this cancellation rule", implement it with StructuredTaskScope today, and keep every call site independent of the preview API. Moving to a later JDK then means changing one class. Preview use goes through your change governance as an explicit, documented decision, with the JDK upgrade path written into the same record. 
  • Move to a later non-LTS JDK. This gets you closer to the final API but leaves the LTS support model, which most banks won't accept for a core payment service. 

In our experience, option 2 is the right balance for most payment teams. The facade costs a few dozen lines. It delivers the leak-free behaviour and single deadline now, where they matter. And it turns the eventual move to the final API into a contained change rather than a refactoring across the codebase. Whichever option you choose, the business rules above (read-only parallelism, explicit timeout outcomes, downstream protection) apply unchanged. 


What this adds up to 


Parallelising payment checks was always possible. Doing it so that a failure, a decline or a timeout leaves nothing running, nothing leaked and nothing ambiguous in the audit trail has been harder than it should be. Structured concurrency makes those properties a consequence of how the code is written, and virtual threads make the parallelism cheap enough to use for every payment. 

The engineering judgement remains the same as ever: be clear about which checks can run together, decide what each timeout means for the customer, protect the systems behind the calls, and treat a preview API as a governed dependency, not a convenience. Done that way, the check stage gets faster, failures become easier to explain, and the platform is ready for the final API as soon as the JDK upgrade lands.