Skip to content

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 forGo to
The whole model in tables you can memoriseEverything in one minute
Why a log and not a queue, and the trade-offWhy Kafka exists
LinkedIn 2011, KIP-98, KIP-500, Kafka 4.0Where it comes from
Topics, partitions, offsets, segments, index files, retention, compaction, tombstonesThe log
Leaders, followers, ISR, acks, min.insync.replicas, high watermark, leader epoch, unclean election, ELRBrokers and replication
Controller quorum, __cluster_metadata, ZooKeeper removalKRaft
Partitioner, batching, linger.ms, compression, retries, idempotence, transactionsProducers
Groups, assignors, eager vs cooperative, KIP-848, static membership, commits, share groupsConsumers
At-most/at-least/exactly-once on KafkaDelivery semantics
Connect, SMTs, Debezium, Streams, Schema Registry, tiered storage, quotas, securityThe ecosystem around the broker
Page cache, sendfile, every knob, every error codeMechanics
franz-go codeGo
laravel-kafka codeLaravel
Kafka against RabbitMQ and Redis StreamsCompared with the others
Lag, under-replicated partitions, partition count, reassignment, upgrades, 4.x, Confluent/Redpanda/WarpStreamOperations
Data loss, duplicates, poison records, rebalance storms, hot partitionsSolving the classic problems
When Kafka is right, and when it is notChoosing Kafka
Monolith to multi-regionIn architecture
Reproduce it on a laptopLab
Wrong beliefs, a cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The nouns. Every row is unpacked below.

TermIn plain wordsTiny exampleWhere it lives
TopicA named stream of eventsordersCluster metadata
PartitionOne ordered, append-only slice of a topicorders-3A directory on each replica's disk
OffsetA record's position in its partition, a 64-bit integer that only growsorders-3 @ 1,204,887Inside the record batch
SegmentOne file of a partition; the last one is active00000000000001200000.logPartition directory
RetentionHow long or how much is kept, whether read or notretention.ms=604800000 (7 d)Topic config
CompactionKeep at least the latest value per keycleanup.policy=compactTopic config, log cleaner thread
Replica, leader, followerCopies of a partition; one leader takes writes, followers fetchRF 3: leader on broker 1Brokers
ISRReplicas that are caught upIsr: 1,2Cluster metadata
High watermarkHighest offset every ISR member has; consumers read below itHW = 10Leader, propagated to followers
Consumer groupA set of consumers that share partitions; one owner per partitiongroup billingGroup coordinator, __consumer_offsets
Committed offsetThe group's bookmark per partitionbilling / orders-3 = 1,204,880__consumer_offsets
Share groupQueue-style group: many consumers per partition, per-record acksgroup thumbnailsShare coordinator, __share_group_state
Controller quorumRaft group that owns cluster metadata3 controllers__cluster_metadata log

The knobs that decide safety.

KnobSideDefault (Kafka 4.4)Safe production valueWhat it buys
replication.factorTopicBroker default.replication.factor (1 unless set)3Survive broker loss
min.insync.replicasTopic12 (with RF 3)acks=all really means 2 copies
acksProducerallallAck only after the ISR has it
enable.idempotenceProducertruetrueRetries do not duplicate or reorder
unclean.leader.election.enableTopicfalsefalseNever elect a stale replica
enable.auto.commitConsumertrue (every 5 s)false, commit after processingNo skipped records
isolation.levelConsumerread_uncommittedread_committed if anyone writes transactionallyHide aborted records
group.protocolConsumerclassicconsumer on 4.x clustersNo stop-the-world rebalances

What Kafka is and is not.

Kafka gives youKafka does not give you
Ordered, replayable history per partitionOrdering across partitions
Many independent readers of the same dataPer-message ack, redelivery timers or priorities in classic groups (share groups add per-record acks)
Throughput from batching and sequential I/ODelayed delivery or per-message TTL
Exactly-once for Kafka-to-Kafka with transactionsExactly-once into your database or an HTTP API
Retention independent of consumptionDeleting 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 ackRecord kept until retention or compaction
Broker tracks every message's stateConsumer group tracks one offset per partition
Per-message redelivery, TTL, priority, DLXReplay by seeking; retries and DLQ are topics you build
Many workers share a queue freelyParallelism capped by partition count (classic groups)
Adding a new consumer sees only new messagesA new group can read from the beginning
Good at work distributionGood 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 ​

  1. "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.
  2. "acks=all means every replica has my write." It means every replica currently in the ISR, which can be only the leader. min.insync.replicas is the floor that makes acks=all meaningful.
  3. "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 ​

Producer Akey o-42Producer Bhash(key) % 3topic "orders"0123456701234012345partition 0partition 1partition 2offsets only grow; order holds per partitionGroup "billing"p0 committed = 7p1 = 4, p2 = 5Group "search"p0 committed = 3replays at its own paceOn disk: orders-0/00000000000000000000.log .index .timeindex | 00000000000000000005.log (active)orange = old segment, deleted whole by retention.ms / retention.bytes

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:

ConceptKafkaRabbitMQRedis Streams
Unit of orderPartitionQueue (or stream)Stream
PositionOffset (int64, per partition)None for queues; offset for streamsEntry ID ms-seq
Parallelism unitPartitionConsumers on one queueConsumers in a group on one stream
Scale-out unitMore partitionsMore 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 path

Real 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,000

Real 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@x

Real 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 ​

Produceracks=allack after ISRhas offset 9Broker 1: LEADER (leader epoch 7)0 1 2 3 4 5 6 7 8 9 | LEO = 10Broker 2: follower, in ISR0 1 2 3 4 5 6 7 8 9 (fetching from leader)Broker 3: follower, OUT of ISR0 1 2 3 4 5 6 (behind > replica.lag.time.max.ms)HWRulesISR = {1, 2}min.insync = 2: OKIf broker 2 dies:ISR = {1} < 2NOT_ENOUGH_REPLICASconsumers readonly below HWunclean election: off

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:

ReplicationKafkaRabbitMQ quorum queues/streamsRedis (Streams)
AlgorithmLeader + dynamic ISR (PacificA-like, per the design docs)Raft (majority)Async primary → replica
Copies to survive 1 failure2 (3 recommended with min.insync.replicas=2)3No guarantee; WAIT gives best effort
Latency depends onSlowest ISR memberMedian (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 lost

Real 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 comboSurvivesAvailability for writesUse for
RF 3, min ISR 2, acks=all1 broker loss, no data lossDown if 2 brokers lostBusiness events
RF 3, min ISR 1, acks=allUsually; loses data if leader alone in ISR then diesUp with 1 brokerTolerant pipelines
RF 3, acks=1Loses acked data if leader dies before followers fetchHighLogs, metrics
RF 1NothingDown with that brokerDev 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 intact

Real 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 overwritten

Real 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 ​

Controller quorum (process.roles=controller), RaftController 1: ACTIVEleader of __cluster_metadatawrites ISR / leader changesController 2: voterreplicates metadata logcan win the next electionController 3: voterreplicates metadata log3 voters tolerate 1 failureBroker 1 (observer)fetches metadata logheartbeats to stay aliveBroker 2 (observer)partition leaders, ISRfrom metadata recordsBroker 3 (observer)serves producers andconsumersMetadataFetch + BrokerHeartbeat (broker.session.timeout.ms)No ZooKeeper since Kafka 4.0; controller.quorum.bootstrap.servers lists the controllers

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 1

Real 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 -> ack

Real 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..9

Real 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 readers

Real 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 -> rebalance

Real 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 ​

C3 joins a group of C1 [p0 p1 p2] and C2 [p3 p4 p5]Eager (range, roundrobin)1. JoinGroup: ALL membersrevoke ALL partitionsC1 [ ] C2 [ ] C3 [ ]2. barrier: leader memberassigns, SyncGroupnobody consumes meanwhile3. C1 [p0 p1] C2 [p2 p3]C3 [p4 p5]stop-the-world pause;all state movedCooperative (KIP-429)1. round 1: keep owned,revoke only p2 and p5C1 [p0 p1] C2 [p3 p4]2. round 2: hand therevoked ones to C3C3 [p2 p5]p0 p1 p3 p4 never stopcooperative-stickystill a client-sideassignor + group barrierConsumer protocol (KIP-848)1. C3 heartbeats; thecoordinator bumps group epochand computes the target2. C1, C2 learn via heartbeat:release p2, p5no JoinGroup / SyncGroup3. C3 gets p2 p5 when freedgroup.protocol=consumerserver-side assignor:uniform or rangeStatic membership (group.instance.id) avoids all three when a member restarts within session.timeout.ms

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 p2

Real 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 trips

Real 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 rebalance

Real 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 processed

Real 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.

StrategyKafka APIRiskWhen
Auto-commitenable.auto.commit=trueLoss (commits before done) or duplicatesMetrics, logs
Sync per recordcommitSync(record)Slow (one round trip each)Low volume, high value
Batch after processingcommitSync() after the loop, franz-go CommitRecordsReplays up to one batchDefault choice
Async + sync on close/revokecommitAsync() + commitSync() in callbacksReplays a few batchesHigh volume
Marks + autocommitfranz-go AutoCommitMarks + MarkCommitRecordsReplays up to one intervalGo services
TransactionalsendOffsetsToTransactionNone for Kafka outputsKafka-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 ​

Consumer group (classic queue-less model)partition 0partition 1C1 owns p0C2 owns p1C3, C4: idle (members > partitions)position = one committed offset per partitiona stuck record blocks its partitionShare group (KIP-932, Kafka 4.2 GA)partition 0partition 1C1C2C3C4record acquired under a lock (30 s default)ACCEPT | RELEASE (redeliver) | REJECTdelivery count limit, then archived / DLQ (4.4)no per-key ordering guarantee

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 sends

Every knob that matters ​

KnobScopeDefault (4.4)Notes
replication.factorTopicdefault.replication.factor3 in production
min.insync.replicasTopic12 with RF 3
unclean.leader.election.enableTopicfalse
retention.ms / retention.bytesTopic604800000 / -1Bytes is per partition
cleanup.policyTopicdeletecompact, compact,delete
segment.bytes / segment.msTopic1 GiB / 7 d
delete.retention.msTopic86400000Tombstone lifetime
min.compaction.lag.ms / max.compaction.lag.msTopic0 / Long.MAX
max.message.bytesTopic1048588Batch after compression
message.timestamp.typeTopicCreateTimeLogAppendTime
remote.storage.enableTopicfalseTiered storage
replica.lag.time.max.msBroker30000ISR eviction
num.partitionsBroker/controller1Auto-created topics
auto.create.topics.enableBrokertrueTurn off in production
offsets.topic.replication.factorBroker3
acksProducerall
enable.idempotenceProducertruelibrdkafka: false
max.in.flight.requests.per.connectionProducer5≤ 5 with idempotence
retries / delivery.timeout.msProducer2147483647 / 120000Timeout is the real bound
batch.size / linger.msProducer16384 / 5Linger was 0 before 4.0
compression.typeProducernonezstd, lz4
transactional.id / transaction.timeout.msProducernull / 60000
partitioner.classProducerbuilt-in sticky/murmur2librdkafka partitioner
group.protocolConsumerclassicconsumer = KIP-848
partition.assignment.strategyConsumerRange, CooperativeStickyClassic only
group.instance.idConsumernullStatic membership
session.timeout.ms / max.poll.interval.msConsumer45000 / 300000
max.poll.recordsConsumer500
enable.auto.commit / auto.commit.interval.msConsumertrue / 5000
auto.offset.resetConsumerlatestearliest, none, by_duration:
isolation.levelConsumerread_uncommittedlibrdkafka: read_committed
group.share.record.lock.duration.msBroker/group30000Share groups
group.share.delivery.count.limitBroker/group5Share groups

Error codes you will catch ​

Error (code)RetriableMeaningWhat to do
NOT_LEADER_OR_FOLLOWER (6)YesLeadership movedClient refreshes metadata; normal during restarts
FENCED_LEADER_EPOCH (74)YesRequest used an old leader epochSame
NOT_ENOUGH_REPLICAS (19)YesISR below min.insync.replicasFix brokers; producer retries until delivery.timeout.ms
NOT_ENOUGH_REPLICAS_AFTER_APPEND (20)YesWritten but ISR shrankRetry (idempotence dedups)
OFFSET_OUT_OF_RANGE (1)NoOffset deleted by retention or never existedauto.offset.reset or explicit seek
MESSAGE_TOO_LARGE (10)NoBatch over max.message.bytesSmaller records, claim-check
UNKNOWN_TOPIC_OR_PARTITION (3)YesTopic missing or metadata staleCreate topic; disable auto-create
COORDINATOR_NOT_AVAILABLE (15)YesGroup/txn coordinator movingRetry
REBALANCE_IN_PROGRESS (27)NoCommit during classic rebalanceRejoin, then commit
ILLEGAL_GENERATION (22) / UNKNOWN_MEMBER_ID (25)NoCommit from an old generation or kicked memberRecords will be redelivered to the new owner
FENCED_INSTANCE_ID (82)NoTwo instances share group.instance.idFix deployment
FENCED_MEMBER_EPOCH (110) / STALE_MEMBER_EPOCH (113)NoKIP-848 member out of dateClient rejoins / retries
OUT_OF_ORDER_SEQUENCE_NUMBER (45)NoIdempotent sequence gapProducer resets; investigate data loss
INVALID_PRODUCER_EPOCH (47) / PRODUCER_FENCED (90)NoA newer instance with the same transactional.idClose this producer
TOPIC_AUTHORIZATION_FAILED (29)NoACL deniesAdd ACL
THROTTLING_QUOTA_EXCEEDED (89)YesController mutation quotaBack 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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).

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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 choiceKafkaRabbitMQRedis Streams
Core abstractionPartitioned logQueues behind exchanges (plus streams)One in-memory log per key
Consumer positionOffset per partition per groupPer-message ack (queues); offset (streams)Last-delivered ID per group + PEL per consumer
Redelivery of one failed messageNo (classic groups); yes in share groupsYes (nack, requeue, x-delivery-limit)Yes (XCLAIM, XAUTOCLAIM)
OrderingPer partitionPer queue (single consumer)Per stream
ReplaySeek to any retained offsetStreams onlyXRANGE, XREADGROUP from ID
RetentionTime/size/compaction, on disk, tieredUntil acked (queues); size/age (streams)MAXLEN/MINID trim, memory-bound
ReplicationISR, min.insync.replicasRaft (quorum queues, streams)Async replicas
RoutingProducer picks topic and keyExchanges and bindingsClient picks stream key
Delayed deliveryNonePlugin or TTL + DLXBuild with sorted sets
Throughput sweet spotVery high, many readersModerate to high, complex routingModerate, 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:

go
// 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:

go
// 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)HealthyAlarm means
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions0A follower is out of the ISR: broker down, disk or network slow
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount0acks=all writes are being refused
kafka.controller:type=KafkaController,name=OfflinePartitionsCount0Partitions with no leader: data unavailable
kafka.controller:type=KafkaController,name=ActiveControllerCount1 (cluster sum)0 = no controller, >1 = split brain
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec / IsrExpandsPerSec~0Flapping replicas
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec0Data was lost
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce (and FetchConsumer, FetchFollower)Stable p99Produce/fetch latency; break down with RequestQueueTimeMs, LocalTimeMs, RemoteTimeMs
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent> 0.3Broker CPU-saturated
Consumer records-lag-max (client)Small, flatConsumer falling behind
Group lag from kafka-consumer-groups.sh --describe / kadm.Lag / Burrow / exportersFlatLag 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.

QuestionRule 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.

bash
# 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 --verify

Upgrades ​

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 ​

OptionWhat it isNotable difference
Apache KafkaThe projectReference implementation, JVM, KRaft
Confluent Platform / CloudCommercial distribution and SaaS by Kafka's creatorsSchema Registry, ksqlDB, managed connectors, own cloud storage engine
Amazon MSK, Aiven, othersManaged Apache KafkaSame protocol, operated for you
RedpandaKafka-API-compatible broker in C++"Producers and consumers interact with Redpanda using the Kafka API."; Raft per partition (majority, not ISR), no JVM
WarpStreamKafka-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 PulsarDifferent system (brokers + BookKeeper)Has a Kafka protocol handler; see Other Brokers

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Acked writes lost when a broker diesRF 3, min.insync.replicas=2, acks=all, unclean offTopic config + producer defaultSurvives one brokerWrites stop when two are down
Duplicates from producer retriesIdempotent producerenable.idempotence=true (PHP: explicit)Free in Java/franz-goOnly within one producer session
Duplicates from consumer crash/rebalanceCommit after process + idempotent handlerUnique key / inbox tableSimple, works everywhereA DB constraint per side effect
DB write + publish atomicallyOutboxInsert outbox row in the same transaction, relayNo dual writeRelay latency, extra table
Poison record blocks a partitionRetry topic + DLQOn failure publish to orders.retry.1m, commit, move on; after N, orders.dlqPartition keeps flowingOrder per key breaks for retried records
Need queue semantics, more workers than partitionsShare groupShareGroup + per-record ackNo over-partitioningNo ordering; client support still growing
Rebalance storms on deployCooperative or KIP-848 + static membershipConfigShort or no pausesSlower failure detection with static ids
Lag growsScale consumers up to partitions, batch work, fix slow callskadm.Lag, alerts on trendBeyond partition count needs more partitions or a share group
Hot partitionBetter key, key salting, or more partitionsSpread one tenant over N sub-keysEven loadPer-key order lost for salted keys
Order breaks after adding partitionsNew topic and migrateDual-write, switch consumers, retireCleanEffort
Kafka-to-Kafka exactly-onceTransactionsGroupTransactSession, Streams EOSNo duplicates downstreamLatency, 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):

sql
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 one

Retry schedules and delay workarounds: Retry, Backoff & Delayed Delivery; DLQ handling and replay: Dead-Letter Queue.

Choosing Kafka ​

SituationRecommendationExtra techniqueReason
Domain events read by many services, need replayKafkaSchema Registry, compaction for state topicsLog + independent groups
CDC from a database into search, cache, warehouseKafka + Connect + DebeziumTombstones, compacted topicsOrdered per key, replayable
Clickstream, logs, metrics at 100k+/sKafkazstd, linger.ms 20, acks=1 maybeBatching, sequential I/O
Background jobs in one Laravel appLaravel queue on Redis/databaseHorizonKafka adds ops cost and no job features
Job fan-out with retries, priorities, delaysRabbitMQ (or SQS)DLX, delivery limitPer-message features built in
Independent jobs on a Kafka-only platformKafka share groups (4.2+)Delivery count, DLQ (4.4)No second broker
Request/reply RPCHTTP/gRPCKafka adds latency and correlation work (Request-Reply)
Small team, low volume, already on RedisRedis StreamsXAUTOCLAIM reaperOne less system
Global, multi-region event backboneKafka with MirrorMaker 2 / Cluster Linking, or a managed servicePer-region topicsMature 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=all on a shrunken ISR. The design docs' own example: with two replicas and one failed, writes with acks=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.ms 5, 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 partitioner defaults to consistent_random (CRC32), while Java and franz-go use murmur2; librdkafka documents murmur2_random as 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 ServerSideBalancer docs recommend Kafka 4.3+ because older brokers can return STALE_MEMBER_EPOCH on 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 pace

Modular 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 -> skip

What 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× ​

LoadShapeChanges
1× (hundreds/s)3 brokers (or managed), 3 controllers (or combined), 6–12 partitions per topic, one group per serviceSafe 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 membershipSchema 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 2Platform 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.

bash
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).

bash
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 partition

2. Produce and consume with keys (expected, not run).

bash
# 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 order

3. Kill a broker and watch the ISR (expected, not run).

bash
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 seconds

4. Lag grows with a slow consumer (expected, not run).

bash
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 0

5. 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 ​

BeliefReality
Kafka is a message queueIt is a replicated log; queue semantics come only with share groups (4.2+)
acks=all means all replicas have itAll in-sync replicas, possibly just the leader; set min.insync.replicas
Reading a message removes itOnly retention or compaction removes data
The topic is orderedOnly each partition is
More consumers = more throughputNot beyond the partition count in a consumer group
Idempotence stops all duplicatesOnly the producer client's own retries in one session
Kafka transactions include my databaseKafka partitions and offsets only
Auto-commit is at-least-onceIt can commit before processing finishes: loss or duplicates
Adding partitions is harmlessIt remaps keys and breaks per-key order across the change
KRaft means data uses RaftOnly the metadata log; data uses leader/ISR
KIP-848 is on by default in 4.0Broker side yes; clients must set group.protocol=consumer
retention.bytes caps the topicIt caps each partition
Compaction keeps exactly one record per keyAt least the latest; the head is not compacted yet
Kafka fsyncs every writeIt relies on replication and the page cache
Static membership speeds up failoverIt slows detection of dead members to session.timeout.ms

Cheat sheet ​

TopicRemember
Durable writesRF 3 + min.insync.replicas=2 + acks=all + unclean off
Producer duplicatesIdempotence on (explicit in librdkafka/PHP)
OrderingSame key, same partition; never add partitions to keyed topics casually
Cross-language keyslibrdkafka partitioner=murmur2_random
Consumer safetyAuto-commit off, commit after processing, idempotent handler
Poll loopUnder max.poll.interval.ms (5 min) per batch
RebalancesCooperative-sticky or group.protocol=consumer; static membership for restarts
Exactly-onceKafka-to-Kafka with transactions; outbox/inbox at the edges
RetentionLonger than worst consumer outage; retention.bytes is per partition
State topicscleanup.policy=compact, keys required, null = tombstone
Queue semanticsShare groups (4.2+), per-record ACCEPT/RELEASE/REJECT
AlertsURP, under-min-ISR, offline partitions, controller count, lag trend
Partitionsmax(t/p, t/c) + headroom; 12/24/48
UpgradesRolling, then kafka-features.sh upgrade --release-version
MetadataKRaft, 3 controllers, no ZooKeeper since 4.0

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
TopicNamed stream of records, split into partitions
PartitionOrdered append-only log; unit of order and parallelism
Offset64-bit position of a record in its partition
SegmentOne file of a partition (.log + .index + .timeindex)
.index / .timeindexSparse maps offset → file position and timestamp → offset
RetentionDeleting whole old segments by retention.ms / retention.bytes
CompactionLog cleaner keeps at least the latest value per key
TombstoneRecord with a null value that deletes its key in a compacted topic
BrokerServer that stores partitions and serves clients
ControllerKRaft node that manages metadata; one is active
KRaftKafka's Raft-based metadata quorum replacing ZooKeeper
__cluster_metadataThe metadata log replicated by controllers and read by brokers
ZooKeeperFormer external metadata store, removed in 4.0
Replication factor (RF)Number of copies of each partition
Leader / followerReplica that takes writes / replicas that fetch from it
ISRIn-sync replicas: caught up within replica.lag.time.max.ms
ELREligible Leader Replicas (KIP-966): out-of-ISR replicas safe to elect
acksProducer wait: 0, 1 or all ISR members
min.insync.replicasMinimum 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 epochLeadership generation stamped on batches; guides truncation
Unclean leader electionElecting an out-of-sync replica, losing data
Preferred replicaFirst replica in the list; default leader
PartitionerProducer logic that picks the partition (murmur2, sticky, CRC32)
Sticky partitionerKeyless records fill one partition's batch, then switch
linger.ms / batch.sizeProducer batching wait and size cap
Idempotent producerPID + sequence numbers so retries do not duplicate
PID / producer epochProducer identity and generation used for dedup and fencing
Transactional producerAtomic writes across partitions and offsets via transactional.id
Transaction coordinatorBroker owning the __transaction_state partition for a transactional id
read_committedConsumer isolation that hides aborted and open transactions
Consumer groupConsumers sharing partitions, one owner per partition
Group coordinatorBroker managing a group's membership and offsets
__consumer_offsetsCompacted internal topic holding committed offsets
Committed offsetNext offset to read for a group and partition
Consumer lagLog end offset minus committed offset
RebalanceRedistribution of partitions among group members
Generation / member epochGroup version in classic / KIP-848 protocols; fences stale commits
Eager rebalanceEveryone revokes all partitions, then reassigns
Cooperative rebalanceIncremental: only moved partitions are revoked (KIP-429)
KIP-848Broker-side consumer rebalance protocol, group.protocol=consumer
Static membershipgroup.instance.id: quick restarts without a rebalance (KIP-345)
Share groupKIP-932 queue-style group with per-record acknowledgement
Acquisition lockTime-limited ownership of a record in a share group
Delivery countTimes a share-group record was delivered; capped then archived/DLQ
Kafka ConnectFramework for source and sink connectors
SMTSingle Message Transform applied in a Connect pipeline
DebeziumCDC source connectors reading database logs
Kafka StreamsJVM library for stream processing on Kafka
Schema RegistryService storing schemas and enforcing compatibility
Tiered storageOld segments in object storage, recent on local disk (KIP-405)
QuotaPer-client byte-rate or request-rate limit enforced by throttling
SASL / ACLAuthentication mechanisms / per-resource authorization rules
Under-replicated partitionPartition whose ISR is smaller than its replica set
MirrorMaker 2Connect-based cross-cluster replication
ReassignmentMoving partition replicas between brokers
RedpandaC++ Kafka-API-compatible broker using Raft per partition
WarpStreamDiskless Kafka-compatible system on object storage
franz-goPure-Go Kafka client (kgo, kadm)
laravel-kafkamateusjunges/laravel-kafka, a Laravel wrapper over php-rdkafka
librdkafkaC client library behind PHP, Python and confluent-kafka-go

References ​

Built by Morteza Negahi