what really happens after you click pay

lagos

Most people see a payment as one action. You tap a button and money moves.

Behind that tap is a chain of steps: validation, compliance checks, currency conversion, ledger entries, settlement. In a real system that can involve half a dozen services before a single cent arrives.

I wanted to make that chain visible.

So I built PayPipeline, a simulator where you send a payment and watch it move through every stage, from CREATED to COMPLETED. It has a live pipeline tracker, an event log, and a fixed table of exchange rates.

This post covers why I built it, how it works, and the decisions behind each layer.

Why Build This

If you're trying to get into fintech, there's a big gap between "I understand REST APIs" and "I understand how a payment moves through a system."

Most learning resources sit at one of two ends. They stay too abstract, or they drop you into production-grade complexity, with Kafka, gRPC and distributed ledgers, before you understand the basics.

PayPipeline sits in between. It walks a payment through the stages a real one passes, with an in-memory backend you can start in seconds. No database. No message queue. Just the core logic, behind a small API, with a React frontend that shows it happening.

The goal was simple: submit a payment and watch it move, one stage at a time.

Three Ways to Pay

Every payment starts the same way: it's created, validated and checked. Then it splits by type.

1. Fiat to fiat. Send USD, GBP or EUR to NGN, KES, GHS or ZAR.

Created → Validated → Compliance → FX Locked → Ledger Posted → Settling → Completed

The simulator sending 500 GBP to Nigeria, four stages in, with the rate and fee shown.

2. Crypto to crypto. Move a stablecoin like USDC, USDT or DAI from one network to another.

Created → Validated → Compliance → Gas Estimated → Contract Called → Bridging → Completed

Nothing here touches a real chain. "Gas" is a 0.5% fee, and the contract and bridging stages are labels with a message, so you can see where those steps would sit.

The simulator moving 500 DAI to USDT, at the gas estimate stage.

3. Crypto to fiat. An off-ramp: crypto comes in, is converted through a liquidity provider, and paid out to a local bank.

Created → Validated → Compliance → Crypto Received → Liquidity Conversion → Fiat Settling → Completed

A finished crypto-to-fiat payment: 500 USDC became 65,340 KES.

The frontend shows each path as a row of nodes. Finished stages turn green, the current one glows purple, a failed one turns red, and the rest stay grey.

The Architecture

The repo has two parts:

payment-playground/
├── client/ # React + Vite + TypeScript
├── server/ # Express + TypeScript

The interesting decisions are in the backend. Every concern gets its own folder:

server/src/
├── models/        # Core domain types
├── repositories/  # Data access (in-memory)
├── services/      # Business logic
├── controllers/   # HTTP request handling
├── routes/        # Express routes
├── orchestrator/  # Runs the pipeline
├── state-machine/ # Which moves are allowed
├── compliance/    # Amount limit checks
├── fx/            # Exchange rates and fees
├── ledger/        # Placeholder, records nothing yet
├── settlement/    # Placeholder, waits a second, records nothing yet
├── events/        # The event log
├── errors/        # Custom error types
├── middleware/    # Express middleware
├── health/        # Health check
└── utils/         # Shared helpers

Each folder is one part of the domain, and each one only knows about its own job.

Decision 1: A State Machine

The core of the system is the PaymentStateMachine. A payment can't change status however it likes. Every move has to be listed as allowed:

const transitions: Record<PaymentStatus, PaymentStatus[]> = {
    [PaymentStatus.CREATED]: [
        PaymentStatus.VALIDATED,
    ],
    [PaymentStatus.VALIDATED]: [
        PaymentStatus.COMPLIANCE_PASSED,
        PaymentStatus.COMPLIANCE_FAILED,
    ],
    [PaymentStatus.COMPLIANCE_PASSED]: [
        PaymentStatus.FX_LOCKED,         // Cross currency path
        PaymentStatus.GAS_ESTIMATED,     // Crypto cross chain path
        PaymentStatus.CRYPTO_RECEIVED,   // Crypto to fiat path
    ],
    // ...each path continues to COMPLETED or FAILED
};

The move itself is short. Look up what's allowed, and throw if this isn't:

transition(payment: Payment, nextStatus: PaymentStatus): Payment {
    const allowed = transitions[payment.status];
    if (!allowed.includes(nextStatus)) {
        throw new Error(
            `Cannot move payment from ${payment.status} to ${nextStatus}`
        );
    }
    payment.status = nextStatus;
    return payment
};

Why this matters: a payment in the wrong state is one of the most dangerous bugs a payment system can have. A payment that jumps from CREATED to settled without passing compliance is a regulatory problem. Here, that move can't happen: the code refuses it.

The fork is at COMPLIANCE_PASSED. From there a payment can go down one of three paths. That shape, shared checks at the top and separate paths after, is the picture at the top of this post, and it's common in real payment systems.

Decision 2: An Orchestrator

The PaymentOrchestrator runs the pipeline. It doesn't do the work itself. It calls the right service at the right time:

async start(paymentId: string) {
    const payment = this.repository.findById(paymentId);
    // ...
    await this.moveTo(payment, PaymentStatus.VALIDATED);

    const approved = this.compliance.check(payment);
    if (!approved) {
        await this.moveTo(payment, PaymentStatus.COMPLIANCE_FAILED, "Sender flagged by AML checks");
        return
    }
    await this.moveTo(payment, PaymentStatus.COMPLIANCE_PASSED);

    switch (payment.type) {
        case PaymentType.CROSS_CURRENCY:
            await this.processCrossCurrency(payment);
            break;
        case PaymentType.CRYPTO_CROSS_CHAIN:
            await this.processCryptoCrossChain(payment);
            break;
        case PaymentType.CRYPTO_TO_FIAT:
            await this.processCryptoToFiat(payment);
            break;
        // ...
    }

    await this.moveTo(payment, PaymentStatus.COMPLETED);
}

Each path has its own method:

private async processCrossCurrency(payment: Payment) {
    this.fxService.quote(payment);
    await this.moveTo(payment, PaymentStatus.FX_LOCKED);

    this.ledgerService.record(payment);
    await this.moveTo(payment, PaymentStatus.LEDGER_POSTED);

    await this.settlementService.process(payment);
    await this.moveTo(payment, PaymentStatus.SETTLING);
}

To be clear about what's simulated: the compliance check is two rules, the amount must be more than 0 and no more than 10,000. And the ledger and settlement services are placeholders. They move the payment on but record nothing yet.

Why not put this in the service layer? Because the orchestrator's job is the order. The FX service doesn't need to know compliance comes first. The ledger service doesn't need to know FX comes first. Each service does one thing, and the orchestrator is the only place that knows the sequence.

It also makes a fourth payment type easy to add: add its stages to the state machine, write a new process method, and add a case to the switch.

Decision 3: Slow on Purpose

Every stage waits 2 seconds before it moves:

private async moveTo(payment: Payment, status: PaymentStatus, message?: string) {
    await sleep(2000);
    this.stateMachine.transition(payment, status)
    this.repository.update(payment);
    this.eventService.log(payment.id, payment.status, message);
}

Real payments don't finish in milliseconds. They wait on other companies' APIs, network confirmations and settlement windows. With 2 seconds a stage, plus 1 more second inside settlement, a fiat payment takes about 13 seconds. That's long enough to watch each stage arrive.

A fiat payment on a time line: validated at 2 seconds, compliance at 4, FX locked at 6, ledger posted at 8, settling at 11, completed at 13.

It also shows a pattern worth knowing. Creating a payment starts the pipeline without waiting for it:

void this.orchestrator.start(createdPayment.id);
return createdPayment

The client gets the payment ID back straight away. Then it asks GET /payments/:id and GET /payments/:id/events once a second to watch the payment move. Many payment APIs work this way: you get an ID immediately, then check its status or wait to be told.

Decision 4: An Event for Every Move

Every move is written to an event log:

log(paymentId: string, status: PaymentStatus, customMessage?: string) {
    this.repository.add({
        paymentId,
        status,
        timestamp: new Date(),
        message: customMessage || this.createMessage(status) || "",
    });
}

GET /payments/:id/events returns the full history: every stage the payment passed, with a time and a readable message.

Why this matters: a regulated payment system has to be able to show when a compliance check ran, when the rate was locked, and when settlement started. A log like this is how you show it. It's an audit trail, not full event sourcing: the payment's current status is still stored on the payment itself, and the log sits beside it.

Decision 5: One Rate per Currency

Instead of a table of every currency pair, each currency has one rate against the US dollar:

const usdRates: Record<string, number> = {
    USD: 1, GBP: 0.78, EUR: 0.92,
    USDC: 1, USDT: 1, DAI: 1,
    NGN: 1640, KES: 132, GHS: 12.5, ZAR: 19.2,
};

const rate = destRate / sourceRate;

Any currency converts to any other in one division. Adding a currency is one line. Then a 1% fee comes off before the conversion:

payment.fee = payment.amount * 0.01;

payment.destinationAmount =
    (payment.amount - payment.fee) * rate;

Sending 500 GBP to Nigeria: 500 minus a 5 GBP fee, times 2,102.56 (1,640 divided by 0.78), equals 1,040,769 NGN.

One thing I'd fix: a currency that's missing from the table quietly gets a rate of 1, because of usdRates[code] || 1. It should be an error.

Decision 6: Wiring by Hand

Everything is connected in app.ts, with plain constructors:

const repository = new PaymentRepository();
const stateMachine = new PaymentStateMachine();
const complianceService = new ComplianceService();
const eventRepository = new EventRepository();
const eventService = new EventService(eventRepository);
const fxService = new FXService();
const ledgerService = new LedgerService();
const settlementService = new SettlementService();

const orchestrator = new PaymentOrchestrator(
  repository, stateMachine, complianceService,
  fxService, ledgerService, settlementService, eventService
);

const paymentService = new PaymentService(repository, orchestrator, eventService);
const paymentController = new PaymentController(paymentService, eventService);

No framework. No decorators. Every dependency is in plain sight. You can read the file top to bottom and understand how the whole thing fits together in 30 seconds.

Why no framework? At this size, a tool like InversifyJS or tsyringe adds more than it gives back. The hand wiring doubles as documentation. In a codebase with hundreds of services, a container starts to earn its place. Here, simple wins.

Decision 7: Error Types

Errors share one base class with a status code, so a service can throw new ValidationError("Amount must be greater than zero") and a single middleware turns it into a JSON response. Unknown errors are meant to get a plain 500, so nothing internal leaks.

That's the design. Going back through the code for this post, I found it doesn't quite work. The error middleware is registered before the routes, and Express only hands errors to handlers registered after them. So my handler never runs. Express's own handler answers instead, with an HTML page. It keeps the right status code, but outside production that page includes the stack trace. The fix is one line: move app.use(errorMiddleware) below the routes.

The Frontend

The client is React, TypeScript and Vite. The PaymentPipeline component knows the stages for each payment type and draws them as a row of nodes. Each node's look comes from the payment's current status:

  • Done (green): stages it has already passed
  • Active (purple, pulsing): the stage it's in now
  • Failed (red): the stage it stopped at
  • Idle (grey): stages it hasn't reached

The lines between nodes animate too. Finished ones turn green, and the active one shimmers.

Below it, the event log lists every event newest first, with times like "just now" and "4s ago" and a readable message for each.

The event log for a finished payment: seven events, newest first.

What a Real Version Would Need

This is a simulator, and it's simple on purpose. A real version would need:

  1. A real database. PostgreSQL for payments, and append-only tables for events.
  2. Push updates. WebSockets instead of asking every second.
  3. Idempotency keys, so a retried request can't create the same payment twice.
  4. A message queue. Starting the pipeline and not waiting for it works here, but in production a restart would lose the payment mid-pipeline. A queue like RabbitMQ or SQS makes sure it still gets processed.
  5. Live exchange rates from a real FX provider, instead of a fixed table.
  6. Authentication, with API keys or tokens and access scoped to each user's payments.
  7. Tracing, with OpenTelemetry spans across every stage, so you can see where time goes.
  8. A real ledger and settlement step. Today they're placeholders.

Try It Yourself

The code is on GitHub. Clone it, run npm install in both client/ and server/, start each with npm run dev, and send some payments.

GitHub: https://github.com/abubakar2906/payment-playground

Live: https://payment-playground-nu.vercel.app/

If you're building in fintech and want to see how a payment system works underneath, I hope this gives you a useful place to start. Fork it, extend it, break it. That's what playgrounds are for.

older: i built a distributed rate limiter in go with zero go experience

first published on medium.

email / github / linkedin / last updated
26/11/26