Kafka in Depth
"Supporting these uses led us to a design with a number of unique elements, more akin to a database log than a traditional messaging system." — Apache Kafka documentation, Design, "Motivation"
Summary: Kafka is a replicated, partitioned, append-only log: producers append, consumers keep a bookmark, and nothing is deleted because somebody read it. Focus: The log on disk, replication with ISR and acks, KRaft, producers (batching, idempotence, transactions), consumer groups and rebalancing (eager, cooperative, KIP-848), share groups, the ecosystem and operations in Kafka 4.x. Learning goal: Configure a topic, a producer and a consumer group that lose nothing and duplicate as little as possible, predict what a broker failure or a rebalance does, and know when Kafka is the wrong tool.
This page is the deep dive on Apache Kafka as a broker: how the log is stored, how replicas agree on what is committed, how the KRaft quorum replaces ZooKeeper, what the producer and the consumer really do on the wire, how groups rebalance, and how you run it in production (metrics, partition counts, reassignment, upgrades). Commands and config defaults in one dense table live in the Kafka Cheatsheet. Several neighbours own cross-broker topics, and this page only gives the Kafka side in one paragraph before linking them: the three delivery semantics in Delivery Guarantees, ack mechanics across brokers in Message Acknowledgment, per-key order in Ordering & Partitioning, scaling worker pools in Competing Consumers & Scaling, windows and state stores in Stream Processing, Debezium in Change Data Capture, schemas and Schema Registry in Message Design & Schema Evolution, TLS, SASL and ACLs in Messaging Security, and the side-by-side decision in Broker Comparison. The other two broker deep dives are RabbitMQ in Depth and Redis Streams & Pub/Sub.
Page map
| If you are looking for | Go to |
|---|---|
| The whole model in tables you can memorise | Everything in one minute |
| Why a log and not a queue, and the trade-off | Why Kafka exists |
| LinkedIn 2011, KIP-98, KIP-500, Kafka 4.0 | Where it comes from |
| Topics, partitions, offsets, segments, index files, retention, compaction, tombstones | The log |
Leaders, followers, ISR, acks, min.insync.replicas, high watermark, leader epoch, unclean election, ELR | Brokers and replication |
Controller quorum, __cluster_metadata, ZooKeeper removal | KRaft |
Partitioner, batching, linger.ms, compression, retries, idempotence, transactions | Producers |
| Groups, assignors, eager vs cooperative, KIP-848, static membership, commits, share groups | Consumers |
| At-most/at-least/exactly-once on Kafka | Delivery semantics |
| Connect, SMTs, Debezium, Streams, Schema Registry, tiered storage, quotas, security | The ecosystem around the broker |
Page cache, sendfile, every knob, every error code | Mechanics |
| franz-go code | Go |
| laravel-kafka code | Laravel |
| Kafka against RabbitMQ and Redis Streams | Compared with the others |
| Lag, under-replicated partitions, partition count, reassignment, upgrades, 4.x, Confluent/Redpanda/WarpStream | Operations |
| Data loss, duplicates, poison records, rebalance storms, hot partitions | Solving the classic problems |
| When Kafka is right, and when it is not | Choosing Kafka |
| Monolith to multi-region | In architecture |
| Reproduce it on a laptop | Lab |
| Wrong beliefs, a cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The nouns. Every row is unpacked below.
| Term | In plain words | Tiny example | Where it lives |
|---|---|---|---|
| Topic | A named stream of events | orders | Cluster metadata |
| Partition | One ordered, append-only slice of a topic | orders-3 | A directory on each replica's disk |
| Offset | A record's position in its partition, a 64-bit integer that only grows | orders-3 @ 1,204,887 | Inside the record batch |
| Segment | One file of a partition; the last one is active | 00000000000001200000.log | Partition directory |
| Retention | How long or how much is kept, whether read or not | retention.ms=604800000 (7 d) | Topic config |
| Compaction | Keep at least the latest value per key | cleanup.policy=compact | Topic config, log cleaner thread |
| Replica, leader, follower | Copies of a partition; one leader takes writes, followers fetch | RF 3: leader on broker 1 | Brokers |
| ISR | Replicas that are caught up | Isr: 1,2 | Cluster metadata |
| High watermark | Highest offset every ISR member has; consumers read below it | HW = 10 | Leader, propagated to followers |
| Consumer group | A set of consumers that share partitions; one owner per partition | group billing | Group coordinator, __consumer_offsets |
| Committed offset | The group's bookmark per partition | billing / orders-3 = 1,204,880 | __consumer_offsets |
| Share group | Queue-style group: many consumers per partition, per-record acks | group thumbnails | Share coordinator, __share_group_state |
| Controller quorum | Raft group that owns cluster metadata | 3 controllers | __cluster_metadata log |
The knobs that decide safety.
| Knob | Side | Default (Kafka 4.4) | Safe production value | What it buys |
|---|---|---|---|---|
replication.factor | Topic | Broker default.replication.factor (1 unless set) | 3 | Survive broker loss |
min.insync.replicas | Topic | 1 | 2 (with RF 3) | acks=all really means 2 copies |
acks | Producer | all | all | Ack only after the ISR has it |
enable.idempotence | Producer | true | true | Retries do not duplicate or reorder |
unclean.leader.election.enable | Topic | false | false | Never elect a stale replica |
enable.auto.commit | Consumer | true (every 5 s) | false, commit after processing | No skipped records |
isolation.level | Consumer | read_uncommitted | read_committed if anyone writes transactionally | Hide aborted records |
group.protocol | Consumer | classic | consumer on 4.x clusters | No stop-the-world rebalances |
What Kafka is and is not.
| Kafka gives you | Kafka does not give you |
|---|---|
| Ordered, replayable history per partition | Ordering across partitions |
| Many independent readers of the same data | Per-message ack, redelivery timers or priorities in classic groups (share groups add per-record acks) |
| Throughput from batching and sequential I/O | Delayed delivery or per-message TTL |
| Exactly-once for Kafka-to-Kafka with transactions | Exactly-once into your database or an HTTP API |
| Retention independent of consumption | Deleting a record because it was processed |
Why Kafka exists
A traditional queue is a to-do list: the broker hands an item to one worker, waits for an ack, deletes it, and keeps per-message state the whole time. That works for jobs. It breaks when the same event is needed by ten teams, when a new service must read last week's events, or when volume is so large that per-message bookkeeping costs more than the message. Kafka's answer is to stop tracking messages at all: the broker stores an ordered log and each reader tracks a single number per partition.
| Classic queue (RabbitMQ classic/quorum queue, SQS) | Log (Kafka, Redis Streams, RabbitMQ streams) |
|---|---|
| Message deleted after ack | Record kept until retention or compaction |
| Broker tracks every message's state | Consumer group tracks one offset per partition |
| Per-message redelivery, TTL, priority, DLX | Replay by seeking; retries and DLQ are topics you build |
| Many workers share a queue freely | Parallelism capped by partition count (classic groups) |
| Adding a new consumer sees only new messages | A new group can read from the beginning |
| Good at work distribution | Good at event distribution, history and fan-out |
The everyday picture. A court stenographer's transcript. Every line is numbered and nothing is erased or reordered. Lawyers, journalists and clerks each keep their own bookmark ("I am at line 4,210"), read at their own speed, and can flip back. Nobody tells the stenographer what they have read. Old volumes go to the shredder after a fixed time whether anyone read them or not. A compacted topic is the land registry: it keeps only the latest deed for each parcel. The page reuses this picture: partitions are separate transcript volumes, replicas are certified copies, and the controller is the court clerk who records which copy is official.
Three common misunderstandings, up front
- "Kafka is a queue." It is a log. Classic consumer groups cannot ack one record and skip another; the bookmark moves forward or it does not. Share groups (KIP-932) add queue behaviour on top, but most Kafka code still works by offset.
- "
acks=allmeans every replica has my write." It means every replica currently in the ISR, which can be only the leader.min.insync.replicasis the floor that makesacks=allmeaningful. - "Kafka gives exactly-once." Idempotence and transactions give exactly-once from a Kafka topic to a Kafka topic. A database write or an email sent from the consumer is outside them; you still need an idempotent consumer.
Where it comes from
Kafka was built at LinkedIn and described by Jay Kreps, Neha Narkhede and Jun Rao in "Kafka: a Distributed Messaging System for Log Processing", NetDB'11, 2011. The problem was activity data (page views, clicks, searches) needed both by Hadoop batch loads and by real-time features. The paper already contains the core idea:
"Unlike typical messaging systems, a message stored in Kafka doesn't have an explicit message id. Instead, each message is addressed by its logical offset in the log."
The 2011 system had no replication and promised only at-least-once. Both changed. Intra-cluster replication with the ISR arrived in 0.8. KIP-98 (Kafka 0.11.0.0) added the idempotent producer and transactions; its motivation says that without them "Duplicates may occur in the stream due to producer retries." KIP-101 replaced high-watermark truncation with the leader epoch after finding that a fast leader change could lose committed data. KIP-500 proposed moving metadata out of ZooKeeper: "Rather than being stored in a separate system, metadata should be stored in Kafka itself." The Kafka 4.0 announcement (18 March 2025) calls 4.0 "the first major release to operate entirely without Apache ZooKeeper". Kafka 4.0 also made the KIP-848 consumer protocol generally available; KIP-932 share groups went from early access (4.0) to preview (4.1) to production-ready in 4.2 (17 February 2026), and 4.4 (22 October 2026) added dead-letter queues for share groups. Facts on this page are checked against the 4.4 documentation.
The log: topics, partitions, offsets, segments
Topic, partition and offset Must-know
In plain words: A topic is split into partitions. Each partition is a numbered list that only grows at the end. The number is the offset.
Common misunderstanding: "A topic is ordered." Only a partition is. Two events for the same order on two partitions can be read in either order, which is why the key matters.
Definition: A partition is a totally ordered, immutable sequence of records. Each record has a 64-bit offset assigned by the partition leader on append, a key (optional bytes), a value (bytes, or null), headers and a timestamp (CreateTime from the producer or LogAppendTime from the broker, chosen by message.timestamp.type). The implementation docs describe a partition on disk as a directory named topic-partition, for example my-topic-0.
Producer P1 (key o-42) Leader of orders-3 Group billing (owner of orders-3)
1 send(o-42, created) -> append at offset 100
2 send(o-42, paid) -> append at offset 101
3 fetch from 100 -> [100, 101]
4 process 100, 101
5 commit offset 102 (= next to read)
6 send(o-42, shipped) -> append at offset 102
7 fetch from 102 -> [102]Real scenario: order lifecycle events keyed by order id so created → paid → shipped stay in order; device telemetry keyed by device id; a ledger keyed by account id; click streams with no key at all, where order does not matter and throughput does.
How each broker models it:
| Concept | Kafka | RabbitMQ | Redis Streams |
|---|---|---|---|
| Unit of order | Partition | Queue (or stream) | Stream |
| Position | Offset (int64, per partition) | None for queues; offset for streams | Entry ID ms-seq |
| Parallelism unit | Partition | Consumers on one queue | Consumers in a group on one stream |
| Scale-out unit | More partitions | More queues (consistent-hash exchange, super streams) | More streams (manual sharding) |
Fix / how to use it: pick the key on purpose (withKafkaKey, kgo.Record.Key), and size partitions for peak consumer parallelism up front; see Partitioner and keys and capacity.
Segments and index files Important
In plain words: A partition is not one huge file. It is a chain of segment files; only the newest one is written to, and the old ones are deleted whole.
Common misunderstanding: "Retention deletes records exactly at 7 days." It deletes segments whose newest record is older than the limit, so a record can live until its whole segment qualifies, and the active segment is never deleted.
Definition: Each segment has a .log file (record batches), an .index file (sparse offset → file position map) and a .timeindex file (timestamp → offset). The file name is the first offset in the segment (00000000000000000000.log). The active segment rolls when it reaches segment.bytes (default 1073741824, 1 GiB) or after segment.ms (default 7 days). index.interval.bytes (default 4096) controls how often an index entry is written, so a read binary-searches the index and then scans at most a few KB. Transactional topics also keep a .txnindex of aborted transactions.
orders-3/
1 00000000000000000000.log .index .timeindex <- closed, older than retention.ms -> deleted whole
2 00000000000000500000.log .index .timeindex <- closed
3 00000000000001000000.log .index .timeindex <- active: appends go here
4 fetch(offset 1000420) -> pick segment 3 by name -> binary search .index -> scan from nearest position
5 offsetsForTimes(09:00) -> .timeindex -> offset -> same pathReal scenario: a consumer resets to "yesterday 09:00" after a bug (kafka-consumer-groups.sh --reset-offsets --to-datetime), which uses the time index; disk usage that never drops because a low-traffic topic's active segment never rolls (set segment.ms); "too many open files" on a broker with thousands of partitions (each segment keeps file handles and memory maps; the hardware page warns about vm.max_map_count).
Fix / how to use it: leave segment.bytes alone for busy topics; set segment.ms lower for low-traffic compacted or short-retention topics; raise the file-descriptor and vm.max_map_count limits per the operations guide.
Retention by time and size Must-know
In plain words: Kafka keeps data for a time or up to a size, then deletes the oldest segments. Reading does not delete.
Common misunderstanding: "retention.bytes is per topic." It is per partition. A 12-partition topic with retention.bytes=10GB can hold 120 GB per replica.
Definition: With cleanup.policy=delete (default), a segment is eligible for deletion when its newest timestamp is older than retention.ms (default 604800000, 7 days; broker log.retention.hours=168) or when the partition exceeds retention.bytes (default -1, unlimited). -1 for retention.ms keeps forever. A consumer whose committed offset fell off the start of the log gets OFFSET_OUT_OF_RANGE and resets according to auto.offset.reset.
T0 day 0 billing commits offset 5,000,000 and its pod is scaled to zero
1 T1 day 3 retention deletes segments below offset 7,000,000
2 T2 day 8 billing restarts, fetches 5,000,000 -> OFFSET_OUT_OF_RANGE
3 T3 auto.offset.reset=latest -> silently skips 2,000,000+ records
4 auto.offset.reset=earliest -> resumes at 7,000,000; still lost 2,000,000Real scenario: a consumer down for a long weekend on a topic with 2-day retention; a staging cluster filling disks because retention.ms=-1 was copied from a compacted topic; regulators requiring 90 days of order events, solved with tiered storage instead of bigger disks.
Fix / how to use it: retention must exceed your longest plausible consumer outage plus replay window; alert on lag in time not just records; set auto.offset.reset deliberately (Kafka 4.x also accepts by_duration:PnDTnHnM per the consumer config docs).
Compaction and tombstones Important
In plain words: A compacted topic keeps the latest value for every key and throws older values away, so the topic becomes a table you can replay.
Common misunderstanding: "Compaction keeps exactly one record per key." It keeps at least the latest; the active segment and the head of the log (newer than min.compaction.lag.ms, or not yet cleaned because min.cleanable.dirty.ratio was not reached) still hold duplicates.
Definition: The design docs: "Log compaction ensures that Kafka will always retain at least the last known value for each message key within the log of data for a single topic partition." The log cleaner rewrites old segments, dropping records whose key has a newer value. Offsets do not change and order is preserved; there are gaps. A record with a null value is a tombstone: it deletes the key, and it is itself removed after delete.retention.ms (default 86400000, 1 day) so that slow readers still see the delete. cleanup.policy=compact,delete combines both (latest per key, but nothing older than retention.ms). Compacted topics need keys; a null key is rejected as CORRUPT_MESSAGE.
before cleaning: 0:(u1,a@x) 1:(u2,b@x) 2:(u1,a2@x) 3:(u3,c@x) 4:(u2,null) 5:(u1,a3@x)
1 cleaner keeps the latest per key:
after cleaning: 3:(u3,c@x) 4:(u2,null) 5:(u1,a3@x)
2 + delete.retention.ms later: 4:(u2,null) removed -> u2 no longer exists
3 a new service reads from offset 0 and rebuilds the current table: u1=a3@x, u3=c@xReal scenario: a customer-profile topic that services load into a local cache on startup; Kafka's own __consumer_offsets and __transaction_state (both compacted); Kafka Connect's offset and config topics; Kafka Streams changelog topics for state stores; CDC tables where Debezium emits a tombstone after a delete; event sourcing snapshots (never the event stream itself, which needs every event).
Fix / how to use it: create with cleanup.policy=compact and RF 3 (the admin snippet below); always set a key; delete with a null value, not with a "deleted" flag if you want the key to disappear; for GDPR erasure in immutable logs see Messaging Security.
Brokers and replication
Leader, followers and the ISR Must-know
In plain words: Every partition has one leader that takes all writes and some followers that copy it. The followers that are keeping up form the in-sync replica set, the ISR.
Common misunderstanding: "Kafka uses majority quorum for data like Raft." It does not. The design docs explain the choice: "With this ISR model and f+1 replicas, a Kafka topic can tolerate f failures without losing committed messages." A majority quorum needs 2f+1 replicas for the same.
Definition: Followers fetch from the leader exactly like consumers. A follower that has not caught up to the leader's log end within replica.lag.time.max.ms (default 30000) is removed from the ISR; one that loses its session with the controller (broker.session.timeout.ms) is removed too. Only ISR members can be elected leader (with unclean election off). A record is committed when every ISR member has it, and the guarantee is stated as: "The guarantee that Kafka offers is that a committed message will not be lost, as long as there is at least one in sync replica alive, at all times." Leadership is spread across brokers using the preferred replica (first in the replica list); auto.leader.rebalance.enable moves leadership back after a restart.
Broker 1 (leader) Broker 2 (follower) Broker 3 (follower)
1 append 0..9 fetch -> has 0..9 GC pause, has 0..6
2 30 s pass (replica.lag.time.max.ms)
3 controller: ISR {1,2,3} -> {1,2} (IsrShrinksPerSec += 1)
4 commits now need only brokers 1 and 2
5 catches up to 9 -> ISR {1,2,3} (IsrExpandsPerSec += 1)Real scenario: a broker with a failing disk falls out of the ISR and UnderReplicatedPartitions rises; a rolling restart shrinks and expands the ISR of every partition on that broker; a cross-AZ link that is slow makes one AZ's replicas flap in and out of the ISR.
How it compares:
| Replication | Kafka | RabbitMQ quorum queues/streams | Redis (Streams) |
|---|---|---|---|
| Algorithm | Leader + dynamic ISR (PacificA-like, per the design docs) | Raft (majority) | Async primary → replica |
| Copies to survive 1 failure | 2 (3 recommended with min.insync.replicas=2) | 3 | No guarantee; WAIT gives best effort |
| Latency depends on | Slowest ISR member | Median (fastest majority) | Primary only |
Fix / how to use it: RF 3 across racks/AZs (broker.rack + rack-aware placement), alert on under-replicated and under-min-ISR partitions (Operations).
acks and min.insync.replicas Must-know
In plain words: acks is how long the producer waits; min.insync.replicas is how many copies the topic insists on before it accepts an acks=all write.
Common misunderstanding: "acks=all alone is durable." The design docs give the counter-example: with two replicas and one failed, "writes that specify acks=all will succeed. However, these writes could be lost if the remaining replica also fails."
Definition: acks=0: fire and forget. acks=1: the leader wrote it to its log (page cache), followers may not have it. acks=all (-1, the default): every current ISR member has it. With acks=all, the leader refuses the write with NOT_ENOUGH_REPLICAS (19) if the ISR is smaller than min.insync.replicas, or answers NOT_ENOUGH_REPLICAS_AFTER_APPEND (20) if it shrank after the append. The topic config doc adds: "Regardless of the acks setting, the messages will not be visible to the consumers until they are replicated to all in-sync replicas and the min.insync.replicas condition is met." Kafka does not fsync per write; durability comes from replication, not the disk (flush.messages/flush.ms exist but are left at defaults).
RF=3, min.insync.replicas=2, acks=all
1 ISR {1,2,3} produce -> waits for 1,2,3 -> ack (safe)
2 broker 3 dies -> ISR {1,2} produce -> waits for 1,2 -> ack (safe, 2 copies)
3 broker 2 dies -> ISR {1} produce -> NOT_ENOUGH_REPLICAS (retriable) -> producer retries until delivery.timeout.ms
4 consumers keep reading committed data; writes are unavailable, nothing acknowledged is lostReal scenario: payments and orders (RF 3, min ISR 2, acks=all); metrics and logs where losing a few seconds is fine (acks=1 for lower latency); a single-broker dev cluster where min.insync.replicas=2 makes every write fail.
| Setting combo | Survives | Availability for writes | Use for |
|---|---|---|---|
RF 3, min ISR 2, acks=all | 1 broker loss, no data loss | Down if 2 brokers lost | Business events |
RF 3, min ISR 1, acks=all | Usually; loses data if leader alone in ISR then dies | Up with 1 broker | Tolerant pipelines |
RF 3, acks=1 | Loses acked data if leader dies before followers fetch | High | Logs, metrics |
| RF 1 | Nothing | Down with that broker | Dev only |
Fix / how to use it: set it on the topic at creation (kafka-topics.sh --config min.insync.replicas=2, or the admin snippet); keep the producer default acks=all; make sure the internal topics are protected too (offsets.topic.replication.factor default 3, transaction.state.log.min.isr default 2).
High watermark and leader epoch Important
In plain words: The high watermark (HW) is the line below which every ISR member has the data; consumers only read below it. The leader epoch is a generation number for leadership, used so a returning broker knows exactly what to throw away.
Common misunderstanding: "The log end offset is what consumers can read." The log end offset (LEO) is where the leader writes next; the HW lags it until followers catch up. A transactional consumer reads even less: up to the last stable offset (LSO), the first offset of a still-open transaction.
Definition: The leader advances the HW as followers confirm offsets in their fetches and tells followers the HW in fetch responses. Before KIP-101, a restarting follower truncated its log to its own HW, which could be behind the leader's; KIP-101 describes the failure: a follower restarts, truncates m2, the leader dies, the follower becomes leader, and "Message m2 has been lost permanently (regardless of whether B comes back or not)." The fix stamps every batch with the 4-byte leader epoch; a follower asks the leader "where did epoch N end?" (OffsetForLeaderEpoch) and truncates to that point instead of to its HW. Stale leaders and clients are fenced with FENCED_LEADER_EPOCH (74).
Before KIP-101 (HW truncation) With leader epoch
1 A (follower) fetched m2; HW on A still = 1 A fetched m2 (epoch 3)
2 A restarts, truncates to HW -> drops m2 A restarts, asks leader B: end of epoch 3?
3 B (leader) dies; A elected leader B answers 3 -> A keeps m2
4 m2 is gone though B acked it B dies; A leads with m2 intactReal scenario: you see FENCED_LEADER_EPOCH in client logs during a leader change (harmless, retriable); consumers lag "for no reason" because the HW is held back by a slow ISR follower; read_committed consumers stuck behind an open transaction (LSO).
Fix / how to use it: nothing to configure; know the terms when reading broker logs and kafka-log-dirs.sh output, and keep transactions short (transaction.timeout.ms, default 60000).
Unclean leader election and Eligible Leader Replicas Important
In plain words: If every in-sync replica is dead, Kafka can wait (stay down) or promote an out-of-date replica (come back, but lose data).
Common misunderstanding: "Turning it on only matters in disasters." It matters every time the ISR shrinks to one broker and that broker dies, which is more common than a full disaster.
Definition: unclean.leader.election.enable (default false since 0.11.0.0) decides. The design docs call it "a simple tradeoff between availability and consistency". Kafka 4.0 added Eligible Leader Replicas (KIP-966, preview in 4.0): the controller tracks replicas that left the ISR but are known to have data up to the HW, so they can be elected safely; the 4.1 upgrade notes say ELR "will be enabled by default on the new clusters". The broker-level min.insync.replicas moves to a cluster-level setting when ELR is enabled.
RF=3, ISR {1}, unclean=false
1 broker 1 (only ISR) dies -> partition OFFLINE (OfflinePartitionsCount > 0)
2 broker 3 (stale, offset 6) is up -> not eligible; writes and reads stop
3 broker 1 returns -> leader again, nothing lost
unclean=true: at step 2 broker 3 leads; offsets 7..9 are lost and later overwrittenReal scenario: a metrics topic where availability beats completeness (enable per topic); a payments topic (never enable); an operator forcing an unclean election by hand with kafka-leader-election.sh --election-type unclean during an incident, after accepting the loss.
Fix / how to use it: leave it false cluster-wide; enable per topic only when you can name what you are willing to lose.
KRaft: the metadata quorum
KRaft controllers and the metadata log Must-know
In plain words: The cluster's own bookkeeping (which topics exist, who leads which partition, who is in the ISR) is itself a replicated log, run by a small Raft group of controllers. ZooKeeper is gone.
Common misunderstanding: "KRaft means the data partitions use Raft now." Only the metadata log (__cluster_metadata) uses Raft. Data partitions still use the leader/ISR protocol above.
Definition: Each server sets process.roles to broker, controller or broker,controller (combined mode, for small or dev clusters). Controllers form a Raft quorum; one is the active controller and leader of the metadata log, the rest are voters. Brokers are observers: they fetch the metadata log, keep a local copy so they start fast, and send heartbeats to stay registered. Everyone finds the controllers through controller.quorum.bootstrap.servers (KRaft version 1 replaced the static controller.quorum.voters; voters can be added and removed with kafka-metadata-quorum.sh add-controller/remove-controller). Storage is formatted with kafka-storage.sh format. A quorum of 3 survives 1 controller failure; 5 survives 2. KIP-500 lists the motivation: metadata in Kafka itself avoids "discrepancies between the controller state and the Zookeeper state", and brokers "should simply consume metadata events".
Controller 1 (active) Controller 2,3 (voters) Broker 2
1 broker 3 misses heartbeats
2 append PartitionChangeRecord: orders-3 leader 3 -> 1, ISR {1,2}
3 replicate, majority acks -> committed
4 fetch metadata -> applies change, now follows 1
5 clients get NOT_LEADER_OR_FOLLOWER from broker 3, refresh metadata, go to broker 1Real scenario: failover of thousands of partition leaders is one batch of metadata records instead of thousands of ZooKeeper writes; upgrading a 3.x ZooKeeper cluster requires migrating to KRaft on 3.9 (the last bridge release) before moving to 4.x; dev clusters run one combined node (process.roles=broker,controller).
Fix / how to use it: run 3 dedicated controllers in production (5 for very large clusters), on separate hosts or AZs; monitor ActiveControllerCount (exactly 1 across the cluster) and kafka-metadata-quorum.sh describe --status for lag.
Producers
Partitioner and keys Must-know
In plain words: The producer, not the broker, picks the partition. With a key, it hashes the key, so one key always goes to one partition. Without a key, it fills one partition's batch and then moves on.
Common misunderstanding: "Every Kafka client hashes keys the same way." Java and franz-go use murmur2; librdkafka (PHP, Python's confluent-kafka, Go's confluent-kafka-go) defaults to consistent_random (CRC32). Mixed-language producers splitting one key across two partitions is a real bug.
Definition: Java's default partitioner: if a partition is set, use it; if a key is present, murmur2(key) % numPartitions; if no key, the sticky partitioner keeps one partition until at least batch.size bytes are produced to it, then switches. partitioner.rack.aware=true with client.rack prefers partitions led in the same rack. librdkafka documents murmur2_random as "functionally equivalent to the default partitioner in the Java Producer."
6 partitions after kafka-topics.sh --alter --partitions 8
1 o-41 -> p3, o-42 -> p0, o-43 -> p5 o-41 -> p5, o-42 -> p6, o-43 -> p5
2 old o-42 events in p0, new ones in p6 -> a consumer can see "shipped" before "paid"
(real output of the partitioner snippet: 5 of 6 keys moved)Real scenario: per-customer ordering in a bank feed; a "hot key" (one celebrity account, one tenant) that overloads one partition; a PHP service and a Go service producing the same keys to different partitions until partitioner=murmur2_random is set.
Fix / how to use it: key by the entity whose order matters (order id, account id); never add partitions to a keyed topic whose consumers rely on order without a migration plan (new topic + dual write, or drain first); salt hot keys only if per-key order is not needed. See Ordering & Partitioning.
Batching, linger.ms and compression Important
In plain words: The producer collects records per partition into batches and sends a batch when it is full or when it has waited linger.ms. Bigger batches compress better and cost fewer requests.
Common misunderstanding: "linger.ms=0 is lowest latency." Under load, many tiny requests queue on the broker and latency gets worse. Kafka changed the default for this reason: "The default changed from 0 to 5 in Apache Kafka 4.0".
Definition: batch.size (default 16384 bytes) caps a batch per partition; linger.ms (default 5) is the maximum wait; buffer.memory (default 32 MB) bounds buffered records, after which send() blocks up to max.block.ms. compression.type (producer default none; gzip, snappy, lz4, zstd) compresses whole batches, and the topic-level compression.type=producer keeps the producer's codec on disk, so the broker stores and serves compressed batches as-is. max.request.size (producer) and max.message.bytes (topic, default 1048588) limit batch sizes; too large gives MESSAGE_TOO_LARGE (10).
t=0 ms send(r1, p2) -> new batch for p2
1 t=1 ms send(r2, p2), send(r3, p2) -> same batch
2 t=5 ms linger.ms reached -> batch [r1 r2 r3] compressed with zstd -> one ProduceRequest
3 t=9 ms leader appends, followers fetch, ISR has it -> ackReal scenario: clickstream producers at 100k records/s using lz4 or zstd and linger.ms=20 to cut broker CPU and network; a payment API that sends one record per request where batching barely matters; a 2 MB image accidentally sent as a record (use the claim-check pattern in Message Design).
Fix / how to use it: keep linger.ms 5–20 and enable zstd or lz4 for volume topics; measure with kafka-producer-perf-test.sh (it now supports --key-distribution in 4.4).
Retries, ordering and the idempotent producer Must-know
In plain words: Networks drop acks, so producers retry. Without idempotence, a retry can write the same batch twice, or write batch 2 before a retried batch 1. With idempotence, the broker recognises the retry and drops it.
Common misunderstanding: "Idempotence dedups my application's resends." It dedups only the producer client's own retries within one producer session. If your code calls send() twice, or the process restarts and resends, those are two different records.
Definition: enable.idempotence=true is the Java default since 3.0 (librdkafka's default is still false). The broker gives the producer a producer ID (PID) and epoch; every batch carries a per-partition sequence number; the leader keeps the last 5 batch sequences per PID-partition and rejects duplicates or gaps (OUT_OF_ORDER_SEQUENCE_NUMBER, 45). The config docs: "enabling idempotence requires max.in.flight.requests.per.connection to be less than or equal to 5", retries greater than 0 and acks=all. retries defaults to 2147483647 and is bounded in practice by delivery.timeout.ms (default 120000), which must be at least request.timeout.ms + linger.ms. Without idempotence and with max.in.flight.requests.per.connection above 1, retries can reorder.
Producer (PID 7) Leader of orders-3
1 batch seq 0..9 -> append, ack lost on the network
2 retry seq 0..9 -> seq already seen for PID 7 -> DUPLICATE, ack again, no write
3 batch seq 10..19 -> append
without idempotence, step 2 appends a second copy of records 0..9Real scenario: duplicate payment.captured events after a network blip (KIP-98's motivating case); reordered events when a team set max.in.flight=10 with idempotence off; zombie duplicates after a pod restart, which idempotence does not catch (use transactions or a consumer inbox).
Fix / how to use it: leave Java and franz-go defaults alone; in PHP set enable.idempotence=true explicitly (the Laravel snippet below); always check the send result (ProduceSync(...).FirstErr(), Kafka::publish()->send() throws).
Transactions Important
In plain words: A transactional producer writes to several partitions (and commits a consumer's offsets) so that read_committed readers see all of it or none of it.
Common misunderstanding: "A Kafka transaction can include my database update." It cannot. It covers Kafka partitions and Kafka offsets only.
Definition: Set a stable transactional.id; initTransactions() registers it with the transaction coordinator (a broker that owns a partition of __transaction_state), bumps the epoch and fences older instances with the same id (PRODUCER_FENCED, 90; INVALID_PRODUCER_EPOCH, 47). Then beginTransaction, send, sendOffsetsToTransaction (for consume-transform-produce), commitTransaction or abortTransaction. The coordinator writes commit/abort markers into every touched partition. Consumers with isolation.level=read_committed read up to the LSO and skip aborted batches; the Java default is read_uncommitted, librdkafka's is read_committed. transaction.timeout.ms (default 60000) aborts stuck transactions; the transaction docs note transactions need at least three brokers by default (transaction.state.log.replication.factor=3, min ISR 2).
Producer (transactional.id=enricher-1) orders-enriched p0, p4 __consumer_offsets read_committed consumer
1 beginTransaction
2 send r1 -> p0, r2 -> p4 r1, r2 appended (pending) sees nothing past LSO
3 sendOffsetsToTransaction(orders: 812) offset staged
4 commitTransaction COMMIT markers written offset 812 committed sees r1, r2
crash before 4 -> new instance with same id fences the old one, aborts; r1, r2 skipped by readersReal scenario: a Kafka Streams app with processing.guarantee=exactly_once_v2; a franz-go enricher using GroupTransactSession (snippet below); an atomic "debit + credit" pair published to two topics (the Laravel snippet).
Fix / how to use it: use transactions for Kafka-to-Kafka pipelines; for "DB write + publish" use the outbox; for "consume + DB write" use the inbox. The three semantics in general: Delivery Guarantees.
Consumers
Consumer groups, the coordinator and __consumer_offsets Must-know
In plain words: Consumers with the same group.id split the partitions between them; each partition has exactly one owner in the group. The group remembers its position by committing one offset per partition.
Common misunderstanding: "Adding consumers always adds throughput." Beyond the partition count, extra members of a classic group sit idle.
Definition: One broker is the group coordinator for a group (the leader of the __consumer_offsets partition that the group id hashes to). Consumers pull with poll(); the client fetches in the background (fetch.min.bytes, fetch.max.wait.ms, max.partition.fetch.bytes) and returns up to max.poll.records (default 500) per call. Liveness has two timers: heartbeats within session.timeout.ms (default 45000) and poll() calls within max.poll.interval.ms (default 300000); missing the second makes the member leave the group even though it is alive. The committed offset is "the next offset to read". With no committed offset (new group, or OFFSET_OUT_OF_RANGE), auto.offset.reset decides: latest (default), earliest, none, or by_duration: (4.x).
group billing, topic orders with 6 partitions
1 C1 joins -> C1 [p0..p5]
2 C2 joins -> rebalance -> C1 [p0 p1 p2], C2 [p3 p4 p5]
3 C3..C6 join -> each owns one partition
4 C7 joins -> C7 owns nothing (members > partitions)
5 C2 handler blocks 6 min -> max.poll.interval.ms exceeded -> C2 leaves -> rebalanceReal scenario: a billing service scaled to 20 pods on a 12-partition topic (8 idle); a slow PDF render in the poll loop that exceeds max.poll.interval.ms and causes endless rebalances; two services that accidentally share a group.id and each see half the events.
Fix / how to use it: one group per logical subscriber (service), partitions ≥ peak consumers, keep processing per poll under max.poll.interval.ms (lower max.poll.records or hand work to a bounded worker pool, see Backpressure).
Assignment strategies and rebalancing: eager vs cooperative Must-know
In plain words: When members join or leave, partitions are redistributed. Eager rebalancing takes every partition away from everyone first; cooperative rebalancing only moves the partitions that must move.
Common misunderstanding: "Rebalances are rare events." Every deploy, autoscale, crash, long GC or slow poll triggers one. In a classic eager group each is a stop-the-world pause for the whole group.
Definition: In the classic protocol, members send JoinGroup (with their supported assignors), the coordinator picks a group leader member that computes the assignment client-side, and everyone receives it via SyncGroup. Each completed rebalance bumps the generation; commits from an old generation fail with ILLEGAL_GENERATION (22) or UNKNOWN_MEMBER_ID (25), and members in the middle see REBALANCE_IN_PROGRESS (27). Assignors (partition.assignment.strategy): RangeAssignor (per topic, contiguous ranges; Java default list is [RangeAssignor, CooperativeStickyAssignor]), RoundRobinAssignor, StickyAssignor (balanced and keeps previous ownership, still eager), and CooperativeStickyAssignor (KIP-429, incremental: two rounds, only moved partitions are revoked). Callbacks: onPartitionsRevoked (commit here), onPartitionsAssigned, onPartitionsLost (do not commit; someone else may own them). KIP-848's motivation summarises the remaining pain: a single misbehaving consumer can take down or disturb the whole group "because a rebalance of the whole group is required whenever a consumer joins, leaves or fails."
Cooperative-sticky: C3 joins C1 [p0 p1 p2], C2 [p3 p4 p5]
1 round 1: JoinGroup from all; leader computes target C1 [p0 p1] C2 [p3 p4] C3 [p2 p5]
2 C1 revokes only p2 (commits it in onPartitionsRevoked), C2 revokes only p5; p0 p1 p3 p4 keep flowing
3 round 2: JoinGroup again; p2 and p5 now free -> assigned to C3
4 C3 starts p2 at billing's committed offset for p2Real scenario: a Kafka Streams app with large state stores that rebuilds state after every eager rebalance; a Kubernetes rolling deploy of 30 pods causing 30 rebalances; Laravel consumers using RebalanceStrategy::COOPERATIVE_STICKY.
Fix / how to use it: use CooperativeStickyAssignor (Java), kgo.CooperativeStickyBalancer() (franz-go), partition.assignment.strategy=cooperative-sticky (librdkafka); commit in the revoke callback; or move to KIP-848 below. Switching a live group from eager to cooperative needs two rolling bounces (first add cooperative to the list, then remove the eager one). Scaling patterns across brokers: Competing Consumers & Scaling.
KIP-848: the consumer rebalance protocol Important
In plain words: In Kafka 4.x the broker computes the assignment and each consumer converges to it through its heartbeats. There is no group-wide barrier, so one slow member cannot freeze the others.
Common misunderstanding: "4.0 turned it on for everyone." The 4.0 announcement says it is "enabled by default on the server side. Consumers must opt-in by setting group.protocol=consumer." The 4.4 consumer docs still list group.protocol default classic, and librdkafka's default is classic too.
Definition: Members send ConsumerGroupHeartbeat; the coordinator keeps a group epoch and a target assignment, computed by a server-side assignor (group.consumer.assignors, default uniform,range; clients may pick with group.remote.assignor). Each member has a member epoch and reconciles: it releases partitions the target takes away, and receives new ones once their previous owner released them. Errors are new: FENCED_MEMBER_EPOCH (110) means rejoin, STALE_MEMBER_EPOCH (113) means retry after the next heartbeat. heartbeat.interval.ms and session.timeout.ms become broker-side group configs (group.consumer.heartbeat.interval.ms, group.consumer.session.timeout.ms). Kafka Streams has its own server-side protocol (KIP-1071, group.protocol=streams, GA with a limited feature set in 4.2).
group epoch 12; C1 [p0 p1 p2], C2 [p3 p4 p5]
1 C3 heartbeats (joins) -> coordinator: group epoch 13, target C1 [p0 p1] C2 [p3 p4] C3 [p2 p5]
2 C1 heartbeat response -> "revoke p2" ; C1 commits p2, heartbeats owning [p0 p1]
3 C2 heartbeat response -> "revoke p5" ; same
4 C3 heartbeat response -> "assigned p2 p5" ; member epoch 13
p0 p1 p3 p4 never paused; no JoinGroup/SyncGroup round tripsReal scenario: large consumer groups (hundreds of members) where classic rebalances took minutes; cloud operators debugging assignment on the broker instead of collecting client logs (KIP-848's first motivation).
Fix / how to use it: Java: group.protocol=consumer; librdkafka/Laravel: withOption('group.protocol', 'consumer'); franz-go: kgo.ServerSideBalancer() with a range or sticky balancer (the cooperative snippet shows both); franz-go's docs add "It is recommended to use this only if you are on Kafka 4.3+." Inspect with kafka-consumer-groups.sh --describe --members or kafka-groups.sh --list (4.0+).
Static membership Important
In plain words: Give each consumer instance a fixed name. If it restarts quickly, it gets its old partitions back and nobody else notices.
Common misunderstanding: "Static membership makes failover faster." It makes it slower: a dead static member is only replaced after session.timeout.ms. You trade restart churn for detection time.
Definition: Set group.instance.id (unique per instance, stable across restarts, e.g. the StatefulSet pod name). KIP-345: a static member leaving does not send LeaveGroup, and a rejoin with the same id within the session timeout returns the cached assignment without a rebalance. Two live instances with the same id: the newer one fences the older with FENCED_INSTANCE_ID (82). Works with both classic and KIP-848 protocols (and for Streams with group.protocol=streams from 4.4).
session.timeout.ms=45s, group.instance.id=billing-0
1 t=0 pod billing-0 stops for a rolling deploy (no LeaveGroup)
2 t=20s pod billing-0 starts, rejoins as billing-0 -> same partitions, no rebalance
3 if it never comes back: t=45s coordinator expires it -> one rebalanceReal scenario: Kubernetes StatefulSets of consumers with large local caches; MirrorMaker clusters (KIP-345's example of long rolling bounces).
Fix / how to use it: Java/librdkafka group.instance.id, franz-go kgo.InstanceID; raise session.timeout.ms to cover a restart; never reuse the id across two running pods.
Commit strategies Must-know
In plain words: Committing offset N says "everything before N is done". When you commit relative to processing decides whether a crash loses records or repeats them.
Common misunderstanding: "Auto-commit commits what I processed." The Java client commits what poll() returned, on a timer (auto.commit.interval.ms, default 5000), during later poll() calls. laravel-kafka's docs say its auto-commit mode commits "after your handler runs, even when it fails".
Definition: Options: auto-commit (enable.auto.commit=true), commitSync (blocks, retries), commitAsync (no wait, no retry; a later commit wins), commit per record, per batch, or per N records, and commit in onPartitionsRevoked. Committing before processing gives at-most-once; after processing gives at-least-once; inside a transaction with sendOffsetsToTransaction gives exactly-once for Kafka outputs. Commits carry the generation (or member epoch); stale ones fail. You can only commit a position, not individual records, so one failing record blocks everything after it in that partition unless you move it aside (retry topic or DLQ).
commit-after-process (at-least-once) commit-before-process (at-most-once)
1 poll -> [100..104] poll -> [100..104]
2 process 100..102 commit 105
3 crash process 100..102, crash
4 restart at last commit 100 -> 100..102 again restart at 105 -> 103, 104 never processedReal scenario: a charge applied twice after a crash (at-least-once without an idempotent handler); orders never shipped after an auto-commit committed them before a crash (at-most-once by accident); a poison record that blocks a partition for hours because the consumer refuses to commit past it.
| Strategy | Kafka API | Risk | When |
|---|---|---|---|
| Auto-commit | enable.auto.commit=true | Loss (commits before done) or duplicates | Metrics, logs |
| Sync per record | commitSync(record) | Slow (one round trip each) | Low volume, high value |
| Batch after processing | commitSync() after the loop, franz-go CommitRecords | Replays up to one batch | Default choice |
| Async + sync on close/revoke | commitAsync() + commitSync() in callbacks | Replays a few batches | High volume |
| Marks + autocommit | franz-go AutoCommitMarks + MarkCommitRecords | Replays up to one interval | Go services |
| Transactional | sendOffsetsToTransaction | None for Kafka outputs | Kafka-to-Kafka |
Fix / how to use it: disable auto-commit for anything that matters, commit after processing, make the handler idempotent (Message Acknowledgment compares this with RabbitMQ acks and Redis XACK).
Share groups: Queues for Kafka (KIP-932) Important
In plain words: A share group lets many consumers read the same partition at once, acknowledge each record separately, and get failed records redelivered, like a work queue, but on an ordinary topic.
Common misunderstanding: "Share groups replace consumer groups." They give up per-partition ordering to get queue semantics. Event processing that needs order still uses consumer groups.
Definition: KIP-932's motivation: "Users of Kafka often have to “over-partition” simply to ensure they can have sufficient parallel consumption to cope with peak loads." In a share group, fetched records are acquired under a time-limited lock (group.share.record.lock.duration.ms, default 30000). The consumer can ACCEPT (done), RELEASE (redeliver, maybe elsewhere), REJECT (unprocessable), or, since 4.2, RENEW the lock. Each record has a delivery count; at group.share.delivery.count.limit (default 5) it is archived, and from 4.4 (with share.version=2) rejected or exhausted records can go to a DLQ topic (errors.deadletterqueue.topic.name). The KIP describes it as "roughly equivalent to a “durable shared subscription” in existing systems". State lives in __share_group_state. A new share group starts at latest unless share.auto.offset.reset is set.
share group thumbnails, partition 0 holds records 50..59
1 C1 fetch -> acquires 50..54 (lock 30 s) C2 fetch -> acquires 55..59
2 C1 ACCEPT 50, 51, 53; RELEASE 52 (delivery count 1)
3 C2 crashes holding 55..59 -> locks expire -> available again
4 C3 fetch -> acquires 52, 55..59 (delivery counts 2, 1 ...)
5 record 52 fails 5 times -> archived (or to the DLQ topic on 4.4)Real scenario: image resizing, email sending, PDF rendering: independent jobs where you want 50 workers on a 6-partition topic; replacing a separate RabbitMQ only used for job fan-out inside a Kafka-only platform.
Fix / how to use it: Java KafkaShareConsumer; franz-go kgo.ShareGroup with r.Ack(kgo.AckAccept/AckRelease/AckReject) (the sharegroup snippet); kafka-share-groups.sh to inspect. librdkafka and therefore laravel-kafka do not expose a share consumer as of v2.13.
Delivery semantics on Kafka
Short version, the whole topic is Delivery Guarantees. At-most-once: commit before processing, or acks=0. At-least-once: acks=all + idempotent producer + commit after processing; duplicates come from consumer crashes and rebalances, so the handler must be idempotent (inbox). Exactly-once: idempotent + transactional producer, sendOffsetsToTransaction, read_committed consumers, all reads and writes in Kafka (Kafka Streams exactly_once_v2, franz-go GroupTransactSession). Producer-side "exactly once into the log" is idempotence; end-to-end exactly-once with an external system is idempotence on that system's side.
The ecosystem around the broker
Kafka Connect, SMTs and Debezium Important
The Connect docs: "Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other systems." A Connect cluster runs workers (standalone or distributed mode); a connector is either a source (database, S3, MQTT → Kafka) or a sink (Kafka → Elasticsearch, S3, JDBC). Tasks are spread across workers using the group protocol, and Connect stores its offsets, configs and status in compacted internal topics (4.4 adds internal.topics.automatic.creation.enable). Single Message Transforms (SMTs) do "lightweight message-at-a-time modifications" (rename fields, route by header, mask PII) in the connector pipeline; converters (JSON, Avro, Protobuf) serialize. Sink errors go to a DLQ topic with errors.tolerance=all and errors.deadletterqueue.topic.name. Connect is managed through a REST API (POST /connectors). Debezium is the common source connector for CDC: it reads the database's log (PostgreSQL logical replication, MySQL binlog) and emits change events; details in Change Data Capture and its use as an outbox relay in Outbox Pattern. MirrorMaker 2 is a set of Connect connectors that replicate topics between clusters.
Kafka Streams Good to know
"Kafka Streams is a client library for building applications and microservices, where the input and output data are stored in Kafka clusters." It is a JVM library, not a cluster: KStream/KTable, joins, windows, local RocksDB state stores backed by compacted changelog topics, and exactly-once via transactions. Event time, windows, watermarks and alternatives (Flink, ksqlDB) are taught in Stream Processing. Go has no official equivalent; teams use Flink, a franz-go consumer with local state, or Bento/Benthos-style pipelines.
Schema Registry Good to know
Kafka stores bytes and never looks inside. Confluent's docs: "Schema Registry provides a centralized repository for managing and validating schemas for topic message data". Serializers register Avro/Protobuf/JSON Schema, put a schema id in the first bytes of each value, and the registry enforces compatibility (BACKWARD by default) per subject (orders-value). Apicurio and Redpanda and WarpStream ship compatible registries. Compatibility modes and evolution rules: Message Design & Schema Evolution.
Tiered storage Important
KIP-405 starts from the operational pain: Kafka "is configured with a shorter retention period in days (typically 3 days)" and older data is copied elsewhere, so consumers need two code paths. Tiered storage splits the log into a local tier (broker disks, recent segments) and a remote tier (S3, GCS, HDFS through a RemoteStorageManager plugin). Enable with broker remote.log.storage.system.enable=true and topic remote.storage.enable=true; local.retention.ms / local.retention.bytes (default -2 = use retention.*) decide how much stays on disk while retention.ms covers both. Only closed segments are uploaded. Reads from old offsets are slower but use the same consumer API. Broker replacement and reassignment get much faster because there is less local data to copy; 4.3 added follower.fetch.last.tiered.offset.enable so a new follower starts from the last tiered offset. Compacted topics cannot use tiered storage.
Quotas Good to know
The design docs: without quotas "a small set of badly behaved clients can degrade user experience for the well behaved ones". Two kinds per (user, client-id) group, enforced per broker: byte-rate quotas (producer_byte_rate, consumer_byte_rate) and request-rate quotas (request_percentage of network and I/O thread time); plus controller_mutation_rate for topic creation (THROTTLING_QUOTA_EXCEEDED, 89). The broker does not reject: it computes a delay, returns it in the response and mutes the channel. Set with kafka-configs.sh --alter --add-config 'producer_byte_rate=10485760' --entity-type users --entity-name analytics. Clients see produce-throttle-time-avg and fetch-throttle-time-avg.
Security: SASL, TLS and ACLs Good to know
Listeners combine a transport and an auth mechanism (SASL_SSL, SSL, PLAINTEXT); SASL mechanisms are PLAIN, SCRAM-SHA-256/512, GSSAPI (Kerberos) and OAUTHBEARER (4.4 now fails fast if a JWKS endpoint is set without expected audience and issuer). Authorization uses ACLs (kafka-acls.sh --add --allow-principal User:billing --operation Read --topic orders --group billing) configured with authorizer.class.name; a denied request returns TOPIC_AUTHORIZATION_FAILED (29). Note that TLS disables the zero-copy sendfile path (Mechanics). The full treatment, including PII in immutable logs, is in Messaging Security.
Mechanics
Why it is fast: sequential I/O, page cache and sendfile Important
Kafka writes appends to the end of a file and lets the OS page cache hold recent data instead of keeping its own heap cache. Reads of recent data are served from memory, and the broker uses sendfile to copy file bytes from the page cache to the socket without going through user space. The design docs: "on a Kafka cluster where the consumers are mostly caught up you will see no read activity on the disks whatsoever as they will be serving data entirely from cache." The record batch format is the same on the wire, on disk and in the producer, so the broker never re-encodes. Two caveats from the same page: sendfile is not used when TLS is enabled, and a consumer reading far behind pulls cold segments from disk, evicting hot data for everyone (tiered storage and follower fetching from the closest replica, KIP-392 replica.selector.class, help).
producer batch (zstd) -> broker appends bytes as-is -> page cache -> sendfile -> consumer socket
1 no decompression on the broker (unless message format conversion or topic compression differs)
2 3 consumer groups reading the head = 1 disk write, 0 disk reads, 3 socket sendsEvery knob that matters
| Knob | Scope | Default (4.4) | Notes |
|---|---|---|---|
replication.factor | Topic | default.replication.factor | 3 in production |
min.insync.replicas | Topic | 1 | 2 with RF 3 |
unclean.leader.election.enable | Topic | false | |
retention.ms / retention.bytes | Topic | 604800000 / -1 | Bytes is per partition |
cleanup.policy | Topic | delete | compact, compact,delete |
segment.bytes / segment.ms | Topic | 1 GiB / 7 d | |
delete.retention.ms | Topic | 86400000 | Tombstone lifetime |
min.compaction.lag.ms / max.compaction.lag.ms | Topic | 0 / Long.MAX | |
max.message.bytes | Topic | 1048588 | Batch after compression |
message.timestamp.type | Topic | CreateTime | LogAppendTime |
remote.storage.enable | Topic | false | Tiered storage |
replica.lag.time.max.ms | Broker | 30000 | ISR eviction |
num.partitions | Broker/controller | 1 | Auto-created topics |
auto.create.topics.enable | Broker | true | Turn off in production |
offsets.topic.replication.factor | Broker | 3 | |
acks | Producer | all | |
enable.idempotence | Producer | true | librdkafka: false |
max.in.flight.requests.per.connection | Producer | 5 | ≤ 5 with idempotence |
retries / delivery.timeout.ms | Producer | 2147483647 / 120000 | Timeout is the real bound |
batch.size / linger.ms | Producer | 16384 / 5 | Linger was 0 before 4.0 |
compression.type | Producer | none | zstd, lz4 |
transactional.id / transaction.timeout.ms | Producer | null / 60000 | |
partitioner.class | Producer | built-in sticky/murmur2 | librdkafka partitioner |
group.protocol | Consumer | classic | consumer = KIP-848 |
partition.assignment.strategy | Consumer | Range, CooperativeSticky | Classic only |
group.instance.id | Consumer | null | Static membership |
session.timeout.ms / max.poll.interval.ms | Consumer | 45000 / 300000 | |
max.poll.records | Consumer | 500 | |
enable.auto.commit / auto.commit.interval.ms | Consumer | true / 5000 | |
auto.offset.reset | Consumer | latest | earliest, none, by_duration: |
isolation.level | Consumer | read_uncommitted | librdkafka: read_committed |
group.share.record.lock.duration.ms | Broker/group | 30000 | Share groups |
group.share.delivery.count.limit | Broker/group | 5 | Share groups |
Error codes you will catch
| Error (code) | Retriable | Meaning | What to do |
|---|---|---|---|
NOT_LEADER_OR_FOLLOWER (6) | Yes | Leadership moved | Client refreshes metadata; normal during restarts |
FENCED_LEADER_EPOCH (74) | Yes | Request used an old leader epoch | Same |
NOT_ENOUGH_REPLICAS (19) | Yes | ISR below min.insync.replicas | Fix brokers; producer retries until delivery.timeout.ms |
NOT_ENOUGH_REPLICAS_AFTER_APPEND (20) | Yes | Written but ISR shrank | Retry (idempotence dedups) |
OFFSET_OUT_OF_RANGE (1) | No | Offset deleted by retention or never existed | auto.offset.reset or explicit seek |
MESSAGE_TOO_LARGE (10) | No | Batch over max.message.bytes | Smaller records, claim-check |
UNKNOWN_TOPIC_OR_PARTITION (3) | Yes | Topic missing or metadata stale | Create topic; disable auto-create |
COORDINATOR_NOT_AVAILABLE (15) | Yes | Group/txn coordinator moving | Retry |
REBALANCE_IN_PROGRESS (27) | No | Commit during classic rebalance | Rejoin, then commit |
ILLEGAL_GENERATION (22) / UNKNOWN_MEMBER_ID (25) | No | Commit from an old generation or kicked member | Records will be redelivered to the new owner |
FENCED_INSTANCE_ID (82) | No | Two instances share group.instance.id | Fix deployment |
FENCED_MEMBER_EPOCH (110) / STALE_MEMBER_EPOCH (113) | No | KIP-848 member out of date | Client rejoins / retries |
OUT_OF_ORDER_SEQUENCE_NUMBER (45) | No | Idempotent sequence gap | Producer resets; investigate data loss |
INVALID_PRODUCER_EPOCH (47) / PRODUCER_FENCED (90) | No | A newer instance with the same transactional.id | Close this producer |
TOPIC_AUTHORIZATION_FAILED (29) | No | ACL denies | Add ACL |
THROTTLING_QUOTA_EXCEEDED (89) | Yes | Controller mutation quota | Back off |
Go
Before
acks=1, idempotence switched off, no key, a fire-and-forget produce with no error callback, and a consumer whose greedy auto-commit commits what it polled on a timer while processing is still running.
// Command before shows a Kafka producer and consumer that "work" in a demo
// and lose or duplicate events in production.
package main
import (
"context"
"log"
"os"
"strings"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
seeds := strings.Split(brokers, ",")
ctx := context.Background()
// Producer: acks=1 means only the partition leader has the record when
// we are told "ok". If the leader dies before followers fetch it, the
// record is gone. Idempotence is off, so a retried batch can be written
// twice. No key, so events for one order land on any partition and lose
// their relative order.
producer, err := kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.RequiredAcks(kgo.LeaderAck()),
kgo.DisableIdempotentWrite(),
)
if err != nil {
log.Fatal(err)
}
defer producer.Close()
producer.Produce(ctx, &kgo.Record{
Topic: "orders",
Value: []byte(`{"order_id":"o-42","status":"paid"}`),
}, nil) // fire and forget: the error callback is nil
// Consumer: greedy auto-commit commits whatever has been polled every
// second, on a background timer, whether or not we have finished
// processing it. A crash mid-batch skips the rest of the batch forever.
consumer, err := kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
kgo.GreedyAutoCommit(),
kgo.AutoCommitInterval(time.Second),
)
if err != nil {
log.Fatal(err)
}
defer consumer.Close()
for {
fetches := consumer.PollFetches(ctx)
fetches.EachRecord(func(r *kgo.Record) {
chargeCustomer(r.Value) // slow; offsets may already be committed
})
}
}
func chargeCustomer(payload []byte) { time.Sleep(200 * time.Millisecond); _ = payload }After
franz-go with acks=all and idempotence (its defaults, spelled out), keyed records so one order stays in one partition, ProduceSync so errors surface, and a group consumer that commits only the records it finished, with rebalances blocked during a batch.
// Command after shows a durable producer and an at-least-once consumer on
// franz-go: acks=all + idempotence on the way in, commit-after-process on
// the way out.
package main
import (
"context"
"encoding/json"
"errors"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
type OrderPaid struct {
OrderID string `json:"order_id"`
Amount int64 `json:"amount_cents"`
}
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
seeds := strings.Split(brokers, ",")
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := publish(ctx, seeds, OrderPaid{OrderID: "o-42", Amount: 1999}); err != nil {
log.Fatal(err)
}
if err := consume(ctx, seeds); err != nil && !errors.Is(err, context.Canceled) {
log.Fatal(err)
}
}
func publish(ctx context.Context, seeds []string, evt OrderPaid) error {
// These are franz-go's defaults; they are spelled out because they are
// the point. acks=all waits for every in-sync replica, and the topic's
// min.insync.replicas (set it to 2 with replication factor 3) decides
// how small the ISR may shrink before writes are refused. Idempotence
// lets the broker drop duplicates created by our own retries.
cl, err := kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.RequiredAcks(kgo.AllISRAcks()),
kgo.ProducerLinger(5*time.Millisecond), // trade 5ms for bigger batches
)
if err != nil {
return err
}
defer cl.Close()
value, err := json.Marshal(evt)
if err != nil {
return err
}
// The key picks the partition (murmur2 hash, like the Java client), so
// every event for o-42 is in one partition, in order.
rec := &kgo.Record{Topic: "orders", Key: []byte(evt.OrderID), Value: value}
return cl.ProduceSync(ctx, rec).FirstErr()
}
func consume(ctx context.Context, seeds []string) error {
cl, err := kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
kgo.DisableAutoCommit(), // we decide when the position moves
kgo.BlockRebalanceOnPoll(), // no partition moves mid-batch
)
if err != nil {
return err
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if err := ctx.Err(); err != nil {
return err
}
fetches.EachError(func(topic string, p int32, err error) {
log.Printf("fetch %s/%d: %v", topic, p, err)
})
var done []*kgo.Record
var procErr error
fetches.EachRecord(func(r *kgo.Record) {
if procErr != nil {
return // stop at the first failure; later offsets stay uncommitted
}
if procErr = handle(ctx, r); procErr == nil {
done = append(done, r)
}
})
// Commit only what was processed. A crash before this line means
// redelivery, so handle must be idempotent (see the inbox pattern).
if len(done) > 0 {
if err := cl.CommitRecords(ctx, done...); err != nil {
log.Printf("commit: %v", err)
}
}
cl.AllowRebalance()
if procErr != nil {
return procErr // restart; the group resumes at the last commit
}
}
}
func handle(ctx context.Context, r *kgo.Record) error {
var evt OrderPaid
if err := json.Unmarshal(r.Value, &evt); err != nil {
return err
}
_ = ctx // charge the customer, keyed by evt.OrderID for idempotency
return nil
}A production-shaped consumer: cooperative-sticky balancing, static membership, marks-based auto-commit, a commit on revoke, and the KIP-848 variant.
// Command cooperative is a production-shaped group consumer on franz-go:
// cooperative-sticky rebalancing (KIP-429), static membership (KIP-345),
// marks-based commits, and a final commit when partitions are revoked.
// A second constructor shows the KIP-848 broker-side protocol instead.
package main
import (
"context"
"errors"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
cl, err := newClassicConsumer(strings.Split(brokers, ","))
if err != nil {
log.Fatal(err)
}
defer cl.Close() // leaves the group (a static member only stops heartbeating)
for {
fetches := cl.PollRecords(ctx, 500) // like max.poll.records
if errors.Is(ctx.Err(), context.Canceled) {
// Last synchronous commit of everything marked before leaving.
if err := cl.CommitMarkedOffsets(context.Background()); err != nil {
log.Printf("final commit: %v", err)
}
return
}
fetches.EachError(func(t string, p int32, err error) {
log.Printf("fetch %s/%d: %v", t, p, err)
})
fetches.EachRecord(func(r *kgo.Record) {
if err := process(ctx, r); err != nil {
// Do not mark: the offset stays behind this record. A real
// service would publish to a retry topic here and then mark.
log.Printf("process %s/%d@%d: %v", r.Topic, r.Partition, r.Offset, err)
return
}
cl.MarkCommitRecords(r) // eligible for the next (auto) commit
})
cl.AllowRebalance()
}
}
func newClassicConsumer(seeds []string) (*kgo.Client, error) {
host, _ := os.Hostname()
var cl *kgo.Client
var err error
cl, err = kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
// Cooperative: only the partitions that move are revoked; everyone
// else keeps fetching during the rebalance.
kgo.Balancers(kgo.CooperativeStickyBalancer()),
// Static membership: a restart with the same id inside the session
// timeout gets its old partitions back without a rebalance.
kgo.InstanceID("billing-"+host),
kgo.SessionTimeout(45*time.Second),
// Commit only what we marked, every 5 s, plus on revoke below.
kgo.AutoCommitMarks(),
kgo.AutoCommitInterval(5*time.Second),
kgo.BlockRebalanceOnPoll(),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), // auto.offset.reset=earliest
kgo.OnPartitionsRevoked(func(ctx context.Context, c *kgo.Client, _ map[string][]int32) {
// The next owner starts from the last commit: commit our work now.
if err := c.CommitMarkedOffsets(ctx); err != nil {
log.Printf("commit on revoke: %v", err)
}
}),
)
return cl, err
}
// newNextGenConsumer opts into the KIP-848 consumer protocol
// (group.protocol=consumer): the broker's group coordinator computes the
// assignment, there is no group-wide sync barrier, and members reconcile
// incrementally. franz-go needs a range or sticky balancer here and advises
// Kafka 4.3+ brokers for this mode.
func newNextGenConsumer(seeds []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(seeds...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
kgo.ServerSideBalancer(),
kgo.Balancers(kgo.StickyBalancer()),
kgo.AutoCommitMarks(),
)
}
var _ = newNextGenConsumer
func process(ctx context.Context, r *kgo.Record) error {
_ = ctx // idempotent side effect keyed by the order id in r.Key
if len(r.Value) == 0 {
return errors.New("empty value")
}
return nil
}For Kafka-to-Kafka pipelines, a GroupTransactSession puts the output records and the input offsets in one transaction and aborts if a rebalance takes the partitions away first.
// Command transactional sketches Kafka's exactly-once consume-transform-produce
// loop: output records and the consumer's offsets commit in ONE transaction.
// It covers Kafka-to-Kafka only; a database write inside the loop is not
// part of the transaction.
package main
import (
"bytes"
"context"
"log"
"os"
"strings"
"sync"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
ctx := context.Background()
// A GroupTransactSession is a group consumer plus a transactional
// producer that aborts the open transaction if a rebalance takes our
// partitions away before we commit.
sess, err := kgo.NewGroupTransactSession(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.TransactionalID("invoice-enricher-1"), // stable per instance; fences zombies
kgo.ConsumerGroup("invoice-enricher"),
kgo.ConsumeTopics("orders"),
kgo.FetchIsolationLevel(kgo.ReadCommitted()), // skip aborted upstream writes
kgo.RequireStableFetchOffsets(),
)
if err != nil {
log.Fatal(err)
}
defer sess.Close()
for {
fetches := sess.PollFetches(ctx)
if fetches.Empty() {
continue
}
if err := sess.Begin(); err != nil {
log.Fatal(err)
}
var (
mu sync.Mutex
prodErr error
wg sync.WaitGroup
)
fetches.EachRecord(func(in *kgo.Record) {
out := &kgo.Record{
Topic: "invoices",
Key: in.Key, // keep per-order ordering downstream
Value: bytes.ToUpper(in.Value),
}
wg.Add(1)
sess.Produce(ctx, out, func(_ *kgo.Record, err error) {
defer wg.Done()
if err != nil {
mu.Lock()
prodErr = err
mu.Unlock()
}
})
})
wg.Wait()
// End commits the produced records AND the polled offsets together,
// or aborts both. read_committed consumers of "invoices" never see
// an aborted batch.
end := kgo.TryCommit
if prodErr != nil {
end = kgo.TryAbort
}
committed, err := sess.End(ctx, end)
if err != nil {
log.Fatal(err) // not retryable: the transactional ID is fenced or failed
}
if !committed {
log.Println("aborted; the group will redeliver from the last committed offset")
}
}
}A KIP-932 share-group worker with per-record accept, release and reject.
// Command sharegroup consumes through a KIP-932 share group ("Queues for
// Kafka", production-ready since Kafka 4.2): records from one partition can go
// to many consumers, each record is acquired under a time-limited lock and
// acknowledged one by one, and the broker counts deliveries.
package main
import (
"context"
"errors"
"log"
"os"
"os/signal"
"strings"
"github.com/twmb/franz-go/pkg/kgo"
)
var errPoison = errors.New("unprocessable")
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
cl, err := kgo.NewClient(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.ShareGroup("thumbnails"), // not ConsumerGroup: no partition ownership
kgo.ConsumeTopics("image-uploaded"),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
for ctx.Err() == nil {
fetches := cl.PollRecords(ctx, 100)
fetches.EachRecord(func(r *kgo.Record) {
switch err := resize(ctx, r); {
case err == nil:
r.Ack(kgo.AckAccept) // done; never redelivered
case errors.Is(err, errPoison):
r.Ack(kgo.AckReject) // give up; with share.version=2 it can go to a DLQ topic
default:
r.Ack(kgo.AckRelease) // try again, maybe on another consumer
}
})
// Acks ride on the next poll; flush them before we block again.
if err := cl.FlushAcks(ctx); err != nil && !errors.Is(err, context.Canceled) {
log.Printf("flush acks: %v", err)
}
}
}
func resize(ctx context.Context, r *kgo.Record) error {
_ = ctx
if len(r.Value) == 0 {
return errPoison
}
return nil
}Topic creation with safe configs, a compacted topic, and consumer lag with kadm.
// Command admin uses kadm (franz-go's admin client) for the three things
// operators script most: create a durable topic, create a compacted topic,
// and compute consumer-group lag.
package main
import (
"context"
"log"
"os"
"strings"
"time"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kgo"
)
func ptr(s string) *string { return &s }
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
cl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...))
if err != nil {
log.Fatal(err)
}
defer cl.Close()
adm := kadm.NewClient(cl)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Event topic: RF 3 + min ISR 2 + acks=all on the producer means one
// broker can die without losing or refusing a write.
if _, err := adm.CreateTopic(ctx, 12, 3, map[string]*string{
"min.insync.replicas": ptr("2"),
"retention.ms": ptr("604800000"), // 7 days
"unclean.leader.election.enable": ptr("false"),
}, "orders"); err != nil {
log.Printf("create orders: %v", err)
}
// State topic: latest value per key forever; null value = tombstone.
if _, err := adm.CreateTopic(ctx, 6, 3, map[string]*string{
"cleanup.policy": ptr("compact"),
"min.insync.replicas": ptr("2"),
"delete.retention.ms": ptr("86400000"), // tombstones visible for 24 h
}, "customer-profile"); err != nil {
log.Printf("create customer-profile: %v", err)
}
// Lag = log end offset - committed offset, per partition.
lags, err := adm.Lag(ctx, "billing")
if err != nil {
log.Fatal(err)
}
lags.Each(func(l kadm.DescribedGroupLag) {
if l.Error() != nil {
log.Printf("group %s: %v", l.Group, l.Error())
return
}
for _, m := range l.Lag.Sorted() {
log.Printf("%s %s/%d committed=%d end=%d lag=%d",
l.Group, m.Topic, m.Partition, m.Commit.At, m.End.Offset, m.Lag)
}
if total := l.Lag.Total(); total > 10_000 {
log.Printf("ALERT group %s total lag %d", l.Group, total)
}
})
}The partitioner, runnable without a broker (used in the lab).
// Command partitioner runs without a broker. It asks franz-go's default key
// partitioner (murmur2, the same hash as the Java client) where each key
// lands, first with 6 partitions and then after growing the topic to 8.
// Same key, same partition: until the partition count changes.
package main
import (
"fmt"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
keys := []string{"o-41", "o-42", "o-43", "o-44", "o-45", "o-46"}
p := kgo.StickyKeyPartitioner(nil).ForTopic("orders")
moved := 0
for _, k := range keys {
r := &kgo.Record{Key: []byte(k)}
before := p.Partition(r, 6) // orders created with 6 partitions
after := p.Partition(r, 8) // kafka-topics.sh --alter --partitions 8
mark := ""
if before != after {
mark = " <- moved: per-key order breaks across the change"
moved++
}
fmt.Printf("key=%s 6 partitions -> p%d 8 partitions -> p%d%s\n", k, before, after, mark)
}
fmt.Printf("%d of %d keys changed partition\n", moved, len(keys))
}The Go angle
Three clients matter. github.com/twmb/franz-go/pkg/kgo is pure Go; its README lists "Full Exactly-Once-Semantics (EOS)", "Idempotent & transactional producers", cooperative-sticky balancing, KIP-848 (ServerSideBalancer) and KIP-932 share groups (ShareGroup). Its defaults are AllISRAcks, idempotent writes and a murmur2 key hash that matches Java. Its auto-commit commits the previous poll by default; AutoCommitMarks commits only what you mark; GreedyAutoCommit commits everything polled and its docs warn it "may result in message loss". kadm is the admin client (topics, configs, ACLs, lag). github.com/segmentio/kafka-go is pure Go with a simpler API and fewer protocol features. confluent-kafka-go wraps librdkafka through cgo, so it shares librdkafka's defaults (CRC32 partitioner, enable.idempotence=false). Go's own contribution is shape: one goroutine per partition preserves order (kgo.Client.PauseFetchPartitions for backpressure), a bounded channel between poll and work is your buffer (Backpressure), and signal.NotifyContext gives a clean final commit on shutdown. Note the module: franz-go v1.22 requires Go 1.26.
Laravel
Before
Kafka::asyncPublish() from mateusjunges/laravel-kafka holds one producer per request and flushes only at shutdown. With no options set, librdkafka's defaults apply: enable.idempotence=false and no key. The consumer keeps the package default auto-commit.
<?php
// app/Services/OrderEvents.php — publish and hope.
namespace App\Services;
use App\Models\Order;
use Junges\Kafka\Facades\Kafka;
final class OrderEvents
{
public function paid(Order $order): void
{
// asyncPublish keeps one producer per request and only flushes it
// when the application shuts down. If the PHP worker dies first,
// the buffered record is gone and nobody hears about it.
//
// Nothing is configured, so librdkafka's defaults apply:
// enable.idempotence=false (a retried batch can be written twice)
// and no key, so events for one order are spread across partitions
// and arrive in any order.
Kafka::asyncPublish()
->onTopic('orders')
->withBody(['order_id' => $order->id, 'status' => 'paid'])
->send();
}
}
// routes/console.php — a consumer on the package defaults.
//
// config/kafka.php ships with 'auto_commit' => true. The package docs say
// that in this mode "the offset of each message is committed after your
// handler runs, even when it fails", so a failed charge is skipped.
//
// Artisan::command('billing:consume', function () {
// Kafka::consumer(['orders'], 'billing')
// ->withHandler(fn ($message) => app(Billing::class)->charge($message->getBody()))
// ->build()
// ->consume();
// });After
Kafka::publish() flushes after each send and throws CouldNotPublishMessage on failure; withConfigOptions() passes acks, enable.idempotence, partitioner and compression.type straight to librdkafka, and withKafkaKey() sets the key.
<?php
// app/Services/OrderEvents.php — a durable, keyed, idempotent publish.
namespace App\Services;
use App\Models\Order;
use Junges\Kafka\Exceptions\CouldNotPublishMessage;
use Junges\Kafka\Facades\Kafka;
final class OrderEvents
{
/** @throws CouldNotPublishMessage when the flush fails after retries */
public function paid(Order $order): void
{
// publish() flushes after every send and throws if the broker did
// not acknowledge, so the caller knows. Raw librdkafka properties
// go through withConfigOptions().
Kafka::publish()
->onTopic('orders')
->withConfigOptions([
'acks' => 'all', // every in-sync replica
'enable.idempotence' => 'true', // broker drops our retry duplicates
'partitioner' => 'murmur2_random', // same key -> partition as Java/franz-go
'compression.type' => 'zstd', // compresses whole batches
'linger.ms' => 5,
])
->withKafkaKey((string) $order->id) // per-order ordering
->withHeaders(['event-type' => 'order.paid'])
->withBody([
'order_id' => $order->id,
'amount_cents' => $order->total_cents,
])
->send();
}
}A handler class (the package's Handler contract) that writes idempotently and commits only on success:
<?php
// app/Kafka/ProcessOrderHandler.php — a handler class with commit-after-process.
namespace App\Kafka;
use Illuminate\Support\Facades\DB;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\Handler;
use Junges\Kafka\Contracts\MessageConsumer;
final class ProcessOrderHandler implements Handler
{
public function __invoke(ConsumerMessage $message, MessageConsumer $consumer): void
{
$event = $message->getBody(); // the default JSON deserializer returns an array
// At-least-once means this can run twice for one event, so the
// write is idempotent: payments.order_id has a UNIQUE index.
DB::table('payments')->insertOrIgnore([
'order_id' => $event['order_id'],
'amount_cents' => $event['amount_cents'],
'kafka_partition' => $message->getPartition(),
'kafka_offset' => $message->getOffset(),
'created_at' => now(),
]);
// Only reached on success. Committing offset N also commits every
// earlier offset of this partition.
$consumer->commit($message);
}
}The long-running consumer command: manual commit, cooperative-sticky, static membership, read_committed, retries and stop-on-failure.
<?php
// app/Console/Commands/ConsumeOrders.php — a long-running group consumer.
namespace App\Console\Commands;
use App\Kafka\ProcessOrderHandler;
use Illuminate\Console\Command;
use Junges\Kafka\Config\RebalanceStrategy;
use Junges\Kafka\Facades\Kafka;
final class ConsumeOrders extends Command
{
protected $signature = 'billing:consume';
protected $description = 'Charge paid orders from the orders topic';
public function handle(): void
{
Kafka::consumer(['orders'], 'billing')
->withManualCommit()
// Incremental rebalancing: only moved partitions are revoked.
->withRebalanceStrategy(RebalanceStrategy::COOPERATIVE_STICKY)
->withOptions([
// Static membership: a deploy that restarts this pod within
// session.timeout.ms does not trigger a rebalance.
'group.instance.id' => 'billing-'.gethostname(),
'session.timeout.ms' => 45000,
'max.poll.interval.ms' => 300000, // a slower handler is kicked out
'auto.offset.reset' => 'earliest',
'isolation.level' => 'read_committed',
])
->retryFailedMessages(3, backoffInMs: 1000)
->stopOnFailure() // stop without committing; the partition resumes here
->withHandler(new ProcessOrderHandler())
->build()
->consume();
}
}The three commit modes side by side (auto, synchronous per record, asynchronous every N):
<?php
// app/Console/Commands/ConsumeClicks.php — the three commit modes side by side.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
final class ConsumeClicks extends Command
{
protected $signature = 'analytics:consume {mode=batch}';
protected $description = 'Consume click events with a chosen commit mode';
public function handle(): void
{
$builder = Kafka::consumer(['clicks'], 'analytics');
match ($this->argument('mode')) {
// 1. Auto commit (package default): the offset is committed after
// the handler runs, even when it failed. Fine for metrics.
'auto' => $builder->withAutoCommit()
->withHandler(fn (ConsumerMessage $m) => $this->count($m)),
// 2. Manual, synchronous: one round trip per record. Safest, slowest.
'sync' => $builder->withManualCommit()
->withHandler(function (ConsumerMessage $m, MessageConsumer $c): void {
$this->count($m);
$c->commit($m);
}),
// 3. Manual, batched and asynchronous: commit every 100th record
// without waiting. A crash replays at most ~100 records.
default => $builder->withManualCommit()
->withHandler(function (ConsumerMessage $m, MessageConsumer $c): void {
$this->count($m);
if ($m->getOffset() % 100 === 0) {
$c->commitAsync($m);
}
}),
};
$builder->build()->consume();
}
private function count(ConsumerMessage $message): void
{
// Increment a counter keyed by page; idempotence is not needed for
// approximate analytics, which is why auto commit is acceptable here.
}
}An atomic two-topic write with the transactional producer:
<?php
// app/Services/LedgerPublisher.php — atomic multi-topic write with a
// transactional producer. Readers must use isolation.level=read_committed.
namespace App\Services;
use Junges\Kafka\Exceptions\Transactions\TransactionShouldBeAbortedException;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
final class LedgerPublisher
{
public function transfer(string $transferId, string $from, string $to, int $cents): void
{
// A stable transactional.id per process: a restarted instance
// with the same id fences the old one (PRODUCER_FENCED).
$producer = Kafka::publish()
->withTransactionalId('ledger-'.gethostname())
->withConfigOptions(['transaction.timeout.ms' => 60000])
->build();
$producer->beginTransaction();
try {
$producer->produce(Message::create('ledger-debits')
->withKey($from)
->withBody(['transfer_id' => $transferId, 'cents' => $cents]));
$producer->produce(Message::create('ledger-credits')
->withKey($to)
->withBody(['transfer_id' => $transferId, 'cents' => $cents]));
// Both records become visible to read_committed consumers, or neither.
$producer->commitTransaction();
} catch (TransactionShouldBeAbortedException $e) {
$producer->abortTransaction();
throw $e;
}
// Not covered: this package has no sendOffsetsToTransaction(), so a
// consume-transform-produce loop in PHP is at-least-once, not EOS.
}
}The Laravel angle
Kafka is not a Laravel queue driver. The Laravel 13 queue docs list connection configurations for "the database, Amazon SQS, Redis, and Beanstalkd drivers" plus sync and null, so Kafka arrives through a package and its own long-running Artisan command (run under Supervisor or as a Kubernetes Deployment), not queue:work. mateusjunges/laravel-kafka (v2.13, PHP 8.2+, Laravel 12+) sits on the rdkafka extension, so librdkafka's defaults apply, not Java's: acks is -1 (all), enable.idempotence is false, isolation.level is read_committed, group.protocol is classic, and the default partitioner is consistent_random (CRC32). A PHP producer and a Go or Java producer writing the same keys put them on different partitions unless you set murmur2_random. The builder offers withRebalanceStrategy() (RANGE, ROUND_ROBIN, STICKY, COOPERATIVE_STICKY), withDlq() (default topic <topic>-dlq), withCommitBatchSize(), retryFailedMessages(), stopOnFailure(), middlewares and withSasl(). The producer has withTransactionalId() and beginTransaction()/commitTransaction()/abortTransaction(), but nothing that adds consumer offsets to a transaction, so consume-transform-produce in PHP is at-least-once. For "save the order and publish the event" inside a request, write an outbox row in the same DB::transaction and relay it (Outbox Pattern); Kafka::fake() exists for tests (Testing Messaging). How Laravel's own queue workers compare: Laravel Queue Internals.
Compared with the others
| Design choice | Kafka | RabbitMQ | Redis Streams |
|---|---|---|---|
| Core abstraction | Partitioned log | Queues behind exchanges (plus streams) | One in-memory log per key |
| Consumer position | Offset per partition per group | Per-message ack (queues); offset (streams) | Last-delivered ID per group + PEL per consumer |
| Redelivery of one failed message | No (classic groups); yes in share groups | Yes (nack, requeue, x-delivery-limit) | Yes (XCLAIM, XAUTOCLAIM) |
| Ordering | Per partition | Per queue (single consumer) | Per stream |
| Replay | Seek to any retained offset | Streams only | XRANGE, XREADGROUP from ID |
| Retention | Time/size/compaction, on disk, tiered | Until acked (queues); size/age (streams) | MAXLEN/MINID trim, memory-bound |
| Replication | ISR, min.insync.replicas | Raft (quorum queues, streams) | Async replicas |
| Routing | Producer picks topic and key | Exchanges and bindings | Client picks stream key |
| Delayed delivery | None | Plugin or TTL + DLX | Build with sorted sets |
| Throughput sweet spot | Very high, many readers | Moderate to high, complex routing | Moderate, low latency |
RabbitMQ
RabbitMQ queues track each message: a consumer acks, nacks or rejects it individually, unacked messages are redelivered, and acked ones are deleted. That gives per-message retry, priorities, TTL, dead-lettering and a delivery limit out of the box, all things Kafka makes you build from topics (or, since 4.2, get from share groups). Kafka gives what classic queues do not: retention independent of consumption, cheap replay, and any number of independent groups reading the same data without copying it into a queue each. Replication differs too: quorum queues and streams use Raft (3 nodes to survive 1 failure, latency set by the faster majority); Kafka uses the ISR (2 copies survive 1 failure, latency set by the slowest ISR member). RabbitMQ streams narrow the gap with what their docs call "non-destructive consumer semantics", and super streams add partitioning, but routing still happens in exchanges, while in Kafka it happens when the producer picks a topic and key. The same consumer, written for RabbitMQ:
// Command vs-rabbitmq is the RabbitMQ shape of the Kafka consumer on this
// page: the broker tracks every message, the consumer acks or nacks each
// one, and an acked message is gone. Compare with Kafka's single committed
// offset per partition.
package main
import (
"context"
"log"
"os"
"os/signal"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Println("AMQP_URL not set; nothing to do")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// A quorum queue is RabbitMQ's replicated queue (Raft); a dead-letter
// exchange gives per-message parking that Kafka makes you build.
if _, err := ch.QueueDeclare("billing", true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-delivery-limit": 5,
"x-dead-letter-exchange": "billing.dlx",
}); err != nil {
log.Fatal(err)
}
if err := ch.Qos(50, 0, false); err != nil { // prefetch: at most 50 unacked
log.Fatal(err)
}
msgs, err := ch.Consume("billing", "billing-1", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for {
select {
case <-ctx.Done():
return
case d, ok := <-msgs:
if !ok {
return
}
if len(d.Body) == 0 {
_ = d.Nack(false, false) // this ONE message goes to the DLX; others continue
continue
}
_ = d.Ack(false) // this message is deleted from the queue
}
}
}See RabbitMQ in Depth for exchanges, quorum queues and streams.
Redis Streams
A Redis stream "acts like an append-only log", with consumer groups, which looks like Kafka, but delivery tracking is per entry: each group has a pending entries list (PEL) that XACK clears and XCLAIM/XAUTOCLAIM can hand to another consumer, so one failing entry does not block the rest. There are no partitions: one stream is one ordered sequence on one shard, and you scale by sharding streams yourself (Redis Cluster places each stream key on one slot). Retention is MAXLEN/MINID trimming in memory, durability follows AOF/RDB persistence and asynchronous replication, not an ISR, so an acknowledged XADD can be lost on failover. It fits modest volume and short history in a stack that already runs Redis. The same consumer on Redis Streams:
// Command vs-redis is the Redis Streams shape of the same consumer: one
// stream (no partitions), a consumer group with a pending entries list
// (PEL) per consumer, XACK per entry, and XAUTOCLAIM to steal entries from
// a dead consumer. Retention is trimming, not time-based segments.
package main
import (
"context"
"log"
"os"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Println("REDIS_ADDR not set; nothing to do")
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
// Produce: MAXLEN ~ caps memory; it is the closest thing to retention.bytes.
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "orders", MaxLen: 1_000_000, Approx: true,
Values: map[string]any{"order_id": "o-42", "amount_cents": 1999},
}).Err(); err != nil {
log.Fatal(err)
}
// "$" = only new entries, like auto.offset.reset=latest; MKSTREAM creates it.
_ = rdb.XGroupCreateMkStream(ctx, "orders", "billing", "$").Err()
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "billing", Consumer: "billing-1",
Streams: []string{"orders", ">"}, Count: 50, Block: 5 * time.Second,
}).Result()
if err != nil && err != redis.Nil {
log.Fatal(err)
}
for _, s := range res {
for _, m := range s.Messages {
// Ack is per entry: a failure on one entry does not hold back the rest.
_ = rdb.XAck(ctx, "orders", "billing", m.ID).Err()
}
}
// Entries pending > 60 s on any consumer move to us (no rebalance exists).
claimed, _, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: "orders", Group: "billing", Consumer: "billing-1",
MinIdle: time.Minute, Start: "0-0", Count: 100,
}).Result()
if err != nil {
log.Fatal(err)
}
log.Printf("reclaimed %d stuck entries", len(claimed))
}See Redis Streams & Pub/Sub, and Broker Comparison for the decision table across all three plus NATS, Pulsar and SQS (Other Brokers).
Operations
Metrics that matter Must-know
| Metric (JMX name) | Healthy | Alarm means |
|---|---|---|
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions | 0 | A follower is out of the ISR: broker down, disk or network slow |
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount | 0 | acks=all writes are being refused |
kafka.controller:type=KafkaController,name=OfflinePartitionsCount | 0 | Partitions with no leader: data unavailable |
kafka.controller:type=KafkaController,name=ActiveControllerCount | 1 (cluster sum) | 0 = no controller, >1 = split brain |
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec / IsrExpandsPerSec | ~0 | Flapping replicas |
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec | 0 | Data was lost |
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce (and FetchConsumer, FetchFollower) | Stable p99 | Produce/fetch latency; break down with RequestQueueTimeMs, LocalTimeMs, RemoteTimeMs |
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent | > 0.3 | Broker CPU-saturated |
Consumer records-lag-max (client) | Small, flat | Consumer falling behind |
Group lag from kafka-consumer-groups.sh --describe / kadm.Lag / Burrow / exporters | Flat | Lag growing = consumers slower than producers |
Consumer lag is log end offset minus committed offset, per partition. Alert on its trend and on lag in seconds (age of the oldest unconsumed record), not on a raw number: 50,000 records is nothing for clickstream and an outage for payments. The client-side records-lag-max uses the consumer's current position, not the committed offset, so it understates lag during reprocessing. Exporting these to Prometheus and tracing through headers is covered in Messaging Observability.
Capacity and partition count Important
Partitions are the unit of parallelism and also a cost: each has file handles, memory maps, replication fetches and a leader to elect on failure. Jun Rao's Confluent post gives the rough formula: measure single-partition throughput for production (p) and consumption (c); for target t "you need to have at least max(t/p, t/c) partitions". The same 2015 post suggested limiting partitions "per broker to two to four thousand and the total number of partitions in the cluster to low tens of thousand" for ZooKeeper-era failover times; KRaft was designed to raise this (KIP-500 targets brokers starting fast with "hundreds of thousands or even millions of partitions"), but per-broker file handles, memory and replication traffic still bound it.
| Question | Rule of thumb |
|---|---|
| How many partitions for a new topic? | max(peak consumers, t/p, t/c) with 1.5–2× headroom; round to a number with many divisors (12, 24, 48) |
| Will I add partitions later? | Avoid on keyed topics; choose generously up front |
| Replication factor? | 3; 2 only for re-creatable data |
| Brokers? | Enough that one broker's loss leaves disk, network and CPU headroom; 3 minimum, racks/AZs ≥ RF |
| Disk? | ingress × retention × RF ÷ brokers, + 30% for compaction/rebalancing headroom; or tiered storage |
| Message size? | Keep under 1 MB; large payloads in object storage with a reference |
Topic configs, reassignment and leadership
Per-topic overrides are changed online with kafka-configs.sh --alter --entity-type topics --entity-name orders --add-config retention.ms=259200000. Partitions move between brokers with kafka-reassign-partitions.sh in three modes (--generate, --execute, --verify); throttle the copy with --throttle so reassignment does not starve clients, and remove the throttle with --verify when done. After restarts, kafka-leader-election.sh --election-type preferred --all-topic-partitions (or auto.leader.rebalance.enable=true) moves leadership back to preferred replicas. 4.3 added cordoned.log.dirs so new partitions avoid a log directory you plan to remove. Cruise Control (LinkedIn) automates rebalancing on big clusters.
# 1. which partitions to move, to brokers 4,5,6
cat > move.json <<'EOF'
{"version":1,"topics":[{"topic":"orders"}]}
EOF
kafka-reassign-partitions.sh --bootstrap-server b:9092 --topics-to-move-json-file move.json --broker-list "4,5,6" --generate
# 2. save the proposed plan as plan.json, execute it throttled to 50 MB/s
kafka-reassign-partitions.sh --bootstrap-server b:9092 --reassignment-json-file plan.json --execute --throttle 50000000
# 3. poll until done; this also removes the throttle
kafka-reassign-partitions.sh --bootstrap-server b:9092 --reassignment-json-file plan.json --verifyUpgrades
KRaft rolling upgrade per the 4.4 upgrade guide: upgrade brokers (and controllers) one at a time, verify, then finalize the metadata version with kafka-features.sh --bootstrap-server b:9092 upgrade --release-version 4.4. Metadata downgrades are not supported across versions with metadata changes. Coming from ZooKeeper: migrate to KRaft on 3.9.x first (3.x clusters older than 3.3 should go to 3.9 before 4.x). Clients are forward and backward compatible through API version negotiation, but the 4.0 upgrade notes say clients (including Streams and Connect) "must be on version 2.1 or higher before upgrading to 4.0". Read the "Notable changes" list per version: for example 4.0 changed linger.ms to 5, 4.4 deprecated broker.id in favour of node.id and made kafka-storage formatted directories not forward-compatible.
Kafka 4.x headlines
| Version (date) | Headline |
|---|---|
| 4.0 (18 Mar 2025) | KRaft only, ZooKeeper removed; KIP-848 consumer protocol GA; share groups early access; ELR preview; linger.ms 5; Java 11 clients / Java 17 brokers |
| 4.1 (4 Sep 2025) | Share groups preview; Streams rebalance protocol (KIP-1071) early access; ELR on by default for new clusters |
| 4.2 (17 Feb 2026) | Share groups production-ready (RENEW ack, lag metrics); Streams server-side rebalance GA (limited) |
| 4.3 (22 May 2026) | KRaft-only reiterated; follower fetch from tiered offset (KIP-1023); cordoned log dirs (KIP-1066) |
| 4.4 (22 Oct 2026) | Share group DLQ (KIP-1191); unregister controllers (KIP-1312); broker.id deprecated (KIP-1232); async bootstrap DNS (KIP-909) |
Versions and ecosystem: Confluent, Redpanda, WarpStream and others
| Option | What it is | Notable difference |
|---|---|---|
| Apache Kafka | The project | Reference implementation, JVM, KRaft |
| Confluent Platform / Cloud | Commercial distribution and SaaS by Kafka's creators | Schema Registry, ksqlDB, managed connectors, own cloud storage engine |
| Amazon MSK, Aiven, others | Managed Apache Kafka | Same protocol, operated for you |
| Redpanda | Kafka-API-compatible broker in C++ | "Producers and consumers interact with Redpanda using the Kafka API."; Raft per partition (majority, not ISR), no JVM |
| WarpStream | Kafka-compatible, stateless agents on object storage | "a diskless data streaming platform designed to seamlessly integrate with cloud object stores such as S3, GCP, and Azure while remaining compatible with Apache Kafka®"; higher latency, far cheaper cross-AZ traffic |
| Apache Pulsar | Different system (brokers + BookKeeper) | Has a Kafka protocol handler; see Other Brokers |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Acked writes lost when a broker dies | RF 3, min.insync.replicas=2, acks=all, unclean off | Topic config + producer default | Survives one broker | Writes stop when two are down |
| Duplicates from producer retries | Idempotent producer | enable.idempotence=true (PHP: explicit) | Free in Java/franz-go | Only within one producer session |
| Duplicates from consumer crash/rebalance | Commit after process + idempotent handler | Unique key / inbox table | Simple, works everywhere | A DB constraint per side effect |
| DB write + publish atomically | Outbox | Insert outbox row in the same transaction, relay | No dual write | Relay latency, extra table |
| Poison record blocks a partition | Retry topic + DLQ | On failure publish to orders.retry.1m, commit, move on; after N, orders.dlq | Partition keeps flowing | Order per key breaks for retried records |
| Need queue semantics, more workers than partitions | Share group | ShareGroup + per-record ack | No over-partitioning | No ordering; client support still growing |
| Rebalance storms on deploy | Cooperative or KIP-848 + static membership | Config | Short or no pauses | Slower failure detection with static ids |
| Lag grows | Scale consumers up to partitions, batch work, fix slow calls | kadm.Lag, alerts on trend | Beyond partition count needs more partitions or a share group | |
| Hot partition | Better key, key salting, or more partitions | Spread one tenant over N sub-keys | Even load | Per-key order lost for salted keys |
| Order breaks after adding partitions | New topic and migrate | Dual-write, switch consumers, retire | Clean | Effort |
| Kafka-to-Kafka exactly-once | Transactions | GroupTransactSession, Streams EOS | No duplicates downstream | Latency, read_committed readers |
The idempotent handler needs a database constraint; this is the table the Laravel handler's insertOrIgnore and an inbox depend on (PostgreSQL; the MySQL version uses BIGINT AUTO_INCREMENT and INSERT IGNORE):
CREATE TABLE payments (
id BIGSERIAL PRIMARY KEY,
order_id TEXT NOT NULL,
amount_cents BIGINT NOT NULL,
kafka_partition INT NOT NULL,
kafka_offset BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT payments_order_uniq UNIQUE (order_id) -- a redelivered event becomes a no-op
);
-- Generic inbox for handlers without a natural key: one row per (group, topic, partition, offset).
CREATE TABLE kafka_inbox (
consumer_group TEXT NOT NULL,
topic TEXT NOT NULL,
partition_id INT NOT NULL,
record_offset BIGINT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer_group, topic, partition_id, record_offset)
);
-- Inside the handler's DB transaction, first:
INSERT INTO kafka_inbox (consumer_group, topic, partition_id, record_offset)
VALUES ('billing', 'orders', 3, 1204887)
ON CONFLICT DO NOTHING; -- 0 rows inserted = already processed, skip the side effect retry-topic flow for a poison record (classic consumer group)
1 orders p3 @ 500 fails 3 times in-process -> produce to orders.retry.5m (same key, header attempt=1) -> commit 501
2 orders.retry.5m consumer waits until record timestamp + 5 min (pause partition, not sleep) -> process
3 fails again -> orders.retry.1h -> ... -> orders.dlq with headers (error, original topic/partition/offset)
4 p3 never blocked; but o-42's later events may be processed before the retried oneRetry schedules and delay workarounds: Retry, Backoff & Delayed Delivery; DLQ handling and replay: Dead-Letter Queue.
Choosing Kafka
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Domain events read by many services, need replay | Kafka | Schema Registry, compaction for state topics | Log + independent groups |
| CDC from a database into search, cache, warehouse | Kafka + Connect + Debezium | Tombstones, compacted topics | Ordered per key, replayable |
| Clickstream, logs, metrics at 100k+/s | Kafka | zstd, linger.ms 20, acks=1 maybe | Batching, sequential I/O |
| Background jobs in one Laravel app | Laravel queue on Redis/database | Horizon | Kafka adds ops cost and no job features |
| Job fan-out with retries, priorities, delays | RabbitMQ (or SQS) | DLX, delivery limit | Per-message features built in |
| Independent jobs on a Kafka-only platform | Kafka share groups (4.2+) | Delivery count, DLQ (4.4) | No second broker |
| Request/reply RPC | HTTP/gRPC | Kafka adds latency and correlation work (Request-Reply) | |
| Small team, low volume, already on Redis | Redis Streams | XAUTOCLAIM reaper | One less system |
| Global, multi-region event backbone | Kafka with MirrorMaker 2 / Cluster Linking, or a managed service | Per-region topics | Mature tooling |
When NOT to use Kafka
- You need a job queue with delays, priorities and per-message retries, and you do not run Kafka already. RabbitMQ, SQS or Laravel's queue does this with zero glue.
- Low volume and a small team. A 3-controller + 3-broker cluster, Schema Registry and Connect are a lot to operate for 50 events per second. A database outbox table polled by workers, or Redis Streams, is fine.
- Request/response. Correlating replies over topics is slower and more fragile than HTTP or gRPC.
- Strict global ordering across all events. That means one partition, so no parallelism.
- Per-entity queues in the millions (one topic or partition per user). Partitions are heavy; use a key on a shared topic or a different system.
- Long-term primary storage of business state. Kafka can retain forever, but querying, correcting and erasing records is hard; keep the system of record in a database and use Kafka to move changes.
In production systems
acks=allon a shrunken ISR. The design docs' own example: with two replicas and one failed, writes withacks=all"will succeed. However, these writes could be lost if the remaining replica also fails." The topic config docs recommend RF 3,min.insync.replicas=2,acks=all.- Kafka 4.0 dropped ZooKeeper and changed defaults. The 4.0 announcement and upgrade notes: KRaft only,
linger.ms5, KIP-848 GA but opt-in on the client. Moving from 3.x means a KRaft migration through 3.9 first. - Mixed-language partitioning. librdkafka's
partitionerdefaults toconsistent_random(CRC32), while Java and franz-go use murmur2; librdkafka documentsmurmur2_randomas Java-equivalent. - Share groups matured over three releases. Early access in 4.0, preview in 4.1 ("still not ready for production"), "production-ready" in 4.2, DLQ in 4.4; franz-go supports them via
ShareGroup; librdkafka-based clients such as laravel-kafka do not expose them yet. - franz-go and KIP-848. franz-go's
ServerSideBalancerdocs recommend Kafka 4.3+ because older brokers can returnSTALE_MEMBER_EPOCHon offset commits that the client cannot handle.
In architecture: from a single process to a distributed system
Monolith: one process, one database
A single Laravel app rarely needs Kafka. Jobs go to Laravel's queue on Redis or the database; in-process events use Event::dispatch. Kafka appears in a monolith when the monolith must publish facts for others (analytics, search indexing, a data team). The simplest correct shape: write the order and an outbox row in one DB::transaction, and a relay (an Artisan command or Debezium) publishes orders keyed by order id with acks=all. The monolith never calls Kafka::publish() inside the transaction, because a rollback cannot un-send.
1 POST /orders -> DB::transaction { insert order; insert outbox(order.created, key=o-42) } -> 201
2 relay: SELECT ... FROM outbox ORDER BY id LIMIT 100 -> Kafka::publish(key o-42) -> mark sent
3 search-indexer group, analytics group, email group each read orders at their own paceModular monolith and multiple databases
Modules talk through in-process interfaces, but Kafka topics can already mark the seams: each module owns its topics (billing.invoice-issued, catalog.price-changed) and its schema, and other modules consume through their own consumer group, even inside the same deployable. Topic naming and one-topic-per-event-type vs per-aggregate is in Routing Topologies. The rule that carries forward: a module never reads another module's tables, only its events; when the module is later extracted, the topic and the group do not change. Distinguishing internal domain events from published integration events is Domain Events vs Integration Events.
Microservices: what survives across service boundaries
Kafka is the backbone here, and every guarantee must be rebuilt at the edges:
Order service Kafka Payment service Shipping service
1 DB tx: order + outbox
2 relay -> orders (key o-42, acks=all, idempotent)
3 orders p3 @ 812
4 group payment: charge, inbox row(812), commit 813
5 DB tx: payment + outbox -> payments (key o-42)
6 group shipping reads payments
7 group order-status reads payments -> order PAID
crash at 4 after charge, before commit -> 812 redelivered -> inbox says done -> skipWhat survives: per-key order (same key everywhere), replay (a new fraud service starts from the beginning), backpressure (lag instead of timeouts). What does not: transactions across services (use a saga), exactly-once into databases (inbox), synchronous answers (use HTTP for queries). Topic contracts outlive teams, so schemas and compatibility rules are not optional. The service-level view of sync vs async is Service Communication, and failure design across services is Designing for Failure & Reliable Messaging.
Distributed data: replicas, racks and multiple regions
Inside one cluster, Kafka is CP-leaning per partition: with min.insync.replicas=2 and unclean election off, it refuses writes rather than lose them. Spread replicas across AZs with broker.rack; consumers can fetch from the nearest follower (KIP-392, client.rack + replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector) to cut cross-AZ cost. A stretched cluster across regions puts cross-region latency into every acks=all write and every controller quorum write; most teams instead run one cluster per region and replicate with MirrorMaker 2 (asynchronous; offsets translated through checkpoint topics) or a vendor feature (Confluent Cluster Linking). Asynchronous replication means a regional failover can lose the last seconds and can reorder relative to the other region, so consumers in the DR region must be idempotent and topics should be region-prefixed (us.orders, eu.orders) to avoid loops. Compare database replication trade-offs in Replication & Failover and consensus in Distributed SQL & Consensus; Kafka's KRaft metadata quorum is the Raft part, data partitions are not.
Scaling path: 1×, 10×, 100×
| Load | Shape | Changes |
|---|---|---|
| 1× (hundreds/s) | 3 brokers (or managed), 3 controllers (or combined), 6–12 partitions per topic, one group per service | Safe defaults, outbox, inbox, lag alerts |
| 10× (tens of thousands/s) | 6–12 brokers, 24–48 partitions on hot topics, compression, batching, cooperative or KIP-848 groups, static membership | Schema Registry, Connect for CDC, quotas per team, rack awareness |
| 100× (millions/s, many teams) | Dozens of brokers or several clusters per domain, tiered storage, Cruise Control, dedicated controllers, per-region clusters + MirrorMaker 2 | Platform team, topic self-service with policies, cost controls, maybe a diskless option (WarpStream-style) for cold or cross-AZ-heavy topics |
Lab
All commands are expected, not run (they need a Kafka cluster; per the site's cost rule no containers were started). Only experiment 1 was run, because it needs no broker. Commands match the Kafka Cheatsheet.
Setup (expected, not run). A 3-broker KRaft cluster, e.g. the official apache/kafka:4.4.0 image with three combined nodes, reachable as b1:9092,b2:9092,b3:9092.
kafka-topics.sh --bootstrap-server b1:9092 --create --topic orders \
--partitions 6 --replication-factor 3 --config min.insync.replicas=2
kafka-topics.sh --bootstrap-server b1:9092 --describe --topic orders
# expected, not run:
# Topic: orders PartitionCount: 6 ReplicationFactor: 3 Configs: min.insync.replicas=2
# Topic: orders Partition: 0 Leader: 1 Replicas: 1,2,3 Isr: 1,2,3
# Topic: orders Partition: 1 Leader: 2 Replicas: 2,3,1 Isr: 2,3,1
# ...1. Keys pick partitions, and adding partitions moves them (run).
cd docs/snippets/messaging/kafka/go && go run ./partitioner
# actual output:
# key=o-41 6 partitions -> p3 8 partitions -> p5 <- moved: per-key order breaks across the change
# key=o-42 6 partitions -> p0 8 partitions -> p6 <- moved: per-key order breaks across the change
# key=o-43 6 partitions -> p5 8 partitions -> p5
# key=o-44 6 partitions -> p4 8 partitions -> p6 <- moved: per-key order breaks across the change
# key=o-45 6 partitions -> p5 8 partitions -> p1 <- moved: per-key order breaks across the change
# key=o-46 6 partitions -> p4 8 partitions -> p6 <- moved: per-key order breaks across the change
# 5 of 6 keys changed partition2. Produce and consume with keys (expected, not run).
# terminal A
kafka-console-producer.sh --bootstrap-server b1:9092 --topic orders \
--property parse.key=true --property key.separator=: --producer-property acks=all
o-42:created
o-42:paid
o-7:created
# terminal B
kafka-console-consumer.sh --bootstrap-server b1:9092 --topic orders --group lab \
--from-beginning --property print.key=true --property print.partition=true --property print.offset=true
# expected, not run (partition numbers follow the Java murmur2 partitioner):
# Partition:0 Offset:0 o-42 created
# Partition:0 Offset:1 o-42 paid
# Partition:x Offset:0 o-7 created <- o-42's two events are in one partition, in order3. Kill a broker and watch the ISR (expected, not run).
docker stop kafka-3 # or kill the broker process
kafka-topics.sh --bootstrap-server b1:9092 --describe --topic orders
# expected, not run: Partition: 0 Leader: 1 Replicas: 1,2,3 Isr: 1,2
kafka-topics.sh --bootstrap-server b1:9092 --describe --under-replicated-partitions
# expected, not run: every partition with a replica on broker 3
# produce still works (ISR 2 >= min.insync.replicas 2). Now stop a second broker:
docker stop kafka-2
echo "o-42:shipped" | kafka-console-producer.sh --bootstrap-server b1:9092 --topic orders \
--property parse.key=true --property key.separator=: --producer-property acks=all
# expected, not run (after retries until delivery.timeout.ms):
# ERROR ... NotEnoughReplicasException: Messages are rejected since there are fewer in-sync replicas than required.
docker start kafka-2 kafka-3 # ISR grows back to 1,2,3 within seconds4. Lag grows with a slow consumer (expected, not run).
kafka-producer-perf-test.sh --topic orders --num-records 200000 --record-size 200 \
--throughput 2000 --producer-props bootstrap.servers=b1:9092 acks=all
# in another terminal: a consumer that sleeps 10 ms per record (100 records/s)
kafka-consumer-groups.sh --bootstrap-server b1:9092 --describe --group slow
# expected, not run, sampled twice 30 s apart:
# GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID ...
# slow orders 0 512 10340 9828
# slow orders 0 1012 20330 19318 <- +9,500 in 30 s: 2,000/s in, 100/s out, over 6 partitions
# start 5 more consumers in group slow: lag growth slows (6 x 100/s = 600/s out) but does not stop;
# a 7th member gets no partition: --describe --members shows it with #PARTITIONS 05. Watch a rebalance (expected, not run). Run the cooperative Go snippet three times with different hostnames, then stop one: kafka-consumer-groups.sh --describe --group billing --members --verbose shows only the stopped member's partitions moving, after session.timeout.ms if it was static. Repeat with kgo.Balancers(kgo.RangeBalancer()) and observe every member's assignment flip at once.
Common misconceptions
| Belief | Reality |
|---|---|
| Kafka is a message queue | It is a replicated log; queue semantics come only with share groups (4.2+) |
acks=all means all replicas have it | All in-sync replicas, possibly just the leader; set min.insync.replicas |
| Reading a message removes it | Only retention or compaction removes data |
| The topic is ordered | Only each partition is |
| More consumers = more throughput | Not beyond the partition count in a consumer group |
| Idempotence stops all duplicates | Only the producer client's own retries in one session |
| Kafka transactions include my database | Kafka partitions and offsets only |
| Auto-commit is at-least-once | It can commit before processing finishes: loss or duplicates |
| Adding partitions is harmless | It remaps keys and breaks per-key order across the change |
| KRaft means data uses Raft | Only the metadata log; data uses leader/ISR |
| KIP-848 is on by default in 4.0 | Broker side yes; clients must set group.protocol=consumer |
retention.bytes caps the topic | It caps each partition |
| Compaction keeps exactly one record per key | At least the latest; the head is not compacted yet |
| Kafka fsyncs every write | It relies on replication and the page cache |
| Static membership speeds up failover | It slows detection of dead members to session.timeout.ms |
Cheat sheet
| Topic | Remember |
|---|---|
| Durable writes | RF 3 + min.insync.replicas=2 + acks=all + unclean off |
| Producer duplicates | Idempotence on (explicit in librdkafka/PHP) |
| Ordering | Same key, same partition; never add partitions to keyed topics casually |
| Cross-language keys | librdkafka partitioner=murmur2_random |
| Consumer safety | Auto-commit off, commit after processing, idempotent handler |
| Poll loop | Under max.poll.interval.ms (5 min) per batch |
| Rebalances | Cooperative-sticky or group.protocol=consumer; static membership for restarts |
| Exactly-once | Kafka-to-Kafka with transactions; outbox/inbox at the edges |
| Retention | Longer than worst consumer outage; retention.bytes is per partition |
| State topics | cleanup.policy=compact, keys required, null = tombstone |
| Queue semantics | Share groups (4.2+), per-record ACCEPT/RELEASE/REJECT |
| Alerts | URP, under-min-ISR, offline partitions, controller count, lag trend |
| Partitions | max(t/p, t/c) + headroom; 12/24/48 |
| Upgrades | Rolling, then kafka-features.sh upgrade --release-version |
| Metadata | KRaft, 3 controllers, no ZooKeeper since 4.0 |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A topic has RF 3 and min.insync.replicas=1. Two followers fall out of the ISR and the leader then dies after acknowledging an acks=all write. What happens to that write? Good to know
Answer
Answer: It can be lost. With the ISR down to the leader alone, acks=all was satisfied by one copy. With unclean election off the partition goes offline until the leader returns; with it on, a stale follower leads and the write is gone. min.insync.replicas=2 would have refused the write. See acks.
2 — Why does a consumer only read up to the high watermark, and what is the LSO? Important
Answer
Answer: Records above the HW are not yet on every ISR member and could vanish in a leader change. The LSO (last stable offset) is lower still for read_committed consumers: the first offset of an open transaction. See High watermark.
3 — What problem did the leader epoch (KIP-101) solve? Good to know
Answer
Answer: Followers truncated to their own high watermark on restart, which could drop committed records if they then became leader. With leader epochs they ask the leader where their epoch ended and truncate only divergent data. See leader epoch.
4 — A Go service and a Laravel service produce events keyed by order id to the same topic. Events for one order arrive out of order. Why? Must-know
Answer
Answer: franz-go hashes keys with murmur2, librdkafka defaults to CRC32 (consistent_random), so the same key lands on different partitions. Set partitioner=murmur2_random in PHP. See Partitioner.
5 — Does enable.idempotence=true protect you when your pod restarts and resends the last batch? Important
Answer
Answer: No. The new process gets a new producer ID; the broker sees new records. Use a transactional id (which fences the old instance and aborts its open transaction) or dedup at the consumer. See idempotence.
6 — Your consumer sometimes takes 8 minutes for one batch. What breaks and how do you fix it? Must-know
Answer
Answer: max.poll.interval.ms (5 min) expires, the member leaves, the group rebalances and the batch is redelivered to someone else, often in a loop. Lower max.poll.records, move slow work off the poll loop, or raise the interval. See Consumer groups.
7 — What is the difference between eager, cooperative and KIP-848 rebalancing? Good to know
Answer
Answer: Eager revokes every partition from everyone behind a group barrier; cooperative revokes only moved partitions over two rounds but still uses the client-side assignor and barrier; KIP-848 computes the assignment on the broker and members reconcile through heartbeats with no barrier. See Rebalancing and KIP-848.
8 — When would you choose a share group over a consumer group? Good to know
Answer
Answer: For independent work items where order does not matter and you want more workers than partitions, per-record acks, redelivery and a delivery limit (DLQ in 4.4). Not for ordered event processing. See Share groups.
9 — Which metric tells you acks=all writes are being rejected right now? Important
Answer
Answer: UnderMinIsrPartitionCount above 0 (and producers seeing NOT_ENOUGH_REPLICAS). UnderReplicatedPartitions warns earlier. See Metrics.
10 — Why is a compacted topic a good source for rebuilding a cache, and what must every record have? Must-know
Answer
Answer: It keeps at least the latest value per key, so reading from offset 0 rebuilds current state; every record needs a key, and deletes are null-value tombstones kept for delete.retention.ms. See Compaction.
11 — What does KRaft replace, and what still does not use Raft? Important
Answer
Answer: It replaces ZooKeeper with a Raft quorum of controllers that own the __cluster_metadata log. Data partitions still use leader + ISR replication. See KRaft.
12 — Name three situations where Kafka is the wrong choice. Must-know
Answer
Answer: A simple job queue with delays and priorities, low volume with a small team, request/reply, strict global ordering, or millions of per-entity queues. See When NOT to use Kafka.
Glossary
| Term | Meaning |
|---|---|
| Topic | Named stream of records, split into partitions |
| Partition | Ordered append-only log; unit of order and parallelism |
| Offset | 64-bit position of a record in its partition |
| Segment | One file of a partition (.log + .index + .timeindex) |
.index / .timeindex | Sparse maps offset → file position and timestamp → offset |
| Retention | Deleting whole old segments by retention.ms / retention.bytes |
| Compaction | Log cleaner keeps at least the latest value per key |
| Tombstone | Record with a null value that deletes its key in a compacted topic |
| Broker | Server that stores partitions and serves clients |
| Controller | KRaft node that manages metadata; one is active |
| KRaft | Kafka's Raft-based metadata quorum replacing ZooKeeper |
__cluster_metadata | The metadata log replicated by controllers and read by brokers |
| ZooKeeper | Former external metadata store, removed in 4.0 |
| Replication factor (RF) | Number of copies of each partition |
| Leader / follower | Replica that takes writes / replicas that fetch from it |
| ISR | In-sync replicas: caught up within replica.lag.time.max.ms |
| ELR | Eligible Leader Replicas (KIP-966): out-of-ISR replicas safe to elect |
acks | Producer wait: 0, 1 or all ISR members |
min.insync.replicas | Minimum ISR size for acks=all writes |
| High watermark (HW) | Highest offset replicated to all ISR members; read limit |
| Log end offset (LEO) | Next offset the leader will write |
| Last stable offset (LSO) | Read limit for read_committed: first open transaction |
| Leader epoch | Leadership generation stamped on batches; guides truncation |
| Unclean leader election | Electing an out-of-sync replica, losing data |
| Preferred replica | First replica in the list; default leader |
| Partitioner | Producer logic that picks the partition (murmur2, sticky, CRC32) |
| Sticky partitioner | Keyless records fill one partition's batch, then switch |
linger.ms / batch.size | Producer batching wait and size cap |
| Idempotent producer | PID + sequence numbers so retries do not duplicate |
| PID / producer epoch | Producer identity and generation used for dedup and fencing |
| Transactional producer | Atomic writes across partitions and offsets via transactional.id |
| Transaction coordinator | Broker owning the __transaction_state partition for a transactional id |
read_committed | Consumer isolation that hides aborted and open transactions |
| Consumer group | Consumers sharing partitions, one owner per partition |
| Group coordinator | Broker managing a group's membership and offsets |
__consumer_offsets | Compacted internal topic holding committed offsets |
| Committed offset | Next offset to read for a group and partition |
| Consumer lag | Log end offset minus committed offset |
| Rebalance | Redistribution of partitions among group members |
| Generation / member epoch | Group version in classic / KIP-848 protocols; fences stale commits |
| Eager rebalance | Everyone revokes all partitions, then reassigns |
| Cooperative rebalance | Incremental: only moved partitions are revoked (KIP-429) |
| KIP-848 | Broker-side consumer rebalance protocol, group.protocol=consumer |
| Static membership | group.instance.id: quick restarts without a rebalance (KIP-345) |
| Share group | KIP-932 queue-style group with per-record acknowledgement |
| Acquisition lock | Time-limited ownership of a record in a share group |
| Delivery count | Times a share-group record was delivered; capped then archived/DLQ |
| Kafka Connect | Framework for source and sink connectors |
| SMT | Single Message Transform applied in a Connect pipeline |
| Debezium | CDC source connectors reading database logs |
| Kafka Streams | JVM library for stream processing on Kafka |
| Schema Registry | Service storing schemas and enforcing compatibility |
| Tiered storage | Old segments in object storage, recent on local disk (KIP-405) |
| Quota | Per-client byte-rate or request-rate limit enforced by throttling |
| SASL / ACL | Authentication mechanisms / per-resource authorization rules |
| Under-replicated partition | Partition whose ISR is smaller than its replica set |
| MirrorMaker 2 | Connect-based cross-cluster replication |
| Reassignment | Moving partition replicas between brokers |
| Redpanda | C++ Kafka-API-compatible broker using Raft per partition |
| WarpStream | Diskless Kafka-compatible system on object storage |
| franz-go | Pure-Go Kafka client (kgo, kadm) |
| laravel-kafka | mateusjunges/laravel-kafka, a Laravel wrapper over php-rdkafka |
| librdkafka | C client library behind PHP, Python and confluent-kafka-go |
References
- J. Kreps, N. Narkhede, J. Rao, "Kafka: a Distributed Messaging System for Log Processing", NetDB'11, 2011. PDF
- Apache Kafka 4.4 documentation: Design, Log implementation, KRaft, Producer configs, Consumer configs, Topic configs, Broker configs, Protocol (error codes), Monitoring, Basic operations, Hardware and OS, Tiered storage, Upgrading, Kafka Connect overview, Connect user guide, Kafka Streams introduction
- Release announcements: 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.4.0
- KIPs: KIP-98 Exactly Once Delivery and Transactional Messaging, KIP-101 Leader Epoch, KIP-345 Static membership, KIP-405 Tiered Storage, KIP-429 Incremental rebalance, KIP-500 Replace ZooKeeper, KIP-848 Next-gen consumer rebalance protocol, KIP-932 Queues for Kafka
- Jun Rao, "How to choose the number of topics/partitions in a Kafka cluster?", Confluent blog. confluent.io
- franz-go: README,
kgopackage v1.22.3,kadmpackage - librdkafka CONFIGURATION.md
- laravel-kafka v2.13 docs: Producing messages, Configuring producers, Message handlers, Consumer groups, Manual commit, Installation; source
- Laravel 13 documentation: Queues
- Confluent Schema Registry overview; Debezium Architecture
- Redpanda Architecture; WarpStream documentation
- Redis Streams, RabbitMQ Streams