Key takeaway
- Build real-time streaming with Apache Spark Structured Streaming and Kafka: architecture, code, delivery guarantees, Real-time Mode and trade-offs.
Real-time streaming with Apache Spark means using Structured Streaming to read an unbounded flow of events, usually from Apache Kafka, and update results continuously as records arrive. Spark documents Structured Streaming as the engine to use: according to its programming guide, the older Spark Streaming (DStreams) is the previous generation and a legacy project with no further updates.
For a CTO or data platform lead the decision is about latency, delivery guarantees and operating cost. The default micro-batch engine gives exactly-once processing at roughly 100 ms latency at best, and a newer Real-time Mode targets millisecond-scale latency for a narrower set of queries (performance tips, Real-time Mode). This guide covers the architecture, a working Kafka pipeline and the trade-offs. For the engine itself, see our Apache Spark architecture guide.
What is real-time streaming, and why use Kafka with Spark?
Streaming data is generated continuously by many sources, such as application logs, device telemetry, transactions and clickstreams. Kafka describes event streaming as "the practice of capturing data in real-time from event sources". Producers publish events to topics, consumers subscribe to them, and the two are "fully decoupled and agnostic of each other". Topics are partitioned across brokers, and events with the same key go to the same partition, so a consumer reads them in order.
Spark is the processing layer. Kafka holds the durable, replayable stream and Spark reads it, transforms it and writes results to a sink. Replayable sources are what make recovery possible, as the next section explains.
How does Structured Streaming work?
According to the Spark programming guide, "the key idea in Structured Streaming is to treat a live data stream as a table that is being continuously appended". You write a query as you would on a static table, and Spark runs it incrementally on the unbounded input table. Every trigger interval, new rows are appended to the input table and the result table is updated. Spark does not keep the whole table: it reads the latest data, updates the result and discards the source data, keeping only the intermediate state it needs.
The guide states that "using replayable sources and idempotent sinks, Structured Streaming can ensure end-to-end exactly-once semantics under any failure", by tracking source offsets, checkpointing and write-ahead logs. The same DataFrame and SQL APIs work for batch and streaming, so one team can maintain one set of transformation logic.
What does a Kafka to Spark pipeline look like?
A common layout has four stages. A collection tool such as Apache NiFi (described on its own site as a system to process and distribute data, with data provenance, flow control and a browser-based interface) or your applications publish events to Kafka. Spark Structured Streaming reads the topics, transforms and aggregates, and writes to a sink such as another Kafka topic, files or a lakehouse table. Dashboards and services consume the results. NiFi is optional: producers can write to Kafka directly.
| Stage | Role | Primary source |
|---|---|---|
| Collect | Ingest from files, databases, devices and applications into Kafka | NiFi and Kafka own sites |
| Stream store | Durable, partitioned, replayable event log | Kafka documentation |
| Process | Structured Streaming queries on DataFrames | Spark programming guide |
| Serve | Write to Kafka, files or tables for dashboards and services | Spark Kafka integration guide |
How do you read a Kafka stream in Spark?
Add the Kafka connector package. The Kafka integration guide gives the artifact as spark-sql-kafka-0-10 for the Spark version in use (version 4.3.0 on the current documentation). Set kafka.bootstrap.servers and exactly one of assign, subscribe or subscribePattern. The startingOffsets option takes earliest, latest or a JSON string per partition; for streaming queries it only applies when a new query starts, and a restarted query resumes from where it left off.
from pyspark.sql import SparkSession
from pyspark.sql.functions import get_json_object, col
spark = SparkSession.builder.appName("kafka-streaming").getOrCreate()
df = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.option("subscribe", "topic1")
.option("startingOffsets", "earliest")
.load())
df.printSchema() # key and value are binary
Keys and values always arrive as bytes, so cast them before use. The source also exposes topic, partition, offset, timestamp and timestampType columns.
How do you transform and write the stream?
The example below parses a country field from JSON messages, counts events per country and writes the running counts back to Kafka. The Kafka sink needs a value column, and the topic can be set as an option.
counts = (df.select(get_json_object(col("value").cast("string"), "$.country").alias("country"))
.groupBy("country").count())
query = (counts.selectExpr("country AS key", "CAST(count AS STRING) AS value")
.writeStream.format("kafka")
.outputMode("update")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.option("topic", "country-counts")
.option("checkpointLocation", "/path/to/checkpoint")
.start())
Two cautions apply. First, according to the integration guide, "Apache Kafka only supports at least once write semantics", so records written to Kafka may be duplicated; the guide suggests a unique key for de-duplication when reading. Second, for aggregations over event time, use a watermark. The programming guide explains that the watermark sets how late data may arrive before old window state is dropped, and that Complete output mode cannot use it to drop state.
Which trigger mode should you choose?
Spark offers three execution styles. The table summarises them from the Spark documentation.
| Mode | Latency and guarantee (per Spark docs) | When it fits | Status |
|---|---|---|---|
| Micro-batch (default) | About 100 ms at best; exactly-once processing | Most pipelines: aggregations, joins, ETL | Current default |
| Continuous processing | About 1 ms; at-least-once; map-like operations only; no automatic task retries | Simple stateless transforms where latency matters most | Experimental since Spark 2.3 |
| Real-time Mode | Millisecond-scale; Kafka source; sink delivery depends on the sink (Kafka sink is at-least-once) | New low-latency workloads | Introduced in Spark 4.1.0; stateful support added in 4.3.0, remaining operations ongoing |
The Real-time Mode page advises preferring it over continuous processing for new low-latency workloads. Its limits matter for design: output mode must be update, a checkpoint location is required, the minimum trigger interval is 5 seconds (a checkpoint interval, not the latency target), stream-stream joins are not supported, and the cluster needs enough cores to run all tasks at once. The docs recommend one Real-time query per cluster. Confirm the details for your Spark version on the official page before committing.
What should enterprise teams govern, secure and cost?
Streaming pipelines run continuously, so small gaps turn into steady operating cost and risk. These are the points to settle before production.
- Delivery guarantee: decide whether the sink tolerates duplicates. Kafka sinks are at-least-once, so design idempotent consumers or de-duplication keys.
- Checkpoints and state: store checkpoints on durable storage, and plan state size, watermarks and recovery tests.
- Late data: set watermarks from observed lateness, not guesses, and agree what happens to data that arrives after the threshold.
- Capacity: Real-time Mode and continuous processing hold cores for long-running tasks, so size the cluster for peak partitions. See our Apache Spark optimisation guide.
- Ownership: record who owns each topic, schema and query, and what policy applies to the data it carries.
Where streaming results feed automated decisions, the pipeline is only half the control. ElixirData Context OS keeps governed context, versioned policy and decision traces in one decision layer above AI agents, and AgentAnalyst lets teams ask questions of enterprise data in plain language and get real-time insights. For presenting results, see real-time streaming data visualisation.
When should you not use Spark Structured Streaming?
- Event-by-event logic with sub-millisecond needs: Spark documents about 1 ms for continuous processing and millisecond-scale for Real-time Mode, so check your latency budget against the docs.
- Stream analytics that do not need a general-purpose engine: compare options in our streaming analytics guide.
- Workloads that are really batch: scheduled jobs are simpler to run than an always-on cluster. For table storage downstream, see data lakehouse architecture.
- New projects on DStreams: Spark labels it legacy, so start on Structured Streaming.
How do you adopt it in sequence?
- Define the event, topic, key and schema, and the latency the business needs.
- Build a micro-batch query with a checkpoint and a watermark, and test failure recovery.
- Set sink semantics and de-duplication, then add monitoring of lag and state size.
- Trial Real-time Mode only for queries that need it and fit its limits.
- Attach policy and ownership to each stream before connecting agents or automated actions.
To map one streaming decision your agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.
FAQ
Is Spark Streaming (DStreams) still recommended?
No. According to the Spark programming guide, Spark Streaming is the previous generation, a legacy project with no further updates, and Structured Streaming should be used for new streaming applications.
Does Structured Streaming give exactly-once delivery?
With replayable sources and idempotent sinks, Spark states it can ensure end-to-end exactly-once semantics. The Kafka sink is at-least-once, so duplicates are possible and need de-duplication.
What is Real-time Mode in Spark?
A streaming execution mode introduced in Spark 4.1.0 that targets millisecond-scale latency, with Kafka as the source. Stateful query support was added in Spark 4.3.0 and remaining operations are ongoing, so check the limits on the official page.
How do you start reading from the beginning of a Kafka topic?
Set startingOffsets to earliest. For streaming queries this applies only when a new query starts; a restarted query resumes from its checkpoint.
Do I need Apache NiFi to stream into Kafka?
No. NiFi is one option for collecting and routing data. Applications and other tools can publish to Kafka directly.
Real-Time Streaming with Apache Spark: Next Step
Talk to our experts about implementing compound AI systems. Discover how industries and various departments leverage Decision Intelligence to become decision-centric. Learn how AI can automate and optimize IT support and operations, enhancing efficiency and responsiveness with Real Time Streaming applications with Apache Spark.
Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.
Ready to put AI agents to work? Explore ElixirClaw, the agentic OS platform to build, orchestrate and govern AI agents.
Explore the XenonStack platform family: ElixirData · ElixirClaw · ElixirHub · NexaStack · MetaSecure · Neural AI · AgentGRC · AgentSRE · AgentAnalyst · AgentInstruct · AgentRAI · AgentScrum · AgentSearch · AgentForce · AI Aviator · SAIF Aviator · CohortIQ · XenonStack AI · XenonStack UAE