You have a stream where micro-batch latency is too high, such as fraud scoring or live alerting, and want real-time mode (RTM). RTM schedules all stages at once and passes rows through them continuously, with long-running batches. That changes cluster sizing, allowed operators and monitoring. Work through this list before production.
1. Confirm the stream fits
- The target is sub-second. If a few seconds is fine, stay on micro-batch, which is cheaper and supports more operators.
- The source is Kafka or Event Hubs through the Kafka connector. Delta isn't a supported RTM source.
- The sink is Kafka, Event Hubs through the Kafka connector, or
foreachwith a custom writer. Delta andforeachBatchsinks aren't supported. - Output mode is
update. Append and complete aren't supported. - The query runs on classic compute. Serverless notebooks and jobs don't run RTM queries directly.
| Feature | RTM status |
|---|---|
| Projection, filter, tumbling and sliding aggregates | Supported |
dropDuplicates, dropDuplicatesWithinWatermark | Supported |
| Broadcast stream-table join | Supported for small static tables; check the current limit |
| Non-broadcast stream-table join | Not supported |
| Stream-stream inner join | DBR 18 LTS+, extra configs needed |
| Stream-stream outer join, session windows | Not supported |
mapPartitions, mapInPandas, mapInArrow, applyInPandas | Not supported |
Row-based transformWithState | Supported, with different call semantics |
transformWithStateInPandas, flatMapGroupsWithState | Not supported |
| Unity Catalog UDFs, Python UDTFs | Not supported |
Tip
If you also need the data in Delta, send RTM output to an Event Hub and run a separate micro-batch stream from it to Delta. It decouples the lake write from the low-latency path.
2. Compute settings
- Photon off, autoscaling off, spot off.
- Dedicated access mode for latency-sensitive UDFs. Standard works for Python only.
-
spark.databricks.streaming.realTimeMode.enabledset on the cluster. - A restart policy on the job, with one concurrent run.
resources:
jobs:
fraud_rtm:
name: fraud-rtm
max_concurrent_runs: 1
continuous:
pause_status: UNPAUSED
job_clusters:
- job_cluster_key: rtm
new_cluster:
spark_version: 17.3.x-scala2.13
node_type_id: Standard_D8ds_v5
num_workers: 4
runtime_engine: STANDARD
data_security_mode: SINGLE_USER
azure_attributes:
availability: ON_DEMAND_AZURE
spark_conf:
spark.databricks.streaming.realTimeMode.enabled: "true"
spark.sql.shuffle.partitions: "20"
tasks:
- task_key: score
job_cluster_key: rtm
notebook_task:
notebook_path: ../src/fraud_rtm.py
Pick the runtime your features need, and confirm the version string with databricks clusters spark-versions.
3. Count task slots
In micro-batch, stages take turns using slots. In RTM, all stages run together, so the cluster needs slots for the sum of their tasks.
| Pipeline | Tasks | Slots needed |
|---|---|---|
Kafka source and sink, maxPartitions 8 | 8 | 8 |
| Source 8, one shuffle of 20 | 8 + 20 | 28 |
| Source 8, two shuffles of 20 | 8 + 20 + 20 | 48 |
- Slots from the cluster above: 4 workers × 8 cores = 32, enough for 28.
-
maxPartitionsis set on the source if the topic has many partitions, so each task reads several. Without it, plan one task per topic partition. -
spark.sql.shuffle.partitionsis chosen deliberately. The default of 200 would need 200 slots per shuffle. - Headroom is left. Aim for about 50% cluster utilization.
Warning
Adding topic partitions later can add source tasks. Recalculate slots before you scale the Event Hub, or the query may no longer fit on the cluster.
4. Write the query
Keep existing Event Hubs authentication in eh_auth:
src = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "myns.servicebus.windows.net:9093")
.options(**eh_auth)
.option("subscribe", "payments")
.option("maxPartitions", "8")
.load())
out = (src.selectExpr("CAST(key AS STRING) AS key",
"CAST(value AS STRING) AS value")
.where("value IS NOT NULL"))
q = (out.writeStream.format("kafka")
.queryName("fraud_rtm")
.option("kafka.bootstrap.servers", "myns.servicebus.windows.net:9093")
.options(**eh_auth)
.option("topic", "payments-scored")
.option("checkpointLocation", "/Volumes/prod/ops/checkpoints/fraud_rtm_v1")
.outputMode("update")
.trigger(realTime="5 minutes")
.start())
The trigger value is the batch length, not the latency. It sets how often progress is committed. Longer batches mean fewer checkpoints, later metrics and a longer replay after a failure.
- Recovery time is measured by killing the driver mid-batch.
- Consumers tolerate duplicates after a replay. Include a stable event ID and make downstream processing idempotent.
5. Stateful and UDF logic
-
transformWithStatecode doesn't assume it sees all of a key's rows at once. A synchronous processor is called once per row in RTM, but once per key per batch in micro-batch. - Per-call work such as timer resets and lookups has been costed at row rate.
- Event-time timers are used only on DBR 19+ with real-time watermark propagation. Otherwise expect
EVENT_TIME_BASED_TIMERS_IN_TRANSFORM_WITH_STATE_NOT_SUPPORTED. - Processing-time timers are tested on a quiet topic. On DBR 18 LTS and below they can wait for the next record.
- Arrow batch size is reviewed. On DBR 18 LTS and below,
spark.sql.execution.arrow.maxRecordsPerBatchof1gives the lowest latency for Arrow UDFs. Pandas UDFs perform poorly at 1, so start at 100 or more. DBR 19+ batches by time instead.
For stream-stream inner joins on DBR 18 LTS+, set all of these before the first start:
spark.databricks.streaming.realTimeMode.streamStreamJoin.enabled true
spark.sql.streaming.join.stateFormatVersion 4
spark.sql.streaming.join.stateFormatV4.enabled true
spark.sql.streaming.stateStore.rocksdb.mergeOperatorVersion 2
spark.sql.streaming.realTimeMode.controlMessage.enabled true
Watermarks on DBR 19+
With real-time watermark propagation, the watermark uses the slowest source partition's maximum. Late filtering can differ from your micro-batch results. A query keeps the setting it started with, even after a restart, and changing it needs a new checkpoint. Plans with a shuffle before withWatermark fail with SHUFFLE_NOT_SUPPORTED_BEFORE_WATERMARK.
6. Measure the right latency
Batch duration means nothing here, because a batch is deliberately minutes long. Use the latencies object:
import json
p = q.lastProgress
if p is not None:
d = json.loads(p.json) if hasattr(p, "json") else p
print(json.dumps(d.get("latencies"), indent=2))
| Metric | Measures | High value suggests |
|---|---|---|
sourceQueuingLatencyMs | Write to the bus until Spark reads it | Too few source tasks, throttled Event Hubs, backlog |
processingLatencyMs | Spark read until the sink write starts | Slow UDF, state or shuffle |
e2eLatencyMs | Bus write until the sink write starts | Sum of the two |
- Alerts use P99, not P50.
- Sink write time is measured separately. None of these metrics includes it, so compare timestamps on the output topic.
-
busyTimeFractionhas been checked in a load test, withspark.databricks.streaming.execution.enableDebugMetricsset totrue. A value near 1 on one stage marks the bottleneck. One hot task in a calm stage means key skew. - An external heartbeat exists. Progress arrives only at the end of a batch, so it can't prove the stream is alive within the last few minutes.
7. Cutover and fallback
- Run RTM alongside the micro-batch query, with its own checkpoint, consumer group handling and output topic.
- Compare counts and results for a full peak period, including late events.
- Switch consumers to the RTM topic.
- Keep the micro-batch job deployable for one release.
Checkpoint v2, used by RTM queries from DBR 16.4 LTS, allows switching between RTM and micro-batch. Test that switch with your own operators in pre-production.
Caution
Don't start two queries on one checkpoint. Both may process and commit the same offsets, which duplicates output and can corrupt progress tracking.
Prevent it next time
- Put the slot calculation in the repo beside the cluster definition, and fail CI when they disagree.
- Schedule runtime upgrades as capacity events. UDF batching, timers and watermark defaults changed across 18 and 19.
- Reserve quota for the fixed node count, so a restart isn't blocked by an Azure capacity shortage.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get