Skip to content

Unit 8 · Distributed Event Streaming: Apache Kafka

3 h contact · 6 h self study · lab Prerequisites: Units 5 to 7 CLO 6

1. Setting the scene

Scenario: A ride app and a sensor network have the same problem

Think of a ride hailing app like Uber. A user requests a ride; the driver's location updates every few seconds; the app shows a moving car on the map. Continuously, the system generates GPS updates, ride status changes and pricing updates: millions of events per second.

SensorGrid is the same kind of system: 4,000 readings per second, and several consumers need every event, at their own pace: the alert service within seconds, the Cassandra writer in batches, the data science team for replay and retraining.

Guiding questions

  1. Why does a central relational database struggle with this workload?
  2. How can one stream feed many independent consumers?
  3. How can consumers read in parallel and still see events in order?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 8.1 Explain why an RDBMS struggles with high velocity event streams. UNDERSTAND 6
ILO 8.2 Describe producers, brokers, topics, partitions, offsets and consumer groups. UNDERSTAND 6
ILO 8.3 Compute the maximum consumer parallelism and consumer lag. APPLY 6
ILO 8.4 Explain replication with leaders and followers. UNDERSTAND 6
ILO 8.5 Build a producer and a consumer group in Python. APPLY 6

3. Why a traditional RDBMS struggles

A relational database is designed for transactions, strong consistency and structured queries. It is not optimised for extremely high write throughput, event streaming, or short lived, high velocity data.

  • Write bottlenecks under massive load (locking, contention).
  • Tight coupling between producers and the database.
  • Scaling requires complex sharding.
flowchart TB
    subgraph R["RDBMS: centralised"]
      direction LR
      D1["Riders and<br/>drivers"] -->|"millions of writes"| DB[("Central RDBMS<br/>locking, one server")]
    end
    subgraph K["Kafka: distributed"]
      direction LR
      D2["Riders and<br/>drivers"] -->|"events"| KC[("Kafka cluster<br/>partitioned log")]
      KC -->|"parallel reads"| C["Consumers<br/>maps · billing"]
    end
    R ~~~ K

Kafka distributes the load. An RDBMS centralises it.

4. What is Apache Kafka?

Kafka is a distributed system for streaming data, designed for high throughput ingestion, fault tolerance through replication, and scalable parallel consumption through consumer groups. Kafka turns data into a continuous stream of events.

Why it fits real time streaming:

  • optimised for high throughput writes;
  • an append only log means sequential disk writes;
  • partitioning enables horizontal scaling;
  • temporary, replayable storage via offsets;
  • it decouples producers from consumers.

Kafka handles velocity first, persistence second.

Temporary versus permanent storage

Event type Relevance Where it belongs
Location updates, raw sensor readings high frequency, short lived Kafka (stream log, retention of hours or days)
Final ride record, daily sensor summary billing, history, long term database (Cassandra, PostgreSQL, HDFS)

Throughput

RDBMS Kafka
optimised for ACID transactions sequential disk writes
limited concurrent write scalability batching and compression
millions of messages per second

5. Architecture: producer, broker, consumer

flowchart LR
    P["Producer<br/>app / sensor"] -->|"publish"| B[("Kafka broker(s)<br/>topic: events")]
    B -->|"subscribe"| C["Consumer<br/>service / analytics"]
  • Producers write events to topics.
  • Brokers store and replicate events.
  • Consumers read events at their own pace.

6. Topics and partitions: parallelism by design

A topic is split into partitions. Each partition is an ordered, append only log; every event gets a sequential offset.

flowchart LR
    PA["Producer A"] --> T
    PB["Producer B"] --> T
    subgraph T["Topic: ride_events"]
      direction TB
      P0["Partition 0 · offsets 0 1 2 3 4"]
      P1["Partition 1 · offsets 0 1 2 3"]
      P2["Partition 2 · offsets 0 1 2 3 4 5"]
    end
    P0 --> C1["Consumer 1"]
    P1 --> C2["Consumer 2"]
    P2 --> C3["Consumer 3"]

Which partition receives an event? Events with a key go to

\[ \text{partition}(k) = h(k) \bmod P \]

so all events of one sensor (key = sensor_id) land in the same partition and stay in order. Order is guaranteed within a partition, not across partitions.

7. Consumer groups: parallel processing of streams

Within a consumer group, each partition is consumed by exactly one consumer. Different groups read the same topic independently.

flowchart LR
    subgraph T["Topic with 3 partitions"]
      P0["P0"]
      P1["P1"]
      P2["P2"]
    end
    subgraph G1["Group: alerting"]
      A1["Consumer A1"]
      A2["Consumer A2"]
    end
    subgraph G2["Group: cassandra writer"]
      W1["Consumer W1"]
    end
    P0 --> A1
    P1 --> A1
    P2 --> A2
    P0 & P1 & P2 --> W1

The useful parallelism of a group is limited by the number of partitions:

\[ \text{active consumers} = \min(P, C), \qquad \text{idle consumers} = \max(0, C - P) \]

Worked example

Topic with \(P = 6\) partitions. A group of \(C = 4\) consumers: 4 active, two of them read 2 partitions each. With \(C = 8\): 6 active, 2 idle. To scale beyond 6 parallel consumers, increase the partition count.

8. Offsets: your position in the log

flowchart LR
    o0["0"] --> o1["1"] --> o2["2"] --> o3["3 ◀ committed offset"] --> o4["4"] --> o5["5 ◀ log end"]

Consumers track their progress with offsets and can replay by resetting them. The distance to the head of the log is the consumer lag:

\[ \text{lag} = \text{log end offset} - \text{committed offset} \]

If producers write at rate \(\lambda\) events/s and a consumer processes \(\mu\) events/s, the lag grows by \((\lambda - \mu)\) per second when \(\lambda > \mu\). The time to catch up after a backlog \(L\) once \(\mu > \lambda\) is

\[ t_{\text{catch up}} = \frac{L}{\mu - \lambda} \]

Worked example: after the storm

The alert group fell behind by \(L = 1.2 \times 10^{6}\) events. Producers write \(\lambda = 4{,}000\)/s; after scaling out, consumers process \(\mu = 10{,}000\)/s: \(t = 1.2 \times 10^{6} / 6{,}000 = 200\) s.

9. Fault tolerance: leaders and followers

Each partition is replicated across brokers. One replica is the leader (all writes go there); the others are followers that copy the leader. If the leader fails, an in sync follower takes over.

sequenceDiagram
    participant P as Producer
    participant L as Leader (broker 1)
    participant F1 as Follower (broker 2)
    participant F2 as Follower (broker 3)
    P->>L: send event (acks = all)
    L->>L: append to log
    par followers fetch
        F1->>L: fetch
        L-->>F1: event
    and
        F2->>L: fetch
        L-->>F2: event
    end
    L-->>P: ack once all in sync replicas have it
    Note over L: broker 1 crashes
    Note over F1: F1 elected new leader, no data lost

Storage needed for retention:

\[ \text{storage} = \lambda \times \text{event size} \times \text{retention} \times \text{RF} \]

For SensorGrid: \(4{,}000 \times 100\ \text{B} \times 7\ \text{days} \times 86{,}400\ \text{s} \times 3 \approx 726\) GB.

10. Kafka through the lens of this course

Lens In Kafka
Distributed computing brokers across machines, replication, failure handling
Parallel computing partitions enable parallel consumers; stream processing scales out horizontally

Kafka = distributed ingestion + parallel processing.

11. Mini pipeline: Kafka → processing → storage

flowchart LR
    P["Producers<br/>apps / IoT"] -->|"events"| K[("Kafka topics")]
    K -->|"consume"| S["Stream processor<br/>Python / Spark"]
    S -->|"batch / write"| D[("Storage<br/>Cassandra / HDFS")]
import json, random, time
from kafka import KafkaProducer

producer = KafkaProducer(
    bootstrap_servers="localhost:9092",
    key_serializer=str.encode,
    value_serializer=lambda v: json.dumps(v).encode(),
    acks="all", linger_ms=20, compression_type="gzip")   # batching + compression

while True:
    sensor = f"S{random.randint(1, 20000)}"
    producer.send("sensor_readings", key=sensor,          # same key → same partition
                  value={"sensor_id": sensor, "ts": time.time(),
                         "pm25": round(random.uniform(2, 40), 1)})
    time.sleep(0.00025)                                   # about 4,000 events per second
import json
from kafka import KafkaConsumer

consumer = KafkaConsumer(
    "sensor_readings",
    bootstrap_servers="localhost:9092",
    group_id="alerting",                 # copies with the same group share partitions
    auto_offset_reset="earliest",
    value_deserializer=lambda b: json.loads(b))

for msg in consumer:
    r = msg.value
    if r["pm25"] > 35:
        print(f"ALERT partition={msg.partition} offset={msg.offset} {r['sensor_id']}")
kafka-topics.sh --create --topic sensor_readings \
  --partitions 6 --replication-factor 3 --bootstrap-server localhost:9092
kafka-consumer-groups.sh --describe --group alerting --bootstrap-server localhost:9092

12. Lab

Kafka lab

Create topics and partitions, publish and consume messages, and observe consumer groups.

Instructions: github.com/bugmend/bigdataanalytics/tree/main/kafka

13. Discussion

Discuss in pairs

  1. Why do partitions enable parallelism in Kafka?
  2. What is the trade off between more partitions and overhead?
  3. Why is shuffling (network movement) expensive in distributed systems like Kafka and Hadoop?
  4. When do we want replay (offset reset) in data science pipelines?
Hints
  1. Each partition is an independent log that one consumer of a group reads; partitions spread over brokers. 2. More partitions: more parallelism, but more open files, more leader elections, longer recovery and more end to end latency. 3. Latency plus limited bandwidth, serialisation cost, and it scales with data volume (Unit 5). 4. Retraining a model on history, fixing a bug in a consumer and reprocessing, backfilling a new feature, debugging.

14. Check your understanding

A topic has 12 partitions. Group A has 5 consumers, group B has 15. How many are active in each?

A: 5 active. B: 12 active, 3 idle.

Why is ordering guaranteed per partition but not per topic?

Each partition is a separate log appended sequentially; events in different partitions are written and read independently.

15. Key takeaways

  • Kafka is a distributed, partitioned, replicated append only log.
  • Partitions give parallelism and per key ordering; consumer groups share partitions.
  • Offsets allow replay; lag measures how far behind a consumer is.
  • Leaders and followers keep data safe when brokers fail.
  • Kafka decouples ingestion from processing and storage.

Portfolio option: build a Kafka → Python → Cassandra pipeline for simulated SensorGrid data, measure throughput and lag with 1, 2, 4 and 8 consumers, and relate the result to the partition count.

Further reading

  • J. Kreps, N. Narkhede, J. Rao (2011), Kafka: a Distributed Messaging System for Log Processing, NetDB.
  • Apache Kafka documentation: kafka.apache.org/documentation