Skip to content

Build a tiny crypto exchange on TigerBeetle

11 min readTigerBeetleFinancialDatabases

Short version: npm i -g layerbase, then lbase create tiger1 -e tigerbeetle --start, then paste the code below into one file and run it. You get a USD/BTC exchange with an in-memory order book, where TigerBeetle guarantees that nobody spends money they don't have and that a trade settles both sides or neither.

This is a proof of concept. It is not an exchange you should run with real money, and the last section lists what's missing. What I wanted to see is how far a few hundred lines of TypeScript get you when the ledger is TigerBeetle: user balances that can't go negative, orders that lock funds without spending them, and trades where the dollars and the bitcoin move together or not at all.

The split of responsibilities is the main idea. The order book and the matching live in the application, in memory. TigerBeetle doesn't know what an order is. It only sees money moving between accounts, and it enforces the rules about that money.

If you have never touched TigerBeetle before, Getting Started with TigerBeetle covers accounts, transfers and flags one at a time. This post assumes you've seen those and puts them to work.

Contents

Run TigerBeetle locally

The Layerbase CLI downloads the TigerBeetle binary for your platform and runs it, no Docker. (What is the Layerbase CLI?)

bash
npm i -g layerbase
lbase create tiger1 -e tigerbeetle --start
lbase url tiger1
text
127.0.0.1:3000

Then the project:

bash
mkdir tiny-exchange && cd tiny-exchange
pnpm init
pnpm add tigerbeetle-node@0.16.70
pnpm add -D tsx typescript @types/node

Pin the client. TigerBeetle's client and server must run the exact same release, and the Layerbase CLI ships 0.16.70. A newer client is evicted with client_release_too_high, and the 0.17 client also reports transfer results differently, so code written against one will not compile against the other.

Every code block below goes into one file, exchange.ts, in order. Everything here was run against that local 0.16.70 instance on Node 24, and the output at the end is what it printed.

The data model

TigerBeetle has accounts, transfers and ledgers. A transfer moves an integer amount from one account to another account on the same ledger. There are no decimals and no currency conversion.

So each asset gets its own ledger:

AssetLedgerUnitScale
USD1cent2
BTC2satoshi8

The ledger doesn't store the scale. That's your convention, and the app has to apply it consistently whenever it formats an amount.

Every user gets one account per asset. The exchange gets two per asset:

  • Hot wallet: what the exchange actually holds, in the bank or on chain. A deposit debits it and credits the user.
  • Escrow: where funds sit while they're locked behind an open order or in the middle of a trade.

Since a transfer can't cross ledgers, a trade is never one transfer. Dave buying 0.5 BTC from Alice for $30,000 is at least two: USD from Dave to Alice on ledger 1, and BTC from Alice to Dave on ledger 2. Making those two legs atomic is the interesting part, and it's what linked transfers are for.

Setup

typescript
import {
  createClient,
  id,
  AccountFlags,
  TransferFlags,
  CreateAccountError,
  CreateTransferError,
  type Account,
  type Transfer,
} from 'tigerbeetle-node'

const client = createClient({
  cluster_id: 0n,
  replica_addresses: [process.env.TB_ADDRESS ?? '127.0.0.1:3000'],
})

// One ledger per asset. Amounts are integers in the asset's smallest unit.
const USD = { ledger: 1, scale: 2, symbol: 'USD' } // 1 USD = 100 cents
const BTC = { ledger: 2, scale: 8, symbol: 'BTC' } // 1 BTC = 100,000,000 sats
type Asset = typeof USD

// Codes record why an account exists or a transfer happened.
// TigerBeetle stores them but never interprets them.
const AccountCode = { user: 10, hotWallet: 20, escrow: 30 }
const TransferCode = { deposit: 100, reserve: 200, fill: 300 }

// Prices are cents per 1 BTC, quantities are sats.
// A 0.01 BTC lot and a $1 tick keep every trade's cost a whole number of cents.
const SATS_PER_BTC = 100_000_000n
const LOT = 1_000_000n // 0.01 BTC
const TICK = 100n // $1.00

function cost(qtySats: bigint, priceCents: bigint): bigint {
  return (qtySats * priceCents) / SATS_PER_BTC
}

id() from the client generates time-based 128-bit ids. We use it for accounts, transfers and order ids.

The lot and tick sizes are there so the integer math stays exact. Cost in cents is sats * cents_per_btc / 100,000,000, and with a 0.01 BTC lot and a $1 tick that division never leaves a remainder. A real exchange has to decide how to round, and who gets the rounding.

Accounts for users and the exchange

typescript
function newAccount(asset: Asset, code: number, flags: number): Account {
  return {
    id: id(),
    debits_pending: 0n,
    debits_posted: 0n,
    credits_pending: 0n,
    credits_posted: 0n,
    user_data_128: 0n,
    user_data_64: 0n,
    user_data_32: 0,
    reserved: 0,
    ledger: asset.ledger,
    code,
    flags,
    timestamp: 0n,
  }
}

type User = { name: string; usd: bigint; btc: bigint }

// hotWallet mirrors what the exchange actually holds (bank balance, on-chain wallet).
// escrow holds funds locked behind open orders and mid-settlement.
const exchange = {
  usd: {
    hotWallet: newAccount(USD, AccountCode.hotWallet, AccountFlags.credits_must_not_exceed_debits),
    escrow: newAccount(USD, AccountCode.escrow, AccountFlags.debits_must_not_exceed_credits),
  },
  btc: {
    hotWallet: newAccount(BTC, AccountCode.hotWallet, AccountFlags.credits_must_not_exceed_debits),
    escrow: newAccount(BTC, AccountCode.escrow, AccountFlags.debits_must_not_exceed_credits),
  },
}

async function createAccounts(accounts: Account[]) {
  // createAccounts only reports the accounts that failed. An empty array means all created.
  const errors = await client.createAccounts(accounts)
  for (const { index, result } of errors) {
    if (result !== CreateAccountError.exists) {
      throw new Error(`account ${index}: ${CreateAccountError[result]}`)
    }
  }
}

async function createUser(name: string): Promise<User> {
  // A user can never spend more than they have.
  const usd = newAccount(USD, AccountCode.user, AccountFlags.debits_must_not_exceed_credits)
  const btc = newAccount(BTC, AccountCode.user, AccountFlags.debits_must_not_exceed_credits)
  await createAccounts([usd, btc])
  return { name, usd: usd.id, btc: btc.id }
}

The flags do the safety work:

  • User accounts use debits_must_not_exceed_credits. TigerBeetle rejects any transfer that would take a user below zero, pending ones included. You don't write that check yourself, and two concurrent requests can't both slip past it.
  • Escrow uses the same flag, so it can never pay out more than was put into it.
  • The hot wallet uses credits_must_not_exceed_debits, the mirror image. Deposits are debits to it, and you can't withdraw more than came in.

One thing to know about the 0.16 client: createAccounts and createTransfers return only the failures, as { index, result } pairs. An empty array means every event succeeded.

Deposits

Deposits are plain transfers from the hot wallet to the user. In a real system a bank webhook or a confirmed on-chain transaction would trigger them, and the transfer id would be derived from that event so a replayed webhook can't credit someone twice.

typescript
type TransferInput = Pick<
  Transfer,
  'id' | 'debit_account_id' | 'credit_account_id' | 'amount' | 'ledger' | 'code'
> &
  Partial<Transfer>

function newTransfer(t: TransferInput): Transfer {
  return {
    pending_id: 0n,
    user_data_128: 0n,
    user_data_64: 0n,
    user_data_32: 0,
    timeout: 0,
    flags: 0,
    timestamp: 0n,
    ...t,
  }
}

// createTransfers only reports failures, so fill in "ok" for everything else.
// Returns one result name per transfer: "ok", "exists", "exceeds_credits", ...
async function submit(transfers: Transfer[]): Promise<string[]> {
  const results: string[] = transfers.map(() => 'ok')
  for (const { index, result } of await client.createTransfers(transfers)) {
    results[index] = CreateTransferError[result]
  }
  return results
}

// Money arrived in the exchange's bank account or wallet:
// debit the hot wallet, credit the user.
async function deposit(user: User, asset: Asset, amount: bigint) {
  const isUsd = asset.ledger === USD.ledger
  const [result] = await submit([
    newTransfer({
      id: id(),
      debit_account_id: isUsd ? exchange.usd.hotWallet.id : exchange.btc.hotWallet.id,
      credit_account_id: isUsd ? user.usd : user.btc,
      amount,
      ledger: asset.ledger,
      code: TransferCode.deposit,
    }),
  ])
  if (result !== 'ok') throw new Error(`deposit failed: ${result}`)
}

Orders, reservations, and atomic fills

When someone places a limit order, we don't want to move their money yet, but we do want to know it's there and can't be spent twice. That's a pending transfer. It adds the amount to debits_pending on the user's account and credits_pending on escrow, so the user's spendable balance drops at once. Later the pending transfer is either posted (the money actually moves) or voided (it's released).

A buy order reserves qty * limit price in USD. A sell order reserves qty in BTC.

When two orders match, one fill is a chain of linked transfers:

  1. Post the buyer's USD reservation for the trade cost.
  2. Move that USD from escrow to the seller.
  3. Post the seller's BTC reservation for the quantity.
  4. Move that BTC from escrow to the buyer.
  5. If either order is only partly filled, open a new reservation for what's left.

Every transfer except the last carries TransferFlags.linked. TigerBeetle treats the chain as one unit: if any transfer in it fails, none are applied, and the rest come back as linked_event_failed. The USD leg and the BTC leg live on different ledgers, and they still commit together.

Step 5 deals with a TigerBeetle detail. When you post a pending transfer for less than its full amount, the remainder goes back to the debit account; it does not stay on hold. Posting is one-shot. So a partly filled order gets a fresh pending transfer for its remainder, in the same linked chain, and there's no moment where those funds are unlocked.

The same detail handles price improvement. Dave bids up to $61,000 but trades at $60,000 against a resting ask, so his reservation was bigger than the trade cost. Posting for the smaller amount hands the difference back to him.

typescript
type Side = 'buy' | 'sell'

type Order = {
  id: bigint // generated by the client, doubles as the idempotency key
  user: User
  side: Side
  price: bigint // limit price, cents per BTC
  qty: bigint // sats
  remaining: bigint // sats not yet filled
  reservationId: bigint // the pending transfer currently locking this order's funds
  seq: number // arrival order, for time priority
}

// Lock the funds an order could need: USD for a buy, BTC for a sell.
function reservation(order: Order, transferId: bigint): Transfer {
  const buy = order.side === 'buy'
  return newTransfer({
    id: transferId,
    debit_account_id: buy ? order.user.usd : order.user.btc,
    credit_account_id: buy ? exchange.usd.escrow.id : exchange.btc.escrow.id,
    amount: buy ? cost(order.remaining, order.price) : order.remaining,
    ledger: buy ? USD.ledger : BTC.ledger,
    code: TransferCode.reserve,
    user_data_128: order.id, // find every reservation for an order later
    flags: TransferFlags.pending,
  })
}

// Post or void a pending transfer. Accounts, ledger and code stay 0:
// TigerBeetle takes them from the pending transfer.
function resolvePending(options: {
  pendingId: bigint
  amount: bigint
  flag: TransferFlags
  tradeId?: bigint
}): Transfer {
  return newTransfer({
    id: id(),
    pending_id: options.pendingId,
    debit_account_id: 0n,
    credit_account_id: 0n,
    amount: options.amount,
    ledger: 0,
    code: 0,
    user_data_128: options.tradeId ?? 0n,
    flags: options.flag,
  })
}

// Settle one fill between a buy order and a sell order, all or nothing.
async function settleFill(fill: { buy: Order; sell: Order; qty: bigint; price: bigint }) {
  const { buy, sell, qty, price } = fill
  const usd = cost(qty, price)
  const tradeId = id()
  const buyLeft = buy.remaining - qty
  const sellLeft = sell.remaining - qty

  const legs: Transfer[] = [
    // USD leg: take the trade cost out of the buyer's reservation, pay the seller.
    // Posting less than the pending amount releases the rest back to the buyer.
    resolvePending({
      pendingId: buy.reservationId,
      amount: usd,
      flag: TransferFlags.post_pending_transfer,
      tradeId,
    }),
    newTransfer({
      id: id(),
      debit_account_id: exchange.usd.escrow.id,
      credit_account_id: sell.user.usd,
      amount: usd,
      ledger: USD.ledger,
      code: TransferCode.fill,
      user_data_128: tradeId,
    }),
    // BTC leg: take the sats out of the seller's reservation, deliver them to the buyer.
    resolvePending({
      pendingId: sell.reservationId,
      amount: qty,
      flag: TransferFlags.post_pending_transfer,
      tradeId,
    }),
    newTransfer({
      id: id(),
      debit_account_id: exchange.btc.escrow.id,
      credit_account_id: buy.user.btc,
      amount: qty,
      ledger: BTC.ledger,
      code: TransferCode.fill,
      user_data_128: tradeId,
    }),
  ]

  // Partially filled orders get a fresh reservation for whatever is left.
  const newBuyReservation = buyLeft > 0n ? id() : 0n
  const newSellReservation = sellLeft > 0n ? id() : 0n
  if (buyLeft > 0n) legs.push(reservation({ ...buy, remaining: buyLeft }, newBuyReservation))
  if (sellLeft > 0n) legs.push(reservation({ ...sell, remaining: sellLeft }, newSellReservation))

  // Every transfer except the last carries the linked flag,
  // so TigerBeetle applies all of them or none of them.
  for (const leg of legs.slice(0, -1)) leg.flags |= TransferFlags.linked

  const results = await submit(legs)
  if (results.some((r) => r !== 'ok')) {
    // Funds were reserved up front, so this means a bug. Stop rather than guess.
    throw new Error(`fill failed, nothing was applied: ${results.join(', ')}`)
  }

  buy.remaining = buyLeft
  sell.remaining = sellLeft
  buy.reservationId = newBuyReservation
  sell.reservationId = newSellReservation
  console.log(
    `  fill: ${sell.user.name} -> ${buy.user.name} ${fmt(qty, BTC)} @ ${fmt(price, USD)} = ${fmt(usd, USD)}`,
  )
}

If a fill fails, the code throws. Both sides had their funds reserved before matching started, so a failure means a bug or a mismatch between the book and the ledger. In a demo, halting is the right response. Retrying blindly isn't.

The transfer id is the idempotency key

The order id is generated on the client when the user clicks Buy, and it becomes the id of the first reservation transfer. That follows TigerBeetle's guidance on reliable transaction submission: the app or browser generates the id, persists it locally, and reuses it on every retry.

If the request times out after TigerBeetle created the reservation, the retry gets exists instead of success. The app treats that as "already placed" and does nothing, so the user isn't charged twice and no second order shows up in the book. If a retry reuses an id with a different amount, TigerBeetle returns exists_with_different_amount, which tells you the client has a bug.

A tiny order book

The book is two sorted arrays. Bids are sorted highest price first, asks lowest first, and ties go to whichever order arrived first (price-time priority). An incoming order matches against the other side for as long as prices cross, and each match trades at the resting order's price. Anything left over rests in the book.

typescript
// The order book lives in the application. TigerBeetle only sees money moving.
const book = { bids: [] as Order[], asks: [] as Order[] }
let nextSeq = 0

function rest(order: Order) {
  const side = order.side === 'buy' ? book.bids : book.asks
  side.push(order)
  // Price-time priority: best price first, then whoever arrived first.
  side.sort((a, b) => {
    if (a.price !== b.price) {
      const aBetter = order.side === 'buy' ? a.price > b.price : a.price < b.price
      return aBetter ? -1 : 1
    }
    return a.seq - b.seq
  })
}

async function match(taker: Order) {
  const makers = taker.side === 'buy' ? book.asks : book.bids
  while (taker.remaining > 0n && makers.length > 0) {
    const maker = makers[0]
    const crosses = taker.side === 'buy' ? maker.price <= taker.price : maker.price >= taker.price
    if (!crosses) break
    const qty = taker.remaining < maker.remaining ? taker.remaining : maker.remaining
    const [buy, sell] = taker.side === 'buy' ? [taker, maker] : [maker, taker]
    await settleFill({ buy, sell, qty, price: maker.price }) // trade at the resting order's price
    if (maker.remaining === 0n) makers.shift()
  }
  if (taker.remaining > 0n) rest(taker)
}

type OrderRequest = { orderId: bigint; user: User; side: Side; price: bigint; qty: bigint }

async function placeOrder(req: OrderRequest): Promise<string> {
  if (req.qty <= 0n || req.qty % LOT !== 0n) {
    return 'rejected: qty must be a positive multiple of 0.01 BTC'
  }
  if (req.price <= 0n || req.price % TICK !== 0n) {
    return 'rejected: price must be a positive multiple of $1'
  }

  const order: Order = {
    id: req.orderId,
    user: req.user,
    side: req.side,
    price: req.price,
    qty: req.qty,
    remaining: req.qty,
    reservationId: req.orderId, // the first reservation reuses the order id
    seq: nextSeq++,
  }

  const [result] = await submit([reservation(order, order.id)])
  if (result === 'exists') return 'duplicate (already placed, nothing charged)'
  if (result !== 'ok') return `rejected: ${result}`

  await match(order)
  if (order.remaining === 0n) return 'filled'
  return order.remaining < order.qty ? 'partially filled, resting' : 'resting'
}

async function cancelOrder(orderId: bigint): Promise<string> {
  for (const side of [book.bids, book.asks]) {
    const i = side.findIndex((o) => o.id === orderId)
    if (i === -1) continue
    const [result] = await submit([
      resolvePending({
        pendingId: side[i].reservationId,
        amount: 0n,
        flag: TransferFlags.void_pending_transfer,
      }),
    ])
    if (result !== 'ok') return `cancel failed: ${result}`
    side.splice(i, 1)
    return 'canceled'
  }
  return 'not found'
}

Matching runs one order at a time. That isn't a TigerBeetle limit; it just keeps the in-memory book simple. Canceling an order voids its current reservation, and the funds become spendable again.

Reading balances back

lookupAccounts takes a batch of ids and returns the accounts it found. The order isn't guaranteed to match the request, so key the results by id. Spendable balance is posted credits minus posted debits minus whatever is locked in pending debits.

typescript
function fmt(amount: bigint, asset: Asset): string {
  const base = 10n ** BigInt(asset.scale)
  const sign = amount < 0n ? '-' : ''
  const abs = amount < 0n ? -amount : amount
  const decimals = asset.ledger === USD.ledger ? asset.scale : 4 // show BTC to 4 places
  const frac = (abs % base).toString().padStart(asset.scale, '0').slice(0, decimals)
  return `${sign}${abs / base}.${frac} ${asset.symbol}`
}

// Spendable now = posted credits - posted debits - funds locked in pending transfers.
function available(a: Account): bigint {
  return a.credits_posted - a.debits_posted - a.debits_pending
}

async function printBalances(users: User[]) {
  const accounts = await client.lookupAccounts(users.flatMap((u) => [u.usd, u.btc]))
  const byId = new Map(accounts.map((a) => [a.id, a]))
  for (const u of users) {
    const usd = byId.get(u.usd)!
    const btc = byId.get(u.btc)!
    console.log(
      `  ${u.name.padEnd(6)} USD ${fmt(available(usd), USD).padStart(13)} (locked ${fmt(usd.debits_pending, USD)})` +
        `   BTC ${fmt(available(btc), BTC)} (locked ${fmt(btc.debits_pending, BTC)})`,
    )
  }
}

// On each ledger, what users and escrow are owed must equal what the hot wallet holds.
async function checkBooks(users: User[]) {
  const sides = [
    [USD, exchange.usd],
    [BTC, exchange.btc],
  ] as const
  for (const [asset, side] of sides) {
    const ids = users.map((u) => (asset.ledger === USD.ledger ? u.usd : u.btc))
    const accounts = await client.lookupAccounts([...ids, side.escrow.id, side.hotWallet.id])
    const owed = accounts
      .filter((a) => a.id !== side.hotWallet.id)
      .reduce((sum, a) => sum + a.credits_posted - a.debits_posted, 0n)
    const hot = accounts.find((a) => a.id === side.hotWallet.id)!
    const held = hot.debits_posted - hot.credits_posted
    const verdict = owed === held ? 'OK' : 'MISMATCH'
    console.log(`  ${asset.symbol}: owed ${fmt(owed, asset)}, held ${fmt(held, asset)}, ${verdict}`)
  }
}

checkBooks is a sanity check for us, not something TigerBeetle needs. Every transfer is double-entry, so the balances on each ledger always net to zero, which means what users and escrow are owed always equals what the hot wallet holds.

The demo

typescript
const usd = (dollars: number) => BigInt(dollars) * 100n
const btc = (hundredths: number) => BigInt(hundredths) * LOT // btc(50) = 0.50 BTC

async function main() {
  await createAccounts([
    exchange.usd.hotWallet,
    exchange.usd.escrow,
    exchange.btc.hotWallet,
    exchange.btc.escrow,
  ])
  const alice = await createUser('alice')
  const dave = await createUser('dave')
  const carol = await createUser('carol')
  const users = [alice, dave, carol]

  await deposit(alice, BTC, btc(100)) // 1.00 BTC
  await deposit(dave, USD, usd(100_000))
  await deposit(carol, USD, usd(20_000))
  console.log('after deposits')
  await printBalances(users)

  console.log(
    'alice sells 0.50 @ 60,000:',
    await placeOrder({ orderId: id(), user: alice, side: 'sell', price: usd(60_000), qty: btc(50) }),
  )
  const aliceAsk2 = id()
  console.log(
    'alice sells 0.30 @ 61,000:',
    await placeOrder({ orderId: aliceAsk2, user: alice, side: 'sell', price: usd(61_000), qty: btc(30) }),
  )

  // Dave's app generates the order id when he clicks Buy, then the request times out and is retried.
  const daveOrder: OrderRequest = {
    orderId: id(),
    user: dave,
    side: 'buy',
    price: usd(61_000),
    qty: btc(60),
  }
  console.log('dave buys 0.60 @ up to 61,000:', await placeOrder(daveOrder))
  console.log("dave's retry, same id:", await placeOrder(daveOrder))

  console.log(
    'carol buys 1.00 @ 61,000:',
    await placeOrder({ orderId: id(), user: carol, side: 'buy', price: usd(61_000), qty: btc(100) }),
  )
  console.log(
    'carol buys 0.20 @ 59,000:',
    await placeOrder({ orderId: id(), user: carol, side: 'buy', price: usd(59_000), qty: btc(20) }),
  )

  console.log('alice cancels her 61,000 ask:', await cancelOrder(aliceAsk2))

  console.log('final balances')
  await printBalances(users)
  console.log(`book: ${book.bids.length} bid(s), ${book.asks.length} ask(s)`)
  console.log('books')
  await checkBooks(users)
  client.destroy()
}

main().catch((error: unknown) => {
  console.error(error)
  client.destroy()
  process.exit(1)
})

Run it:

bash
pnpm exec tsx exchange.ts
text
after deposits
  alice  USD      0.00 USD (locked 0.00 USD)   BTC 1.0000 BTC (locked 0.0000 BTC)
  dave   USD 100000.00 USD (locked 0.00 USD)   BTC 0.0000 BTC (locked 0.0000 BTC)
  carol  USD  20000.00 USD (locked 0.00 USD)   BTC 0.0000 BTC (locked 0.0000 BTC)
alice sells 0.50 @ 60,000: resting
alice sells 0.30 @ 61,000: resting
  fill: alice -> dave 0.5000 BTC @ 60000.00 USD = 30000.00 USD
  fill: alice -> dave 0.1000 BTC @ 61000.00 USD = 6100.00 USD
dave buys 0.60 @ up to 61,000: filled
dave's retry, same id: duplicate (already placed, nothing charged)
carol buys 1.00 @ 61,000: rejected: exceeds_credits
carol buys 0.20 @ 59,000: resting
alice cancels her 61,000 ask: canceled
final balances
  alice  USD  36100.00 USD (locked 0.00 USD)   BTC 0.4000 BTC (locked 0.0000 BTC)
  dave   USD  63900.00 USD (locked 0.00 USD)   BTC 0.6000 BTC (locked 0.0000 BTC)
  carol  USD   8200.00 USD (locked 11800.00 USD)   BTC 0.0000 BTC (locked 0.0000 BTC)
book: 1 bid(s), 0 ask(s)
books
  USD: owed 120000.00 USD, held 120000.00 USD, OK
  BTC: owed 1.0000 BTC, held 1.0000 BTC, OK

Walking through it:

  • Dave's buy for 0.60 BTC sweeps Alice's 0.50 at $60,000, then takes 0.10 of her 0.30 at $61,000. He pays $36,100, not the $36,600 he reserved.
  • The retry with the same order id comes back exists. Nothing is charged and nothing is added to the book.
  • Carol's 1 BTC bid needs $61,000 locked and she has $20,000. TigerBeetle rejects the reservation with exceeds_credits, and the order never reaches the book.
  • Carol's $59,000 bid doesn't cross, so it rests with $11,800 locked.
  • Alice cancels the 0.20 BTC left on her second ask, and that BTC is spendable again.

Each run creates fresh accounts, so you can run it as many times as you like against the same tiger1 instance.

What's missing before this is real

A lot. Roughly in order of how much each would hurt:

  • Custody. The hot wallet account is a number in a ledger. Real custody means key management, cold storage, withdrawal approval, and reconciling the ledger every day against what's actually on chain and in the bank.
  • Persisting the book. The book lives in memory. If the process dies, resting orders vanish while their funds stay locked in pending transfers. You'd persist orders, or rebuild the book on startup from open reservations (that's why each reservation carries the order id in user_data_128), and you'd put a timeout on pending transfers as a backstop.
  • A crash between TigerBeetle and the book. If the reservation is created and the process dies before the order reaches the book, a retry gets exists and the app shrugs. A real system recovers the order from the ledger in that case instead of ignoring it.
  • Fees. There's no fee account and no maker/taker schedule. Fees would be extra legs in the same linked chain.
  • Rounding. The lot and tick sizes avoid rounding entirely. Real markets have finer sizes, and every partial fill needs a rule for who absorbs the leftover fraction of a cent or a sat.
  • Throughput. Matching is single-threaded and sends one chain per fill. TigerBeetle is built for batches, so a real engine would batch fills and run one matching thread per market.
  • Everything else on the order side: withdrawals, self-trade prevention, market orders, stop orders.
  • Compliance. KYC, AML screening, the travel rule, licensing, audit trails and reporting. This is most of the work of running an exchange, and none of it is in the code.

Running it on Layerbase Cloud

You can run the same code against TigerBeetle on Layerbase Cloud, on a dedicated server of your own. TigerBeetle never runs on the shared cloud. Change TB_ADDRESS and cluster_id to the values the dashboard shows and the rest of the file stays as it is. Instances run 0.16.70 like the CLI, so the same pinned client works.

Before the client can connect, add your app's IP addresses to the instance's allowlist. TigerBeetle has no authentication of its own (no passwords, no keys), so on Layerbase an IP allowlist is required. Only whitelisted addresses can reach the port.

The thing to know is where TigerBeetle wants to live. It is built to sit next to the application, on the same server or the same private network, so a round trip costs microseconds and the app can batch thousands of transfers per request. A Layerbase instance is a network hop away from your app, and every createTransfers call pays that hop. For learning the model, building a prototype, or running a staging ledger, that's fine. If you're building something where transactions have to settle instantly, a real exchange or a payment path with tight latency targets, we don't recommend hosting TigerBeetle on Layerbase past the development stage. Run it on the same machines as your app, or talk to TigerBeetle about their own offering.

TigerBeetle databases on Layerbase also don't support branching, because a TigerBeetle cluster keeps its identity inside its data. Give each experiment its own database, or stay local, where lbase create gives you a fresh one in seconds.

When you're done locally:

bash
lbase stop tiger1     # stop the server
lbase start tiger1    # start it again
lbase url tiger1      # print the address for the client