Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Stream Processing

Apache Kafka

Distributed event streaming platform:

Core Concepts

Producer → Topic (Partitioned) → Consumer Group
              ├── Partition 0 → Consumer 1
              ├── Partition 1 → Consumer 2
              └── Partition 2 → Consumer 3
  • Topic: Named stream of records
  • Partition: Ordered, immutable sequence of records
  • Offset: Position of a record within a partition
  • Consumer Group: Group of consumers that divide partitions
  • Broker: A Kafka server

Key Properties

PropertyDescription
DurabilityReplicated across brokers
OrderingGuaranteed within a partition
ReplayConsumers can re-read from any offset
ScalabilityAdd partitions and consumers
RetentionConfigurable time/size-based retention

Delivery Semantics

  • At-most-once: Commit before processing (may lose messages)
  • At-least-once: Commit after processing (may process duplicates)
  • Exactly-once: Kafka transactions + idempotent producers (requires coordination)

Consumer Groups

from kafka import KafkaConsumer

consumer = KafkaConsumer(
    'my-topic',
    group_id='my-group',
    auto_offset_reset='earliest',
    enable_auto_commit=False
)

for message in consumer:
    process(message.value)
    consumer.commit()

Stream processing framework:

StreamExecutionEnvironment env = 
    StreamExecutionEnvironment.getExecutionEnvironment();

DataStream<Event> events = env
    .addSource(new KafkaSource<>())
    .keyBy(Event::getUserId)
    .window(TumblingEventTimeWindows.of(Time.minutes(5)))
    .aggregate(new CountAggregate());

events.addSink(new KafkaSink<>());
env.execute("Streaming Job");
AspectFlinkSpark Streaming
ModelTrue streaming (event-by-event)Micro-batch
LatencyMillisecondsSeconds
StateNative state managementExternal state
Exactly-onceNativeVia checkpointing
WindowingRich (event time, session)Basic (processing time)

Stream Processing Patterns

  1. Filtering: Drop unwanted events
  2. Transformation: Enrich, map, aggregate
  3. Windowing: Tumbling, sliding, session windows
  4. Joining: Stream-stream, stream-table joins
  5. Aggregation: Count, sum, average per window
  6. Pattern matching: Complex event processing (CEP)

References