Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Kaspar's Actor Framework: Zero-Cost Abstractions for Low-Latency HFT

This article dissects the actor framework of Kaspar, an open-source CME-certified futures trading system, revealing five key low-latency design choices—including dual message paths, O(1) dispatch, pre-allocated mailboxes, and per-message-type memory pools—that achieve ~50ns round-trips via fast_send and enable deterministic replay for backtesting.

What Is an Actor

The actor model, introduced in 1973, provides a formal description of concurrent computation. An actor is a sequential program with a mailbox: it owns private state inaccessible to others, processes one message at a time, and communicates solely by sending messages to other actors. No shared mutable state exists; an actor's state is read/written only by its own handler, eliminating locks. Concurrency occurs only between actors, so internal code reads like single-threaded logic. Though not designed for cache lines, the "no shared state" constraint that simplifies formal reasoning also enables scaling on modern multi-core hardware.

Five Design Decisions for a Low-Latency Actor Framework

For low-latency systems, an actor framework reduces to five design choices:

No shared state. Each actor exclusively owns its data, accessed only via messages. Business code never locks actor state. Enforced by convention in C++, by the type system in Rust.

Two message paths. One synchronous (direct call on caller's thread, stack-allocated message), one asynchronous (enqueue to target's mailbox). Deployment config selects per actor-pair path without changing actor code.

O(1) dispatch. Finding the handler from a message must avoid hash tables, dynamic_cast, or if chains.

Pre-allocated mailboxes. Enqueue never calls malloc.

No allocation on the hot path. Messages come from memory pools, not the general allocator.

Get these right and framework overhead becomes negligible; latency is dominated by business logic.

send vs fast_send

3.1 Ping-Pong with send (Async)

Standard async messaging: messages enter target's mailbox, target's thread dequeues and dispatches. Requires heap allocation, mutex + condition variable enqueue, thread wakeup, and release. Fine for 10k msg/s, but too slow for market-data-to-order latency.

struct Ping { count: i32 }
define_message!(Ping, 10);

struct Pong { count: i32 }
define_message!(Pong, 11);

struct PingActor {
    pong: ActorRef,
    handle: ManagerHandle,
    max: i32,
}
impl PingActor {
    fn on_start(&mut self, _m: &Start, ctx: &mut ActorContext) {
        self.pong.send(Box::new(Ping { count: 1 }), ctx.self_ref());
    }
    fn on_pong(&mut self, m: &Pong, ctx: &mut ActorContext) {
        if m.count >= self.max {
            self.handle.terminate();
        } else {
            self.pong.send(Box::new(Ping { count: m.count + 1 }), ctx.self_ref());
        }
    }
}
handle_messages!(PingActor, Start => on_start, Pong => on_pong);

struct PongActor;
impl PongActor {
    fn on_ping(&mut self, m: &Ping, ctx: &mut ActorContext) {
        ctx.reply(Box::new(Pong { count: m.count }));
    }
}
handle_messages!(PongActor, Ping => on_ping);
define_message!

assigns a compile-time integer ID. handle_messages! registers handlers. send() is async: message goes to mailbox, caller returns immediately, target's thread later dequeues and dispatches.

3.2 fast_send: Stack-Passed Messages

Same logic with fast_send:

fn on_start(&mut self, _m: &Start, ctx: &mut ActorContext) {
    for i in 1..=self.max {
        let p = Ping { count: i }; // stack allocated
        let rep = self.pong.fast_send(&p, ctx.self_ref()); // executes on current thread
        let rep = rep.unwrap();
        let pong = rep.as_any().downcast_ref::<Pong>().unwrap();
        // pong.count available immediately
    }
    self.handle.terminate();
}
fast_send

does not enqueue. It looks up the handler, calls it directly on the caller's thread, and returns the reply. Request message is borrowed, no heap, no mailbox, no thread wakeup. Overhead: one lock acquisition, one array index, one indirect call.

PongActor unchanged. Same type, same handler, same reply(). Receiver doesn't know if invoked asynchronously by its own thread or synchronously by another's; deployment config decides. reply() branches on arrival path:

Via fast_send: sets return value, which becomes fast_send 's result. No message send, no enqueue, no thread switch.

Via send: issues another async send to sender's mailbox, so both legs cross threads. fast_send runs target's handler on caller's thread while target may simultaneously process its mailbox on its own thread → two threads accessing same object. Framework gives each actor a mutex; every dispatch locks it. Usually uncontended, lock takes nanoseconds.

Limitation: fast_send holds target's lock. If a call chain cycles back to an actor already executing on this thread (A→B→A), deadlock occurs (both C++ and Rust).

3.3 Measured Round-Trip Latency

Test: one request + one reply, 1M iterations, two actors on two threads, Apple Silicon, C++ -O3 -march=native, Rust --release with LTO, optimization barriers prevent elision.

Round-trip latency chart
Round-trip latency chart

Results (request + reply): fast_send (direct call, 1 thread): C++ ~50 ns, Rust ~43 ns send (async mailbox, 2 threads): C++ ~7.5 µs, Rust ~4.3 µs

send latency is 100–160x fast_send. Difference almost entirely from OS thread wakeup latency: send wakes target thread twice per round-trip; fast_send never leaves caller thread. Framework provides two paths because of this gap: latency-sensitive chains use fast_send; logging, I/O, etc. use mailbox.

Notes on send numbers:

Rust faster (~4.3 µs vs ~7.5 µs). Both use mutex+condvar; measures cost of waking a blocked thread on macOS. Linux futex may lower both.

Threads not pinned. Scheduler may cause cross-core wakeups, core migration, or both actors on same core, increasing latency and variance. Pinning would improve. fast_send unaffected.

Dispatch-only (no reply allocation): fast_send C++ 12.9 ns, Rust 14.0 ns (lock, array index, indirect call). Rust safety adds near-zero overhead on sync hot path.

Full round-trip Rust slightly faster (~43 ns vs ~50 ns) because C++ reply uses polymorphic new Pong via unique_ptr (heap ~36 ns), while Rust boxes plain struct. With pool allocation (~7 ns), fast_send round-trip ~25 ns.

O(1) Dispatch by Integer ID

Each message type gets a compile-time integer ID. handle_messages! generates a per-actor-type array indexed by ID. Dispatch:

fn process_message(&mut self, msg: &dyn Message, ctx: &mut ActorContext<_>) {
    let id = msg.message_id() as usize;
    if let Some(Some(h)) = Self::__dispatch_table().get(id) {
        h(self, msg, ctx);
    }
}

Each table entry is a function that downcasts &dyn Message to concrete type and calls the registered handler. Macro checks ID bounds at compile time. C++ version uses member function pointers. No hash lookup, no type chain, just index, type check, call.

Mailbox (BQueue)

Async path uses a pre-allocated RingBuffer (circular array) with capacity; enqueue within capacity allocates zero. Overflow handled by a deque. Synchronization uses mutex + condition variable deliberately, not lock-free: blocked thread doesn't consume a core or invalidate other cores' cache lines, while spinning would.

Rust version mirrors: fixed-capacity VecDeque as RingBuffer, another VecDeque for overflow, plus Mutex and Condvar.

Per-Message-Type Memory Pools

6.1 General Allocator Overhead

malloc

handles variable sizes, causing overhead per allocation: size-class mapping (branch/lookup), free-list search, splitting/merging blocks, fragmentation management, thread arenas and locking. In actor systems, allocation thread often differs from freeing thread (cross-core ownership transfer), which thread-local arenas aren't optimized for, adding migration overhead.

6.2 One Pool per Message Type

Kaspar creates a dedicated pool per message type. C++: message inherits MemoryPool<T>, overloads operator new/delete. Rust: macro define_pooled_message!(Quote, 20, 8) (ID 20, 8 blocks per thread cache). Allocation via MsgBox::pooled(Quote { ... }). Macro generates thread-local free list and global shared pool; block size fixed at compile time.

With fixed-size blocks: no size-class mapping, no free-list search (any block fits), no splitting/merging, no fragmentation (freed block always fits next request). Allocation reduces to popping a pointer from a stack.

6.3 Three-Tier Allocation

Tier 1: Thread-local cache. thread_local Vec, lock-free, pop from tail. Most common case, few instructions.

Tier 2: Shared free list. When local empty, refill under mutex moves cap blocks from shared pool to local (amortizes lock cost over cap allocations).

Tier 3: Slab from system allocator. When shared pool empty, allocate one large slab (size = block_size * cap, cache-line aligned), slice into cap blocks. Only this tier calls system allocator; after warm-up, pool size converges and only recycling occurs.

6.4 Key Details

Cache-line alignment. Block size rounded up to 64-byte multiple; slab aligned to 64 bytes. Prevents false sharing when messages written on one core, read on another.

LIFO (last-in-first-out). Both local and shared pools use Vec push/pop at tail. Recently freed block likely still in L1/L2 cache; allocating it next keeps cache hot. FIFO would give coldest block.

Flush excess to shared pool. On free, push to local; if local length > 2*CAP, flush excess to shared pool under lock. Producer threads drain local cache; consumer threads accumulate. Flush returns blocks to producers.

C++ refines further: tracks hasAllocated per thread; pure consumers batch releases to separate cache, not allocation cache. Shared pool mutex aligned to cache line ( alignas(64)) to avoid false sharing on lock.

6.5 Benchmarks

32-byte message, alloc+free, 5M iterations, single thread:

System heap (C++ new /Rust Box): C++ 36.4 ns, Rust 35.6 ns

Memory pool: C++ 8.4 ns, Rust 6.8 ns

Pool reduces cost to 1/4–1/5. Both use same system allocator; pool benefit exceeds language choice on async path where every message allocates. Microbenchmark is best-case for system allocator (single thread, single size, hot thread cache, no contention). Real workloads with mixed sizes, many allocation sites, and cross-thread free show larger gaps.

Thread Mapping and Group

7.1 Actor-to-Thread Mapping

Latency heavily depends on mapping. Kaspar mapping set by config/connections, no handler changes:

Dedicated thread. One std::thread + mailbox per actor, can pin to core.

Group. Multiple actors share one thread and one message queue; intra-group messages don't cross threads.

Remote. Actor in another process/machine via ZMQ; send() call syntax identical.

fast_send. No thread switch; handler runs on caller's stack.

Latency-sensitive actors pinned to fixed cores ( sched_setaffinity) with real-time priority ( SCHED_FIFO). Workflow: write actor graph, verify correctness, profile on real data to find critical path, then decide thread boundaries based on where critical path crosses threads.

Cross-thread send requires condition variable notify, kernel wakeup, scheduler; receiver cache may be cold, jitter uncontrolled. On Linux, two independent threads send round-trip p50 1.5–7 µs varying with core placement. Same actors in one Group: p50 ~90 ns.

Optimization: collapse hot path. Put order book, execution logic, order management in same Group or connect via fast_send. Off-path (logging, DB, monitoring) on separate threads/cores. Entire market-data-to-order decision path can run on one thread, one core, zero wakeups.

7.2 Group

Classic actor model: one mailbox, one logical thread per actor, only async send. Kaspar keeps semantics, changes two things:

fast_send. Default async is correct, but if caller blocks for reply, queueing adds thread switch. fast_send executes handler on caller thread, returns reply directly. Semantics preserved: receiver still processes one message at a time, owns its state; only stack changes. Most latency gain from this.

Explicit actor-to-thread mapping. Original model leaves scheduling to implementation. Kaspar makes mapping explicit via Group: actors share thread and queue; intra-group messages zero thread hops.

One thread per Group intentional. Could extend to thread pool, but then intra-group messages might land on different threads, reintroducing handoffs. Group is a serial fast path; adding parallelism inside defeats purpose. If a Group saturates its thread, split into two Groups.

7.3 Deterministic Replay

Production: pipeline spread across cores for latency. Backtest: same actors, same code in one Group. Market data, order entry, matching execute on single thread in strict queue order, no inter-thread races.

Group guarantees message order. For identical replay results: same PCAP input and config; timers driven by message timestamps not system clock; fixed random seeds in simulator. Then same PCAP yields same strategy decisions and simulated fills.

If backtest and live use different code, replay doesn't reproduce live behavior.

C++ and Rust

8.1 Rust Port

Framework core rewritten in Rust to test which C++ techniques survive borrow checker:

fast_send lock. Rust cannot express "two threads mutate same &mut state" without lock, so each actor gets a mutex, same as C++ fast_send_mutex.

Memory pools. Biggest divergence. C++ uses inheritance + operator new/delete; virtual operator delete dispatches to correct pool at free. Rust lacks per-type operator new; Box<dyn Message> erases type, so drop doesn't know which pool. Solution: custom smart pointer MsgBox carrying a reclaim function alongside type-erased pointer: enum Reclaim { Heap, Pool(unsafe fn(*mut u8)) } Manually implements C++ virtual delete. Porting revealed bug: deallocating zero-sized types is UB; signal messages like Start, Shutdown are zero-sized.

Intrusive lists. Order book example: price-time priority, partial fills, cancel/replace, match at maker price. One actor per symbol, all order events serialized through its mailbox, sole writer, deterministic matching, no locks in order book code. Design same as C++: BTreeMap price→level, each level a slab-based intrusive doubly-linked FIFO list, plus order_id → node map. Removing order from level list O(1); finding level via BTreeMap; matching processes multiple orders. C++ uses raw prev/next pointers. Rust cannot hold multiple &mut to nodes, so list redesigned as Vec slab with integer indices. Result: contiguous storage, cache-friendly, no per-order allocation. Single-threaded release build direct call (no actor mailbox): ~6M orders/s, ~8.7M matches/s, ~8.7M cancels/s (each buy matches one sell at same level). Early version used VecDeque per level; cancel O(depth), clear deep level O(n²). Slab improved order/match ~2x.

Group. Rust version not yet implemented. Mapping straightforward: one single-threaded executor per Group, thread drains group queue, dispatches to actors in order.

C++-fast patterns (intrusive structures, per-type pools, stack passing) can't be copied directly; must redesign around ownership. Performance parity because design eliminates contention: uncontended per-actor lock ~ns, integer ID dispatch O(1), fast_send request borrowed not allocated, async path uses three-tier pools. Language changes how safety is proven (C++ conventions + code review, Rust compile-time borrow checking), not runtime overhead.

8.2 Cross-Language In-Process Calls

Next step: C++ and Rust actors in same process, using existing send / fast_send.

Location transparency. ActorRef is enum:

pub enum ActorRef {
    Local(Arc<ActorCell>), // in-process Rust actor
    Cpp(CppRef),          // C++ actor via FFI bridge
}
send

/ fast_send / name are match on enum: Local uses Rust path, Cpp converts message and calls C++. Manager::get_ref("name") returns Local or Cpp; caller sees same type.

Only POD structs across boundary. Cross-boundary messages are plain C structs: fixed-width ints, double, fixed arrays, fixed strings. No std::string, Vec, or heap-holding types. Passed by value via extern "C" functions: cpp_actor_send, cpp_actor_fast_send, cpp_actor_exists (C++ impl, Rust calls) and reverse rust_actor_send, etc. Allocator doesn't cross boundary: sender fills POD on stack, receiver copies into own message.

Single definition, generated for both languages. Risk of silent memory corruption if struct layouts diverge. Single header file edited by humans, read by generator:

INTEROP_MESSAGE(Ping, 400)
typedef struct { int32_t count; } Ping;

INTEROP_MESSAGE(DataRequest, 402)
typedef struct {
    int32_t request_id;
    interop_string symbol;
} DataRequest;

Python script generates Rust #[repr(C)] structs with to_c / from_c and native wrappers, C++ classes, and dispatch tables. C++ includes header; Rust uses generated definitions. Add field, regenerate, both sides consistent.

Call flow: Rust cpp.fast_send(&Ping { count }) → match ID 400 → Ping::to_c() (copy to stack CPing) → cpp_actor_fast_send("cpp_pong", 400, &CPing) → C ABI → C++ get_actor_by_name("cpp_pong") → Ping::from_c() → target.fast_send(&msg::Ping) (lock, O(1) dispatch, call handler). For actor, same as local fast_send.

Example: single binary with Rust driver and real C++ actor. C++ side creates Manager and actor cpp_pong, registers by name, calls cpp_actor_init(). Rust side installs generated dispatch table, resolves C++ actor, sends:

unsafe { hybrid_setup(); } // C++: Manager + "cpp_pong" + cpp_actor_init
actors::interop::generated::register(); // install dispatch table + C++ name resolution
let cpp = mgr.get_ref("cpp_pong", "rust_driver").unwrap(); // ActorRef::Cpp
cpp.fast_send(&Ping { count: 1 }, None); // via bridge executes C++ handler

Build: cargo compiles Rust, build.rs links generated C++ bridge objects and C++ framework static library, rustc final link.

Cross-language overhead (Apple Silicon, single thread, release, no-reply fast_send):

Rust→Rust: ~15 ns

C++→C++: ~13 ns

Rust→C++: ~70 ns

C++→Rust: ~46 ns

Same-language dispatch ~13–15 ns (C++ slightly faster). Cross-boundary adds: format conversion ( to_c / from_c two copies), extern "C" call, per-call by-name lookup, receiver dispatch. Asymmetry: Rust→C++ calls C++ get_actor_by_name (constructs std::string, lookup, returns ActorRef by value). C++→Rust uses Rust-side name resolution + catch_unwind guard. Per-call name lookup can be eliminated: latency-sensitive callers resolve once and hold reference.

Current limits: only POD (strings in fixed buffers); no sync reply across languages – cross-language fast_send fire-and-forget, request/reply uses send + separate reply message; mixed binary requires precompiled C++ framework, not cargo -only.

A memory-safe Rust actor can drop into a running C++ trading system, accessing C++ actors like local ones.

Actors and AI Programming

An actor is a small, closed unit with explicit contract: which messages it receives, which it sends, private state, touches nothing else. Easy for humans, better for AI coding assistants because they don't need whole-system context to write one piece correctly.

Give AI natural language description (e.g., "actor listening to order book updates, tracking buy/sell imbalance on rolling window, emits signal message when threshold exceeded") and it returns actor class, message structs with IDs, handle_messages! registration, and handlers. Fixed structure, local contract, little room for error outside business logic.

Testing gains more. Actor directly drivable: construct, fast_send a message, check reply. No external test scaffolding, no mocks:

#[test]
fn handles_ping_message() {
    let mut mgr = Manager::new();
    let pong = mgr.manage("Pong", Box::new(PongActor), ThreadConfig::default());
    let reply = pong.fast_send(&Ping { count: 42 }, None).unwrap();
    let pong_msg = reply.as_any().downcast_ref::<Pong>().unwrap();
    assert_eq!(pong_msg.count, 42);
}

Uses fast_send: handler runs synchronously on test thread, no concurrency, no sleeps, no flaky timing.

Actor structure bounds generated code: one actor can't mutate another's state, can't see data not sent to it, can't introduce data races because no shared memory exists to race on.

Conclusion

A 1973 concurrency model on today's multi-core hardware yields: actor internals written as single-threaded code; latency paths adjusted at deploy time not in code; backtest and live share identical codebase.

Project on GitHub: https://github.com/vincent212/kaspar-hft

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion