5 min read
Kafka in a trading stack: where it fits, and what it guarantees
Kafka does not belong between a market-data tick and an order, and it is very good at everything after the fill. Partition keys and ordering, what idempotent producers and transactions cover, compaction for current state, and a post-trade consumer that is safe to replay.
Kafka turns up in most trading architectures, and the first design question is where to put it. The answer is determined by one property: it is a durable, replicated log reached over the network through a broker. That makes it the wrong tool on one side of the fill and an excellent one on the other.
Not on the hot path
Between a market-data update and the order it causes, every stage is budgeted in microseconds or less. A produce request travels to a broker, is appended to a log and, if you want durability, replicated to other brokers before it is acknowledged; the consumer then fetches it. With careful tuning that round trip is measured in milliseconds, and its tail depends on batching, page cache behaviour, replica health and garbage collection in the broker.
None of that is a criticism. Those costs buy durability and replay, which the hot path gets by other means: in-process ring buffers, shared memory, or purpose-built messaging with sequenced, low-latency transport. Kafka sits beside that path, receiving a copy of what happened.
Where it earns its place
After an execution exists, the requirements invert. Nothing downstream needs it within a microsecond; everything downstream needs it without loss, in order, and again tomorrow if a system has to be rebuilt.
- Drop-copy distribution. One stream of orders and fills, consumed independently by position keeping, risk, P&L, booking, surveillance and client reporting. A new consumer is added without touching the producer.
- Replay. A downstream service that was wrong for an hour is fixed, reset to an earlier offset and re-run against the same input. Retention is the feature.
- Audit trail. An ordered, immutable record of what each system was told and when.
- Market data for consumers that are not latency-critical. Analytics, research capture, end-of-day processing, slower dashboards.
- Current-state topics. Reference data and positions on compacted topics, covered below.
Partition keys decide ordering
Kafka orders records within a partition and gives no ordering across partitions. The record key selects the partition, so choosing the key is choosing the ordering guarantee.
For executions the key is normally the order id: every event for an order lands in one partition, and a consumer always sees new, partial fill, fill, in that sequence. If a consumer needs all activity for an instrument or an account in order, the stream has to be keyed that way instead, or republished to a second topic with a different key. One topic cannot provide both.
Two consequences are easy to miss. Increasing the partition count changes which partition a key maps to, so ordering for a key is broken across the resize; size the topic generously at the start. And a skewed key, such as one instrument that is a large share of the volume, makes one partition hot, and its consumer becomes the bottleneck whatever the cluster size.
What the guarantees cover
Three settings, three different guarantees.
acks=all with min.insync.replicas means an acknowledged write survives the loss of a broker. With acks=1 an acknowledged fill can disappear in a leader failover.
The idempotent producer attaches a producer id and sequence numbers so that a retry after a timeout is not appended twice, and ordering within the partition survives retries. It is the default in the Java client since Kafka 3.0; other clients may need it switched on. It covers duplicates caused by the producer's own retries within one session. It does not cover an application that restarts and sends the same business event again.
Transactions make a consume-transform-produce step atomic: the output records and the consumed offsets commit together or not at all. That is exactly-once processing between Kafka topics. It ends at the edge of Kafka. A consumer that writes to a database, calls a booking system or sends an email is at-least-once, and no broker setting changes that.
So the sink has to be idempotent, and trading data makes that easy because the events carry a natural key. An execution id assigned by the venue is unique for ever. A sink that upserts on it can receive a fill ten times and book it once.
A replay-safe consumer
With kafkajs, a producer keyed by order id and a consumer that commits only after the fill has been applied:
import { Kafka } from "kafkajs";
const kafka = new Kafka({ clientId: "post-trade", brokers: ["broker-1:9092"] });
type Fill = {
execId: string;
orderId: string;
symbol: string;
qty: number;
px: string;
};
// Producer: one partition per order, so every consumer sees an order's
// fills in the order they were written.
const producer = kafka.producer({ idempotent: true, maxInFlightRequests: 1 });
export async function publishFill(fill: Fill) {
await producer.send({
topic: "executions",
acks: -1, // all in-sync replicas
messages: [{ key: fill.orderId, value: JSON.stringify(fill) }],
});
}
// Consumer: at-least-once delivery, made effectively-once by the sink.
const consumer = kafka.consumer({ groupId: "position-keeper" });
export async function run(applyFill: (fill: Fill) => Promise<void>) {
await producer.connect();
await consumer.connect();
await consumer.subscribe({ topic: "executions", fromBeginning: true });
await consumer.run({
autoCommit: false,
eachMessage: async ({ topic, partition, message }) => {
const fill: Fill = JSON.parse(message.value!.toString());
await applyFill(fill); // must be idempotent on execId
await consumer.commitOffsets([
{ topic, partition, offset: (BigInt(message.offset) + 1n).toString() },
]);
},
});
}This type-checks against kafkajs 2; I have not run it against a broker here. Three points about it:
- The offset is committed after
applyFillsucceeds, and the committed value is the next offset to read. A crash between the two replays the fill, which the idempotent sink absorbs. Committing first would turn a crash into a lost fill. - The price travels as a string. A JSON number is a binary double, which is not a type for money.
- Committing per message is the simplest correct form and the slowest. Committing per batch is the usual optimisation and does not change the reasoning, because replay is already safe.
JSON keeps the example short. A production topic wants a schema with explicit evolution rules (Avro or Protobuf with a registry), because the topic outlives every version of every consumer.
Compacted topics for current state
A compacted topic retains at least the latest record for each key and discards older ones in the background. Keyed by instrument for reference data, or by account and instrument for positions, it is a table that can be read from the beginning to obtain current state and then followed for changes. A record with a null value is a tombstone and deletes the key.
This is the cleanest way to bootstrap a service: read the compacted topic to the end, then go live on the event stream. Two caveats: compaction is asynchronous, so a reader may see several versions of a key and must keep the last; and a compacted topic is a snapshot, not a history, so the audit trail belongs on a topic with time-based retention.
Operating it
- Consumer lag is the health metric, measured per partition and alerted on as time behind, not as message count. A position keeper thirty seconds behind is showing wrong positions.
- Rebalances pause consumption. When a consumer joins, leaves or misses its poll deadline, partitions are reassigned and processing stops meanwhile. Static group membership and cooperative rebalancing reduce the disruption. A handler that sometimes takes longer than the poll timeout causes rebalance loops that look like an outage.
- Retention is a business decision. It sets how far back a downstream system can be rebuilt. If the recovery plan says "replay from start of day", retention must comfortably exceed a long weekend.
- Know what happens when Kafka is unavailable. The trading path must not block on a broker. It buffers locally with a bound, and the bound, together with what happens when it is reached, is a risk decision made in advance.
The summary is short. Kafka is the system of record for what happened, not the mechanism by which it happens. Key by the entity whose order matters, make every sink idempotent on a business id, and treat replay as the normal way to recover.