I work with Kafka a lot and this post is a summary of some interesting facts about it.
Topic & Partitions
- Topic is a logical grouping of partitions. But a partition is the storage unit in Kafka 1
- Producer can decide which partition to publish to by explicitly setting the partition on the message.
- If producer does not set a partition (or sets
PartitionAnyin confluent-kafka-go), the partitioner picks one: messages with a key go to a partition chosen by hashing the key, so the same key always lands on the same partition. Keyless messages are spread across partitions (older Java clients used round-robin; newer ones fill one partition per batch). offsetis maintained per partition and is a monotonically increasing number starting from 0. (new-id=last-id +1)- Topic is always an append-only log. Message already published cannot be modified or deleted by the producer.
- Order of messages is guaranteed within a partition but not at topic level.
# create a topic with 3 partitions and no replication.
$ kafka-topics --create --topic til-kafka --partitions 3 --replication-factor 1 --zookeeper localhost:2181
# show the metadata for the topic fetched from the bootstrap server.
$ kafkacat -b localhost:9092 -L -t til-kafka
Storage
- Each partition corresponds to a log directory in
log.dirspath. (i.e.,til-kafka-0,til-kafka-1andtil-kafka-2) - Each partition directory contains storage segments2 each consisting of 3 files:
x.log- actual record log. append only file.x.index- Index for fast access. Maintains record offset ↔ file offset mapping inx.logx.timeindex- Index for fast access. Maintains record offset ↔ timestamp mapping 3.
- A new segment is created when the current active segment reaches the limit set using
log.segment.bytes - New segment name is always the last offset in the old segment + 1 which also means the name reflects the first record offset in the segment.
- The newly created segment becomes the active segment, and the writes are done only on the active segment.
- Segments make it easy to enforce retention policy. The segment files with age greater than
log.retention.hourscan be simply deleted.
# examine a log file in partition
$ kafka-run-class kafka.tools.DumpLogSegments --deep-iteration --print-data-log \
--files logs/til-kafka-0/00000000000000000000.log
Replication
- Each topic has a replication factor that can be at max the number of brokers available at the time of creation of the topic.
- Configured number of copies of partitions of the topic are maintained with one acting as leader (accepts reads + writes) and others acting as passive followers.
- Kafka never places two replicas of the same partition on the same broker, so losing one broker loses at most one copy: fault-tolerance.
- Replicas that are no more than
replica.lag.time.max.msbehind the leader are calledIn-Sync Replicas (ISR). - If the leader goes down, one of the ISRs is chosen as the new leader 4.
Try it: slow a follower down until it leaves the ISR, then kill the leader.
til-kafka-0 · replication factor 3 · producer with acks=allThe producer writes to the leader; followers fetch from it. A record is committed, and visible to consumers, once every in-sync replica has it: that offset is the high watermark.
Solid cells are committed (at or below the high watermark). A follower that hasn't caught up within replica.lag.time.max.ms (2 s here) leaves the ISR.
Consumer
- Consumer is an entity that consumes records from partitions of a topic 5.
- Consumers subscribe to one or more topics and run a
poll()loop to read messages and get partition assignments. - Consumer group can be used to process records concurrently. Number of partitions decide how many active consumers can
exist at a time.
- If count(consumers) > count(partitions), consumers-partitions number of consumers will be idle.
- If count(consumers) < count(partitions), some consumers will be assigned more than 1 partition to read from.
- Based on
enable.auto.commitconfig, consumers may commit messages automatically at interval set byauto.commit.interval.msor a manualcommit()may be required. With auto-commit enabled,at-least oncedelivery semantics apply as long as each batch is fully processed before the nextpoll(), since thatpoll()is what commits it. - Following steps can be taken to achieve required delivery semantics:
- at-least once: auto-commit enabled OR
poll(),process()and thencommit() - at-most once: auto-commit false AND
poll(),commit()and thenprocess()
- at-least once: auto-commit enabled OR
- Consumer must process each message within
max.poll.interval.mstime and invoke the nextpoll()to make sure the broker does not end up assuming the consumer to be dead. If this does happen, a partition re-balance will occur causing the consumer to be kicked out of the group. In addition to this, consumer must also send heartbeats within everysession.timeout.mswindow. If violated, this also causes a re-balance.
Here is a consumer group on a 6-partition topic. Add consumers past the partition count, remove one until lag builds, or stall one until it gets kicked out:
til-kafka · consumer group billing · range assignorThe producer writes 12 messages/s round-robin; each consumer can process 5/s. Tap a consumer to stall it.
Footnotes
-
https://medium.com/@durgaswaroop/a-practical-introduction-to-kafka-storage-internals-d5b544f6925f ↩
-
https://jaceklaskowski.gitbooks.io/apache-kafka/content/kafka-log-LogSegment.html ↩
-
https://jaceklaskowski.gitbooks.io/apache-kafka/content/kafka-log-TimeIndex.html ↩
-
https://blog.knoldus.com/apache-kafka-topic-partitions-replicas-isr/ ↩
-
https://www.confluent.io/blog/tutorial-getting-started-with-the-new-apache-kafka-0-9-consumer-client ↩