Kafka
Kafka carries what crosses a service's boundary: the commands other contexts send a context, the receipts that come back, and the streams it publishes for whoever reads them. Inside a service, the log is the bus and Kafka is not involved. This page explains which topics a service uses, how to create them, and how to configure the transport.
When a service needs Kafka
A service needs a topic transport, Kafka in production, when one of these holds:
- its sagas send commands to another context;
- other contexts send commands to it (
wow.kafka.command-intake.enabled: true); - an aggregate type's commands are routed through Kafka for durable intake;
- it subscribes to another context's published stream;
- it publishes its failure ledger with
wow.ops.publish.enabled: true.
A node without a transport refuses to start in any of these cases, naming what needs one. Its published streams are no such need: every aggregate is published by default, which does not mean anyone reads it. Without a transport the node publishes none of them, and says so once at startup:
This service runs without a topic transport, so it does not publish its streams [<context>.<aggregate>, …]. To publish them, configure Kafka (wow.kafka.bootstrap-servers) or another transport provider.A node that publishes nothing either logs This service needs no topic transport: it publishes no stream and takes no topic. Receipts need nothing of their own: they come back for commands sent to another context, which need the transport already. Waits and a saga's synchronous calls use the internal HTTP port, not Kafka.
wow.transport selects the node's topic transport. With auto, the default, a node takes the transport it finds configured (Kafka, once wow.kafka.bootstrap-servers is set). Without one, a node in development (a profile of wow.dev-profiles) keeps its topics in its JVM: services in one process reach each other without a broker, every context it hosts takes its commands, and it publishes its failure ledger when the ops context runs in the same JVM (or with wow.ops.publish.enabled: true). Any other node runs without topics. wow.transport=memory keeps the topics in the JVM on purpose; outside development it is refused. Each partition of those topics keeps its last wow.memory.topic-retention records (1,000 by default) and drops older ones as a broker's retention would, so a subscription that falls further behind reads on from the oldest kept. They are for trying a service out, never for a load test or a deployment. wow.transport=none gives a node no topics in any profile, whatever is configured, and refuses to start a node that needs them; a blank wow.kafka.bootstrap-servers does not turn the topics off, since a node in development then keeps them in its JVM.
The transport is wired when the wow-kafka module is on the classpath and wow.kafka.bootstrap-servers is set. The eShop's ordering service connects with its kafka profile:
wow:
kafka:
bootstrap-servers: localhost:9092
# Execute the commands other contexts send to wow.eshop-ordering.commands (the payment's), which has as many
# partitions as the context's log (wow.log.partitions, 64 by default).
command-intake:
enabled: trueTopics
Each context owns its topics; the topics of other contexts are theirs.
| Topic | Written by | Read by |
|---|---|---|
wow.<context>.<aggregate>.state | This context's Kafka sink, one record per commit of each published aggregate | Other contexts' subscriptions, external consumers |
wow.<context>.commands | Other contexts' sagas and timers; this context's own nodes for aggregate types routed through Kafka; ops' actions on its failure ledger (wow.ledger.*), whenever it publishes it | This context |
wow.<context>.receipts | Other contexts, when they reject a command this context's sagas sent, or commit one a saga asked a receipt for. A context has it when one of its sagas may send commands to another context: it has an @OnRejected or @OnCommitted handler, or derives or schedules a command class none of the context's aggregates decides as its own (@Sends, else its return type). A lifecycle or schedule command counts, since every aggregate decides it and it may go to any context's. A command carries the topic in its replyTo only when its context has it | This context's sagas |
An aggregate is published by default; it can stay unpublished, publish without its state, or name another topic. wow.kafka.topics.prefix puts a prefix before every topic name, such as staging., on both the writing and the reading side. Every record is an envelope keyed by the aggregate, so one aggregate's records stay in order (Wire protocols).
A state topic has a record for every commit of a published aggregate, so an aggregate's versions on it run on without a gap from its first record: a commit whose events the aggregate all retired is published with no events, which a Wow subscription passes over, and a commit that only sets or cancels schedules with its schedule events (State event). A version goes missing only when you skip a commit the transport sink has parked, such as a record the broker refuses for good. The services that read the topic then park the aggregate at the missing version, and an operator's retry there accepts the gap (A version a state topic did not deliver). Create a state topic that a 10.0 pre-release wrote again before a 10.0 release publishes to it, as every pre-release store is.
A state topic holds each state and event with its @Sensitive values masked: the transport sink masks them as it writes. Two kinds of record hold raw values:
- A stream the owner declares revealing (
@AggregateRoot(revealsDisplay = true)) holds itsDISPLAYvalues raw, unless the owner turnswow.query.sensitivity.display-sharedoff. - Records written by 10.0.0-beta.14 or earlier hold every value as committed (Upgrade a Deployment).
The topic keeps them for as long as it retains them, so the topic's ACL is what decides who reads them: grant read on a context's state topics to the services that subscribe to it and to the external consumers meant to read it.
Partitions
- A command topic has exactly as many partitions as its context's log (
wow.log.partitions). A command's partition in the topic is its aggregate's partition in the log, so the node that reads it is the node that owns the aggregate. With another count, commands would reach nodes that do not own their aggregates, so a node that reads a command topic checks it at startup, whateverwow.kafka.ddlsays, and refuses to start while it is missing or has another count. A context whose commands the node does not take, only the ledger's, is checked for the topic alone: on another count the node warns and runs without the ledger's commands. Never add partitions to a command topic. - A state topic has at least as many partitions as its context's log.
- Placement: each record goes to its aggregate's partition in the log, as a command does, and says so in its
wow-partitionsheader (Kafka envelope). A publishing node checks the count at startup, whateverwow.kafka.ddlsays, and refuses to start while the topic is missing or has fewer partitions. - Growth: partitions can be added while services run, and moves no aggregate: the added ones stay empty, so they buy no parallelism. A published stream reads in as many partitions as its context's log (
wow.log.partitions). - Records placed by the key's hash: a record without that header, from a publisher of an earlier version or another producer, is in the partition its key maps to. A reading node warns once per partition when it finds one. Adding partitions moves such keys, and the producer sees a growth up to its
metadata.max.age.mslater, Kafka's five minutes by default. Before you upgrade a pre-release's publishers, follow Published streams on Kafka.
- Placement: each record goes to its aggregate's partition in the log, as a command does, and says so in its
- A receipts topic can have any number of partitions, placed by its key's hash, and partitions can be added while services run.
For both kinds of topic, a reading node looks for new partitions every wow.kafka.topics.partition-refresh-interval (30 seconds) and reads them from their beginning, without a restart. For records placed by the key's hash, an aggregate a subscription had parked at the growth cannot be retried afterwards: its earlier records are in the partition it left, its later ones in the new one. The owner of the new partition holds the later records back and marks the entry skip-only (skipOnly): it is never retried, by an operator either, and its reason names both partitions. Resolve those parked entries before you add partitions, or expect to skip them once their earlier records are dealt with (Failures). An aggregate parked on a record placed by its log's partition is retried where it was read, whatever partitions the topic gained.
Publish rate
The transport sink publishes one aggregate's records one after another: each is a send of its own that waits for the producer to send it and for its acknowledgement, so the aggregate's next commit is published after it, in version order. A single aggregate so sustains about 150 records a second with the default producer settings. Measured on an Apple M5 Max (PostgreSQL and Kafka on one virtual CPU each), one aggregate committing 150 times a second was published as fast; at 300 a second its stream fell 19 seconds behind in 30 seconds, and was level again 38 seconds after the load. Many aggregates are not bound by it: their records are published side by side, and with keys spread over 100,000 aggregates the sink kept up with the node's own saturation, about 25,000 commits a second. A stream that falls behind is late, never out of order, and catches up once the aggregate's rate drops; the aggregate's commands are answered meanwhile.
Watch it on the transport sink's subscription, wow.transport-sink.<aggregate>: wow.subscription.backlog and wow.subscription.progress for the aggregate's partition (Observability). Most of a record's time is the producer's linger.ms, Kafka's 5 ms by default, which wow.kafka.properties.linger.ms sets for every producer of the node (Client settings); no other value has been measured.
Creating topics
At startup, a node checks the topics its contexts own, as wow.kafka.ddl says; it follows wow.ddl when not set, so the stores and the topics share one setting:
ddl | At startup |
|---|---|
auto (default) | The node first creates the missing topics, with the log's partition count, wow.kafka.topics.replication-factor, wow.kafka.topics.min-insync-replicas and wow.kafka.topics.configs.*, then validates. It never alters an existing topic. A min-insync-replicas above replication-factor refuses the start: every write that waits for all replicas would fail. |
validate | The node does not start while one of its topics is missing, or its command topic does not have exactly the log's partitions. The message names each such topic. A service that publishes its failure ledger needs its command topic even when no other context calls it, for ops' wow.ledger.* actions. It also needs the command topic of each peer context it sends commands to, which it never creates, and its own receipts topic when a saga of its may send commands to another context (as the topic table says), whether or not the saga handles their rejections: a rejection no handler takes parks the saga's aggregate (Sagas). |
none | The node creates nothing and validates none of its topics: they are someone else's. A node that takes a context's commands still refuses to start while that command topic is missing or its partitions are not the log's. |
auto suits development and tests. In production, create the topics yourself and set wow.ddl: validate (or wow.kafka.ddl alone), which catches a missing one at the first start. For the eShop's ordering context:
kafka-topics --bootstrap-server kafka:9092 --create --topic wow.eshop-ordering.commands --partitions 64 --replication-factor 3 --config min.insync.replicas=2
kafka-topics --bootstrap-server kafka:9092 --create --topic wow.eshop-ordering.receipts --partitions 64
kafka-topics --bootstrap-server kafka:9092 --create --topic wow.eshop-ordering.order.state --partitions 64The command topic takes the replication factor and min.insync.replicas that Durability asks of it; the others may take the broker's defaults.
No node ever creates a topic as a side effect of reading it, so a stream that does not exist yet is waited for, not created with the broker's default partition count. The broker may, though: with auto.create.topics.enable on, Kafka's default, a producer that writes to a missing topic creates it with the broker's default count, often one. A service that takes commands refuses to start on a command topic made so, and one that takes the ledger's commands alone runs without them and warns. Turn it off on the brokers, and let Wow create its topics (ddl: auto) or check them (validate). Unlike a missing topic, which is waited for, brokers whose names do not resolve at a node's start stop it: the node exits, naming the hosts and wow.kafka.bootstrap-servers, and its orchestrator restarts it.
Durability
A command accepted on a command topic must survive the loss of a broker. That holds only when the topic's replication factor and min.insync.replicas are both at least 2. At startup, a node warns about each command topic of its contexts that is below that, and about a configuration that would create one, unless the node is in development: a profile of wow.dev-profiles is active (dev and local by default).
The producer is idempotent and waits for every in-sync replica (acks=all), whatever wow.kafka.properties says. Within one send, an aggregate's next message goes to the broker only once its previous one is acknowledged. A message Kafka refuses for good, whether the client or the broker refuses it, is never overtaken by that aggregate's later ones: those of the same send are not written, and the send fails. Messages of different aggregates go together.
Durable command intake
By default a command is routed over the cluster channel to the owner of its aggregate, and accepted only means it passed admission: a node that stops before running it loses it. For commands that must not be lost once accepted, such as asynchronous intake or absorbing load peaks, route their aggregate type through Kafka with wow.aggregates.[<context>.<aggregate>].routing: topic:
- The node that admits such a command writes it to the context's command topic and waits for the broker. A request that waits only for
acceptedis answered 202 once the broker has acknowledged it; from then on, the command is durable. - The owner of the aggregate's partition reads it from the topic and executes it, so one aggregate's commands keep their order. A longer wait, such as
snapshot, goes on as usual. - If the broker does not acknowledge within the wait's timeout, the wait ends at
accepted, failed. It ends then even while the node cannot reach any broker, when the Kafka client holds the send back for up to itsmax.block.ms(it has no metadata for the topic yet, or its buffer is full); the command may still be written once the client gets through, and a send that then fails is logged. A node keeps at mostwow.wait.max-registeredsuch sends that outlived their waits; beyond that, a command for a command topic is answeredwow.command.busyat once and is not sent, while commands that go to no topic run as usual. A retry with the same request id is not decided twice.
Only commands admitted at the edge take this route. A command a saga or a timer sends is already durable, because its sender retries until it commits.
A context whose aggregate types are routed through Kafka reads its command topic whatever wow.kafka.command-intake.enabled says. Otherwise, set wow.kafka.command-intake.enabled: true on a service that should execute the commands other contexts send it. The ops service's actions on parked aggregates arrive the same way, as wow.ledger.* commands on the service's command topic. A service that publishes its failure ledger reads them by itself, with intake off: it runs those commands alone, and passes over the others (The Ops Service and Console). Its command topic must then exist, with as many partitions as its log.
A command topic deleted and created again loses what it held: a command on the old topic that the intake had not taken yet is never run. A caller that waited beyond accepted sees its wait time out, and a retry with the same request id sends it again, to the new topic. The intake keeps its checkpoints per topic id, as a subscription of another context's stream does, so it never reads the new topic from an offset of the old one; but a node reads the topic's id once, as its intake starts. So create a command topic again in this order:
- Stop sending commands to it and let the intake take those it holds, or accept that the commands it has not taken are gone.
- Delete the topic and create it again, with as many partitions as the log.
- Restart every node of the service. A node that starts takes every command of the new topic from its beginning.
A node that is not restarted keeps the old topic's id. Usually it refuses each read of the new topic by name: its log has a warning at each attempt that names the topic and both its ids, then an error once the read's retries are spent, and it retries until it is restarted, taking none of the new topic's commands. Kafka fetches a running read by the topic's name, though, so in one case the node reads on: when that read's first fetch after the recreation finds the new partition already at the read's offset, and the record it then reads is at no lower leader epoch than the one before it (a lower one ends the read, which then refuses as above; a topic whose leader never changed is at epoch 0 on both sides). The node then takes the new topic's commands from that offset until it is restarted; the commands before that offset are taken only at the restart, and those it took are taken again then: a command that committed is answered as a duplicate, by its request id, and one that did not is decided again.
The intake's checkpoints are under <service>/<context>#<topic id>, its subscription wow.commands (wow.ledger.commands on a node that takes the ledger's commands alone), and the incarnation's marker under <service>/<context>, the group in which every subscription of the context's log keeps its checkpoints too. The warning at the start names the intake's checkpoints of the old topic, and no other subscription's. Remove them, and the old topic's marker, with statements that name the intake's subscriptions, never with the group alone. On PostgreSQL: DELETE FROM wow_checkpoint WHERE lease_group = '<service>/<context>#<old id>' AND subscription IN ('wow.commands', 'wow.ledger.commands') and DELETE FROM wow_checkpoint WHERE lease_group = '<service>/<context>' AND subscription = 'wow.incarnation#<old id>'. On MongoDB: db.wow_checkpoint.deleteMany({ lease_group: "<service>/<context>#<old id>", subscription: { $in: ["wow.commands", "wow.ledger.commands"] } }) and db.wow_checkpoint.deleteMany({ lease_group: "<service>/<context>", subscription: "wow.incarnation#<old id>" }). Those it lists as "none named", a pre-release's or those of a source that told no incarnation, are the rows of <service>/<context> whose subscription is wow.commands or wow.ledger.commands; every other row of that group is a live checkpoint of the log's subscriptions. The checkpoints a 10.0 pre-release kept for its intake are not read: an intake that kept them takes the command topic's retained commands again, each one that committed answered as a duplicate.
Reading other contexts' streams
A service reads other contexts' topics without a consumer group. Its leases assign the topic's partitions to its nodes, the same way they assign the log's, and the offsets are kept in the service's own checkpoint store, beside its other checkpoints. One consumer per node and topic feeds every subscription that reads the topic. So there is no consumer group to manage, reset or monitor in Kafka; a subscription's position is its checkpoint.
When a partition no longer holds the offset a subscription is to read from, because retention deleted it, that is an offset gap. wow.kafka.offset-gap decides what happens:
fail(default): the read fails and the subscription stays where it is, logging errors;earliest: the subscription reads on from the earliest retained offset, skipping what was lost.
Either way the gap is logged as an error and counted in the metric wow.subscription.offset.gaps; alert on it. Set each topic's retention longer than any subscription may fall behind.
A topic deleted and created again under its name is not a gap but another topic: its offsets name other records. A subscription keeps its checkpoints per topic id, the id the broker gives each creation of a topic, so it never reads the new topic from an offset of the old one, however many records the new one holds. A node that reads the topic follows the new one at its next look for added partitions (wow.kafka.topics.partition-refresh-interval, 30 seconds by default, which cannot be switched off): each subscription reads it as its start says, from the beginning for a subscription of another service's stream, with no memory of the old topic's aggregates. Until then the node places no read of it: each read is checked once, as it is placed, and nothing is checked per record. A read already running when the topic is deleted, or placed just before it is created again, goes on asking the broker for its offset under the topic's name, and ends as soon as the new partition is shorter than that offset, which a topic just created is, whatever wow.kafka.offset-gap says; every read placed after it is refused. Only when the new partition already holds that offset at the read's first fetch after the recreation, as when the node was stalled while the publisher wrote, can the read go on in the new topic. Kafka gives a client no topic id with what it fetches, so every read of a partition, the node's shared one and a second read such as a subscription catching up, compares the leader epochs of the records it reads, which never decrease along one partition's offsets: a record at a lower epoch than the one before it ends the read as a gap, logged and counted as above, and the round then joins the new topic. A topic whose leader changed since its creation has a higher epoch than the new topic's first, 0; one whose leader never changed, a single broker's for one, is at 0 on both sides, and its read goes on until the round. What it reads then is handled by the old topic's subscriptions, and handled again in the new one from their start, so nothing is lost, and at most one refresh interval of it is handled twice. On a stream of state events, that read can meet an aggregate's later version before its earlier ones, which the version check parks under the old topic; once the subscriptions join the new one, that entry is of the old topic, holds nothing back, and is skipped. To avoid the window, stop the services that read a topic, or pause their subscriptions, before deleting it and creating it again; if that was not done, skip what parked under the old topic once the readers follow the new one. A node that starts after the topic was created again reads the new one the same way. Each logs one warning naming the topic, the two ids, and the checkpoints of the old topic with their count: they are kept and no longer read, and the warning comes at every start while they are. Delete them to end it, under the group the warning names, <service>/topic:<topic>#<old id>, with the marker of the old id under <service>/topic:<topic>. On PostgreSQL: DELETE FROM wow_checkpoint WHERE lease_group = '<service>/topic:<topic>#<old id>' and DELETE FROM wow_checkpoint WHERE lease_group = '<service>/topic:<topic>' AND subscription = 'wow.incarnation#<old id>'. On MongoDB: db.wow_checkpoint.deleteMany({ lease_group: "<service>/topic:<topic>#<old id>" }) and db.wow_checkpoint.deleteMany({ lease_group: "<service>/topic:<topic>", subscription: "wow.incarnation#<old id>" }). Checkpoints the warning lists as "none named", a pre-release's or a source's that told no incarnation, are the rows of <service>/topic:<topic> whose subscription does not start with wow.incarnation#. What the old topic held after those checkpoints is lost to its subscriptions with the topic. An aggregate a subscription had parked in the old topic holds back nothing of the new one: its entry can only be skipped, its reason saying it names an offset of the earlier topic, and its skip drops nothing read since. If the aggregate fails again in the new topic, its new parking replaces that entry, with a warning that names the entry replaced and says that what it held back of the old topic went with that topic; the new parking is shown, retried by its spec and requested as any. A topic subscription's parked entries are shown under the group of the incarnation it reads, <service>/topic:<topic>#<topic id>, alike in /wow/ops/subscriptions and /wow/ops/parked, on wow.subscription.parked.aggregates (its wow.group) and in webhooks; once the subscription joins a new incarnation, all its entries, those parked in the old one too, are shown under the new one's group. wow.kafka.offset-gap decides only an offset before the earliest one a partition retains. A partition truncated by an unclean leader election (unclean.leader.election.enable) also ends before a running read's offset, and that read ends the same way, whatever the option says; its read is placed again only once the partition holds that offset again, so the records written below that offset meanwhile are not read. An unclean election gives up records Kafka had acknowledged, which is outside what Kafka itself keeps. Reading a topic's id needs DESCRIBE on it, which READ already grants.
To recover a subscription stopped by a gap, set wow.kafka.offset-gap: earliest and restart its nodes: the read resumes from the earliest retained offset. The skipped range is lost to that subscription, and stays counted in wow.subscription.offset.gaps. Set the option back to fail afterwards to keep the strict default. When the loss is not acceptable and what was published is still complete elsewhere, rebuild under a new subscription name instead.
A topic may also hold a record Wow cannot read:
- An envelope this version cannot read, of a later format say. It parks its aggregate for an operator, or is passed over when its key names no aggregate, and is counted in
wow.subscription.undecodable.messages. - A record that is no envelope at all, a record of no value (a tombstone) included. Another producer writes the topic, most likely a 9.x service on the same broker, whose state topics are named
wow.<context>.<aggregate>.stateas published streams are by default. The topic is the wrong one, so nothing parks: the read of its partition fails, its subscriptions stay before the record and retry with a backoff, and each failure is logged with the topic, partition and offset. The topic's other partitions read on. Give the Wow services topics of their own withwow.kafka.topics.prefix, the same on the services that publish and those that read, or a broker of their own, and restart them.
Client settings
wow.kafka.properties.* passes settings to every producer and consumer as they are, such as security.protocol and SASL settings, client.id or linger.ms. A few settings belong to Wow and cannot be overridden, because the guarantees rest on them: the idempotent producer with acks=all, consumers without a group that commit nothing and reset no offset on their own, and no topic creation on read.
wow.kafka.* accepts only the settings the Kafka transport declares, which Configuration Keys lists, and any key under properties and topics.configs; another key fails the start, naming it. topics.prefix, command-intake.enabled, ddl and topics.partition-refresh-interval are settings every topic transport has, so a community transport takes them under its own type.