Apache Spark Structured Streaming on Amazon EMR
Spark Structured Streaming gives a streaming application a dataframe-shaped contract: Spark reads an incrementally growing input, applies a query, and advances a durable offset only as far as the output is complete. Amazon EMR supplies the distributed runtime, while the design of checkpoints, sinks, and capacity still determines whether the application is useful in production.
This article builds a practical EMR design for Kafka or Amazon Kinesis, with S3 as the state and checkpoint store and S3 or Kafka as the result sink.
Select the ingestion contract first
Kafka exposes partitions and offsets; Kinesis exposes shards and sequence numbers. Both support replay, but the connector and offset semantics differ.
For Kafka, do not use a changing wildcard topic list unless late topic creation is intended. Pin the broker protocol, truststore, consumer group properties, and starting position explicitly. Consumer groups are not the source of truth for Spark offsets; the Structured Streaming checkpoint is.
aws s3 mb s3://example-streaming-checkpoints
aws s3api put-bucket-versioning \
--bucket example-streaming-checkpoints \
--versioning-configuration Status=Enabled
A Kinesis source can be useful when the producer and consumers already live in AWS. The practical shard count should be based on required bytes per second / safe bytes per shard per second and independently checked against record rate. Keep 30 to 40 percent headroom because downstream micro-batches are not perfectly smooth.
Use a Kinesis connector version certified for the EMR release’s Spark and Scala versions. Connector package names and Maven coordinates vary across releases, so verify them in a staging cluster rather than mixing Spark 2 and Spark 3 artifacts. The application shape is similar:
kinesis = spark.readStream \
.format("kinesis") \
.option("streamName", "orders-stream") \
.option("region", "us-east-1") \
.option("endpointUrl",
"https://kinesis.us-east-1.amazonaws.com") \
.option("startingPosition", "LATEST") \
.load()
kinesis_events = kinesis.select(
F.from_json(F.col("data").cast("string"), schema).alias("payload")
).select("payload.*")
Place the connector jar in a controlled S3 artifacts prefix and reference it with --packages or --jars in the EMR step. Give the job role kinesis:GetRecords, kinesis:GetShardIterator, kinesis:DescribeStream, and kinesis:ListShards; broad kinesis:* is not required for a read-only consumer.
Micro-batch versus continuous processing
Micro-batch is the safer default on EMR. It supports the widest sink and operation set and makes batch progress visible. A trigger interval of 10 to 30 seconds often balances checkpoint overhead and latency. The interval is a target, not a guarantee: if processing takes 18 seconds and the trigger is 10 seconds, batches start consecutively and lag grows.
Continuous processing can reduce end-to-end latency to the order of milliseconds to one second for a limited set of operations. It has narrower support, different fault-tolerance behavior, and more difficult operational diagnosis. Choose it only when a measured business SLO cannot tolerate micro-batch latency and the exact query and sink are validated for continuous mode.
The query below parses Kafka values, assigns event time, and writes partitioned Parquet:
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import StructType, StructField, StringField, LongType
spark = SparkSession.builder \
.appName("orders-stream") \
.config("spark.sql.shuffle.partitions", "120") \
.config("spark.sql.streaming.stopGracefullyOnShutdown", "true") \
.getOrCreate()
schema = StructType([
StructField("order_id", StringField()),
StructField("amount", LongType()),
StructField("event_epoch_ms", LongType()),
StructField("region", StringField())
])
raw = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers",
"b-1.kafka.internal:9093,b-2.kafka.internal:9093") \
.option("subscribe", "orders.v1") \
.option("startingOffsets", "latest") \
.option("kafka.security.protocol", "SASL_SSL") \
.option("kafka.sasl.mechanism", "AWS_MSK_IAM") \
.option("kafka.sasl.jaas.config",
"software.amazon.msk.auth.iam.IAMLoginModule required;") \
.option("kafka.sasl.client.callback.handler.class",
"software.amazon.msk.auth.iam.IAMClientCallbackHandler") \
.option("failOnDataLoss", "true") \
.load()
events = raw.select(
F.from_json(F.col("value").cast("string"), schema).alias("payload"),
F.col("topic"), F.col("partition"), F.col("offset")
).select(
"payload.*", "topic", "partition", "offset"
).withColumn(
"event_time",
F.to_timestamp(F.from_unixtime(F.col("event_epoch_ms") / 1000))
).withWatermark("event_time", "15 minutes") \
.withColumn("event_date", F.to_date("event_time"))
query = events.writeStream \
.format("parquet") \
.outputMode("append") \
.option(
"checkpointLocation",
"s3://example-streaming-checkpoints/orders/v3"
) \
.option("path", "s3://example-lake/silver/orders") \
.partitionBy("event_date", "region") \
.trigger(processingTime="20 seconds") \
.start()
query.awaitTermination()
Use separate checkpoint paths for every logical query and semantic schema version. Do not copy another query’s checkpoint as a shortcut. startingOffsets=latest applies only when no checkpoint exists; after restart, the checkpoint’s last committed batch wins. failOnDataLoss=true prevents a query from silently skipping retained-source offsets that have expired. Disable it only for an explicitly accepted recovery policy that records the missing range and triggers a backfill.
Output modes are part of the data contract
Append mode writes rows once the event-time rules allow them to be final. It is a good fit for immutable files, but it does not provide exactly-once file output by itself. A failed S3 task can leave a partial set of files while the checkpoint remains behind; the corresponding batch is retried and foreachBatch or a transactional table format is often needed for an end-to-end transactional boundary.
Update mode writes rows whenever an aggregate changes. The sink must support upserts if the consumer expects one current record per key. Complete mode emits every result row and is appropriate for small bounded aggregate state, not an ever-growing cardinality dimension.
For deduplicated output with an idempotent warehouse table, foreachBatch can make replay behavior explicit:
def upsert_batch(batch_df, batch_id):
batch_df.write \
.mode("append") \
.format("jdbc") \
.option("url", "jdbc:postgresql://warehouse:5432/analytics") \
.option("dbtable", "staging.orders_stream") \
.option("user", "loader") \
.option("password", spark.conf.get("spark.sql.secret.db_password")) \
.save()
write_query = events.writeStream \
.foreachBatch(upsert_batch) \
.outputMode("append") \
.option("checkpointLocation",
"s3://example-streaming-checkpoints/orders-upsert/v1") \
.start()
The staging key must have a uniqueness constraint, and the merge should use batch_id plus source identifiers for auditability. A JDBC password belongs in an EMR secret-loading process, not literal source control.
Size EMR for sustained load, not a benchmark spike
Start with one core group capable of holding the working state and a task group for elastic capacity. Disable scale-in while checkpoints, state stores, or local shuffle live on task nodes that EMR may terminate. S3 checkpointing preserves offsets and state, but executors still need time to recover.
For a target lag below 60 seconds:
- Keep p95 batch duration below 50 percent of the trigger interval.
- Alert if input rows exceed processed rows for three consecutive batches.
- Keep task CPU between 50 and 75 percent at peak and memory GC time below 10 percent.
- Set executor loss alerts; a stable query with falling throughput usually has a skew, source, or external sink problem.
- Retain source data for at least two times the maximum expected recovery window.
Autoscaling should react to lag or pending tasks, not CPU alone. On EMR instance groups, a CloudWatch scaling rule can add task nodes after AppsPending remains high. On instance fleets, diversify capacity across instance types and Availability Zones while keeping the minimum required EBS throughput per executor.
Observe lag where it actually occurs
Spark exposes query progress as JSON. Emit numInputRows, inputRowsPerSecond, processedRowsPerSecond, durationMs.triggerExecution, and sources[].endOffset to a durable metric system. Source-side lag must also be computed against Kafka end offsets or Kinesis iterator age. A moving processedRowsPerSecond alone can look healthy after input stalls.
A dead-letter path is essential for malformed JSON. Route failures with the original topic, partition, offset, and parse reason to a replayable object prefix. A pipeline that silently accepts bad records is not highly available; it is merely quiet.
Failure, recovery, and replay
Graceful termination matters because Spark should stop scheduling new micro-batches and finish its current work. On EMR, submit a step and use the Streaming query’s shutdown signal:
aws emr add-steps --cluster-id j-EXAMPLE \
--steps 'Type=Spark,Name=orders-stream,ActionOnFailure=CONTINUE,Args=[--deploy-mode,cluster,s3://example-code/orders_stream.py]'
aws emr list-steps --cluster-id j-EXAMPLE --step-states RUNNING PENDING
To restart from the checkpoint, rerun the exact query with the same checkpoint URI and application semantics. To replay a controlled interval, restore or create a new checkpoint and specify timestamped Kafka offsets:
{"orders.v1":{"0":850000,"1":820000,"2":830000}}
Pass that JSON with startingOffsets only to a new application version and a new output prefix. Reuse of the old checkpoint ignores it. After replay, compare row counts, unique business keys, and aggregate amounts before atomically switching consumers to the rebuilt output.
If S3 retains source data, EMR nodes can be replaced with no data migration. If Kafka retention expires or S3 checkpoints are deleted, there is no automatic catch-up: resume begins only from remaining source offsets or from an explicit rebuild. Protect the checkpoint bucket from lifecycle expiration and test restoration by reconstructing a query on a new EMR cluster at least quarterly.
Release checklist
Change one variable at a time: connector version, Spark application, schema, output path, or scaling policy. Before release, measure trigger duration for 30 minutes, inject malformed records, terminate a task instance, and restart with the same checkpoint. A release is ready when no rows are lost, duplicates are bounded or merged, lag returns to the steady-state target, and the recovery runbook includes exact checkpoint, source-offset, and output-validation commands.