Building TestExchange: From a Single-Server CEX to a Decoupled Matching Engine

Building TestExchange: From a Single-Server CEX to a Decoupled Matching Engine

August 20, 2026ยท10 min readยท
#cex#system design#full stack

TestExchange is a learning-focused mini Centralized Exchange (CEX) built from scratch to understand how trading systems, order books, matching engines, balances, persistence, and event-driven architectures work together.

Building TestExchange: From a Single-Server CEX to a Decoupled Matching Engine

TestExchange is a learning-focused mini Centralized Exchange (CEX) built from scratch to understand how trading systems, order books, matching engines, balances, persistence, and event-driven architectures work together.

TestExchange Landing Page

๐Ÿš€ Project Overview

I built TestExchange as a hands-on project to understand the internal architecture of a centralized exchange rather than simply consuming an exchange API.

The project started as a simple Version 0 monolithic application where everything ran inside a single server:

  • Authentication
  • User management
  • Wallet/balances
  • Order creation
  • Order matching
  • Order book
  • Trade execution
  • PostgreSQL persistence

The next step was to evolve the system into a more realistic Version 1 architecture, where the matching engine becomes an independent service and communication happens through Redis queues.

The overall evolution is:

V0

Client
  โ”‚
  โ–ผ
Backend
  โ”‚
  โ”œโ”€โ”€ Authentication
  โ”œโ”€โ”€ Order API
  โ”œโ”€โ”€ Matching Engine
  โ”œโ”€โ”€ OrderBook (RAM)
  โ”œโ”€โ”€ Balances (RAM)
  โ””โ”€โ”€ PostgreSQL

to:

V1

Client
  โ”‚
  โ–ผ
Backend Service
  โ”‚
  โ–ผ
Redis Queue
  โ”‚
  โ–ผ
Matching Engine
  โ”‚
  โ”œโ”€โ”€ OrderBook (RAM)
  โ”œโ”€โ”€ Balances (RAM)
  โ””โ”€โ”€ Engine State
          โ”‚
          โ–ผ
      PostgreSQL

The goal wasn't to build a production exchange. The goal was to understand the engineering problems that appear when building one.


๐Ÿง  What Is a Centralized Exchange?

A centralized exchange, or CEX, is a platform where users submit orders to a central system that maintains the market and matches buyers with sellers.

For example:

Hardik wants to buy:

2 SOL @ $10

Another user might submit:

Raghav wants to sell:

2 SOL @ $10

The exchange's matching engine finds the compatible orders and creates a trade.

Conceptually:

Buyer
  โ”‚
  โ”‚ BUY 2 SOL @ $10
  โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚    Matching Engine   โ”‚
โ”‚                      โ”‚
โ”‚  BUY 2 @ 10          โ”‚
โ”‚        โ†•             โ”‚
โ”‚  SELL 2 @ 10         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  โ”‚
  โ–ผ
Trade executed

The exchange is responsible for maintaining:

  • Users
  • Balances
  • Orders
  • Order books
  • Trades/fills
  • Market state
  • Authentication
  • Order matching

๐Ÿฆ Broker vs Exchange

One important distinction I learned while building this project is that a broker and an exchange are not the same thing.

A broker primarily provides access to markets and routes or executes customer orders.

An exchange maintains the market itself.

A simplified exchange looks like:

BUYERS
  โ”‚
  โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚    ORDER BOOK      โ”‚
โ”‚                    โ”‚
โ”‚ BIDS     ASKS      โ”‚
โ”‚ $10      $11       โ”‚
โ”‚ $9       $12       โ”‚
โ”‚ $8       $13       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  โ–ฒ
  โ”‚
SELLERS

The matching engine is responsible for determining which orders can trade.


๐Ÿ“– Core Trading Concepts

Order Book

For every market, the exchange maintains two sides:

Bids

Orders from users willing to buy.

BIDS

Price     Quantity

$12       2 SOL
$11       5 SOL
$10       3 SOL

Bids are sorted from highest price to lowest price.

The highest bid is the best bid.


Asks

Orders from users willing to sell.

ASKS

Price     Quantity

$13       2 SOL
$12       4 SOL
$11       3 SOL

Asks are sorted from lowest price to highest price.

The lowest ask is the best ask.


Therefore:

              ORDER BOOK

SELL SIDE
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
$13     2 SOL
$12     4 SOL
$11     3 SOL   โ† Best Ask
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
          $10.50
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
$10     5 SOL   โ† Best Bid
$9      3 SOL
$8      2 SOL
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BUY SIDE

The difference between the best ask and best bid is the spread.


๐Ÿ“Œ Limit Orders

A limit order specifies a price.

For example:

{
  "type": "limit",
  "side": "buy",
  "market": "SOL",
  "price": 10,
  "quantity": 5
}

This means:

Buy up to 5 SOL, but don't pay more than $10 per SOL.

If the order cannot be completely filled, the remaining quantity can stay in the order book.

For example:

BUY 5 SOL @ $10

Existing asks:

2 SOL @ $9

The order executes:

2 SOL @ $9

Remaining:

3 SOL @ $10

The remaining 3 SOL becomes a resting bid.


๐Ÿ“Œ Market Orders

A market order does not specify a price.

For example:

{
  "type": "market",
  "side": "buy",
  "market": "SOL",
  "quantity": 5
}

The instruction is essentially:

Buy 5 SOL using the best available sellers.

The matching engine walks through the asks from cheapest to most expensive.

ASKS

2 SOL @ $10
1 SOL @ $11
3 SOL @ $12

For:

BUY MARKET 5 SOL

The engine executes:

2 @ $10
1 @ $11
2 @ $12

Total:

5 SOL

Market orders can also be partially filled.

If only:

2 SOL @ $10

exists, then:

Requested: 5 SOL
Filled:    2 SOL
Remaining: 3 SOL

The remaining market order is not placed into the order book.


๐Ÿงฉ Partial Fills

Partial fills are an important part of the matching engine.

Suppose:

BUY 10 SOL @ $10

and the order book contains:

SELL 3 SOL @ $9
SELL 2 SOL @ $10

The engine executes:

3 SOL @ $9
2 SOL @ $10

Result:

Filled:    5 SOL
Remaining: 5 SOL

Because this is a limit order, the remaining 5 SOL can rest in the order book:

BIDS

5 SOL @ $10

๐Ÿ—๏ธ Version 0 Architecture

The first version intentionally kept the architecture simple.

flowchart TD
    Client[Frontend] --> API[Express API]

    API --> Auth[JWT Authentication]
    API --> OrderAPI[Order API]
    API --> Profile[Profile API]

    OrderAPI --> Engine[Matching Engine]

    Engine --> OrderBook[In-Memory OrderBook]
    Engine --> Balances[In-Memory Balances]

    API --> DB[(PostgreSQL)]
    Engine --> DB

    DB --> Users[Users]
    DB --> Orders[Orders]
    DB --> Fills[Fills]

Everything runs inside one server.

This made Version 0 much easier to develop and debug.


๐Ÿ› ๏ธ Technology Stack

Backend

  • Bun
  • TypeScript
  • Express

Database

  • PostgreSQL
  • Prisma

Authentication

  • JWT
  • HTTP-only cookies

Matching Engine

  • TypeScript
  • In-memory order book
  • In-memory balance manager

Frontend

  • React
  • Trading UI
  • Order book
  • Market data
  • Profile/wallet pages

๐Ÿ” Authentication

Users authenticate using JWT-based authentication stored in HTTP-only cookies.

The general flow is:

Login
  โ”‚
  โ–ผ
Validate credentials
  โ”‚
  โ–ผ
Generate JWT
  โ”‚
  โ–ผ
HTTP-only Cookie
  โ”‚
  โ–ผ
Authenticated requests

Protected routes extract the user ID from the authentication context before performing operations.

This prevents users from simply sending another user's ID when placing orders or accessing private account information.


๐Ÿ’ฐ Balances

In V0, balances are maintained in memory.

For example:

const BALANCES = {
  1: {
    USD: {
      available: 100,
      locked: 20
    },
    SOL: {
      available: 100,
      locked: 20
    }
  }
};

The distinction between available and locked is important.

Suppose a user has:

USD Available = $100
USD Locked    = $0

They place:

BUY 5 SOL @ $10

The exchange reserves:

$50

so the balance becomes:

USD Available = $50
USD Locked    = $50

The user cannot spend the locked $50 on another order.


๐Ÿ“š Database Models

The core database entities in V0 are:

User
  โ”‚
  โ”œโ”€โ”€ Orders
  โ”‚
  โ””โ”€โ”€ Fills

Stock

Order
  โ”‚
  โ””โ”€โ”€ Fills

Fill

Simplified Prisma models:

model User {
    id       Int      @id @default(autoincrement())
    username String   @unique
    password String

    orders   Order[]
    fills    Fill[]
}

model Stock {
    id     Int    @id @default(autoincrement())
    name   String @unique
    symbol String @unique
}

model Order {
    id               Int      @id @default(autoincrement())
    userId           Int
    market           String
    price            Int
    quantity         Int
    type             Type
    side             Side

    filledQuantity   Int
    remainingQuantity Int
    status           Status

    createdAt        DateTime @default(now())

    user User   @relation(fields: [userId], references: [id])
    fills Fill[]
}

model Fill {
    id               Int      @id @default(autoincrement())
    quantity         Int
    side             Side
    type             Type
    userId            Int
    price             Int
    market            String
    originalOrderID  Int

    createdAt        DateTime @default(now())

    user     User  @relation(fields: [userId], references: [id])
    original Order @relation(fields: [originalOrderID], references: [id])
}

๐Ÿ“ฆ The In-Memory Order Book

The V0 engine maintains something similar to:

const ORDERBOOK = {
  SOL: {
    bids: [],
    asks: [],
    lastTradePrice: 0
  },

  ETH: {
    bids: [],
    asks: [],
    lastTradePrice: 0
  }
};

The important rule is:

BIDS โ†’ highest price first

ASKS โ†’ lowest price first

This allows the matching engine to simply inspect:

const bestAsk = book.asks[0];

or:

const bestBid = book.bids[0];

๐Ÿš€ Creating an Order

The order lifecycle in V0 is:

flowchart TD
    Request[POST /order] --> Auth[Authenticate User]
    Auth --> Validate[Validate Request]
    Validate --> Lock[Lock Funds]
    Lock --> DBOrder[Create Order in PostgreSQL]
    DBOrder --> Match{Buy or Sell?}

    Match -->|BUY| Buy[matchBuy]
    Match -->|SELL| Sell[matchSell]

    Buy --> Trade[Execute Trades]
    Sell --> Trade

    Trade --> Memory[Update In-Memory State]
    Memory --> Persistence[Persist Fills and Order Updates]
    Persistence --> Response[Return Final Order]

๐Ÿงฎ processOrder()

The high-level implementation looks like:

export async function processOrder(order: UserOrder) {
    validateOrder(order);

    lockFunds(order);

    const dbOrder = await prismaClient.order.create({
        data: {
            ...order,
            status: "open",
            filledQuantity: 0,
            remainingQuantity: order.quantity
        }
    });

    const result =
        order.side === "buy"
            ? matchBuy(dbOrder)
            : matchSell(dbOrder);

    await persistMatchingResult(result);

    return dbOrder;
}

The important architectural decision here is that the matching engine doesn't need to perform the database writes itself.


โš™๏ธ Matching a BUY Order

For a buy order, we walk through the asks from cheapest to most expensive.

while (
    order.remainingQuantity > 0 &&
    asks.length > 0
) {
    const currentBestAsk = asks[0];

    if (
        order.type === "limit" &&
        currentBestAsk.price > order.price
    ) {
        break;
    }

    const trade = executeTrade(
        order,
        currentBestAsk
    );

    fills.push(...trade.fills);

    if (
        currentBestAsk.remainingQuantity === 0
    ) {
        asks.shift();
    }
}

The important part is:

BUY LIMIT
    โ†“
Cheapest Ask
    โ†“
Next Cheapest Ask
    โ†“
Next Cheapest Ask

A market buy follows the same process but doesn't have a maximum price.


โš™๏ธ Matching a SELL Order

For a sell order, we walk through the bids from highest to lowest.

while (
    order.remainingQuantity > 0 &&
    bids.length > 0
) {
    const currentBestBid = bids[0];

    if (
        order.type === "limit" &&
        currentBestBid.price < order.price
    ) {
        break;
    }

    const trade = executeTrade(
        currentBestBid,
        order
    );

    fills.push(...trade.fills);

    if (
        currentBestBid.remainingQuantity === 0
    ) {
        bids.shift();
    }
}

So:

SELL LIMIT
    โ†“
Highest Bid
    โ†“
Next Highest Bid
    โ†“
Next Highest Bid

๐Ÿ”ฅ Executing a Trade

The most important function in the engine is executeTrade().

It doesn't talk to Prisma.

It changes the in-memory trading state and produces data that can later be persisted.

export function executeTrade(
    buyOrder: Order,
    sellOrder: Order
) {
    const tradeQty = Math.min(
        buyOrder.remainingQuantity,
        sellOrder.remainingQuantity
    );

    const tradePrice = sellOrder.price;

    buyOrder.remainingQuantity -= tradeQty;
    buyOrder.filledQuantity += tradeQty;

    sellOrder.remainingQuantity -= tradeQty;
    sellOrder.filledQuantity += tradeQty;

    buyOrder.status =
        buyOrder.remainingQuantity === 0
            ? "closed"
            : "partial_filled";

    sellOrder.status =
        sellOrder.remainingQuantity === 0
            ? "closed"
            : "partial_filled";

    return {
        fills: [
            {
                side: "buy",
                type: buyOrder.type,
                quantity: tradeQty,
                price: tradePrice,
                market: buyOrder.market,
                userId: buyOrder.userId,
                originalOrderID: buyOrder.id
            },
            {
                side: "sell",
                type: sellOrder.type,
                quantity: tradeQty,
                price: tradePrice,
                market: sellOrder.market,
                userId: sellOrder.userId,
                originalOrderID: sellOrder.id
            }
        ],

        updatedOrders: [
            {
                id: buyOrder.id,
                filledQuantity: buyOrder.filledQuantity,
                remainingQuantity: buyOrder.remainingQuantity,
                status: buyOrder.status
            },
            {
                id: sellOrder.id,
                filledQuantity: sellOrder.filledQuantity,
                remainingQuantity: sellOrder.remainingQuantity,
                status: sellOrder.status
            }
        ],

        tradePrice
    };
}

This separation was one of the important improvements made during V0 development.


๐Ÿง  Separation of Responsibilities

Instead of allowing executeTrade() to perform everything, responsibilities are separated.

executeTrade()
โ”‚
โ”œโ”€โ”€ Update order quantities
โ”œโ”€โ”€ Update balances
โ”œโ”€โ”€ Update last trade price
โ””โ”€โ”€ Return persistence data

While:

matchBuy()
โ”‚
โ”œโ”€โ”€ Walk asks
โ”œโ”€โ”€ Decide whether matching can continue
โ”œโ”€โ”€ Remove completely filled asks
โ””โ”€โ”€ Place remaining limit order into bids

And:

matchSell()
โ”‚
โ”œโ”€โ”€ Walk bids
โ”œโ”€โ”€ Decide whether matching can continue
โ”œโ”€โ”€ Remove completely filled bids
โ””โ”€โ”€ Place remaining limit order into asks

This makes the engine easier to reason about and test.


๐Ÿงพ Fills vs Orders

One trade produces two fills.

For example:

BUY Order #101
SELL Order #205

Trade:

2 SOL @ $10

Creates:

Fill #1

userId = buyer
side = BUY
quantity = 2
price = 10
originalOrderID = 101

and:

Fill #2

userId = seller
side = SELL
quantity = 2
price = 10
originalOrderID = 205

This makes it possible to build:

  • Trade history
  • User fill history
  • Order history
  • Market trade history

๐Ÿ’พ Database Persistence

The matching engine produces:

{
    fills,
    updatedOrders,
    lastTradePrice
}

The persistence layer then writes those changes to PostgreSQL.

For related changes, PostgreSQL transactions provide all-or-nothing behavior: either the grouped changes commit, or they are rolled back.

For example:

await prismaClient.$transaction(async (tx) => {

    await tx.fill.createMany({
        data: fills
    });

    for (const order of updatedOrders) {
        await tx.order.update({
            where: {
                id: order.id
            },
            data: {
                filledQuantity:
                    order.filledQuantity,

                remainingQuantity:
                    order.remainingQuantity,

                status:
                    order.status
            }
        });
    }
});

This is especially important because a trade usually changes multiple pieces of state:

Buyer
 โ”œโ”€โ”€ USD
 โ””โ”€โ”€ SOL

Seller
 โ”œโ”€โ”€ USD
 โ””โ”€โ”€ SOL

Buyer Order
Seller Order

Buyer Fill
Seller Fill

Those database changes should not be treated as unrelated operations.


๐Ÿ›‘ Cancelling Orders

Canceling an order also requires careful balance handling.

For a partially filled BUY:

BUY 10 SOL @ $10

Filled:    3 SOL
Remaining: 7 SOL

Initially:

Locked = $100

After the 3 SOL trade:

Locked = $70

When canceling:

Unlock $70

not the $30 that was already spent.

For a SELL:

SELL 10 SOL

Filled:    3
Remaining: 7

The remaining 7 SOL should be unlocked.

The order should then transition to something like:

OPEN
   โ†“
PARTIALLY_FILLED
   โ†“
CANCELLED

rather than using a single ambiguous closed state for both filled and cancelled orders.


๐Ÿ“Š TestExchange UI

The frontend was designed with a retro, hand-drawn visual style rather than copying the traditional polished-finance aesthetic.

TestExchange Trading Page

The trading page contains:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ TestExchange                         spot   stocks        โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚                                                          โ”‚
โ”‚  Chart                  Order Book             Order     โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”       ASKS                  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚              โ”‚       $90                    โ”‚ Buy   โ”‚ โ”‚
โ”‚  โ”‚ Price Chart  โ”‚       $89                    โ”‚ Sell  โ”‚ โ”‚
โ”‚  โ”‚              โ”‚       โ”€โ”€โ”€                   โ”‚       โ”‚ โ”‚
โ”‚  โ”‚              โ”‚       $88                    โ”‚ Limit โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜       BIDS                  โ”‚Market โ”‚ โ”‚
โ”‚                           $87                  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                           $86                            โ”‚
โ”‚                                                          โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Balances | Open Orders | Order History | Fill History    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“ˆ Spot Market Page

The spot page provides an overview of available markets.

Spot Markets

Markets display information such as:

  • Name
  • Symbol
  • Current price
  • 24h volume
  • Market cap
  • 24h change
  • Recent price movement

Clicking a market takes the user to:

/spot/trade/:market

For example:

/spot/trade/BTC

๐Ÿ‘ค Profile Page

The profile page provides:

  • User information
  • Balances
  • Deposits
  • Orders
  • Fills
  • Trading history

TestExchange Profile


๐Ÿ’ฅ The Problem With V0

V0 worked, but it exposed a major architectural problem.

The order book and balances lived only in RAM.

For example:

const ORDERBOOK = {
    SOL: {
        bids: [],
        asks: [],
        lastTradePrice: 0
    }
};

const BALANCES = {
    1: {
        USD: {
            available: 100,
            locked: 20
        }
    }
};

If the Node/Bun process crashes:

SERVER CRASH
     โ”‚
     โ–ผ
RAM LOST
     โ”‚
     โ”œโ”€โ”€ ORDERBOOK โŒ
     โ””โ”€โ”€ BALANCES  โŒ

PostgreSQL still contains users, orders, and fills, but the engine's current in-memory state disappears.

This led to the next architectural question:

How can the matching engine remain extremely fast while surviving server restarts?


๐Ÿ’พ V0.1: Snapshot Persistence

One possible improvement is periodically writing the in-memory state to a snapshot.

RAM
 โ”‚
 โ”‚ every 2 minutes
 โ–ผ
snapshot.json

Example:

{
  "timestamp": "2026-08-17T10:00:00Z",
  "orderbook": {
    "SOL": {
      "bids": [],
      "asks": [],
      "lastTradePrice": 150
    }
  },
  "balances": {
    "1": {
      "USD": {
        "available": 80,
        "locked": 20
      }
    }
  }
}

On restart:

snapshot.json
       โ”‚
       โ–ผ
ORDERBOOK + BALANCES

This is simple, but it introduces a recovery window.

If the last snapshot was two minutes ago:

10:00 โ†’ Snapshot
10:01 โ†’ Trade
10:02 โ†’ Trade
10:03 โ†’ Crash

The 10:01 and 10:02 state changes could be lost.


๐Ÿš€ Version 1: Decoupling the Matching Engine

The biggest architectural change planned for V1 is separating the matching engine from the API/backend server.

Instead of:

Frontend
   โ”‚
   โ–ผ
Backend + Engine

we move toward:

flowchart LR
    Client[Frontend] --> Backend[Backend Service]

    Backend --> RequestQueue[(Redis Request Queue)]

    RequestQueue --> Engine[Matching Engine]

    Engine --> Memory[In-Memory State]

    Memory --> OrderBook[OrderBook]
    Memory --> Balances[Balances]

    Engine --> ResponseQueue[(Redis Response Queue)]

    ResponseQueue --> Backend

    Engine --> DB[(PostgreSQL)]

Now the backend and matching engine have separate responsibilities.


๐Ÿงฉ Backend Service

The backend becomes responsible for:

Authentication
User APIs
Profile
Market APIs
Order requests
WebSocket connections
Database access

It does not directly perform the matching logic.


โš™๏ธ Matching Engine Service

The engine becomes responsible for:

Order validation
OrderBook
Balances
Matching
Trade execution
Market state
Order state transitions

Its most important data structures remain in memory because order matching needs extremely fast access.


๐Ÿ“ฌ Redis as the Communication Layer

The backend can send an order to the engine through Redis.

Conceptually:

Backend

{
    correlationId: "abc-123",
    type: "CREATE_ORDER",
    userId: 10,
    market: "SOL",
    side: "buy",
    type: "limit",
    price: 100,
    quantity: 5
}

        โ”‚
        โ–ผ

Redis Queue

        โ”‚
        โ–ผ

Matching Engine

The engine processes the request and publishes a response:

{
    correlationId: "abc-123",
    status: "success",
    orderId: 101,
    filledQuantity: 5,
    remainingQuantity: 0
}

The correlationId allows the backend to associate the asynchronous engine response with the original request.


๐Ÿ”„ V0 vs V1

AreaV0V1
BackendSingle serviceSeparate service
Matching EngineSame processSeparate process
OrderBookRAMEngine RAM
BalancesRAMEngine RAM
PostgreSQLDirectly accessiblePersistence layer
CommunicationFunction callsRedis
Order processingSynchronousAsynchronous
ScalingLimitedEasier to scale
Engine restartRebuild manuallySnapshot/recovery
Failure isolationLowHigher

๐Ÿง  Why Keep OrderBook in Memory?

The matching engine constantly needs:

Best Bid
Best Ask
Next Bid
Next Ask

For example:

const bestAsk = orderBook.asks[0];

The matching engine should not need to perform:

SELECT *
FROM orders
WHERE ...
ORDER BY price ASC
LIMIT 1;

for every matching operation.

The order book is a highly active data structure.

The database is better suited for durable storage and historical queries.

This leads to an important principle:

Memory is optimized for speed. Database storage is optimized for durability and querying.


๐Ÿงฑ V1 Recovery Strategy

A separate matching engine introduces another problem:

What happens if the engine crashes?

The engine could use a combination of:

Snapshot
+
Event/Operation Log

The conceptual recovery process becomes:

flowchart TD
    Crash[Engine Crash] --> Snapshot[Load Latest Snapshot]
    Snapshot --> Replay[Replay Events After Snapshot]
    Replay --> State[Rebuild In-Memory State]
    State --> Ready[Start Consuming Redis Orders]

For example:

10:00
Snapshot created

10:01
Order placed

10:02
Trade executed

10:03
Order cancelled

10:04
Engine crashes

Recovery:

Load 10:00 snapshot

โ†“

Replay 10:01 order

โ†“

Replay 10:02 trade

โ†“

Replay 10:03 cancellation

โ†“

Current state restored

This approach reduces the amount of state that needs to be rebuilt from scratch.


๐Ÿ—๏ธ Target Architecture

The longer-term architecture looks like:

flowchart TB

    User[User / Browser]

    Frontend[Frontend Service]

    Backend[Backend API]

    RedisIn[(Redis Request Queue)]

    Engine[Matching Engine]

    EngineMemory[Engine Memory]

    OrderBook[OrderBook]
    Balances[Balances]

    RedisOut[(Redis Response Queue)]

    DB[(PostgreSQL)]

    Snapshot[(Snapshot / Recovery)]

    User --> Frontend
    Frontend --> Backend

    Backend --> RedisIn

    RedisIn --> Engine

    Engine --> EngineMemory

    EngineMemory --> OrderBook
    EngineMemory --> Balances

    Engine --> RedisOut
    RedisOut --> Backend
    Backend --> Frontend

    Engine --> DB
    Engine --> Snapshot

๐Ÿ” Complete Order Journey in V1

A BUY order would travel through the system like this:

User
 โ”‚
 โ”‚ POST /order
 โ–ผ
Backend
 โ”‚
 โ”‚ authenticate
 โ”‚ validate request
 โ”‚ create correlationId
 โ–ผ
Redis Request Queue
 โ”‚
 โ–ผ
Matching Engine
 โ”‚
 โ”œโ”€โ”€ validate engine state
 โ”‚
 โ”œโ”€โ”€ lock funds
 โ”‚
 โ”œโ”€โ”€ inspect order book
 โ”‚
 โ”œโ”€โ”€ match order
 โ”‚
 โ”œโ”€โ”€ update balances
 โ”‚
 โ”œโ”€โ”€ update order book
 โ”‚
 โ”œโ”€โ”€ generate fills
 โ”‚
 โ””โ”€โ”€ persist result
 โ”‚
 โ–ผ
Redis Response Queue
 โ”‚
 โ–ผ
Backend
 โ”‚
 โ–ผ
User

๐Ÿ” Why Correlation IDs Matter

Once communication becomes asynchronous, the backend cannot simply do:

const result = matchBuy(order);

Instead:

Backend
   โ”‚
   โ”œโ”€โ”€ Request A โ†’ Engine
   โ”œโ”€โ”€ Request B โ†’ Engine
   โ””โ”€โ”€ Request C โ†’ Engine

Engine
   โ”‚
   โ”œโ”€โ”€ Response B
   โ”œโ”€โ”€ Response A
   โ””โ”€โ”€ Response C

Responses may not necessarily arrive in the same order.

Therefore:

correlationId

becomes important.

Example:

{
  "correlationId": "order-request-123",
  "type": "CREATE_ORDER",
  "payload": {
    "userId": 10,
    "market": "SOL",
    "side": "buy",
    "quantity": 2
  }
}

The response contains the same identifier.


๐Ÿ“ก WebSockets

The trading UI also benefits from WebSockets.

Instead of repeatedly polling:

GET /orderbook
GET /trades
GET /price
GET /orders

the server can push updates.

For example:

Matching Engine
       โ”‚
       โ–ผ
Trade Event
       โ”‚
       โ–ผ
WebSocket Server
       โ”‚
       โ–ผ
Browser

The browser can immediately update:

  • Order book
  • Last trade price
  • Recent trades
  • User order status
  • Balance changes

๐Ÿ“Š Example Trade Event

A trade event could look like:

{
  "type": "TRADE_EXECUTED",
  "market": "SOL",
  "price": 100,
  "quantity": 2,
  "timestamp": 1720000000
}

The frontend can use this event to update the trading interface without requesting the entire market state again.


โš ๏ธ Concurrency Is the Next Challenge

A single-process V0 engine is relatively easy to reason about because JavaScript executes engine operations sequentially within the process.

Once the engine is distributed, concurrency becomes much more important.

Imagine:

User A โ†’ BUY 10 SOL
User B โ†’ SELL 5 SOL
User C โ†’ BUY 5 SOL

The engine needs a deterministic ordering.

For a single market, the matching engine should process commands in a well-defined sequence:

Order 101
   โ†“
Order 102
   โ†“
Order 103

rather than allowing multiple workers to mutate the same order book concurrently.

This is one reason a dedicated matching engine is useful.


๐Ÿ’ณ Money and Precision

One lesson from building the exchange was that financial values should not be treated casually.

Instead of relying on JavaScript floating-point values such as:

10.25

a real implementation should consider integer units or a decimal representation.

For example:

$10.25

โ†“

1025 cents

or for crypto:

1.234567 SOL

โ†“

1234567 base units

The important idea is to avoid unexpected floating-point rounding during financial calculations.


๐Ÿงช Testing the Matching Engine

The matching engine can be tested independently from HTTP.

For example:

describe("matching engine", () => {

    it("should fully fill a buy order", () => {
        // setup order book

        // place buy order

        // assert fills

        // assert remaining quantity
    });

});

Important cases include:

โœ“ Full fill
โœ“ Partial fill
โœ“ No fill
โœ“ Limit buy
โœ“ Limit sell
โœ“ Market buy
โœ“ Market sell
โœ“ Multiple fills
โœ“ Exact price match
โœ“ Price improvement
โœ“ Order cancellation
โœ“ Insufficient balance
โœ“ Empty order book
โœ“ Market order with insufficient liquidity

๐Ÿง  Lessons From V0

Building V0 first was intentional.

It allowed me to understand the actual business logic before introducing distributed systems.

The most important concepts I learned were:

1. The order book is a data structure

It's not just a database table.

It needs:

Price ordering
Fast best-price access
Quantity updates
Order removal

2. Matching is deterministic

A matching engine needs clear rules:

Best price first
Then time priority

3. Balances need available and locked states

Without locked balances, users could potentially reuse funds committed to open orders.

4. Orders and fills are different concepts

An order represents the user's instruction.

A fill represents an actual execution.

One order can generate multiple fills.

5. Market orders don't rest

If a market order cannot find enough liquidity, the unfilled remainder doesn't become a resting order.

6. Limit orders can rest

A partially filled limit order can remain in the book.


๐Ÿงฉ Why I Didn't Start With Redis

It would have been tempting to immediately build:

Redis
Kafka
WebSockets
Multiple Services
PostgreSQL

But that would make it difficult to understand whether problems came from:

Matching logic
OR
Distributed communication
OR
Persistence
OR
Concurrency

Starting with V0 made the core trading engine understandable first.

Then the architecture can evolve around a working domain model.


๐Ÿšง What V1 Is Trying to Solve

V1 isn't about changing the matching rules.

The core logic remains:

Order
 โ†“
Validate
 โ†“
Lock
 โ†“
Match
 โ†“
Trade
 โ†“
Settlement

The difference is where the components live.

V0:

Everything in one process

V1:

Backend
   โ”‚
Redis
   โ”‚
Matching Engine
   โ”‚
PostgreSQL

This separation improves:

  • Failure isolation
  • Independent scaling
  • Engine performance
  • Maintainability
  • Clear service boundaries

๐Ÿ—บ๏ธ Roadmap

V0 โ€” Completed

  • JWT authentication
  • HTTP-only authentication cookies
  • User registration/login
  • USD deposits
  • User balances
  • Spot markets
  • Order book
  • Limit orders
  • Market orders
  • Partial fills
  • Full fills
  • Order cancellation
  • Trade/fill history
  • Order history
  • Profile page
  • Trading page
  • In-memory matching engine
  • PostgreSQL persistence

V0.1 โ€” Reliability Improvements

  • Periodic snapshots
  • Engine state recovery
  • Better error handling
  • Matching engine unit tests
  • Better persistence boundaries

V1 โ€” Decoupled Architecture

  • Separate matching engine service
  • Redis request queue
  • Redis response queue
  • Correlation IDs
  • WebSocket market updates
  • Engine snapshots
  • Event replay
  • Engine recovery
  • Better concurrency control

Future

  • Multiple markets
  • Improved market data service
  • More advanced order types
  • Rate limiting
  • Observability
  • Metrics
  • Distributed deployment
  • Load testing
  • Fault injection testing

๐ŸŽฏ Final Thoughts

The most valuable part of building TestExchange wasn't the UI or even the API.

It was understanding what actually happens after a user clicks Buy.

A simple:

BUY 2 SOL @ $100

eventually becomes:

Authentication
       โ†“
Validation
       โ†“
Balance reservation
       โ†“
Order creation
       โ†“
Order book lookup
       โ†“
Price matching
       โ†“
Trade execution
       โ†“
Balance settlement
       โ†“
Fill creation
       โ†“
Order state update
       โ†“
Market update
       โ†“
Response to user

And when the system evolves from a single process to a distributed architecture, the same business operation becomes:

Client
  โ†“
Backend
  โ†“
Redis
  โ†“
Matching Engine
  โ†“
In-Memory State
  โ†“
Persistence
  โ†“
Redis
  โ†“
Backend
  โ†“
Client

That transition from a simple monolith to a decoupled event-driven system is the main reason I built this project.

TestExchange is not intended to be a production financial exchange. It is a practical engineering project for understanding how exchanges, matching engines, state management, persistence, and distributed systems fit together.


๐Ÿ“ธ Project Screenshots

Landing Page

TestExchange Landing

Spot Markets

TestExchange Spot Markets

Trading Page

TestExchange Trading

Profile

TestExchange Profile

Architecture

TestExchange Architecture


๐ŸŽฅ Demo

<!-- Paste your GitHub user-attachments video URL here -->

https://github.com/user-attachments/assets/YOUR-VIDEO-ID


๐Ÿ› ๏ธ Tech Stack

Frontend
  โ”œโ”€โ”€ React
  โ””โ”€โ”€ WebSocket

Backend
  โ”œโ”€โ”€ Bun
  โ”œโ”€โ”€ TypeScript
  โ””โ”€โ”€ Express

Trading Engine
  โ”œโ”€โ”€ TypeScript
  โ”œโ”€โ”€ In-Memory OrderBook
  โ””โ”€โ”€ In-Memory Balances

Communication
  โ””โ”€โ”€ Redis

Persistence
  โ”œโ”€โ”€ PostgreSQL
  โ””โ”€โ”€ Prisma

Authentication
  โ””โ”€โ”€ JWT + HTTP-only Cookies

๐Ÿ“š What I Learned

Building a CEX is less about creating a BUY button and more about building a system where state, ordering, money, execution, and persistence remain consistent while the system is changing constantly.

That is the problem I wanted TestExchange to help me understand.

Written by Manish Patidar

Comments

Loadingโ€ฆ
โ€œMan is made by his belief. As he believes, so he is.โ€_
โ€” Bhagavad Gita