Prerequisites
- !Event time versus arrival time and why they differ
- !Basic SQL: SELECT, GROUP BY, JOIN
- !A rough sense of what a tumbling interval is
What You'll Learn
- 1Choose between tumbling, hopping, sliding and snapshot windows by the question being asked
- 2Write a temporal join that tolerates late and missing reference rows
- 3Explain streaming units, parallelism and where a job silently throttles
- 4Handle late-arriving events with adjust latency and watermarks
- 5Decide when Stream Analytics is the wrong tool for the job
What the query engine actually does
Azure Stream Analytics takes one or more inputs, runs a continuous SQL query over them, and pushes rows to one or more outputs. There is no interactive session and no table to store: the query is the job, and changing it means redeploying the job. Everything you can express must fit inside that SQL dialect, which is simultaneously its greatest strength and its hardest constraint.
The engine processes events in batches defined by the out-of-order tolerance. Within each batch it evaluates window functions, joins and aggregations, then emits results. Because output rows may be emitted more than once if a job restarts or a batch is retried, every downstream write should be idempotent. Upserting into Cosmos DB with a deterministic identifier, or writing to a partitioned path keyed by window start, both work. A plain append into a billing table does not.
Three settings govern behaviour before you write a single line of SQL: the timestamp column used for event time, the late-arrival window, and the compatibility level. The first is the one people get wrong most often, because defaulting to arrival time produces aggregates that look plausible and are quietly incorrect under backlog.
Choosing a window
A window defines which events are grouped together. The four built-in shapes answer four different questions, and picking the wrong one is the most common Stream Analytics design error.
| Window | Shape | Emits | Use it for |
|---|---|---|---|
| Tumbling | Fixed, non-overlapping intervals | One row per interval | Per-minute counts, hourly revenue |
| Hopping | Fixed size, fixed hop smaller than size | One row per hop, each covering a longer span | Moving averages where several rows overlap |
| Sliding | Moves with every event | Rows only when the content changes | Exact continuous aggregates with no empty windows |
| Snapshot | Same instant across all partitions | One row per distinct timestamp | Correlating events that share a timestamp |
Tumbling windows are the default answer for dashboards. Hopping windows overlap, so the same event appears in several output rows, which is correct for a rolling average but produces double counting if you sum the output naively. Sliding windows emit only on change, so a quiet stream produces no rows at all, which is fine for a trigger and confusing for a chart.
WITH
OrdersTumbling AS (
SELECT
region,
COUNT(*) AS orderCount,
SUM(orderValue) AS revenue,
AVG(orderValue) AS avgOrder,
System.Timestamp() AS windowEnd
FROM orders
TIMESTAMP BY eventEnqueuedUtcTime
GROUP BY region, TumblingWindow(minute, 5)
),
OrdersRolling AS (
SELECT
region,
AVG(orderValue) AS rollingAvg15m
FROM orders
TIMESTAMP BY eventEnqueuedUtcTime
GROUP BY region, HoppingWindow(minute, 15, 5)
)
SELECT * INTO ordersOut FROM OrdersTumbling;
SELECT * INTO rollingOut FROM OrdersRolling;
Note that each SELECT feeds its own output. A Stream Analytics query is a graph of streams, not a result set, so a single statement cannot feed two sinks without being written twice or materialised through a intermediate step.
Event time, late data and adjust latency
Event time is when something happened; arrival time is when the platform saw it. A device with a dropped connection, a producer retrying after a timeout, or a backlogged Event Hub all break the assumption that these are close together.
Stream Analytics handles this with the timestamp clause plus a late-arrival window, configured on the job as adjust latency. Setting tolerance to zero means an event whose window has already been closed is dropped. Setting it to five minutes means results can be revised for five minutes after the window closes, at the cost of emitting updated rows.
That trade-off is worth stating explicitly in an interview. Larger tolerance improves correctness for unreliable sources and increases state, latency and the chance that a downstream consumer sees a correction. A fraud pipeline that must act within seconds cannot wait five minutes for stragglers; a billing pipeline that reconciles daily can tolerate hours and should be configured accordingly.
There is no built-in watermark UI beyond this tolerance setting, so the discipline is on you: define what fraction of your events typically arrive late, measure it for a week, then set tolerance from data rather than from a guess.
Temporal joins without lying about the data
Joining a stream to reference data is where analytics and correctness collide. A stream of orders joined to a slowly changing customer dimension needs the customer as it was when the order happened, not as it is now, and a stream-to-stream join needs both sides aligned in time.
Stream Analytics supports lookup joins against reference blobs or tables, and streaming joins between two inputs with an explicit time boundary. The reference side is loaded at job start and refreshed only when the job restarts, which is an important operational fact: change a dimension file and your job does not see it until you redeploy.
WITH
EnrichedOrders AS (
SELECT
o.orderId,
o.customerId,
o.orderValue,
c.segment,
c.creditTier,
o.eventEnqueuedUtcTime
FROM orders o TIMESTAMP BY eventEnqueuedUtcTime
LEFT JOIN customers c
ON o.customerId = c.customerId
),
SessionBreaks AS (
SELECT
orderId,
customerId,
eventEnqueuedUtcTime,
LAG(second, 30) OVER (
PARTITION BY customerId
ORDER BY eventEnqueuedUtcTime
) AS previousEventTime
FROM EnrichedOrders
)
SELECT * INTO enrichedOut FROM EnrichedOrders;
SELECT * INTO sessionOut FROM SessionBreaks;
The subtlety in a stream-to-stream join is that both sides carry timestamps and the engine needs a bound on how far apart they may be. Without an explicit time range the join state grows without limit. Constrain it, and design the reference side to be reloaded on a schedule so dimension changes propagate predictably.
Inputs, outputs and delivery semantics
An input is Event Hubs, Blob or ADLS, a Cosmos DB container, a SQL table, or a Kafka topic. An output has its own semantics: Event Hubs and Kafka give at-least-once, Cosmos DB gives upsert or append depending on your mapping, and Blob writes are partitioned files that a downstream job materialises.
Because the engine may replay, the rule is that outputs must tolerate duplicates. Cosmos DB output with Upsert keyed on a natural identifier makes a replay harmless. A SQL insert with a primary key constraint fails the job on replay instead, which surfaces as an outage rather than a quiet correction.
| Output | Default semantics | Replay behaviour | Best for |
|---|---|---|---|
| Cosmos DB | Upsert or append by mapping | Upsert is idempotent | Serving layer, low-latency reads |
| Event Hubs | At-least-once | Duplicates possible | Feeding downstream consumers |
| Blob / ADLS | Partitioned files | Repeated blobs under retry path | Archival and later batch processing |
| Azure SQL | Insert or upsert via function | Constraint violations on naive insert | Relational serving with care |
| Power BI | Push datasets | Repeated rows aggregate incorrectly | Live dashboards with idempotent measures |
Streaming units, parallelism and throttling
A streaming unit (SU) bundles CPU, memory and network. The default of six is enough for a modest stream and not enough for a production feed, and the failure mode is not a crash: it is the job falling behind while events pile up upstream, so latency grows until a consumer times out.
Parallelism depends on input partitioning. Event Hubs with eight partitions can be processed by up to eight SUs; beyond that, extra units buy nothing because the partitions are already saturated. Blob and ADLS inputs are read in file-level parallelism, so a container full of tiny files limits you differently.
# Inspect the job: throughput, SU quota, late arrivals
az stream-analytics job show \
--resource-group rg-streaming-prod \
--name asa-orders-enrich \
--query "{su: streamingUnits, compat: compatibilityLevel, tz: outputStartPolicy}"
az monitor metrics list \
--resource /subscriptions/SUB/resourceGroups/rg-streaming-prod/providers/Microsoft.StreamAnalytics/streamingjobs/asa-orders-enrich \
--metric "SUUtilization,InputEvents,OutputEvents,LateEvents" \
--interval PT1M --aggregation Average -o table
Watch LateEvents alongside SUUtilization. High utilization with zero late events usually means the query is fine and the input is simply larger than provisioned. High late events with low utilization usually means event time is wrong or tolerance is too tight, and adding streaming units will not help.
When Stream Analytics is the wrong tool
Its SQL dialect has no user-defined functions, no iterative state beyond windows, and no easy way to call an external API for enrichment. If your logic needs a machine learning call, a complex sessionisation across long gaps, or a stateful counter with custom eviction, a Flink job in Microsoft Fabric, Azure Functions on Event Hubs, or Databricks Structured Streaming will be less painful.
Equally, Stream Analytics is excellent when the logic is genuinely a SQL-shaped aggregation over a bounded window and you want zero operations work. Choosing it for the right shape is a senior decision; choosing it everywhere is how teams end up fighting a language instead of shipping pipelines.
Common Mistakes
Leaving the timestamp on arrival time because the job ran fine in testing
Fix: Always declare TIMESTAMP BY the event-time column and measure how many events arrive after their window closes
Summing the output of a hopping window as if it were non-overlapping
Fix: Use tumbling windows for totals, or divide by the hop-to-span ratio when a true rolling sum is required
Using INSERT-style output against a keyed SQL table
Fix: Use upsert with a deterministic key so a job retry or replay does not fail on constraint violations
Raising streaming units to fix a job that is late
Fix: Check input partitioning and late-event counts first; parallelism is bounded by partitions and state issues are not solved by CPU
Best Practices
- Set reference data refresh as an explicit operational step, since lookup joins only reload on restart
- Keep the out-of-order tolerance tied to measured lateness rather than a round number
- Make every downstream write idempotent, because at-least-once delivery is the default
- Alert on consumer lag and late events together; either alone gives a partial picture
Interview Questions
Q1: Difference between a tumbling window and a hopping window?
Tumbling windows are fixed and non-overlapping, so each event lands in exactly one emit. Hopping windows are fixed size with a smaller hop, so windows overlap and events appear in several emits, which suits rolling averages but double counts totals.
Q2: What does the TIMESTAMP BY clause control?
It selects the event-time column used for windowing and joins. Without it the engine uses arrival time, which drifts from true event time under retries or backlogs.
Q3: How does Stream Analytics handle late events?
Through the out-of-order tolerance or adjust latency setting. Events arriving within the tolerance revise the affected window's output; events later than that are dropped, because the window is already closed.
Q4: Why can a job show healthy CPU while the dashboard is stale?
Latency may come from input partitioning limits or from the sink, not compute. Partition count bounds parallelism, and a slow Cosmos DB or SQL sink back-pressures the job regardless of streaming units.
Q5: When would you choose Flink over Stream Analytics?
When the logic needs user-defined code, long-lived state with custom eviction, sessionisation across long gaps, or external calls during processing. For straightforward windowed SQL aggregation, Stream Analytics costs less to operate.
Key Takeaways
- The query is a continuous stream graph, and each branch feeds its own output
- Window shape must match the question: tumbling for totals, hopping for rolling, sliding for change-driven emits
- Event time and out-of-order tolerance determine correctness far more than CPU does
- Reference data is refreshed only when the job restarts, so dimension changes need a deployment step
- All outputs must tolerate replay because delivery is at-least-once