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

Actor Model on FPGA: How Kaspar Maps Actors to Hardware for Trading

This article details how the Kaspar open-source futures trading system implements the actor model on FPGA, covering FPGA architecture, high-level synthesis, process/FIFO communication, hardware actors, group mapping, CPU-FPGA differences, PCIe link optimization, and cross-device actor messaging via direct memory access.

FPGA Architecture Fundamentals

An FPGA consists of configurable logic units and interconnects. Key components include:

LUT (Look-Up Table) : Small memory implementing arbitrary logic functions (6-input on AMD UltraScale+). All logic (comparisons, adders, multiplexers, state machines) becomes LUT networks.

Flip-flops : 1-bit registers holding values across clock cycles (counters, message fields, state machine states).

Block RAM and UltraRAM : Distributed on-chip storage (36 Kb and 288 Kb blocks) allowing hundreds of independent reads/writes per cycle.

DSP slices : Hardened multiply-accumulate units for arithmetic that would be too large or slow in LUTs.

Routing resources : Programmable interconnects linking the above.

Hard IP : Fixed circuits for PCIe, high-speed transceivers, memory controllers.

A large FPGA contains ~1M LUTs, 2M flip-flops, and thousands of Block RAMs.

From Code to Circuit

FPGAs do not execute code; code is compiled into a circuit. The flow: describe hardware in Verilog/VHDL or C++ with HLS (AMD Vitis HLS). Synthesis converts to LUTs, flip-flops, RAM, DSP; place-and-route assigns physical locations and connections. The output is a bitstream loaded to configure the chip. Everything runs on a clock (e.g., 300 MHz = 3.3 ns cycle). On each clock edge, all driven flip-flops update simultaneously; combinational logic computes next values between edges. There is no instruction stream or shared program counter; every part of the circuit works every cycle.

High-Level Synthesis (HLS)

HLS lets developers write C++; the tool infers the circuit. Each C++ function becomes a hardware block: a datapath (adders, comparators, multiplexers, registers) plus a small state machine. The tool outputs Verilog/VHDL and a resource/timing report.

Function Example

Adding four numbers: on CPU, three sequential add instructions. HLS generates four 32-bit inputs and three adders in a tree: a + b and c + d computed in parallel, then merged. No instructions execute; inputs flow through the adder tree, and the sum appears after a fixed number of cycles.

Loop Implementation

Loops can be implemented in three ways via pragmas:

Sequential: one adder + state machine, 8 iterations over many cycles (less hardware, more cycles). #pragma HLS PIPELINE: new iteration starts every cycle while previous ones are still in flight (pipelined). #pragma HLS UNROLL: replicate hardware 8 times, all iterations run in one cycle (more hardware, fewer cycles).

Hardware usage and cycle count trade off inversely.

Parallel Functions

With #pragma HLS DATAFLOW, sequentially called functions become concurrent hardware blocks. hls::stream variables between them become hardware FIFOs. The same C++ source can be compiled for CPU (where hls::stream is a software queue) for testing before synthesis. However, a design that runs in software may still fail to fit or meet timing on the FPGA.

HLS Restrictions

Hardware is fixed at build time, so:

No heap: no new, malloc, std::vector, std::string.

Loop bounds must be known at compile time.

No recursion, virtual functions, or function pointers; every call maps to a specific circuit.

Processes and FIFOs

Process

An FPGA process corresponds to an HLS-generated hardware block from a C++ function, with its own datapath, registers, Block RAM, and state machine. It starts at configuration and runs forever (typically an infinite loop: wait for input, process, output). Each function in a DATAFLOW region becomes a process; functions called outside are inlined into the caller's process. Unlike threads, processes are independent circuits running simultaneously every cycle.

FIFO

Processes communicate via FIFOs ( hls::stream), implemented as LUT shift registers or Block RAM with full/empty handshake signals. Differences from software queues:

Blocking reads/writes : a process reading an empty FIFO stalls; writing to a full FIFO stalls. Only that process waits; the rest of the chip continues. No polling or wake-up; the state machine simply pauses until handshake completes.

Single writer, single reader : HLS enforces this, eliminating contention and locks. To receive from multiple sources, a process uses multiple FIFOs and selects which to read (e.g., via empty() checks).

Hardware Actors

Mapping

In Kaspar's FPGA runtime:

Actor runs in a process : one process runs one actor or a group of actors. Actor private state lives in that process's registers and Block RAM; other processes have no wires to it.

Mailbox is a set of FIFOs : one per sender, merged by the receiver's process.

Reference = port number + actor ID : port determines which FIFO the message enters (hence which process); ID is placed in the envelope header to identify the target actor within the process. References are bound at build time.

Message types inherit kfpga::Message<id> (CPU side: Message_N<id>), listing integer fields. The ID is manually assigned because messages cross the CPU-FPGA boundary; both sides must match. Each message is declared once in a shared header compiled into both FPGA design and CPU program.

Actors inherit kfpga::Actor<Self>, hold state and per-message handlers, keep ActorRef s for peers, and use ref.send(m, this) and reply(...) exactly like CPU actors. The base class uses the actor's own type as a template parameter (no virtual functions). A macro expands handler registration into a switch on message ID, which synthesizes into a multiplexer selecting the handling logic.

send

send

places the message in the sender's outbox (a staging area in the handler), then returns. After the handler finishes, the process writes outbox messages to their respective port FIFOs in order; if a FIFO is full, the process stalls. Two processes are connected only by a FIFO—no router, no shared bus. A reference to a CPU actor looks the same in code but binds to the board-to-CPU link; a bridge component on the CPU side forwards the message to the target actor. reply(r) is also a send targeting the original sender, going through the same outbox/FIFO path.

Inter-process send can deadlock if FIFOs form a cycle and all become full simultaneously (each process blocked writing to the next). The runtime does not detect this; designers must avoid cycles or size FIFOs to absorb maximum burst.

fast_send

On CPU, fast_send makes the caller execute the receiver's handler immediately (locking the receiver) and returns the reply. On FPGA, fast_send is only allowed for actors in the same group (same process). Reason: a handler is a circuit built in the receiver's process; another process cannot execute it. Emulating fast_send across processes would require writing a request to a FIFO, waiting for the receiver to process it, and reading a reply FIFO—effectively a send plus blocking wait, slower and introducing new deadlock possibilities (two processes waiting on each other). Hence the runtime does not provide it.

Within a process, actors can be grouped; references between group members bind directly to the target actor (not a FIFO), and the target's logic resides in the same process. fast_send becomes a direct function call with zero FIFO overhead. The actor code does not reveal where the receiver runs; only references to same-group actors expose fast_send, so moving an actor to another group causes a compile error until the call is changed to send. Direct calls cannot deadlock (cycles would be recursion, rejected at build time). Latency equals the handler's cycle count (shown in HLS report).

Groups and Processes

A CPU Group runs several actors on one thread sharing a mailbox. An FPGA process running a group exhibits the same key properties:

Concurrency : CPU group members share one thread (one handler at a time, no locks needed); FPGA process has one state machine, finishes one handler before taking the next message.

Internal send : CPU: enqueued in group queue, processed after current handler returns; FPGA: enqueued in internal process queue, processed later.

Internal fast_send : CPU: direct call on same thread, returns reply; FPGA: direct circuit call.

External messages : CPU: arrive at shared mailbox, delivered in arrival order; FPGA: arrive via process input FIFOs, delivered one by one.

Determinism : both are deterministic—same input order yields same handler invocation sequence.

Inter-group communication : CPU: different threads, parallel, send; FPGA: every cycle parallel, send via FIFOs.

The difference lies in mailbox construction. CPU group has one multi-writer queue. FPGA FIFO allows only one writer, so the group's mailbox merges multiple inputs: an internal queue for intra-group send, one FIFO per external reference pointing to a group member, one FIFO per outgoing reply, and one link from CPU. The process dequeues round-robin: internal queue first, then each input FIFO in turn. Ordering is deterministic; same inputs on same cycles produce same order. Merge logic grows with the number of incoming references.

Thus a process is a Group, declared at the HLS top level as kfpga::Group<A, B, ...> (CPU side uses grp.add(...)). Grouping criteria are identical: actors needing synchronous mutual calls and no concurrency go together; actors only exchanging messages go separate for parallelism.

CPU vs FPGA Actors

Both sides share the same model (private state, one message at a time, no shared memory), API, and group rules. send syntax is independent of receiver location; deployment decides placement. Messages from the same sender arrive in send order. Differences:

fast_send scope : CPU can target any actor (any thread can run any handler, but reentrancy forbidden); FPGA only within group.

Execution model : CPU threads execute actor code, many actors time-share a core; FPGA processes are independent circuits, all running every cycle.

Language restrictions : FPGA actors obey HLS rules (no heap, fixed loop bounds, no recursion/virtual functions); Kaspar messages only allow integer fields.

Static structure : CPU actors/references created at runtime; FPGA actors, groups, references, FIFO depths fixed at build time—wrong connections caught at compile.

Queue behavior : CPU default mailbox overflows to non-blocking overflow area; FPGA FIFO depth fixed at build, sender blocks when full.

Waiting : CPU thread sleeps/spins on empty mailbox; FPGA process checks its FIFOs each cycle without consuming other processes' time.

Board Adaptation Layer

FPGA boards differ in chip, PCIe interface, DMA engine, network ports, and vendor shells. To keep actor code portable, all board-specific logic is isolated in an adaptation layer. On the FPGA side, the actor design connects to the outside world via two streams: messages from CPU and messages to CPU (same format as CPU side). These streams are wired to the board's PCIe interface (using whatever transport, vendor shell, etc.) in a separate layer that varies per board. On the CPU side, a bridge component connects CPU actors to FPGA actors via a small board-specific interface. Supporting a new board means writing these two adaptation layers; actors, messages, runtime, and bridge remain unchanged. The current implementation uses a software-simulated board (each FPGA process as a thread) for testing.

PCIe Link

Read vs Write

All data moves via PCIe transactions. Writes are posted (fire-and-forget); reads are round-trips (request, wait for data, 0.5–1 µs latency, requesting core stalls). Therefore CPU writes to board, board writes to host memory; each side only reads its own memory. PCIe guarantees in-order delivery of writes from the same sender.

Three Transfer Methods

MMIO (PIO) : Board exposes register windows (BARs) mapped into CPU address space. CPU writes to these addresses become PCIe writes. With write-combining mapping, up to 64 bytes merge into one transaction—lowest latency for small messages. A store barrier forces immediate dispatch. Reads from these windows are slow.

DMA : Board reads/writes host memory directly. For board-to-CPU: board writes to a RingBuffer in host memory; a CPU thread polls it. For CPU-to-board: CPU writes message/descriptor to host memory, then writes a doorbell register (MMIO) telling board to fetch. Board-initiated read adds latency vs PIO for single small messages, but suits bulk transfers. RingBuffer: single writer, single reader, circular array; writer never overwrites unread slots; reader periodically informs writer of progress. No lock needed.

Interrupt (MSI-X) : Board signals interrupt; CPU driver wakes a waiting thread. Adds several microseconds plus scheduler latency; used for latency-insensitive messages. Polling preferred for latency-sensitive paths.

DMA write destination matters: if platform supports DDIO (Direct Data I/O), writes land in CPU cache, next poll hits cache; otherwise writes go to main memory, invalidating cache line, first poll costs ~100 ns.

Typical Overheads

Interrupt+wakeup exceeds a board round-trip (1–2 µs). Synchronous round-trip to board takes 1–2 µs. Latency-sensitive flows should stay on one side of the link, minimizing cross-link synchronous calls.

Bypassing the Kernel (VFIO)

Normally devices are managed by kernel drivers; each write / read / ioctl incurs a user-kernel transition, often exceeding message processing time. VFIO (Virtual Function I/O) gives the device directly to a userspace program. Program binds board to vfio-pci, calls a few ioctl / mmap at startup to create two mappings:

Board registers mapped into process : register window mapped to process memory; a pointer write becomes a PCIe write.

Process memory mapped to board : RingBuffer allocated, registered with VFIO; board DMA writes directly into it. Messages appear in process memory; a normal read retrieves them.

After setup, kernel is out of the path: send = one write to board window; receive = one read from own memory. No per-message read / write / ioctl.

RingBuffer memory must:

Use huge pages (2 MB or 1 GB) to reduce TLB misses (single page table entry).

Be locked in memory (pinned) so board's physical addresses stay valid.

Be registered in IOMMU (board uses I/O addresses; IOMMU translates to physical addresses and restricts access).

CPU and board share the RingBuffer under rules:

Sequence number written last : writer writes payload (60 bytes), then 4-byte sequence number. Board DMA uses PCIe strict ordering (not relaxed) so writes arrive in order. CPU sees expected sequence number before reading payload.

One message per 64-byte slot : matches cache line. Slot size ≠ PCIe transaction size; hardware may split a slot write into multiple transactions, so receiver cannot use transaction boundaries to detect completeness.

Batch reader position updates : reader periodically tells writer how far it has read, not per message.

No batching on hot path : latency-sensitive messages sent immediately.

On-Board Network Processing

On the X3522PV, both sides build their own logic: FPGA design in Vivado, CPU program standalone. FPGA design provides at its PCIe interface: a window for CPU to write 64-byte messages, and a DMA engine writing to host RingBuffer. CPU accesses both via VFIO. Since network ports connect directly to FPGA, the same design can include:

NIC : one Ethernet MAC per port, packets enter FPGA logic directly.

Market data processing : MDP3 (CME market data protocol) decoder receiving UDP multicast, decoding SBE (binary encoding), FPGA actors building order books.

Order entry : iLink 3 (CME order entry protocol) session, SBE encoding orders, maintaining TCP connection to exchange, plus order management actor.

Host only handles actor messages. CPU actors receive market data as messages from FPGA actors, send orders as messages to them; packets stay on the board.

Cross-PCIe Actor Messages

Message Format

Goal: same send code regardless of receiver side. CPU actor holds ActorRef to FPGA actor, calls send identically; FPGA actor does the same for CPU actor.

CPU messages are heap-allocated C++ objects (can contain double, std::string); FPGA messages only have integer fields and fixed ID. Conversion happens at the boundary.

Cross-link messages use an envelope format identical to FPGA runtime FIFOs: 12-byte header + 48-byte payload = 60 bytes. Plus a 32-bit sequence number = 64 bytes (one cache line). Fields are integers only: price as tick count, quantity as integer, contract as index. No floating-point error. Twelve 32-bit words suffice for an order or trade.

Cross-link messages declared once in shared header. CPU message class derives from shared definition, satisfying CPU runtime base class requirements, so bridge can encode into a stack-allocated envelope without allocation.

Cross-Link fast_send

Both directions only use send. Reason: board handler is a circuit only board can run; CPU handler is code only CPU thread can run. Cross-link fast_send would be send + wait for reply (at least one PCIe round-trip), caller blocked, new deadlock risk. Thus cross-link request/reply are two separate messages: caller send s request, continues; receiver's reply arrives later as a message handled by a second handler.

Routing Thread Problem

Early Kaspar prototype used a router thread: all board messages arrived there, it polled board, decoded, placed into target actor's mailbox. Every board message incurred an extra cross-thread hop. If target thread was sleeping, wakeup took several microseconds—longer than a board round-trip (1–2 µs) and far longer than FPGA actor processing (tens of ns).

Board-Written Mailboxes

Kaspar extends the FPGA FIFO rule (single writer, single reader, direct connection) across PCIe. Each cross-link FIFO becomes either a board register window (CPU→FPGA) or a host RingBuffer (FPGA→CPU), with the other end being exactly one CPU actor or Group. Window = slice of board register window assigned to one CPU actor, written by that actor. Lane = RingBuffer in host memory written by board for one CPU actor.

vs router thread: eliminates cross-thread hop. Each CPU actor writes its own window, reads its own lane. Actors in a Group share one window and one lane.

CPU → FPGA : send completes entirely in sender's thread. Encodes envelope on stack, writes to actor's board window. Window mapped write-combining; after 64 bytes, a barrier ensures board sees full slot. Each actor has private window, so sends don't interfere. Ordering guaranteed: same sender thread, same window, board moves envelopes to target actor's FIFO in arrival order. If window full, send blocks until board consumes a slot.

FPGA → CPU : Board writes directly into target actor's mailbox. An actor receiving FPGA messages usually also receives CPU messages, so its thread uses a dedicated FpgaLanes mailbox with two parts:

CPU queue : lock-free MPSC queue ( LockFreeMPSC), any CPU actor can enqueue.

One or more lanes : RingBuffers in host memory written only by board; one per board-to-host stream.

Only the owning thread reads this mailbox. Loop checks lanes first, then CPU queue, processes one message per iteration. If thread runs a Group, all members share this mailbox. When both empty, executes pause instruction and retries.

Handler receives message with sender represented by a proxy object for that FPGA actor, so reply() works unchanged—reply goes out via this actor's own window.

On board side, one RingBuffer per writer means each (FPGA actor → CPU actor/Group) pair gets a dedicated lane. Board routing table maps CPU actor ID to lane; fixed at build. Board host in and host out processes handle host communication. If a lane fills, host out stalls waiting for CPU actor to consume slots; other lanes queue behind.

Windows, lanes, CPU queue are bounded; writer blocks when full. Default CPU BQueue overflows to non-blocking area—different behavior. Threads reading market data that send to FpgaLanes actors should size capacity for maximum burst.

Receiver Spins

Actors using FpgaLanes spin: their thread continuously polls lanes and CPU queue. Spinning allows simultaneous reception from CPU and FPGA actors. Normal CPU actors sleep on condition variable, woken by another CPU thread; board would need interrupt (file descriptor event) to wake them, adding microseconds. To wait on both, both would need to be file descriptors, still microseconds wakeup. Spinning thread checks both every cycle.

Therefore FpgaLanes only for actors receiving FPGA messages. Other actors keep normal mailbox (sleeping). They can still send to FPGA actors (send is just a write from their thread). Spinning consumes a core per actor, so FPGA-receiving actors should be grouped into one Group to spin together on one core.

On-Board Order Management (Design Concept)

Placing order management on board is planned, not yet implemented. CME iLink 3 order management suits this: if board holds exchange connection, order management sits next to it. Trading strategy (CPU actor) sends order/cancel requests to order management; order management tracks each live order, hands to board iLink 3 session, sends exchange acks/fills/rejects back to strategy.

Messages ( NewOrder, Fill, Ack) declared once in shared header. Board order management uses fixed-size array indexed by order ID for remaining quantity (no heap). iLink 3 session is another board actor handling SBE encoding and TCP, converting exchange execution reports to messages for order management.

Board-internal: order management and session communicate via FIFOs. Acks/fills/rejects destined for CPU strategy leave board via host out into strategy's lane. One order and its ack are two messages separated by exchange round-trip.

Strategy is a normal CPU actor holding ActorRef to order management, sending messages like any actor. Order send = one write to strategy's window; acks/fills/rejects arrive later as messages handled by respective handlers.

Conclusion

FPGA has no threads, scheduler, or allocator, yet actor model rules map directly: process = actor or group, FIFO = send, intra-group fast_send = direct circuit call. 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.

HLSHardware AccelerationFPGAHigh-Frequency TradingActor ModelPCIeVFIOKaspar

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion