Stream Processing - Apache Kafka
Introduction
Motivation
Goal: To provide a High-Performance, Reliable Distributed Unified Logging Platform- High throughput to support high volume event feeds
- Support real-time processing of these feeds to create new, derived feeds
- Support large data backlogs to handle periodic ingestion from offline systems
- Support low-latency delivery to handle more traditional messaging use cases
- Guarantee fault-tolerance in the presence of machine failures
Kafka
It is a Distributed Unified Logging Platform
- Kafka maintains feeds (streams) of records (messages) organized in different categories called topics
- Support the “Publish and Subscribe” model for streams of records (messages)
- Fault Tolerant Storage via Replication to multiple servers
- Process records as they occur
- Fast, Efficient I/O, Batching, Compression and more
- Decouple the Producers and Consumers of those records (messages)
- Commit Log as a Messaging system

General Applications
- Major Role (via the original Kafka “Core components”):
- Log Aggregation
- Capture and Ingest Data into Spark / Hadoop / Storm / Flink etc
- Command-Query Responsibility Segregation (CRQS), Replay, Error Recovery
- Guaranteed Distributed Commit Log for in-memory computing
- Metrics Collection and Monitoring
- Supporting Role (with recent extensions from Confluent):
- Stream Processing
- Website Activity Tracking
- Real Time Analytics
System Architecture

- Broker: Kafka server that runs in a Kafka Cluster. Each Cluster has 1+ Broker ; Each Broker has a Unique Broker ID
- ZooKeeper: Coordinate Brokers/Cluster topology:
- Stable storage for Cluster configuration
- Election for Broker and Partition Leaders and Coordinate Cluster changes
- Used by Consumers to track message (reading) offsets
Key Concepts

- Producers write data to Brokers
- Consumers read data from Brokers
- Data is stored in Topics
- Topics are split into Partitions, which are Replicated
- All this is distributed
- Multi-Broker Kafka Cluster

Topics
It feeds the name to which messages are published
- Creating a topic
1
2
3kafka-topics.sh --zookeeper zookeeper1:2181 --create --topic zerg.hydra \
--partitions 3 --replication-factor 2 \
--config x=y
Partitions
A topic consists of partitions (ordered + immutable sequence of messages that is continually appended to)
- #partitions of a topic is configurable
- #partitions determines max #consumers (threads) in each Consumer Group
- Consumer group A, with 2 consumers, reads from a 4-partition topic
- Consumer group B, with 4 consumers, reads from the same topic

- Partition Offset: messages in the partitions are each assigned a unique (per partition) and sequential id called the offset
Consumers track their pointers via (offset, partition, topic) tuples

Producers
- Producers publish data to the topics of their choice
- Producer is responsible for choosing which message to assign to which partition within the topic
- This can be done in a round-robin fashion simply to balance load or it can be done according to some semantic partition function
Consumers
a single consumer abstraction that generalizes both queuing and publish-subscribe mode
- Consumers label themselves with a consumer group name, and each message published to a topic is delivered to one consumer instance within each subscribing consumer group
Guarantees
Kafka is able to provide both ordering guarantees and load balancing over a pool of consumer processes, by guarantee each partition is consumed by exactly one consumer in the group
- There cannot be more consumer instances in a consumer group than partitions
Kafka only provides a total order over messages within a partition, not between different partitions in a topic
Ordering Guarantee
- Messages sent by a producer to a particular topic partition will be appended in the order they are sent
- A consumer instance sees messages in the order they are stored in the log
Message Delivery Semantics:
- At Least Once (default): Messages are never lost but may be redelivered
- At Most Once: Messages can be lost but never redelivered
- Exactly Once: 2 components
- Durability guarantees when publishing a message (by the Producer)
- Durability guarantees when reading a message (by a Consumer)
Distribution and Replication
- The partitions of the log are distributed over the servers (brokers) in the Kafka cluster
- Each partition is replicated across a configurable number of servers for fault tolerance
- Each partition has one server which acts as the “leader” and zero or more servers which act as “followers”
- If the leader fails, one of the followers will automatically become the new leader (similar to zookeeper)
- Each server acts as a leader for some of its partitions and a follower for others so load is well balanced within the cluster

- The leader of a partition handles all read and write requests for the partition while the followers (Replicas) ONLY passively replicate the leader
- Replicas exist solely to prevent data loss
- Replicas are never read from and never written to (they are just used for fault tolerance, do NOT help to increase producer or consumer parallelism)
Describe
Inspecting the current state of a topic by describing it
- Example:
1
2
3
4
5$ kafka-topics.sh --zookeeper zookeeper1:2181 --describe --topic zerg.hydra
Topic:zerg2.hydra PartitionCount:3 ReplicationFactor:2 Configs:
Topic: zerg2.hydra Partition: 0 Leader: 1 Replicas: 1,0 Isr: 1,0
Topic: zerg2.hydra Partition: 1 Leader: 0 Replicas: 0,1 Isr: 0,1
Topic: zerg2.hydra Partition: 2 Leader: 1 Replicas: 1,0 Isr: 1,0- Broker 0 is leader for partition 1
- Broker 1 is leader for partitions 0 and 2
- All replicas are in-sync with their respective leader partitions
Writing Data to Kafka
- Use Kafka “Producers” to write data to Kafka brokers
| Configuration Key | Description |
|---|---|
client.id |
Identifies producer app, e.g. in system logs |
producer.type |
Async or sync |
acks |
Acking semantics |
serializer.class |
Configure encoder, e.g. using Avro |
bootstrap.servers |
For bootstrapping from a list of well-known brokers |
- Two modes of writing: “async” and “sync”
- Sync Producer “send” call will block
- Async Producer is preferred to achieve high throughput (non-blocking)
- Sends messages in background = no blocking in client
- Communication from async->sync producer happens via a queue
- Async producer may drop messages if its queue is full
- Don’t push data to producer faster than it is able to send to brokers.
- Queue full == need more brokers, add them now! Use this solution in favor of solution 3 particularly if your producer cannot block (async producers)
- Set
queue.enqueue.timeout.msto-1(default). Now the producer will block indefinitely and will never willingly drop a message. - Increase
queue.buffering.max.messages(default: 10,000)
Message ACKing
In Kafka, a message is considered committed when “any required” ISR (in-sync replicas) for that partition have applied it to their data log. The exact meaning of “any required” is defined by request.required.acks.
values of
request.required.acks0(better latency): producer never waits for an ack from the broker- Gives the lowest latency but the weakest durability guarantees
1: producer gets an ack after the leader replica has received the data- Gives better durability as the we wait until the lead broker acks the request
-1(better durability): producer gets an ack after all ISR have received the data- Gives the best durability as Kafka guarantees that no data will be lost as long as at least one ISR remains
Write Processing
When writing to a topic in Kafka, producers write directly to the partition leaders (brokers) of that topic
- How to know the “right” partition for a given topic?
In Kafka, a producer – i.e. the client – decides to which target partition a message will be sent (sepcify the key)1
2KeyedMessage<String, String> msg = new KeyedMessage<>("zerg-hydra", "myValue");
KeyedMessage<String, String> msg = new KeyedMessage<>("zerg-hydra", "myKey", "myValue");- If a key is not specified, producer will ignore any configured partitioner, it will pick a random partition from the list of available partitions and stick to it for some time before switching to another one = NOT round robin or similar
- If a key is specified, Key is retained as part of the msg, will be stored in the broker. One can design a partition function to route the msg based on key. The default partitioner assigns messages to a partition based on their key hashes, via
key.hashCode % numPartitions
- How to know the current leader broker/replica of a partition?
Via broker discovery aka bootstrapping, it is achieved by providing producers with a “bootstrapping” broker listmetadata.broker.list- Scenario: N=5 brokers total, 2 of which are for bootstrap
Reading Data from Kafka
Use Kafka “consumers” to read data from Kafka brokers
Three API options for JVM users:
- High-level consumer API
- Simple consumer API
- Hadoop consumer API
Consumers pull from Kafka
- Consumers’ responsibility to track their read positions i.e. offsets
| Configuration Key | Description |
|---|---|
| group.id | Assigns an individual consumer to a “group” |
| zookeeper.connect | To discover brokers/topics/etc., and to store consumer state (e.g., when using the high-level consumer API) |
| fetch.message.max.bytes | Number of message bytes to (attempt to) fetch for each partition; must be >= broker’s message.max.bytes |
Reading Data Guarantees
- A message is only ever read by a single consumer in a group
- A consumer sees messages in the order they were stored in the log
- The order of messages is only guaranteed within a partition
- If you have multiple partitions per thread there is NO guarantee about the order you receive messages, other than that within the partition the offsets will be sequential
- Example: You may receive 5 messages from partition 10 and 6 from partition 11, then 5 more from partition 10 followed by 5 more from partition 10, even if partition 11 has data available
Rebalancing
The assignment of brokers – via the partitions of a topic – to consumers is quite important, and it is dynamic at run-time
- dynamic at run-time: Machines can die and be added; Consumer apps may die, be re-configured, and added

- Consumers in a group come into consensus on which consumer is consuming which partitionsàrequired for distributed consumption

