🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Azure Event Hubs: Partitions, Consumer Groups & Capture

Azure Data EngineeringAzure Event Hubs⭐ Premium

Prerequisites

  • !What an append-only log is and why ordering matters within a segment
  • !Rough idea of how Kafka topics and consumer groups behave
  • !Comfortable with the idea of a data lake landing zone

What You'll Learn

  • 1Calculate throughput units and know when to enable auto-inflate
  • 2Explain what a partition key actually guarantees about ordering
  • 3Use consumer groups so two teams read the same stream independently
  • 4Compare Event Hubs Capture with a Stream Analytics or Flink job
  • 5Troubleshoot a consumer that silently stops making progress

An event hub is a log, not a queue

The distinction that unlocks everything else is this: an event hub does not hand a message to a consumer and delete it. Producers append events to a partition, events stay there for a retention window you choose, and any number of readers may read the same events at their own position. Nothing is consumed in the destructive sense, which is why two teams can independently analyse the same live stream without coordinating.

That model has consequences. Because readers track their own offset, a consumer that falls behind does not block producers and does not lose data, it simply reads further back. Because events are never removed early, retention becomes a storage and cost decision rather than a delivery guarantee. And because there is no per-message acknowledgement, "exactly once" has to be built on top using checkpointing, not assumed from the transport.

Retention default is one day and can extend to ninety days. Shorter retention keeps cost down and forces consumers to keep up; longer retention lets a batch job replay yesterday's window without asking producers to resend.

Partitions, keys and the ordering contract

A partition is an independent log with its own offset sequence. Events are distributed across partitions either round-robin or by a partition key you supply. The guarantee is narrow and interviewers test it precisely: ordering holds within a partition, never across partitions.

If you set the partition key to device_id, then every event from that device lands in the same partition and arrives in send order. If you set nothing, two events from the same device may land in different partitions and be read in either order. So the key is not a performance detail, it is the ordering contract, and choosing it means deciding which identity in your domain must never be observed out of order.

Too many partitions for your throughput means idle partitions and higher cost; too few means a single hot partition that caps consumption. A useful starting point is to size partitions from peak ingest rate and downstream parallelism together: there is no benefit in thirty-two partitions if your sink can only accept four concurrent writers.

SettingEffect on orderingEffect on parallelismChoose it when
No partition keyNone across partitionsMaximum spreadEvents are independent measurements
Key per entityPer-entity order preservedSpread by key hashState depends on a device, user or order
Single key valueEverything in one partitionNoneAlmost never, because it creates a hot partition
Max event size above 1 MBRejected at ingestNot applicableCheck your schema before blaming the network

Consumer groups and the balance problem

A consumer group is a named, independent cursor position over the same log. Every group reads all events from the start of retention unless it has checkpointed. This is how a real-time dashboard and a nightly archival job coexist: different groups, different speeds, no interference.

Within a group, partitions are distributed across the active readers. That distribution is the balance problem. If one reader receives two partitions while another receives none, throughput is limited by the unlucky reader and adding readers does not help until balance evens out. Event Hubs uses a greedy balanced distribution, so balance improves as readers join, but a reader that is slow to claim its partitions still skews the picture for a while.

python
from azure.eventhub import EventHubConsumerClient, EventHubSharedKeyCredential

CONNECTION = "Endpoint=sb://ns-data.servicebus.windows.net/;SharedAccessKeyName=Root;SharedAccessKey=KEY"
STORAGE_CONTAINER = "consumer-checkpoints"

def on_event(partition_context, event):
    body = event.body_as_str(encoding="UTF-8")
    props = event.properties
    # Persist business logic here; checkpoint happens after success
    partition_context.update_checkpoint(event)

client = EventHubConsumerClient.from_connection_string(
    conn_str=CONNECTION,
    consumer_group="$Default",
    checkpoint_store_blobs=STORAGE_CONTAINER,
)

# One process handles the partitions assigned to this reader
with client:
    client.receive(
        on_event=on_event,
        on_error=lambda ctx, err: print("error", err),
        starting_position="-1",
        max_wait_time=30,
    )

$Default is a real consumer group, not a placeholder, and every reader pointed at it shares the balance. Production readers should declare their own group so restarting one service does not reset another's position.

Capture: the cheap path into the lake

Event Hubs Capture continuously writes the incoming stream to Blob or ADLS Gen2 in Avro, on a size or time trigger, without any compute running. For a large fraction of streaming architectures this replaces an entire tier of infrastructure: nothing to schedule, nothing to scale, and the lake gets a faithful, ordered-per-partition copy of everything that arrived.

Capture has clear limits. It writes raw events as they arrive, so it cannot filter, enrich or join. It cannot write to a warehouse. And it delivers at-least-once with a lag of a few minutes, so it is not suitable where the sink must see events in under a second.

az eventhubs eventhub update \
  --resource-group rg-streaming-prod \
  --namespace ns-data-platform \
  --name orders \
  --capture-enabled true \
  --capture-interval 300 \
  --capture-size-limit 314572800 \
  --archive-name-format "orders/{Year}/{Month}/{Day}/{Hour}/{PartitionId}/{EnqueuedTimeUtc}.avro" \
  --blob-container-name raw-events \
  --destination azure-blob-storage

The archive name format deserves attention. Including PartitionId keeps files separated by partition, which preserves the ordering you rely on downstream. Including a time component makes partition-by-date queries cheap. Omitting both produces a flat directory that every reader must scan.

Where a streaming job is still necessary

The moment you need a filter, a windowed aggregation, a join against reference data, or a different sink, you need a compute job reading the stream. Azure Stream Analytics is the managed choice with SQL, Azure Functions or a Flink job in Microsoft Fabric is the code-first choice, and Databricks Structured Streaming is the choice when the logic already lives in Spark.

The architectural decision is whether the job is required for correctness or only for latency. If the sink can be a raw file in the lake that a nightly job processes, Capture alone is correct and the streaming job only buys time. If the sink is an operational store that must reflect a fraud rule within a second, the job is load-bearing and needs its own outage story.

-- Stream Analytics query: windowed aggregate straight into Cosmos DB
WITH
WindowedOrders AS (
  SELECT
    customerId,
    COUNT(*) AS orderCount,
    SUM(orderValue) AS revenue
  FROM orders
  TIMESTAMP BY eventEnqueuedUtcTime
  GROUP BY customerId, TumblingWindow(minute, 5)
)
SELECT
  w.customerId,
  w.orderCount,
  w.revenue,
  c.tier
INTO cosmosOutput
FROM WindowedOrders w
LEFT JOIN customers c
  ON w.customerId = c.id

Note the explicit timestamp clause. Without it, Stream Analytics uses arrival time, which is fine for steady sources and wrong the moment a producer retries or a backlog drains, because then arrival order and event time diverge.

Diagnosing a stalled consumer

A consumer that receives nothing while events keep arriving usually has one of four causes. The reader is in a different consumer group than the one that has the checkpoint. The checkpoint container is unreachable, so offsets cannot be read or written. The reader's identity lacks the Azure Event Hubs Data Receiver role. Or the partitions are balanced away from it because another reader in the same group holds them.

Work through it in that order and stop as soon as the cause appears, because the first three produce a hard failure or a silent no-op while the fourth looks perfectly healthy in logs. The quickest overall test is to read from the beginning of a single partition with a temporary reader and confirm that events arrive at all.

# Does the hub have traffic, and are partitions evenly loaded?
az eventhubs eventhub show \
  --resource-group rg-streaming-prod \
  --namespace ns-data-platform \
  --name orders \
  --query "{partitions: partitionCount, capture: capture.enabled, retention: messageRetentionInDays}"

# Check ingestion vs capture and pending fan-out
az monitor metrics list \
  --resource /subscriptions/SUB/resourceGroups/rg-streaming-prod/providers/Microsoft.EventHub/namespaces/ns-data-platform \
  --metric "IncomingMessages,IncomingBytes,SuccessfulRequests" \
  --interval PT1M --aggregation Total -o table

If IncomingMessages is climbing while your reader sees nothing, the problem is on the read side. If it is flat, look upstream at the producer before touching the consumer.

Common Mistakes

Putting every reader into $Default and assuming each gets its own stream

Fix: Give each application its own consumer group so checkpoint position and restart behaviour stay independent

Assuming ordering across partitions because the producer sends in order

Fix: Set a partition key for any entity whose event order matters, and state the guarantee explicitly in the design

Using Event Hubs Capture as a real-time delivery path

Fix: Treat Capture as a lake landing path with minutes of lag; use a streaming job when the sink must be current

Choosing partition count from ingest rate only

Fix: Size partitions against peak ingest, downstream sink parallelism and retention cost together

Best Practices

  • Enable auto-inflate so a traffic spike does not drop events at the throughput ceiling
  • Include partition ID and event time in the archive path so downstream partition pruning works
  • Checkpoint after successful processing, never before, and keep checkpoint storage in the same region
  • Monitor incoming messages alongside consumer lag; either one alone hides half the picture

Interview Questions

Q1: What ordering guarantee does an event hub provide?

Strict ordering inside a single partition, no ordering across partitions. A partition key guarantees all events for that key share a partition, which is how per-entity ordering is obtained.

Q2: Explain the purpose of a consumer group.

It is an independent checkpoint position over the same log, letting several applications read the same events at their own pace without interfering with each other's offsets.

Q3: When would you use Event Hubs Capture instead of Stream Analytics?

When the destination is Blob or ADLS and the raw events are enough, because Capture runs with no compute and no code. A streaming job is needed for filtering, windowing, enrichment or a non-file sink.

Q4: How does Event Hubs differ from Azure Queue Storage?

A queue removes a message once it is received and gives one consumer exclusive access, while an event hub retains events for a retention period so many consumer groups can replay the whole stream.

Q5: A consumer shows no errors but processes nothing. What do you check?

Consumer group name, checkpoint store reachability, the Data Receiver role on the identity, and partition balance against other readers in the same group.

Key Takeaways

  • Event Hubs is an append-only log with per-consumer offsets, not a destructive queue
  • Ordering exists per partition only, and the partition key is what defines it
  • Consumer groups give independent cursors; production readers should never share $Default
  • Capture lands raw events into ADLS cheaply but with lag and no transformation
  • Partition count, throughput units and retention are the three cost and capacity levers
🔒

Premium Content

Azure Event Hubs: Partitions, Consumer Groups & Capture

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement