So I built an order matching engine from scratch. No fancy library holding my hand, just me, a whiteboard, and honestly way too much coffee. And here's the thing nobody warns you about: an order book looks trivial until the second order shows up. Then correctness, speed, and determinism all start fighting each other and suddenly you're the referee.
I went in thinking it'd be a weekend project. Cute. It was not. But it ended up being one of the most fun things I've ever built, so let me walk you through the parts that actually mattered.
Price time priority, aka who goes first
The rule sounds dead simple on paper. Best price wins, and if two orders are sitting at the same price, whoever got there first gets filled first. Easy, right? Well, I stored my bids in reverse order so the highest price floats to the top, and that one tiny decision quietly flips your whole intuition. The best bid is now the first key, not the last one.
I lost an embarrassing amount of time to exactly that bug. Everything looked right, the tests were green, and trades were still coming out wrong. Learn from my pain and double check which end of the book you're actually reading from.
Determinism isn't a nice to have. It's the thing that lets you actually sleep at night.
The event journal that saved my sanity
Every single order and every trade gets written to a journal before it ever touches memory. Sounds like overkill. It is absolutely not. Replay that journal and you rebuild the exact same book, trade for trade, in the exact same order. That one feature quietly powers your tests, your audits, and your oh no the server just died recovery story.
My advice? Build the journal first, not last. It's tempting to bolt it on later once the fun matching logic works, but the moment you have weird behavior in production and no way to replay it, you'll wish you had it. Been there.
Would I do it all over again? Yeah, in a heartbeat. There's something stupidly satisfying about watching two orders match at the right price, in the right order, every single time. It just clicks, and that feeling is worth all the coffee.