Streaming from Event Hubs and Kafka

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Streaming from Event Hubs and Kafka: A Comprehensive Guide

Introduction: The Shift to Real-Time Data

In the traditional world of data engineering, we spent decades relying on batch processing. We would collect data throughout the day, store it in databases, and then run large, heavy jobs overnight to process it. While this approach is stable and predictable, it suffers from a fundamental flaw: the data is always stale by the time it reaches the decision-makers. In today’s fast-moving environment, waiting 24 hours to understand customer behavior or system health is simply not an option.

Streaming data architecture changes the paradigm by moving from "collect-and-process" to "process-as-it-happens." Whether you are tracking financial transactions, monitoring IoT sensor data from a manufacturing floor, or analyzing clickstream activity on a website, the ability to ingest and transform data in real-time provides a competitive advantage. Apache Kafka and Azure Event Hubs are the two most prominent technologies used to facilitate this movement of data. Understanding how to interact with these systems is no longer a niche skill; it is a core competency for any modern data engineer or architect.

This lesson explores the mechanics of streaming data, focusing on the architectural similarities and practical implementation details of Kafka and Event Hubs. We will move beyond the basic definitions and dive into the specific patterns, code structures, and operational strategies required to build reliable streaming pipelines.


Not read yet

Understanding the Fundamentals: The Streaming Pipeline

At its core, a streaming platform acts as a distributed, persistent commit log. Producers send events (records) to the platform, and consumers read those events. Both Apache Kafka and Azure Event Hubs follow this publish-subscribe model, but they are built for different contexts.

The Role of Producers

Producers are the applications or services that generate data. This could be a mobile app sending user location updates, a server logging error messages, or an IoT gateway sending temperature readings. The producer does not need to know who is consuming the data or how many consumers there are; it simply pushes data to a specific topic or hub.

The Role of the Broker/Hub

The broker (in Kafka) or the hub (in Event Hubs) serves as the intermediary. It is responsible for ordering the data, ensuring it is durable, and managing the state of the consumers. The data is organized into partitions, which allow for parallel processing. By spreading data across multiple partitions, we can scale our streaming system horizontally to handle massive throughput.

The Role of Consumers

Consumers are the applications that process the data. They track their progress using an "offset" or a "checkpoint," which tells the system exactly which records have been processed and which remain in the queue. This mechanism allows consumers to stop, restart, or failover without losing their place in the data stream.

Callout: Kafka vs. Event Hubs – Understanding the Distinction While Kafka and Event Hubs share similar concepts, they are distinct in their operational model. Apache Kafka is an open-source platform that requires you to manage your own infrastructure (or use a managed service like Confluent). It is highly customizable and offers deep integration with the broader Java ecosystem. Azure Event Hubs is a fully managed Platform-as-a-Service (PaaS) offering. It is designed for simplicity, integration with the Azure ecosystem, and minimal operational overhead. Choosing between them often comes down to whether you need the granular control of Kafka or the "hands-off" nature of a cloud-native service.


Not read yet

Working with Apache Kafka: Architecture and Implementation

Apache Kafka is designed for high-throughput, low-latency processing. To work effectively with Kafka, you must understand its core components: Topics, Partitions, Consumer Groups, and Offsets.

Setting Up a Kafka Producer

A producer in Kafka is responsible for sending records to a specific topic. You can configure the producer to acknowledge receipts, which ensures that data is not lost during transmission. Below is a standard example of how to produce a message using the Kafka Python client, confluent-kafka.

from confluent_kafka import Producer
import json

# Configuration for the producer
conf = {'bootstrap.servers': 'localhost:9092'}

# Initialize the producer
producer = Producer(conf)

def delivery_report(err, msg):
    if err is not None:
        print(f"Message delivery failed: {err}")
    else:
        print(f"Message delivered to {msg.topic()} [{msg.partition()}]")

# Sending a message
data = {'sensor_id': 101, 'temperature': 24.5}
producer.produce('sensor-data', json.dumps(data).encode('utf-8'), callback=delivery_report)

# Wait for pending messages to be delivered
producer.flush()

The flush() method is critical here. Producers often buffer messages to improve throughput; calling flush() ensures all messages are actually sent to the broker before the application terminates.

Consuming Data in Kafka

Consumers read data from topics. The most important concept here is the "Consumer Group." When multiple consumers belong to the same group, Kafka automatically balances the partitions among them. If you have a topic with four partitions and a consumer group with two consumers, each consumer will process two partitions.

from confluent_kafka import Consumer

conf = {
    'bootstrap.servers': 'localhost:9092',
    'group.id': 'analytics-group',
    'auto.offset.reset': 'earliest'
}

consumer = Consumer(conf)
consumer.subscribe(['sensor-data'])

try:
    while True:
        msg = consumer.poll(1.0)
        if msg is None: continue
        if msg.error():
            print(f"Consumer error: {msg.error()}")
            continue
        print(f"Received: {msg.value().decode('utf-8')}")
except KeyboardInterrupt:
    pass
finally:
    consumer.close()

Note: The auto.offset.reset configuration is vital. Setting it to earliest ensures that if your consumer is new and there is no saved offset, it will read from the beginning of the topic. If you set it to latest, it will only read new messages arriving after the consumer starts.


Not read yet

Working with Azure Event Hubs: The Managed Approach

Azure Event Hubs operates on the same logic as Kafka but is integrated deeply into the Azure cloud. It provides a Kafka-compatible endpoint, meaning you can often use existing Kafka libraries to connect to Event Hubs.

Creating an Event Hub Namespace

Before you can stream data, you need an Event Hubs Namespace. This acts as a container for your hubs. You can create this via the Azure Portal or the Azure CLI. Once created, you obtain a connection string, which acts as the authentication mechanism for your producers and consumers.

Producing to Event Hubs

The following Python example uses the azure-eventhub library, which is the native way to interact with Event Hubs.

from azure.eventhub import EventHubProducerClient, EventData

connection_str = "YOUR_CONNECTION_STRING"
eventhub_name = "sensor-hub"

producer = EventHubProducerClient.from_connection_string(
    conn_str=connection_str, 
    eventhub_name=eventhub_name
)

event_data = EventData("New sensor reading: 25.0")
with producer:
    event_data_batch = producer.create_batch()
    event_data_batch.add(event_data)
    producer.send_batch(event_data_batch)

The batching mechanism in Event Hubs is highly optimized. Instead of sending one record at a time, you bundle them into a batch. This significantly reduces network overhead and improves the performance of your producer application.

Consuming from Event Hubs

Event Hubs uses a checkpointing system to track progress. In a production environment, you should store these checkpoints in a persistent store, like an Azure Storage account. The EventHubConsumerClient manages this for you automatically if you provide a checkpoint store.

from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import BlobCheckpointStore

checkpoint_store = BlobCheckpointStore.from_connection_string("STORAGE_CONN_STRING", "container-name")
client = EventHubConsumerClient.from_connection_string(
    "EVENTHUB_CONN_STRING",
    consumer_group="$Default",
    eventhub_name="sensor-hub",
    checkpoint_store=checkpoint_store
)

def on_event(partition_context, event):
    print(f"Received: {event.body_as_str()}")
    partition_context.update_checkpoint(event)

with client:
    client.receive(on_event=on_event)

Not read yet

Comparison: Kafka vs. Event Hubs

Feature Apache Kafka Azure Event Hubs
Deployment Self-managed or Managed (Confluent) Managed (PaaS)
Scalability Manual partition management Auto-inflate feature
Ecosystem Strong Java/JVM integration Deep Azure integration
Operational Effort High Low
Protocol Native Kafka protocol Kafka API + AMQP + HTTPS
Cost Model Infrastructure + Licensing Throughput units/Processing units

Best Practices for Streaming Data Pipelines

Building a streaming pipeline is only half the battle; keeping it running at scale requires discipline. Here are the industry-standard practices for managing streaming data.

1. Partitioning Strategy

Partitions are the unit of scale in both Kafka and Event Hubs. If your data is not partitioned correctly, you will hit performance bottlenecks. A common mistake is using too few partitions, which limits the number of consumers that can read the data in parallel. Conversely, having too many partitions can lead to excessive memory usage on the broker. Always choose a partition key that ensures even distribution of data—for instance, using user_id or device_id as the key is usually better than a timestamp.

2. Handling Idempotency

In distributed systems, failures are inevitable. A producer might send a message, but a network glitch prevents it from receiving an acknowledgment. The producer might retry, leading to duplicate records in the stream. To solve this, design your downstream consumers to be idempotent. This means the consumer can process the same message multiple times without changing the final state. For example, if you are updating a database, use "upsert" logic (update if exists, insert if new) rather than simple "insert" commands.

3. Monitoring and Alerting

Streaming pipelines are "always on." If a consumer crashes, data will begin to accumulate in the broker, leading to increased latency. You must monitor:

  • Consumer Lag: This is the difference between the latest message in the partition and the message the consumer has most recently processed. If lag increases, your consumers cannot keep up with the incoming data.
  • Producer Error Rates: Watch for failed deliveries or timeouts.
  • Resource Utilization: Keep an eye on CPU and memory usage on your brokers or within your managed service tiers.

Callout: The "Poison Pill" Problem A "poison pill" is a malformed message that causes your consumer to crash repeatedly. When the consumer restarts, it attempts to process the same message again, leading to an infinite crash loop. Always implement a try-except block in your consumer logic. If a message fails to process after a defined number of attempts, move it to a "Dead Letter Queue" (DLQ) and continue to the next message.

4. Serialization Formats

Do not send raw, unstructured text if you can avoid it. Using binary serialization formats like Avro or Protobuf offers several advantages. They are more compact than JSON, leading to better network performance, and they enforce a schema. When you have a schema, you can detect breaking changes in your data format before they reach the production pipeline.


Not read yet

Common Pitfalls and How to Avoid Them

Pitfall 1: Ignoring Throughput Limits

Every streaming system has a ceiling. If your producer sends data faster than the broker can persist it, you will experience backpressure. In Kafka, this might mean the broker starts dropping messages or refuses connections. In Event Hubs, you will see throttling errors. Always perform load testing to understand your system's capacity and implement graceful backoff logic in your producers.

Pitfall 2: Over-relying on "Auto-Commit"

Many Kafka clients have an enable.auto.commit setting. While convenient, it is dangerous. If your consumer crashes after auto-committing but before the data is actually processed/stored in the downstream database, you will lose data. It is almost always better to perform manual commits only after the data has been successfully written to the destination.

Pitfall 3: Inadequate Retention Policies

Streaming platforms are not meant to be long-term storage. If you keep data in Kafka for too long, you will run out of disk space. Define a strict retention policy based on your business needs (e.g., 7 days). If you need to store data for auditing or historical analysis, use a "sink" connector to move that data into a data lake or a cold storage system.


Not read yet

Step-by-Step: Building a Robust Consumer

Let's walk through the architecture of a production-grade consumer that avoids the common pitfalls discussed above.

  1. Initialize the Consumer: Configure the consumer group and set the auto.offset.reset to earliest. Disable auto.commit.
  2. Poll Loop: Enter a continuous loop that polls for messages.
  3. Process and Validate: Inside the loop, wrap the processing logic in a try-except block. Validate the data schema immediately.
  4. Write to Destination: If the processing is successful, write the data to your database or storage.
  5. Manual Commit: Only after the database confirms the write, commit the offset back to the streaming platform.
  6. Handle Errors: If the processing fails, log the error and decide whether to retry (for transient issues) or route the message to a Dead Letter Queue (for malformed data).

This workflow ensures "at-least-once" delivery, which is the standard for most business applications. It guarantees that no data is lost, even if a consumer fails midway through a batch.


Not read yet

Advanced Streaming Concepts

Schema Registry

When working with multiple teams, data formats will change. Using a Schema Registry allows producers to register their data structure (the schema). Consumers then fetch this schema to decode the data correctly. This prevents the "upstream change breaks downstream consumer" scenario, which is a major source of downtime in data engineering.

Exactly-Once Processing

Achieving "exactly-once" delivery is the holy grail of streaming. This means that even in the face of network failures or application crashes, each message is processed and reflected in the final output exactly once. This is difficult because it requires coordination between the streaming platform and the destination system (like a database). Modern frameworks like Kafka Streams or Flink handle this using distributed transactions, but they add significant complexity. For most use cases, "at-least-once" with idempotent downstream processing is sufficient and much easier to maintain.

Windowing

Streaming data often requires aggregation. You might want to calculate the "average temperature per 5-minute window." Windowing allows you to group events based on time.

  • Tumbling Windows: Fixed-size, non-overlapping time intervals.
  • Sliding Windows: Fixed-size windows that move forward by a set increment, allowing for overlapping data.
  • Session Windows: Windows that group events based on activity, closing when a user is inactive for a certain period.

Not read yet

Frequently Asked Questions (FAQ)

Q: Can I use Kafka and Event Hubs together? A: Yes. You can use Event Hubs as an ingestion layer and then use a Kafka Connect source to pull that data into a self-managed Kafka cluster for processing. This is a common pattern for companies that want to leverage Azure's ingestion capabilities while keeping their processing logic on Kafka.

Q: What happens if I change the number of partitions? A: Changing the number of partitions after a topic is created is possible in Kafka, but it is dangerous. It can break the ordering of messages if your producers rely on keys to ensure that all messages for a specific key land in the same partition. Always plan your partition count during the initial design phase.

Q: Is streaming data expensive? A: Streaming platforms can be expensive if not managed correctly. Costs are usually driven by throughput (data volume) and retention (storage duration). By optimizing your data format (using binary instead of JSON) and keeping retention periods short, you can significantly reduce your monthly bill.

Q: How do I handle late-arriving data? A: In a streaming environment, data does not always arrive in the order it was generated. If you are doing windowed aggregations, you should use "watermarking." A watermark defines how long the system will wait for late data before closing a window and finalizing the calculation.


Not read yet

Key Takeaways

  1. Shift to Real-Time: Streaming architecture enables immediate data processing, moving away from slow, overnight batch jobs to responsive, real-time insights.
  2. Understand the Components: Regardless of whether you use Kafka or Event Hubs, mastering the roles of producers, brokers/hubs, consumers, and partitions is essential for building scalable systems.
  3. Prioritize Idempotency: Because network failures are inevitable, design your downstream consumers to handle duplicate records gracefully. This is the most effective way to ensure data consistency.
  4. Monitor Consumer Lag: This is the most critical metric in streaming. If your lag is growing, your system is failing to keep up with the data volume, and you need to scale your consumer group.
  5. Manage Partitions Carefully: Partitions are your primary mechanism for parallel processing. Choose a partitioning key that distributes data evenly to avoid hotspots and performance degradation.
  6. Avoid Auto-Commit: For production systems, always implement manual offset management. This prevents data loss during consumer failures by ensuring offsets are only updated after successful processing.
  7. Plan for Failures: Always include a strategy for dealing with "poison pills" (malformed messages) by using Dead Letter Queues, ensuring your pipeline remains resilient even when facing bad data.

By following these principles and best practices, you can build streaming pipelines that are not only performant but also resilient enough to handle the demands of a modern, data-driven organization. The transition to streaming is a significant step, but with a solid grasp of these core concepts, you are well-equipped to navigate the complexities of real-time data engineering.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.