🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Real-Time Pipeline: Event Hubs → Stream Analytics → Cosmos DB

Azure Data EngineeringStreaming Pipeline⭐ Premium

Prerequisites

  • !Event Hubs partitions and consumer groups
  • !What a tumbling window is in stream processing
  • !Cosmos DB partition keys and consistency levels

What You'll Learn

  • 1Assemble ingest, process and serve stages with explicit guarantees
  • 2Choose a Cosmos DB partition key for a real-time serving workload
  • 3Design idempotent writes so replays do not corrupt state
  • 4Measure and alert on end-to-end lag rather than on errors
  • 5Decide when a raw archive path should run alongside the live path

Real time is a latency budget, not a vibe

"Real time" means nothing until someone attaches a number to it. Fraud scoring inside one second, a dashboard that refreshes within fifteen seconds, and a nightly report that is merely early are three different architectures wearing the same label. The first needs the processing in the request path or immediately after it, the second tolerates windowing, and the third needs nothing streaming at all.

Decomposing the budget makes the design obvious. Ingest latency, processing latency, sink write latency and client refresh each take a slice. If the total is one second, a tumbling window of one minute is disqualified immediately regardless of how attractive it looks, and you are pushed toward per-event processing or very short windows.

The second decision is whether the serving layer must be correct or merely current. A live counter that is occasionally a second behind is acceptable if the underlying write is idempotent. A payment decision that must never be applied twice needs a transactional boundary, which usually means the write path carries a deterministic identifier and the sink enforces uniqueness.

Latency targetTypical windowServing choiceFailure posture
Under 1 secondNone, per eventCosmos DB or a cacheMust be idempotent, retried aggressively
1 to 15 secondsShort or no windowCosmos DB with TTLAt-least-once plus deduplication
15 seconds to 5 minutesTumbling windowCosmos DB or warehouseCorrectness beats freshness
Beyond 5 minutesMicro-batchBlob or Delta, then queryArchive-first, live path optional

Ingest and buffering: Event Hubs as the shock absorber

Producers should never write directly to the serving database. A downstream outage then becomes an upstream outage, and the operational coupling spreads until every producer needs to know about every sink. An event hub sits in between and absorbs bursts with retention, so a Cosmos DB maintenance window costs a delay rather than a data loss.

Partitioning at ingest determines what parallelism you can ever have downstream. Keying on the entity whose order must be preserved, such as a device or account, keeps that entity in one partition while spreading everything else. Throughput units bound ingest capacity and should auto-inflate so a traffic spike does not silently drop events at the ceiling.

A raw archive path is worth running in parallel, usually through Event Hubs Capture into ADLS. It costs almost nothing because there is no compute, and it turns every future question about what the live path did into a query over files rather than an argument about logs.

Processing: keep the logic boring

Stream Analytics is the default choice for SQL-shaped windowed aggregation, and the discipline is to keep the query simple. Complex enrichment, external API calls or long-lived session state belong in a Flink job or Structured Streaming, where code is a first-class citizen rather than a constraint.

Idempotency belongs in the processing layer, not only the sink. Emitting one row per window with a deterministic identifier derived from the window start and group key means a replay overwrites rather than duplicates. Emitting a row with no identity means every replay adds a phantom.

WITH
Accumulated AS (
  SELECT
    deviceId,
    SUM(reading)        AS totalReading,
    COUNT(*)            AS eventCount,
    MAX(eventTime)      AS lastEvent,
    System.Timestamp()  AS windowEnd
  FROM iotHub
  TIMESTAMP BY eventTime
  GROUP BY deviceId, TumblingWindow(second, 10)
)
SELECT
  deviceId,
  totalReading,
  eventCount,
  lastEvent,
  CONCAT(deviceId, '/', CAST(windowEnd AS NVARCHAR(50))) AS documentId
INTO cosmosSink
FROM Accumulated;

The documentId is the whole trick. Concatenating the natural key with the window end gives Cosmos DB a stable identity, so output upsert semantics turn a duplicate delivery into a harmless overwrite.

Serving: partition keys and consistency in Cosmos DB

The partition key is the single most consequential Cosmos DB decision, and it cannot be changed after data exists. It determines physical storage distribution, the scope of every cross-partition query and the unit of transactional consistency.

For a device telemetry store, the device identifier is usually right: all documents for one device land together, reads by device are single-partition and cheap, and writes for one device can be transactional. Choosing a high-cardinality key that spreads every document alone gives distribution but no locality; choosing a low-cardinality key such as region recreates the hot partition problem that Event Hubs partitions were designed to avoid.

Consistency level is the other lever. Session consistency is the sensible default for a read-after-write dashboard, because a client that writes then reads sees its own write without paying for multi-region latency. Bounded staleness suits analytics read paths where a few seconds of drift is irrelevant. Strong consistency across regions is expensive and rarely justified for telemetry.

# Container with a partition key path, TTL and a uniqueness guarantee
az cosmosdb sql container create \
  --account-name cosmos-iot-prod \
  --database-name telemetry \
  --name readings \
  --partition-key-path "/deviceId" \
  --default-ttl -1 \
  --throughput 1000 \
  --unique-key-policy '[{"kind":"Path","path":"/documentId"}]'

The unique key policy is the enforcement half of the idempotency story. Even if a bug produces two documents for the same window, the container rejects the second rather than corrupting the aggregate.

Backpressure and what happens when the sink slows

Every streaming system eventually meets a sink slower than its input, and the only question is how it behaves then. Event Hubs absorbs the difference into retention. Stream Analytics scales with streaming units until it hits its own ceiling. Cosmos DB throttles with HTTP 429 responses, which the writer must back off on rather than retry immediately.

The visible symptom is growing lag: the difference between the newest event enqueued and the position the processor has reached. Lag is the health metric of a streaming pipeline, because it integrates every upstream and downstream problem into one number. Error counts miss the dangerous case where everything succeeds but slowly.

Alert thresholds should be set from the burn-down rate rather than a guess. If the pipeline normally drains a backlog of ten thousand events in two minutes, an alert at five minutes of sustained backlog means something has genuinely degraded, while a momentary spike during a deploy does not page anyone.

Observability across three services

A real-time path fails in the seams: producer to hub, hub to processor, processor to sink. Each seam has its own metric, and watching only one leaves you guessing. Incoming messages at the hub tells you producers are working. Input events and late events at the processor tells you whether the query is struggling or the data is simply late. Success and throughput at the sink tells you whether writes are being throttled.

Correlating them requires a shared identifier. A run identifier propagated from the producer into message properties, carried through the processor and written into the served document, lets you trace one event end to end. Without it, three healthy dashboards can coexist while the user-visible latency is unexplained.

# End-to-end check in three commands
az monitor metrics list \
  --resource /subscriptions/SUB/resourceGroups/rg-streaming/providers/Microsoft.EventHub/namespaces/ns-iot \
  --metric IncomingMessages --interval PT1M --aggregation Total -o table

az stream-analytics job show \
  --resource-group rg-streaming --name asa-iot-agg \
  --query "{su: streamingUnits, state: provisioningState}"

az monitor metrics list \
  --resource /subscriptions/SUB/resourceGroups/rg-streaming/providers/Microsoft.DocumentDB/databaseAccounts/cosmos-iot-prod \
  --metric "NormalizedRUConsumption,ThrottledRequests" --interval PT1M --aggregation Average -o table

If incoming messages rise while throughput at the sink is flat, the problem is between them. If input events at the job are flat while the hub receives traffic, the problem is the job's input binding or its consumer position.

When to abandon the live path

Some workloads are better served by a micro-batch over the lake. If consumers query by partition and tolerate minutes of delay, writing raw events to ADLS through Capture and materialising a serving table every five minutes costs a fraction of a continuously running processor and is far easier to recover.

The honest design conversation is about the cost of the live path against the value of the reduced latency. Keeping both is common: a cheap archive for correctness and replay, plus a live path for the specific consumers who genuinely need seconds. Naming which consumers those are is how you keep the live path from becoming permanent infrastructure nobody chose deliberately.

Common Mistakes

Writing producers directly to Cosmos DB so the path is shorter

Fix: Buffer through Event Hubs so a sink outage becomes a delay rather than an upstream failure

Choosing a Cosmos DB partition key for write distribution alone

Fix: Optimise for the read and transaction pattern of the workload, since the key cannot be changed after data exists

Emitting results without a deterministic identifier

Fix: Derive a stable document ID from the natural key and window so replayed output overwrites instead of duplicating

Alerting on error counts only

Fix: Alert on sustained end-to-end lag, which captures slow-but-successful degradation that errors never reveal

Best Practices

  • Publish a raw archive alongside the live path so questions become queries
  • Set a unique key in the container as a backstop against upstream idempotency bugs
  • Propagate a correlation identifier from producer to served document
  • Derive alert thresholds from measured drain rates rather than round numbers

Interview Questions

Q1: Why put Event Hubs between producers and the serving database?

It decouples availability. The hub absorbs bursts and retains events, so a Cosmos DB outage causes delay rather than data loss, and producers never need to know about the sink.

Q2: How do you make a windowed aggregation safe to replay?

Emit one document per window with an identifier derived from the natural key and window end, and set output to upsert so repeated delivery overwrites rather than duplicates.

Q3: What makes a good Cosmos DB partition key for telemetry?

One that matches the dominant read and transaction pattern, such as device ID, giving single-partition reads and writes while staying high enough in cardinality to avoid a hot partition.

Q4: Which metric tells you a streaming pipeline is degrading?

End-to-end lag between the newest enqueued event and the processed position. Error counts stay flat while the pipeline falls behind.

Q5: When is a micro-batch over the lake preferable to a live path?

When consumers tolerate minutes of delay and query by partition. The archive-first approach is cheaper, simpler to recover and easier to justify than continuously running compute.

Key Takeaways

  • Attach a latency number to real time before choosing any service
  • Buffer through a log so failures become delays instead of losses
  • Idempotency requires a deterministic identifier written into the serving document
  • Partition key and consistency level shape the Cosmos DB workload more than throughput does
  • Lag, not error rate, is the honest health metric of a streaming pipeline
🔒

Premium Content

Real-Time Pipeline: Event Hubs → Stream Analytics → Cosmos DB

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