Cloud PlatformsComplete guide

Azure Event Hubs

Azure Event Hubs is a fully managed big-data streaming platform that can receive and process millions of events per second with low latency, offering Kafka protocol compatibility and deep Azure ecosystem integration.

Overview

Azure Event Hubs is a managed append-only event streaming service for telemetry, logs, clickstreams, IoT signals, and other high-volume ordered streams. Producers publish batches to a hub, optionally selecting a partition key so related events retain order within one partition. Independent consumer groups read the retained log at their own pace. EventProcessorClient coordinates partition ownership across .NET consumer instances and persists checkpoints, commonly in Blob Storage, but checkpointing is not an atomic transaction with business side effects. Production designs therefore require idempotency, poison-event handling, bounded concurrency, stable partition keys, retention and Capture strategy, schema evolution, managed identity, private networking, throughput capacity, lag monitoring, replay runbooks, and downstream backpressure. Event Hubs also exposes Kafka protocol compatibility, but it remains an Azure service with its own tier and feature model.

What you will learn

  • Explain namespaces, hubs, partitions, keys, sequence, offsets, retention, and consumer groups.
  • Design producer batching, schemas, routing, and client reuse.
  • Operate EventProcessorClient ownership, checkpoints, replay, and idempotent side effects.
  • Choose capacity, partitions, concurrency, Capture, and downstream backpressure.
  • Secure producers, consumers, storage, networks, and deployment identities.
  • Test lag, throttling, poison events, rebalances, retention loss, and disaster recovery.

Prerequisites

  • Event streaming, async workers, serialization, eventual consistency, and idempotency.
  • Azure identity, RBAC, Blob Storage, networking, monitoring, and Bicep.
  • Capacity planning, load testing, schema evolution, and recovery procedures.

When to use Azure Event Hubs

Good fit

  • High-volume append-only events need replay and independent consumers.
  • Per-key ordering and partitioned scale fit the domain.
  • Stream analytics or Capture-based data pipelines are required.

Choose another approach when

  • Commands need queue locks, dead lettering, sessions, or transactional broker features.
  • Strict global ordering is required at high parallelism.
  • The workload is simple request-response or low-volume task dispatch.

Key concepts

Namespace, hub, and partitions

A namespace contains event hubs; each hub is an ordered set of fixed partition logs that provide the unit of parallel consumption.

Partition keys and ordering

A stable key routes related events to one partition and preserves their order there; global ordering is not provided across partitions.

Producers and batching

Producers reuse clients and send bounded batches; routing choice, event size, retry, and idempotent semantics affect throughput and hot partitions.

Consumer groups

Each logical application uses its own independent view of the stream, partition ownership, position, and checkpoint namespace.

EventProcessorClient

The .NET processor cooperates with peer instances to claim partitions, rebalance ownership, receive events, and persist progress.

Checkpoints and replay

A checkpoint records the last completed position, reducing recovery replay but never making external side effects exactly once.

Retention, Capture, and schema

Time-based retention supports short replay; Capture archives events for longer recovery and analytics while schemas evolve compatibly.

Capacity and operations

Throughput or processing units, partitions, quotas, throttling, consumer lag, network paths, identity, and disaster recovery define production limits.

Architecture

Producers send events to Event Hubs partitions; EventProcessorClient instances compete for partition ownership and checkpoint progress to Blob Storage; Capture writes the stream to Data Lake for batch consumers.

Event producers
Event Hubs partitions
EventProcessorClient cluster
Azure Blob / Data Lake

Conceptual architecture · Adapt to your system context

Implementation walkthrough

Build the critical path deliberately, then verify its observable behavior.

  1. 01
    Define stream contracts

    Document event IDs, keys, schemas, owners, volume, ordering, retention, sensitivity, and consumers.

  2. 02
    Choose tier and partitions

    Model event size, ingress, egress, parallelism, retention, Capture, availability, and growth.

  3. 03
    Build producers

    Reuse clients, batch safely, apply stable keys only when needed, and emit versioned metadata.

  4. 04
    Build consumer isolation

    Assign one consumer group and checkpoint scope per application and use EventProcessorClient for coordination.

  5. 05
    Make effects replay-safe

    Validate events, deduplicate atomically, bound retries, quarantine poison records, then checkpoint.

  6. 06
    Secure and deploy

    Provision identity, RBAC, networking, hub, consumer groups, checkpoint storage, Capture, diagnostics, and alerts with code.

  7. 07
    Load and recovery test

    Measure skew and lag, kill processors during work, rebalance instances, replay from archive, and test retention-window failure.

Code example

EventProcessorClient handles partition ownership and checkpoint coordination. This simple handler processes one event at a time and checkpoints only after success; high-throughput applications should checkpoint at a deliberate interval rather than writing a checkpoint for every event.

OrderEventProcessor.cs
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Processor;
using Azure.Storage.Blobs;

var storageClient = new BlobContainerClient(
    config["Storage:ConnectionString"],
    "event-checkpoints");

var processor = new EventProcessorClient(
    storageClient,
    "orders-consumer-group",
    config["EventHubs:ConnectionString"],
    "order-events");

processor.ProcessEventAsync += async args =>
{
    try
    {
        var body = args.Data.Body.ToArray();
        var orderEvent = JsonSerializer.Deserialize<OrderPlaced>(body);

        if (orderEvent is not null)
        {
            logger.LogInformation(
                "Processing order {OrderId} from partition {Partition}",
                orderEvent.OrderId,
                args.Partition.PartitionId);

            await orderService.ProcessAsync(orderEvent, args.CancellationToken);
        }

        // Simple example: checkpoint after success. At scale, checkpoint less often.
        await args.UpdateCheckpointAsync(args.CancellationToken);
    }
    catch (Exception ex)
    {
        logger.LogError(ex,
            "Failed to process event from partition {Partition}",
            args.Partition.PartitionId);
        // Do NOT checkpoint on failure — event will be reprocessed
    }
};

processor.ProcessErrorAsync += args =>
{
    logger.LogError(args.Exception,
        "Event Hubs processor error on partition {Partition}",
        args.PartitionId);
    return Task.CompletedTask;
};

await processor.StartProcessingAsync();
await Task.Delay(Timeout.Infinite); // Keep alive
await processor.StopProcessingAsync();

Testing strategy

Prove application logic locally and authoritative platform behavior in an isolated Event Hubs environment.

  • Unit test schemas, partition-key selection, idempotency, retry classification, poison routing, and checkpoint decisions.
  • Integration test serialized events, producer batches, EventProcessorClient, and Blob checkpoint access.
  • Run multiple processor instances and verify ownership balancing during scale and crashes.
  • Crash after a durable side effect but before checkpointing to prove replay safety.
  • Load test event size, batching, key skew, ingress, egress, lag, throttling, and downstream saturation.
  • Replay from a chosen offset or Capture archive and rehearse retention-loss recovery.

Security considerations

Secure the namespace, hub, checkpoint storage, Capture destination, network, identities, and event data.

  • Use managed identity and least-privilege Event Hubs Data Sender or Receiver roles.
  • Use separate identities and scopes for producers, each consumer, Capture, and deployment.
  • Disable local authentication where all clients support Entra ID and rotate unavoidable SAS credentials.
  • Use TLS and private endpoints with complete DNS and egress design when required.
  • Do not place secrets or unnecessary PII in event bodies, properties, logs, or partition keys.
  • Protect checkpoint and archive storage from public access and destructive permissions.

Performance and scalability

Throughput depends on event size, batch efficiency, partition distribution, capacity units, consumers, and downstream work.

  • Batch producer sends within service limits and reuse long-lived clients.
  • Track per-partition ingress and lag to detect hot keys masked by namespace totals.
  • Tune processor batch, prefetch, and concurrency from downstream capacity.
  • Scale consumers only up to useful partition parallelism within a consumer group.
  • Checkpoint at a cadence that balances storage operations and acceptable replay.
  • Autoscale or increase capacity before sustained throttling, then verify end-to-end useful throughput.

Deployment and operations

Provision the complete streaming path and promote consumers with schema and replay compatibility.

  • Deploy namespace, hub, partitions, retention, consumer groups, storage, Capture, identity, RBAC, network, diagnostics, and alerts with code.
  • Keep local authentication disabled when identity migration is complete.
  • Deploy producers before consumers only when schema compatibility permits.
  • Use separate consumer groups for blue-green validation without stealing partitions.
  • Smoke publish and consume a uniquely identified event and verify checkpoint and telemetry.
  • Rollback or replay only with idempotency and schema compatibility proven.

Common problems and fixes

Consumer instances run but lag grows

Likely cause: Hot partitions, insufficient units, downstream saturation, throttling, or excessive per-event work limits useful throughput.

Fix: Graph per-partition age, rate, ownership, throttles, duration, and dependency capacity; tune or repartition future keys deliberately.

Events repeat after restart

Likely cause: The last side effects occurred after the saved checkpoint or processing crashed before checkpointing.

Fix: Treat replay as normal, make effects idempotent, and choose checkpoint cadence from recovery objectives.

Some consumer instances stay idle

Likely cause: A consumer group cannot usefully assign more active processors than partitions.

Fix: Compare partition and instance counts and scale only to useful parallelism.

Processor repeatedly loses ownership

Likely cause: Checkpoint storage latency, inconsistent configuration, duplicate processor identifiers, or aggressive load balancing destabilizes leases.

Fix: Verify shared checkpoint scope, storage health, processor settings, time synchronization, and version consistency.

Authentication succeeds locally but fails in Azure

Likely cause: Credential source, token audience, RBAC data role scope, DNS, firewall, or private endpoint configuration differs.

Fix: Inspect the deployed identity, role propagation and scope, fully qualified namespace, token audience, and network path.

Replay cannot reach old events

Likely cause: The retention window expired and no suitable Capture archive exists.

Fix: Set retention from outage objectives, enable and monitor Capture, and rehearse archive replay before an incident.

Best practices

  • Choose partition count from long-term peak parallelism and throughput because it is a durable architectural constraint.
  • Use high-cardinality stable partition keys only when per-key order matters, and monitor for hot partitions.
  • Reuse producer clients, build bounded batches, handle partial batch sizing, and propagate event IDs, schema versions, and correlation.
  • Give every logical application its own consumer group and checkpoint store prefix.
  • Checkpoint only after durable successful side effects at a measured cadence, and make the sink idempotent for replay.
  • Bound processor concurrency, prefetch, and batches to downstream capacity; quarantine poison events without blocking a partition forever.
  • Use managed identity, least-privilege data roles, TLS, private networking where required, and disable local authentication when feasible.
  • Monitor ingress, egress, throttling, partition skew, consumer lag and event age, checkpoint health, errors, retention risk, and Capture.

Production checklist

  • Event contracts, keys, schemas, ordering, volume, retention, sensitivity, and owners are documented.
  • Tier, capacity, partitions, consumer groups, and Capture match long-term requirements.
  • Producers reuse clients, batch safely, and emit event ID, schema version, and correlation.
  • Consumers are idempotent, bounded, cancellation-aware, poison-safe, and checkpoint after durable success.
  • Managed identities, least-privilege roles, TLS, storage controls, and network paths are verified.
  • Per-partition skew, lag, age, throttling, errors, checkpoint health, retention risk, and Capture are monitored.
  • Scale, crash, rebalance, replay, schema rollback, retention loss, and regional recovery are rehearsed.

Common interview questions

Event Hubs versus Service Bus?

Event Hubs is a retained partitioned stream for high-throughput telemetry and independent readers. Service Bus is a broker for commands and workflows with queues, topics, locks, dead lettering, sessions, and transactions.

What ordering does Event Hubs guarantee?

Events have a defined sequence within one partition. There is no total order across partitions, so related ordered events must share a partition key.

What does EventProcessorClient do?

It coordinates partition ownership and load balancing across consumer instances, receives events, and uses a checkpoint store to resume progress.

Why is checkpointing not exactly once?

The business side effect and checkpoint are separate operations. A crash after the side effect but before the checkpoint causes replay.

Why use separate consumer groups?

Each logical consumer needs independent partition ownership and progress; sharing a group makes instances cooperate and split events rather than each receive the stream.

How does Kafka compatibility affect design?

Kafka clients can use the Event Hubs Kafka endpoint, but supported features, authentication, capacity, retention, and operational controls remain those of the chosen Event Hubs tier.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Event Hubs Checkpoint Processor

A .NET 10 local stream processor demonstrating stable partition keys, ordered sequences, checkpoints, bounded processing, replay-safe idempotency, and Event Hubs Bicep.

.NET 10Azure Event HubsAzure StorageBicep
dedicated-sampleevent-streamingcheckpointingidempotency
Run
dotnet run --project src/EventHubsCheckpointProcessor
Test
dotnet test EventHubsCheckpointProcessor.slnx