blog · solution ·
Durable order matching in Go: group commit at 1,383 orders/sec
An order should only be accepted once it's on disk, and fsync is slow. Here's how my matching engine batches many orders into one fsync without a timer, with the real benchmark numbers and their caveats.
In a trading system, "order accepted" has to mean the order survives a crash. If the server dies right after telling a client "accepted", the order must still be there when it restarts. That means writing it to a write-ahead log (WAL) and calling fsync before you reply.
fsync is slow. On my laptop (btrfs on an encrypted NVMe drive) one fsync takes about 3.4 ms. If every order waits for its own fsync, one symbol tops out at about 294 orders/sec.
Dhukuti is an order matching engine I built in Go. This post covers how it raises durable throughput without breaking the rule that an acknowledged order is on disk.
The rule: nothing is acknowledged until fsync returns
Each symbol (NABIL, ADBL, and so on) has one sequencer goroutine that owns that symbol's order book. Orders reach it over a single channel. For each batch the sequencer:
- Assigns order IDs and reserves balances. Rejected orders never get a log position.
- Appends every order in the batch to the WAL.
- Calls fsync once for the whole batch.
- Only then applies the orders to the book and replies to each caller.
If the append or the fsync fails, the book is left untouched, every caller in the batch gets the error, and their reserved balances are released. A trade is never acknowledged unless it's already recoverable.
Group commit without a timer
Many group-commit designs wait a few milliseconds to collect a batch. This one doesn't wait at all. The sequencer takes one request, drains whatever else is already queued, and commits:
func (s *Sequencer) run(ctx context.Context) {
batch := make([]request, 0, maxBatch)
for {
select {
case req := <-s.reqs:
batch = append(batch[:0], req)
s.drain(&batch)
s.commit(batch)
// ...
}
}
}
func (s *Sequencer) drain(batch *[]request) {
for len(*batch) < maxBatch {
select {
case req := <-s.reqs:
*batch = append(*batch, req)
default:
return
}
}
}
When the system is quiet, a lone order commits right away. When it's busy, orders pile up while the previous fsync runs, and the next batch takes them all. Queue depth decides the batch size. The cap is 256 per batch, and no test ever reached it.
You can see it work in the WAL benchmark (one symbol, real disk):
| Producers | Orders per fsync | Orders/sec |
|---|---|---|
| 1 | 1.00 | ~294 |
| 4 | 2.03 | ~567 |
| 16 | 10.52 | ~2,741 |
| 64 | 61.30 | ~12,594 |
Work out the time per batch and you get between 3.4 and 4.9 ms every time: about the cost of one flush. Group commit doesn't make fsync faster. It makes each fsync carry more orders.
Why one goroutine per symbol
One goroutine owns each book, so the book needs no lock. To be fair, a plain mutex around the book was faster in my single-symbol benchmark: 5,216 ns/op against 10,212 at 64 producers. I kept the channel design for other reasons:
- A caller's cancellation and timeout work through
select. You can't cancel aMutex.Lock. - There's exactly one place for "write the WAL before matching", tracing and timing.
- Shutdown is clean.
Partitioning by symbol has a real cost too. Each symbol batches separately, so more symbols means smaller batches. With 64 clients and the WAL on: 1 symbol did 7,012 orders/sec, 2 did 4,626, 4 did 3,690, and 8 did 3,134. Without the WAL it stayed flat at about 41,000 to 45,000. On a single disk, fewer symbols per node is better for durable throughput.
The log format and crash recovery
Each WAL record holds its length, a sequence number, a timestamp, the payload and a CRC32 checksum. The payload is JSON, so I can read the log with xxd. It's about three times bigger than a binary format, and easy to swap later.
On restart, the engine replays every log segment into the book. The hard part is telling a torn write apart from corruption:
- A record cut short at the end of the last segment is a write that never finished. It was never acknowledged, so replay stops there, and the writer cuts the tail off before appending again.
- A complete record with the wrong checksum is different: the disk returned bad data. Replay stops with an error instead of carrying on past it.
want := binary.LittleEndian.Uint32(tail[:])
got := crc32.Update(crc32.Update(0, crc32.IEEETable, hdr[:]), crc32.IEEETable, payload)
if got != want {
return Record{}, fmt.Errorf("%w: crc mismatch at offset %d (computed %08x, stored %08x)",
ErrCorruptWAL, r.offset, got, want)
}
A chaos test runs the engine in a child process, submits 10,000 orders and crashes it partway through. The parent then rebuilds the book from the log alone and checks it matches exactly. Replay runs at about 90,000 records/sec (100,000 records in 1.13 s).
Settlement: idempotent double entry in Postgres
Each trade writes four journal entries. The buyer gets a position debit and a cash credit, and the seller gets a cash debit and a position credit. The WAL logs orders, not trades, so after a crash, replay can produce the same trade a second time. Settlement has to be safe to repeat. It uses a unique index on (symbol, trade_id, account_id, asset, direction) plus INSERT ... ON CONFLICT DO NOTHING.
The load test caught a bug here. My first unique key left out direction. When an account traded with itself, its debit and credit entries had the same key, so ON CONFLICT DO NOTHING quietly dropped half of them. That left 12,266 rows missing and net cash at -40,013,771 instead of 0. After adding direction: 47,322 trades, each with exactly 4 entries, and net cash and net shares both 0.
The lesson: an idempotency key needs every column that makes a row unique, or "do nothing" quietly does the wrong thing.
The headline number, with its caveats
Full stack for 60 seconds, with 64 gRPC clients, 4 symbols, settlement in Postgres and a live follower replica: 1,383 orders/sec, p50 38.7 ms, p99 130 ms. The p99.9 was 301 ms and the max 541 ms. Live group commit averaged 6.9 orders per fsync.
A benchmark without caveats is marketing, so here they are:
- It's one laptop (Ryzen 5 4600H). The load generator, Postgres and both WALs share the machine, and the two WALs share one disk. Without the follower it did 1,476 orders/sec.
- Replication is async. The primary acknowledges after its own fsync, not the follower's, so if the primary dies while the follower is behind, those orders are lost. The follower peaked at about 550 records behind in this run.
- There are no snapshots yet, so restart time grows with the log.
- Settlement runs once per order, which roughly halves throughput (from 3,910 to 1,973 orders/sec in an earlier run). One settlement transaction per group commit is the obvious next fix.
Takeaways
- If "accepted" means "durable", fsync is your latency. Measure it on the disk you'll actually run on.
- Batch by queue depth, not by a timer. Quiet periods stay fast, and busy periods get bigger batches.
- Treat a torn tail and a bad checksum differently: cut off the first, stop on the second.
- Make settlement idempotent, and put every distinguishing column in the key.
The code, design notes and raw benchmark output are on GitHub.