← Back to Blog

Decoupling Post-Settlement Side Effects

Adding receipt webhooks, AML volume tracking, and fee-rebate points to our Fiat & Crypto Settlement Hub without letting side effects bleed into the ledger path.

SETTLE LEDGER WEBHOOK AML COUNTER REBATES

In Milestone 1, we taught our Settlement Hub how to price a transfer cleanly. Now a transfer actually settles, and immediately three different teams want a piece of that moment.

When TransferService.settle() commits a debit or credit to the ledger, the money has moved. That single fact matters to several other corners of the platform:

  • The tenant integrations team needs an HTTP webhook receipt fired to the partner's callback URL.
  • The compliance team needs a running daily AML volume counter per tenant so any tenant crossing $10,000 triggers an alert.
  • The growth team wants to award fee-rebate loyalty points based on the settled fee.

All three care deeply that a transfer settled, yet none of them belong to the accounting act of appending an immutable LedgerEntry.

Drawing a Line Around the Core Ledger

Let's be clear about the boundary between the core ledger and its side effects. First, the ledger append is the source of truth: once LedgerStore.append() succeeds, that settlement happened. Second, a failing downstream action must never crash settle() or make the caller think the money did not move. If a partner's webhook server returns HTTP 503 during an outage, the ledger entry still stands, and the AML counter and rebate calculator still need to run.

Third, new downstream reactions will keep showing up over the life of the hub (audit logs, Slack ops alerts, Prometheus metrics). Adding a fourth reaction should not require editing TransferService.settle() or injecting yet another constructor dependency into the core accounting class.

The hasty shortcut is to wire WebhookClient, AmlTracker, and RebateService directly into TransferService and call them sequentially at the bottom of settle(). Within a few sprints, your core ledger service holds six unrelated dependencies, its unit tests require mocking HTTP clients just to verify a balance debit, and an uncaught exception from a marketing points table threatens to abort a financial settlement.

Tilted black-and-white 1950s Polaroid photograph of a telephone switchboard operator overwhelmed holding two handsets tangled in patch cables
TransferService.settle() after three teams ask it to dial webhooks, AML counters, and loyalty points itself.

Flipping the Dependency Direction

Instead of making TransferService reach out to every downstream system by name, flip the direction of knowledge. Think of settle() as publishing a small, immutable snapshot of what just happened (a SettledTransferEvent) to anyone who asked to be notified.

First, let's define the core ledger types alongside that immutable event payload. Notice that SettledTransferEvent carries only plain facts about the completed settlement, not mutable wallet references or database handles.

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

record LedgerEntry(
        String transferId,
        String walletId,
        BigDecimal delta,
        String currency,
        Instant recordedAt
) {}

record SettledTransferEvent(
        String transferId,
        String tenantId,
        String walletId,
        String rail,
        String currency,
        BigDecimal amount,
        BigDecimal fee,
        Instant settledAt
) {}

Next, we define a minimal contract for any component that wants to react after settlement: PostSettlementListener. Because it has a single method, tests can pass a one-line lambda without standing up concrete classes.

@FunctionalInterface
interface PostSettlementListener {
    void onTransferSettled(SettledTransferEvent event);
}

Now look at TransferService. Its constructor takes only LedgerStore. Downstream hooks attach via registerListener(), backed by a thread-safe CopyOnWriteArrayList. That collection choice matches the access ratio of a payment hub: listeners are registered once at application startup, while thousands of settlements iterate through that list every minute without taking a lock.

Look closely at the order inside settle(). First, the ledger entry is appended and committed as the source of truth. Only after that write succeeds does the service build the SettledTransferEvent and walk the listener list. Each listener runs inside its own defensive try/catch block, so a tenant's flaky webhook returning HTTP 503 gets logged for retry without aborting the AML counter, the rebate points, or the settled ledger row.

static class LedgerStore {
    private final List<LedgerEntry> entries = new ArrayList<>();

    public void append(LedgerEntry entry) {
        entries.add(entry);
        System.out.printf("[Ledger] Committed %s: wallet=%s delta=%s %s%n",
                entry.transferId(), entry.walletId(), entry.delta(), entry.currency());
    }

    public List<LedgerEntry> entries() {
        return Collections.unmodifiableList(entries);
    }
}

static class TransferService {
    private final LedgerStore ledger;
    private final List<PostSettlementListener> listeners = new CopyOnWriteArrayList<>();

    TransferService(LedgerStore ledger) {
        this.ledger = ledger;
    }

    public void registerListener(PostSettlementListener listener) {
        listeners.add(listener);
    }

    public void removeListener(PostSettlementListener listener) {
        listeners.remove(listener);
    }

    public void settle(
            String transferId,
            String tenantId,
            String walletId,
            String rail,
            String currency,
            BigDecimal amount,
            BigDecimal fee
    ) {
        Instant now = Instant.now();
        BigDecimal netDebit = amount.add(fee).negate();
        ledger.append(new LedgerEntry(transferId, walletId, netDebit, currency, now));

        var event = new SettledTransferEvent(transferId, tenantId, walletId, rail, currency, amount, fee, now);
        for (PostSettlementListener listener : listeners) {
            try {
                listener.onTransferSettled(event);
            } catch (RuntimeException ex) {
                System.out.printf("[SideEffectError] %s failed for %s: %s%n",
                        listener.getClass().getSimpleName(), transferId, ex.getMessage());
            }
        }
    }
}

Now each downstream concern lives in its own self-contained class implementing PostSettlementListener. None of them know about LedgerStore or about each other, and each maintains only the tiny slice of memory it cares about.

static class WebhookReceiptListener implements PostSettlementListener {
    private boolean simulateOutage = false;

    void setSimulateOutage(boolean simulateOutage) {
        this.simulateOutage = simulateOutage;
    }

    @Override
    public void onTransferSettled(SettledTransferEvent event) {
        if (simulateOutage) {
            throw new IllegalStateException("Tenant webhook endpoint returned HTTP 503");
        }
        System.out.printf("[Webhook] Dispatched receipt for %s to tenant=%s (amount=%s %s)%n",
                event.transferId(), event.tenantId(), event.amount(), event.currency());
    }
}

static class DailyAmlVolumeTracker implements PostSettlementListener {
    private final BigDecimal threshold;
    private final Map<String, BigDecimal> dailyTotals = new ConcurrentHashMap<>();

    DailyAmlVolumeTracker(BigDecimal threshold) {
        this.threshold = threshold;
    }

    @Override
    public void onTransferSettled(SettledTransferEvent event) {
        BigDecimal updated = dailyTotals.merge(event.tenantId(), event.amount(), BigDecimal::add);
        System.out.printf("[AML] Tenant=%s daily settled volume=%s %s%n",
                event.tenantId(), updated, event.currency());
        if (updated.compareTo(threshold) >= 0) {
            System.out.printf("[AML ALERT] Tenant=%s crossed reporting threshold (%s)%n",
                    event.tenantId(), threshold);
        }
    }
}

static class FeeRebatePointsListener implements PostSettlementListener {
    private final Map<String, Long> pointsByTenant = new ConcurrentHashMap<>();

    @Override
    public void onTransferSettled(SettledTransferEvent event) {
        long earned = event.fee().multiply(BigDecimal.TEN).longValue();
        long total = pointsByTenant.merge(event.tenantId(), earned, Long::sum);
        System.out.printf("[Rebate] Tenant=%s earned %d pts (balance=%d pts)%n",
                event.tenantId(), earned, total);
    }
}

Let's wire all three into Main and simulate a webhook outage on the second transfer to prove the core ledger and the other two listeners keep running cleanly:

public static void main(String[] args) {
    var ledger = new LedgerStore();
    var service = new TransferService(ledger);

    var webhook = new WebhookReceiptListener();
    var amlTracker = new DailyAmlVolumeTracker(new BigDecimal("10000.00"));
    var rebatePoints = new FeeRebatePointsListener();

    service.registerListener(webhook);
    service.registerListener(amlTracker);
    service.registerListener(rebatePoints);

    service.settle("tx-101", "tenant-acme", "wal-usd-1", "BANK_WIRE", "USD",
            new BigDecimal("6500.00"), new BigDecimal("15.00"));

    System.out.println("--- Simulating webhook outage on second settlement ---");
    webhook.setSimulateOutage(true);
    service.settle("tx-102", "tenant-acme", "wal-usd-1", "BANK_WIRE", "USD",
            new BigDecimal("4200.00"), new BigDecimal("15.00"));

    System.out.println("Committed ledger entries: " + ledger.entries().size());
}

Observed output from Java 21:

[Ledger] Committed tx-101: wallet=wal-usd-1 delta=-6515.00 USD
[Webhook] Dispatched receipt for tx-101 to tenant=tenant-acme (amount=6500.00 USD)
[AML] Tenant=tenant-acme daily settled volume=6500.00 USD
[Rebate] Tenant=tenant-acme earned 150 pts (balance=150 pts)
--- Simulating webhook outage on second settlement ---
[Ledger] Committed tx-102: wallet=wal-usd-1 delta=-4215.00 USD
[SideEffectError] WebhookReceiptListener failed for tx-102: Tenant webhook endpoint returned HTTP 503
[AML] Tenant=tenant-acme daily settled volume=10700.00 USD
[AML ALERT] Tenant=tenant-acme crossed reporting threshold (10000.00)
[Rebate] Tenant=tenant-acme earned 150 pts (balance=300 pts)
Committed ledger entries: 2

Spot the Pattern

Step back and trace the dependency arrows in that code. Before this refactor, adding any new post-settlement behavior meant opening TransferService, wiring in another client, and hoping an exception in a peripheral feature would not disturb the core debit. Now TransferService imports neither webhooks, nor AML counters, nor loyalty points. Instead, it holds an abstract list of subscribers behind PostSettlementListener and broadcasts an immutable snapshot whenever its ledger changes.

That publish-subscribe relationship is the Observer pattern: one subject (TransferService) notifies a dynamic set of observers (PostSettlementListener implementations) when an event occurs, keeping the producer completely decoupled from its consumers.

TransferService Subject / Publisher 1. ledger.append() 2. notify listeners <<interface>> PostSettlementListener onTransferSettled(event) WebhookReceiptListener HTTP receipt (isolated failure) DailyAmlVolumeTracker Per-tenant daily threshold FeeRebatePointsListener Accrues partner points
Observer pattern: TransferService emits SettledTransferEvent without knowing which listeners are attached.

When NOT to Use It

Do not reach for Observer when the side effect must succeed or fail atomically inside the same database transaction as the core write (for example, debiting wallet A and crediting wallet B). If two operations share an all-or-nothing invariant, call them directly inside one transactional service method. Also, if there is only one fixed follow-up call that never varies, a direct method call is clearer and avoids indirection.

Cost & Trade-offs

  • Synchronous vs. durable delivery: Our in-process loop isolates exceptions, but a slow HTTP call inside WebhookReceiptListener still blocks the calling thread, and a process crash drops in-memory notifications. In production, the listener often writes a row to a transactional outbox table or pushes to a queue rather than calling external HTTP inline.
  • Execution order is implicit: Observers should never depend on running before or after another observer. If strict ordering matters, you want an explicit pipeline, not a listener list.
  • Memory leaks if unsubscribed carelessly: Long-lived subjects holding references to short-lived listeners keep those objects alive until explicitly removed.

Real-World Appearances

  • Java JDK: java.beans.PropertyChangeListener and java.util.concurrent.Flow.Publisher / Subscriber.
  • Spring Framework: ApplicationEventPublisher paired with @EventListener and @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT), which solves the exact outbox/commit boundary cleanly.
  • Fintech & Payments: Post-settlement webhook dispatchers, real-time fraud scoring streams, and ledger-to-analytics event pipelines (Kafka / SNS / outbox relays).