Matching Engine
A single-threaded event loop with price-time priority matching and copy-on-write execution.
Design Principles
The Vela matching engine is designed around three non-negotiable properties: determinism, low latency, and verifiability. Every design decision flows from these constraints.
- Determinism: Given the same sequence of requests in the same order, the engine must always produce the same output. This is required for the fraud proof system to work — a verifier seeding from a snapshot must be able to reproduce the exact same state root as the original execution.
- Low latency: The engine is single-threaded to avoid synchronization overhead. There are no locks, no mutexes, no async I/O on the critical path. All state mutations are in-memory.
- Verifiability: Every state transition is expressed as a delta that can be re-applied deterministically. The MPT root after each batch is a cryptographic commitment to the full state.
Order Matching Algorithm
Vela uses price-time priority (FIFO within a price level), the standard algorithm used by all professional exchanges:
- The incoming order is validated: balance check, nonce check, signature verification.
- Execution begins in a copy-on-write (CoW) cache — a snapshot of the current book state. No mutations to live state occur during execution.
- The engine scans the opposing side of the book for matchable orders, starting at the best price and working outward.
- At each price level, orders are filled in FIFO order — the oldest resting order at a given price is filled first.
- For each match, balances are updated in the CoW cache: the taker's quote balance decreases, the taker's base balance increases, the maker's positions flip. Fees and rebates are applied.
- If the incoming order is GTC and quantity remains after exhausting crossable price levels, the remainder rests in the book.
- If IOC: remainder is cancelled. If FOK and full fill is impossible: the entire CoW cache is discarded and no changes are committed.
- The CoW cache delta is committed to engine memory. A
CommitBatchmessage is sent to the committer channel.
Fixed-Point Arithmetic
All prices and quantities are stored as 64-bit unsigned integers scaled by 1,000,000. This eliminates floating-point rounding errors entirely. A price of $3,200.50 is stored as 3200500000. Arithmetic on these values is exact integer arithmetic with no rounding.
Fee calculations use the same fixed-point representation. The only rounding that occurs is in the final fee amount, which rounds down (in favor of the exchange) to the nearest microsatoshi equivalent.
Performance
On a realistic market maker workload (continuous two-sided quoting, frequent cancel-and-replace), the engine achieves 0.68 μs p50 match latency and 1,430,000 ops/sec sustained on Apple M3. The dominant cost is memory access — the hot path touches only a small working set of in-memory structures.