How a log of events becomes a queryable history
Prerequisites
- !Event Hubs basic concepts: namespaces, hubs, and consumer groups
- !Azure Storage blobs and ADLS Gen2 containers
- !At-least-once versus exactly-once delivery semantics
What You'll Learn
- 1Reason about ordering guarantees per partition and design keys that preserve them
- 2Configure Event Hubs Capture with sane archive formats and naming
- 3Choose partition counts and throughput units from measured traffic
- 4Replay events from a specific offset or timestamp after an incident
The one thing every Event Hubs interview gets wrong
Candidates often claim Event Hubs guarantees global ordering across the whole hub. It does not. Ordering exists only inside a single partition, enforced by a monotonically increasing sequence number that each partition assigns as events arrive. Once two events land in different partitions, their relative order is undefined forever. This single fact drives the entire partitioning design: if your consumer must process a device's readings in arrival order, every event from that device must share a partition key so the hub routes them to the same partition. If you omit the key, the producer client round-robins events across partitions and per-device ordering silently breaks.
The corollary is throughput design. Partitions are the unit of parallelism for consumers: a consumer group with more active readers than partitions wastes the extra readers, because each partition is leased to exactly one reader within a group. So you need enough partitions for your peak consumer parallelism, but not so many that you pay for idle ones. Standard tier hubs support up to 32 partitions and Premium supports up to 128, so the ceiling is usually not the constraint; the discipline of choosing deliberately is.
Partition keys, hot partitions, and the producer contract
When you supply a partition key, the hub hashes it and routes the event to the corresponding partition. The hash is stable, so the same key always lands in the same partition and ordering holds. The failure mode is the hot partition: if your key space is tiny, say a region identifier with three values, one partition absorbs roughly a third of all traffic while the rest sit idle. A good key has high cardinality and an even distribution, which typically means a device ID, a user ID, or a tenant ID, never a timestamp or a status flag.
import json
from azure.eventhub import EventHubProducerClient, EventData, EventHubConsumerClient
CONN_STR = "Endpoint=sb://ns-dataeng.servicebus.windows.net/;SharedAccessKeyName=send;SharedAccessKey=..."
def send_reading(device_id: str, temperature: float) -> None:
producer = EventHubProducerClient.from_connection_string(
CONN_STR, eventhub_name="iot-readings"
)
try:
event = EventData(json.dumps({
"device_id": device_id,
"temperature": temperature,
"event_ts": "2026-03-14T10:22:31Z",
}))
# Key by device so per-device order is preserved inside the partition
producer.send_batch([event], partition_key=device_id)
finally:
producer.close()
def verify_distribution(hub_name: str) -> None:
"""Read one consumer group and count events per partition."""
counts = {}
def on_event(partition_context, event):
pid = partition_context.partition_id
counts[pid] = counts.get(pid, 0) + 1
partition_context.update_checkpoint()
client = EventHubConsumerClient.from_connection_string(
CONN_STR, consumer_group="$Default", eventhub_name=hub_name
)
try:
client.receive(on_event, starting_position="-1", max_wait_time=10)
finally:
client.close()
for pid, n in sorted(counts.items(), key=lambda kv: -kv[1]):
print(f"partition {pid}: {n} events")
Run the distribution check after any key-design change. If the busiest partition carries more than roughly one and a half times the average of the others, your key cardinality is too low and you are paying for parallelism you cannot use.
Capture: turning the stream into a lake without code
Event Hubs Capture is a namespace-level feature that durably lands every event into ADLS Gen2 or blob storage on a time or size trigger, completely independent of any consumer application. This is the cheapest possible way to satisfy the "we need a replayable archive" requirement, because there is no cluster to run and no code to maintain. Capture writes either Avro or Parquet; choose Parquet whenever downstream consumers are analytical engines like Synapse serverless or Databricks, because columnar statistics let those engines skip files.
The archive name format matters more than it looks. Including the partition ID and the timestamp means a downstream reprocessing job can reconstruct per-partition order by sorting file names, and can do time-windowed reads without listing the entire container. Set skipEmptyArchive to true so quiet partitions do not produce hourly zero-byte files that clutter the lake and inflate small-file counts.
| Capture setting | Recommended value | Why |
|---|---|---|
| Encoding | Parquet | Columnar stats enable file skipping in Synapse and Databricks |
| Time window | 5 minutes | Balances file count against replay granularity |
| Size limit | 100 MB | Avoids tiny files without creating oversized blobs |
| Name format | Namespace, hub, partition, Y, M, D, H, min, sec | Enables ordered, time-windowed replay |
| Skip empty archive | true | Prevents zero-byte clutter in the lake |
{
"properties": {
"captureDescription": {
"enabled": true,
"encoding": "Parquet",
"destination": {
"properties": {
"storageAccountResourceId": "/subscriptions/SUB/resourceGroups/RG/providers/Microsoft.Storage/storageAccounts/stlake001",
"blobContainer": "eventhubs-capture",
"archiveNameFormat": "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}",
"timeWindow": "00:05:00",
"sizeLimitInBytes": 104857600
}
},
"skipEmptyArchive": true
}
}
}
Throughput units, scaling, and what actually throttles you
Throughput units (TU on Standard, PU on Premium) are the currency of Event Hubs performance. One Standard TU buys ingress of up to 1 megabyte per second or 1,000 events per second, plus a matching egress allowance. Autoscale can raise the TU count within a namespace, but it reacts after the fact, so sustained production workloads should set a floor above measured peak rather than relying on reactive scaling. Premium tier removes the shared-tenant noisy-neighbor problem entirely and adds features like customer-managed keys and increased partition ceilings, which is why it is the right choice once latency SLOs harden.
A subtlety interviewers love: adding partitions increases potential consumer parallelism but does not increase per-partition ordering capacity, and adding TUs increases raw ingest bandwidth. If your producer is throttled with a retriable error, you need more TUs. If your consumer group cannot keep up and readers are CPU-bound, you need more partitions or more consumer instances, up to the partition count. These are orthogonal levers, and confusing them wastes a scaling meeting.
from azure.mgmt.eventhub import EventHubManagementClient
from azure.identity import DefaultAzureCredential
def scale_namespace(subscription_id: str, rg: str, ns: str, tus: int) -> None:
mgmt = EventHubManagementClient(DefaultAzureCredential(), subscription_id)
# Pre-provision the TU ceiling; autoscale operates inside this bound
patch = {"sku": {"name": "Standard", "capacity": tus}}
ns_obj = mgmt.namespaces.begin_update(rg, ns, patch).result()
print(f"{ns} scaled to capacity {ns_obj.sku.capacity}")
# Throttle detection query used from Log Analytics (KQL), not the management SDK:
# AzureMetrics
# | where ResourceProvider == "MICROSOFT.EVENTHUB"
# | where MetricName == "ThrottledRequests"
# | summarize Throttled = summax(Total) by bin(TimeGenerated, 5m)
# | where Throttled > 0
Monitoring and the replay playbook
The metrics that matter are IncomingMessages, IncomingBytes, OutgoingBytes, and critically, ThrottledRequests. A rising throttle count with flat throughput means you have hit the TU ceiling; a flat throttle count with rising consumer lag means the problem is downstream. For consumer lag specifically, the cheapest signal is checkpoint age: how long since each consumer group last wrote a blob checkpoint for each partition. An old checkpoint on one partition with fresh ones on the rest is the classic signature of a skewed key.
When a downstream bug requires replay, you have two paths. If the consumer uses checkpointing, you can reset the offset by creating a new consumer group and starting it at a chosen sequence number or UTC timestamp; the hub retains events for the retention period, which is one day on Standard and up to seven on Premium and Capture-enabled configurations. If you enabled Capture, the archive in ADLS is the durable long-term replay source and does not expire with hub retention, which is the argument for turning Capture on even when no consumer currently needs the files.
from datetime import datetime, timezone
from azure.eventhub import EventHubConsumerClient
replay_from = datetime(2026, 3, 14, 9, 0, tzinfo=timezone.utc)
received = []
def collect(partition_context, event):
received.append((partition_context.partition_id, event.sequence_number,
event.body_as_str()))
# Note: no checkpoint update, so a restart replays again from the same point
client = EventHubConsumerClient.from_connection_string(
CONN_STR, consumer_group="replay-audit", eventhub_name="iot-readings"
)
try:
client.receive(
collect,
starting_position=replay_from,
max_wait_time=30,
max_events=5000,
)
finally:
client.close()
print(f"replayed {len(received)} events from {replay_from.isoformat()}")
Consumer groups: independent cursors over one log
A consumer group is a named, independent cursor over the same partitioned log. Each group tracks its own offset per partition, so an analytics consumer lagging by six hours never blocks an alerting consumer reading in real time. This is the mechanism that lets one Event Hub feed Delta landings, real-time anomaly detection, and a partner API simultaneously without the consumers interfering with each other. The practical limit is that within a single group, one partition is leased to exactly one active reader, so adding a second reader to the same group does nothing unless you also add partitions.
Design groups per downstream purpose, not per team. A group named "analytics" that three teams read from with independent checkpoints will produce confusing lag metrics and mysterious rebalancing when one team's reader restarts. A group named "delta-landing" with one owner and one checkpointing consumer produces metrics that mean what they say. Checkpointing itself belongs in durable storage, typically a blob container, because an in-memory offset lost on restart means replaying from the beginning of retention, which is a costly surprise on a high-volume hub. Consumer instances should also handle transient ownership loss gracefully: when a reader crashes, the partition is reassigned to a sibling in the same group after an expiration window, and your handler must tolerate seeing events it already processed.
Common Mistakes
Believing Event Hubs orders events across the entire hub
Fix: Design for per-partition ordering only; use partition keys derived from entity IDs whenever a consumer needs a guaranteed sequence
Choosing a low-cardinality partition key like region or status to keep things simple
Fix: Measure the partition histogram after deploy and switch to high-cardinality keys such as device_id or tenant_id if the hottest partition exceeds 1.5 times the average
Treating Capture as optional because a consumer already persists to Delta
Fix: Enable Capture anyway for long-term replayable archives; hub retention is measured in days while Capture files persist in ADLS indefinitely
Scaling throughput units when the real problem is consumer lag
Fix: Check ThrottledRequests first; if throttles are flat, add partitions or consumer instances instead of TUs
Best Practices
- Set a TU floor above measured peak rather than depending on autoscale during traffic spikes
- Name Capture archives with partition ID and timestamp so reprocessing can reconstruct order without listing the whole container
- Use a dedicated consumer group for replay audits so production groups keep their checkpoints intact
- Alert on checkpoint age per partition, not just on aggregate throughput
- Prefer Premium tier for latency-sensitive workloads that cannot tolerate shared-tenant interference
Interview Questions
Q1: What ordering guarantee does Event Hubs provide?
Events are totally ordered within a single partition by sequence number. There is no ordering across partitions. The partition key determines which partition receives an entity's events, so keying by a device or user ID preserves that entity's order while sacrificing global order.
Q2: How do you replay events from a specific point in time?
Create or reuse a consumer group and start the consumer at a UTC timestamp or sequence number instead of at the latest offset. The hub retains events for the configured retention period. For longer-term replay, read the Capture files written to ADLS Gen2, which persist beyond hub retention.
Q3: You see one partition at 90 percent utilization while the rest sit at 10 percent. What is wrong?
This is a hot partition caused by a skewed partition key, typically low-cardinality like a region code, or by omitting the key so the client-side round-robin is hashing unevenly. Redesign the key for cardinality, or if a single tenant genuinely dominates traffic, isolate that tenant onto its own hub.
Q4: When would you choose Premium over Standard tier?
When you need dedicated throughput without shared-tenant interference, more partitions, customer-managed keys, longer retention, or private endpoints. Standard is fine for development and tolerant batch ingestion; Premium is the production choice for latency-bound streaming.
Key Takeaways
- Ordering is a per-partition property enforced by sequence numbers; the partition key is the only lever that preserves entity-level order
- Partitions set consumer parallelism, throughput units set ingest bandwidth; scaling one does not fix the other
- Capture lands every event into ADLS as Avro or Parquet with zero application code and is the durable replay story
- Watch ThrottledRequests to separate TU limits from consumer lag, and checkpoint age to find the slow partition
- Replay by starting a consumer group at a timestamp or by reading Capture archives, depending on how far back you must go