A fraud check that never approves blind, the Resilience4j decorator order, virtual threads with a finite pool, outbox and projection metrics and alerts, bounded retention, and processes that fail if they start what they should not
Published: November 21, 2026
Reading time: 17 min
Keywords: resilience4j, fail closed, java observability, outbox lag, java 25 virtual threads, opentelemetry spring boot
Payments Platform in practice series
The fraud service stopped responding. What does your payment system do with the next charge?
There are three possible answers. Return an error to the client and lose the sale. Approve without screening and find out how bad it was on next month's chargeback bill. Or store the payment in a state that moves no money until someone decides. The Payments Platform picks the third, and the choice is in the title of ADR 0012: "Fraud screening never approves on failure".
This final chapter is about what happens when things go wrong and how whoever is on call finds out. The previous four chapters built the guarantees. This one shows how they behave under failure and which signals the system exposes to prove they are holding. Code from commit 5277f6c.
UNDER_REVIEW instead of approvalFraud screening is an HTTP call to an external provider, made before the payment is stored and, as we saw in chapter 4, with no transaction open. The adapter handles each failure type and maps every one of them to the same result:
// src/main/java/com/muse/payments/payments/infrastructure/fraud/HttpFraudScreeningAdapter.java:101-129
@Override
public FraudScreeningResult screen(FraudScreeningRequest request) {
Objects.requireNonNull(request, "request must not be null");
Callable<FraudScreeningResult> timed = timeLimiter.decorateFutureSupplier(
() -> executor.submit(() -> exchange(request)));
Callable<FraudScreeningResult> limited = Bulkhead.decorateCallable(bulkhead, timed);
Callable<FraudScreeningResult> guarded = CircuitBreaker.decorateCallable(circuitBreaker, limited);
Callable<FraudScreeningResult> retried = Retry.decorateCallable(retry, guarded);
try {
return retried.call();
} catch (BulkheadFullException ex) {
log.warn("Fraud screening bulkhead is full for payment {}", request.paymentId());
return FraudScreeningResult.underReview(FALLBACK_BULKHEAD);
} catch (CallNotPermittedException ex) {
log.warn("Fraud screening short-circuited for payment {}", request.paymentId());
return FraudScreeningResult.underReview(FALLBACK_CIRCUIT_OPEN);
} catch (FraudTransientException | ResourceAccessException | TimeoutException ex) {
log.warn("Fraud screening fallback for payment {} after {}: {}",
request.paymentId(), ex.getClass().getSimpleName(), ex.getMessage());
return FraudScreeningResult.underReview(FALLBACK_EXHAUSTED);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
log.warn("Fraud screening interrupted for payment {}", request.paymentId());
return FraudScreeningResult.underReview(FALLBACK_EXHAUSTED);
} catch (Exception ex) {
log.error("Fraud screening failed unexpectedly for payment {}", request.paymentId(), ex);
return FraudScreeningResult.underReview(FALLBACK_UNEXPECTED);
}
}
Full bulkhead, open circuit, exhausted retries, interruption or unexpected exception: all of them end in underReview. No failure path returns CLEAR. The payment is stored as UNDER_REVIEW and the published event is PaymentHeldForReview, not PaymentCreated. As the previous chapter showed, a payment in that state cannot be confirmed by its owner or settled by a webhook. Only a user with the ADMIN or FRAUD_REVIEWER role, who is not the payment's owner, can release or reject it.
The ADR is explicit about the cost: "A provider outage creates held payments instead of failing the request closed. Operators release or reject them." A fraud provider outage turns into a manual review queue. For a high-volume business, that needs people and tooling. For payments, it is still the right side to err on.
The composition above, from outside in, is Retry(CircuitBreaker(Bulkhead(TimeLimiter(call)))). The adapter's javadoc repeats the order, and the reason becomes clear when you swap the layers:
That last choice has a consequence ADR 0012 records: because each retry is a circuit-breaker call, minimum-number-of-calls must be at least max-attempts. Otherwise a single screening with three failed attempts can open the circuit for everyone. The application refuses to start with a configuration that violates this. It also refuses a connect timeout longer than the time limiter, a read timeout that is not longer than the time limiter, and an idempotency lease TTL shorter than the worst case of attempts plus backoff.
That last cross-check between settings from different modules is the kind of validation that is usually missing. The idempotency lease (chapter 4) must outlast the slowest possible screening. If it does not, a request still in flight loses its lease, a second request with the same key takes a new one, and the customer ends up with two payments. Validating this at startup turns a rare, hard-to-reproduce incident into a deploy error.
The circuit also has a deliberate blind spot. Any 4xx that is not an explicit "declined" is treated as a normal return: no retry, no failure counted in the circuit, and the payment goes to review. A permanent 401 caused by an expired provider credential would never open the circuit. Every screening would silently go to manual review. That is why the payments.fraud.screening.unexpected_client_errors counter exists, along with an alert that fires on the first increment.
The project runs on Java 25 with spring.threads.virtual.enabled=true. Tomcat requests, scheduled tasks and RabbitMQ listeners run on virtual threads. It is tempting to conclude that blocking is no longer a problem. ADR 0015 explains why that conclusion is wrong, with a concrete case from the project itself.
Register and login ran BCrypt inside @Transactional. Each request held one of the 20 pooled connections for the entire hash. Virtual threads make the thread cheap, but the connection is still a finite resource. And BCrypt is pure CPU: a virtual thread is not preempted until it blocks, so as many concurrent hashes as there are carriers stalled every other virtual thread in the JVM.
The fix had three parts: take the hash out of the transaction, move BCrypt to a bounded pool of platform threads (OffloadedPasswordEncoder), and lower the default BCrypt cost from 12 to 10. The ADR records the measurements, taken on a local machine with JDK 25.0.1 and 11 processors, as single runs:
| Path | Before | After |
|---|---|---|
| 100 sleeps of 2 ms on a virtual thread while 44 virtual threads verify BCrypt | 1,623 ms | 298 ms |
| The 44 hashes in that same run | 1,623 ms | 2,485 ms |
| Sequential login (20 logins), p95 | 330.6 ms | 74.7 ms |
The second row is the one I like showing most, because the ADR does not hide it: the hashes got slower in total. The gain is that the rest of the system keeps responding while they run. It trades authentication throughput for latency across the whole system, on purpose.
The third row needs a caveat the ADR itself makes: part of the login latency drop came from lowering the BCrypt cost from 12 to 10, which means roughly four times less CPU per hash. The ADR justifies it with the OWASP minimum for bcrypt and keeps BCRYPT_COST=12 available for stricter requirements. It is a security decision presented as a security decision, not buried inside a performance number. When I see a login latency improvement, that is the first question I ask.
docs/observability.md opens with a sentence I would adopt in any project: "PostgreSQL remains the source of truth. Metrics describe the running process; they are not a second ledger."
The custom metrics cover exactly the guarantees from the previous chapters:
| Metric | Type | What it answers |
|---|---|---|
payments.outbox.pending | gauge | How many events are not yet published |
payments.outbox.lag.seconds | gauge | Age of the oldest unpublished event |
payments.outbox.publish.lag | timer | Time from occurred_at to publication, with SLO buckets at 1 s, 10 s, 30 s and 60 s |
payments.outbox.attempts | gauge | Sum of attempts on pending rows |
payments.queue.messages{role="main"|"dlq"} | gauge | Messages in the main queue and in the DLQ |
payments.cache.hits/misses/errors | counter | Cache-aside behavior |
projection.lag | gauge | Distance between the event store and each async projection's checkpoint |
payments.psp.intent.failed | counter | Provider intents not created after the commit |
payments.fraud.screening.unexpected_client_errors | counter | Fraud provider 4xx responses that are not a decision |
Two outbox metrics look redundant and are not. publish.lag is a histogram of publish time for events that were published. lag.seconds is the age of the oldest one that has not been. If the relay stops entirely, the histogram stops receiving samples and the percentile freezes at a good value. Only the age gauge grows. The alert description in the repository makes the point: "This gauge is the age of the oldest unpublished row, not the publish-lag percentile".
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
My agent's telemetry ships disabled, points at localhost by default and excludes prompts. It still shows duration, fallbacks and routing decisions.
A module boundary that only exists in a diagram does not exist. How the Payments Platform turns a forbidden dependency into a failing test, and when this design is the wrong call.
The same payment has two findById methods: one rebuilds the aggregate from events, the other reads an indexed projection. That is what CQRS means in the Payments Platform, with no second database.
A 47-point checklist to find bugs, security risks, and performance issues before launch.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
prometheus-alerts.yml defines eight rules. A few that show the reasoning:
# deploy/observability/prometheus-alerts.yml:4-11
- alert: OutboxPendingHigh
expr: max(payments_outbox_pending) > 100
for: 5m
labels:
severity: warning
annotations:
summary: Outbox backlog is above 100 unpublished events
description: The relay is not keeping up with commits. Check RabbitMQ and payments_outbox_lag_seconds. max() folds the same backlog reported by every replica.
The max() is a detail from someone who has been fooled by a sum(). Every replica queries the same table and reports the same number. Summing three replicas would triple the apparent backlog.
# deploy/observability/prometheus-alerts.yml:35-42
- alert: NotificationDlqNotEmpty
expr: max by (role) (payments_queue_messages{role="dlq"}) > 0
for: 1m
labels:
severity: critical
annotations:
summary: Notification DLQ has messages
description: Permanent or exhausted failures need an operator. Do not claim they were processed.
Any message in the DLQ is critical, because the project has no automatic reprocessing, as chapter 4 showed. "Do not claim they were processed" is an instruction for humans, written into the alert.
The remaining rules cover outbox age above 60 s, p95 publish lag above 30 s, payment read p95 above 300 ms, unexpected 4xx from the fraud provider, a 5xx rate above 1% and projection lag above 100. The 5xx rule carries a note I find mature: "Availability SLO is 99.5% over 30 days. This is an early signal, not the SLO itself." The alert does not pretend to be the SLO.
About ProjectionLagHigh, recall what I explained in chapter 3: the gauge measures distance in global positions, and positions from other stream types interleave. The threshold of 100 is a trend signal. It fires earlier than an exact count would, which is acceptable for a warning.
An HTTP request arrives with an X-Correlation-Id (or gets one), which goes into the log MDC and the response header. Nothing unusual so far. The problem is the outbox: the event is published seconds later, by another thread, in a different transaction. Anything stored in a ThreadLocal is gone.
The project solves this by storing the context on the outbox row itself. The correlation id and the original request's W3C traceparent go into the headers column. When the relay publishes, it restores the parent trace before sending:
// src/main/java/com/muse/payments/shared/infrastructure/OutboxRelayService.java:193-205
private CorrelationData send(PublishCandidate event) {
Map<String, Object> headers = readHeaders(event.headers());
String correlationId = correlationId(headers);
CorrelationData correlation = new CorrelationData(UUID.randomUUID().toString());
traceContext.runWithParent(headers, () -> rabbitTemplate.convertAndSend(
RabbitMqConfig.EXCHANGE_PAYMENTS,
event.routingKey(),
event.payload(),
message -> {
var props = message.getMessageProperties();
props.setContentType("application/json");
props.setHeader("X-Correlation-Id", correlationId);
props.setHeader("X-Event-Id", event.id().toString());
runWithParent extracts the context from the stored headers and opens an "outbox relay" span as a child of the original trace (W3cTraceContextPropagation.java:51-69). The notifications consumer continues the same trace. In a trace viewer, the POST /payments, the async publication and the notification processing show up as a single tree, even though seconds and a broker separate them.
The difference between the two identifiers matters. The correlation id is a stable business value the client can send, and it shows up in logs and in RFC 7807 error responses. The trace id is technical, generated by instrumentation and sampled. In production, the prod profile samples 10% of traces. The correlation id is in 100% of logs, and it is what support uses to find a specific request.
Operational tables grow forever if nobody cleans them. ADR 0018 caught this in a production-readiness review and introduced OperationalRetentionCleanup:
// src/main/java/com/muse/payments/shared/infrastructure/retention/OperationalRetentionCleanup.java:26-35
private static final String DELETE_PUBLISHED_OUTBOX_BATCH = """
DELETE FROM outbox_events
WHERE id IN (
SELECT id FROM outbox_events
WHERE published_at IS NOT NULL
AND published_at < ?
ORDER BY published_at ASC
LIMIT ?
)
""";
Outbox rows published more than 7 days ago and processed events older than 30 days are deleted in batches of 500. Small batches avoid a long transaction, which would hold back the database's xmin and, as chapter 3 showed, delay asynchronous projections. Unpublished outbox rows are never deleted.
And the event store is never touched. The class javadoc says so explicitly, consistent with the immutability trigger. The consequence is explicit too: event_store grows without bound. Retention is bounded for everything except the source of truth.
The processed_events window defines the real horizon of consumer deduplication, a point I covered in chapter 4. Changing that TTL changes a consistency guarantee, not just a cleanup setting.
ADR 0018 also records a classic bug the project had: the rate limiter ran INCR and EXPIRE as two separate Redis calls. If the process died between them, the key had no TTL and the user was locked out forever. The fix is a Lua script, which Redis runs atomically:
// src/main/java/com/muse/payments/identity/infrastructure/AuthRateLimiter.java:32-38
private static final RedisScript<Long> INCREMENT_WITH_TTL = new DefaultRedisScript<>("""
local count = redis.call('INCR', KEYS[1])
if count == 1 or redis.call('PTTL', KEYS[1]) < 0 then
redis.call('PEXPIRE', KEYS[1], ARGV[1])
end
return count
""", Long.class);
The PTTL < 0 condition also repairs old keys left without a TTL by the previous bug. Login is limited per IP and per account, using the SHA-256 of the normalized email so no plaintext email is stored in Redis. Payment writes are limited per user.
If Redis goes down, the limiter falls back to a size-bounded in-memory counter (AuthRateLimiter.java:81-92). That keeps some limit, but per instance: with four replicas, the effective limit can be up to four times higher. The project prefers that to leaving login unlimited or refusing every login while Redis is down.
The last piece is the one I most often see missing in real systems. Migrations and projection rebuilds run as modes of the same binary, and each mode checks its own guarantees before exiting.
With APP_MIGRATION_ONLY, the process starts with no web server, no listeners and no schedulers, runs Flyway and checks:
// src/main/java/com/muse/payments/PaymentsApplication.java:122-146
private static String migrationProblem(ConfigurableApplicationContext context) {
if (context instanceof WebServerApplicationContext web && web.getWebServer() != null) {
return "Migration mode started an HTTP server";
}
if (rabbitListenersRunning(context)) {
return "Migration mode started Rabbit listeners";
}
if (context.getBeanNamesForType(ScheduledAnnotationBeanPostProcessor.class).length > 0) {
return "Migration mode started the outbox scheduler";
}
Flyway flyway;
try {
flyway = context.getBean(Flyway.class);
} catch (RuntimeException ex) {
log.error("Flyway bean is missing", ex);
return "Flyway is not active in migration mode";
}
if (flyway.info().pending().length > 0) {
return "Flyway left pending migrations";
}
if (flyway.info().applied().length == 0) {
return "Flyway applied no migrations";
}
return null;
}
Any problem becomes exit code 1. In a Kubernetes Job, that means the Job fails and the rollout stops. Without this check, a forgotten environment variable could make the migration Job start an HTTP server, consume queue messages and publish the outbox, competing with the real replicas. A comment in PaymentsApplication explains why this mode's settings are inserted ahead of every other property source: the Kubernetes ConfigMap sets SPRING_FLYWAY_ENABLED=false for the Deployment, and that variable would otherwise outrank the migration profile file.
APP_PROJECTION_REBUILD applies the same idea to chapter 3's offline rebuild: no HTTP, no consumers, no schedulers; rebuild the requested projection and exit. The two modes cannot be combined.
prod profile does not export traces until someone configures the collector URL. Without it, W3C propagation exists but nobody sees the traces.Across five chapters, the same idea kept coming back in different forms: a guarantee only exists when something fails if it is violated. The module boundary is a test that breaks the build. The write aggregate is the only way to change state. The event store rejects UPDATE in the database, and the asynchronous projection waits for the fence before advancing. The idempotency key, the outbox and the webhook turn repetition into a single effect. And operations expose signals that show when any of those guarantees is lagging or failing.
The repository has gaps, and I made a point of showing each one: no personal data erasure, no reconciliation of orphaned intents, no retry ceiling on the outbox, offset pagination, a single payment provider. A sample that hides its gaps teaches you to trust what you should not. One that records them in ADRs teaches you how to make decisions.
The code is at github.com/Andersonlimahw/java-clean-arch-sample, with the 19 ADRs behind every choice discussed here.
If your team is taking a payments or other high-stakes system to production and wants an architecture and operations review grounded in the code, that is the work I do at LEMON.DEV.
java-clean-arch-sample repository, commit 5277f6c (checked on November 21, 2026).docs/observability.md and prometheus-alerts.yml.