How Event Hubs works
๐ฑProducers
The app sends one event per order
๐กEvent hub 'orders'
4 partitions; key = customer_id
๐ฅConsumer groups
$Default (Spark) and analytics (dashboards)
๐Lake / alerts
Bronze Delta tables, real-time metrics
| Concept | Meaning |
|---|---|
| Namespace | The container (and endpoint) for event hubs, with a pricing tier and capacity |
| Event hub | One stream, like a Kafka topic (ours: orders) |
| Partition | An ordered log; parallelism unit; order guaranteed only within one |
| Partition key | Hash decides the partition: same key โ same partition |
| Consumer group | An independent view of the stream with its own positions |
| Retention | How long events stay (1 day+ by tier); consumers can re-read within it |
Run it locally: the official emulator
Microsoft publishes an Event Hubs emulator. A config file declares the namespace, hub, partitions and consumer groups:
{
"UserConfig": {
"NamespaceConfig": [
{
"Type": "EventHub",
"Name": "emulatorNs1",
"Entities": [
{
"Name": "orders",
"PartitionCount": "4",
"ConsumerGroups": [ { "Name": "analytics" } ]
}
]
}
],
"LoggingConfig": { "Type": "File" }
}
}name: shopkart-eventhubs
services:
emulator:
image: mcr.microsoft.com/azure-messaging/eventhubs-emulator:latest
volumes:
- ./Config.json:/Eventhubs_Emulator/ConfigFiles/Config.json
ports:
- "5672:5672"
- "9092:9092"
environment:
BLOB_SERVER: azurite
METADATA_SERVER: azurite
ACCEPT_EULA: "Y"
depends_on: [azurite]
azurite:
image: mcr.microsoft.com/azure-storage/azurite:latest
ports:
- "10010:10000"
- "10011:10001"
- "10012:10002"$docker compose up -d$pip install azure-eventhub
Send events with a partition key
import json, csv
from azure.eventhub import EventHubProducerClient, EventData
# The emulator's documented local connection string (in Azure: DefaultAzureCredential, no keys)
CONN = "Endpoint=sb://localhost;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"
producer = EventHubProducerClient.from_connection_string(CONN, eventhub_name="orders")
print("partitions:", producer.get_partition_ids())
with open("../pyspark/data/orders/orders_2026-10-01.csv") as f:
orders = list(csv.DictReader(f))[:40] # the first 40 orders of the day as events
by_customer = {}
for o in orders: # group so each batch has one partition key
by_customer.setdefault(o["customer_id"], []).append(o)
for customer_id, events in by_customer.items():
batch = producer.create_batch(partition_key=customer_id) # same customer -> same partition -> in order
for o in events:
batch.add(EventData(json.dumps(o)))
producer.send_batch(batch)
producer.close()
print(len(orders), "events sent for", len(by_customer), "customers")partitions: ['0', '1', '2', '3']
40 events sent for 35 customersWe sent the first 40 orders of 1 October, batched per customer so each batch carries one partition_key.
Receive, and check ordering
import threading
from collections import Counter
from azure.eventhub import EventHubConsumerClient
def read_all(consumer_group, seconds=8):
seen = []
client = EventHubConsumerClient.from_connection_string(CONN, consumer_group=consumer_group, eventhub_name="orders")
def on_event(partition_context, event):
seen.append((partition_context.partition_id, json.loads(event.body_as_str())))
t = threading.Thread(target=client.receive, kwargs={"on_event": on_event, "starting_position": "-1"})
t.start(); t.join(seconds); client.close(); t.join()
return seen
events = read_all("$Default")
print(len(events), "events read by $Default")
print("per partition:", dict(sorted(Counter(p for p, _ in events).items())))40 events read by $Default
per partition: {'0': 7, '1': 11, '2': 8, '3': 14}# Ordering is guaranteed within a partition: one customer's events all sit in one partition
from collections import defaultdict
parts = defaultdict(set)
for p, e in events:
parts[e["customer_id"]].add(p)
multi = {c: p for c, p in parts.items() if len(p) > 1}
print("customers whose events landed in more than one partition:", len(multi))
busiest = max(parts, key=lambda c: sum(1 for _, e in events if e["customer_id"] == c))
print("customer", busiest, "->", [e["order_id"] for _, e in events if e["customer_id"] == busiest], "in partition", parts[busiest])customers whose events landed in more than one partition: 0
customer 68 -> ['100005', '100035'] in partition {'1'}The 40 events spread over all 4 partitions, and no customer's events were split: customer 68's two orders sit together in partition 1, in order. That's what partition keys buy you.
Consumer groups read independently
# A second consumer group reads the same stream independently (its own position)
analytics = read_all("analytics")
print(len(analytics), "events read by the 'analytics' consumer group")40 events read by the 'analytics' consumer groupThe analytics group read all 40 events too, unaffected by $Default having read them. Give every consuming application its own consumer group.
Into the lakehouse with Spark
# Not run here: reading Event Hubs from Spark with its Kafka-compatible endpoint (Databricks/Fabric)
events = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "evhns-shopkart.servicebus.windows.net:9093")
.option("subscribe", "orders")
.option("kafka.security.protocol", "SASL_SSL")
.option("kafka.sasl.mechanism", "OAUTHBEARER") # Entra ID tokens, no connection-string secrets
.load())From here it's our PySpark streaming lesson: a checkpointed stream into bronze Delta, then foreachBatch MERGEs into silver. Event Hubs Capture can also write raw events to ADLS automatically (Avro/Parquet) with no code.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is a partition in Event Hubs?Fresher+
Q2What is a consumer group?1โ3 yrs+
Q3How do you stream Event Hubs into Delta tables?1โ3 yrs+
Q4Consumers fall behind at peak. What do you do?3+ yrs+
Key takeaways
- โEvent Hubs is the front door for real-time data on Azure.
- โPick partition keys for the ordering you need.
- โOne consumer group per consuming application.
- โSpark reads it like Kafka, and the rest is PySpark streaming.
Frequently asked questions
What is Azure Event Hubs?
A fully managed service for ingesting streams of events (app clicks, orders, IoT telemetry) at high volume. Producers send events to an event hub; consumers read them in order per partition, each tracking its own position. It also exposes a Kafka-compatible endpoint.
How many partitions should I use?
Enough for your peak parallelism: each partition is read by at most one consumer instance per consumer group at a time. Start with 4โ8 for modest streams; the count can be increased on Premium/Dedicated tiers but not decreased.
What are checkpoints?
Saved positions (offsets) per partition and consumer group, usually in Blob Storage, so a consumer that restarts continues where it stopped. Spark Structured Streaming keeps its own checkpoints.
Event Hubs or Service Bus?
Event Hubs for high-throughput event streams read by many consumers (telemetry, clickstreams, CDC). Service Bus for business messages that need queues, transactions, sessions, dead-lettering and per-message handling.
๐ง Quick check: Event Hubs
1. Why send with partition_key=customer_id?
2. Two apps must each read every event at their own pace. Use...
3. starting_position='-1' means...
4. Spark reads Event Hubs most easily through...
Checking your accessโฆ