Batch Processing at Scale with Apache Spark on Amazon EMR
A Spark batch job can be correct and still be operationally unsuccessful. The useful target is not only a successful spark-submit; it is predictable completion before a business deadline, with an explainable rerun and a cost that matches the value of the dataset. Amazon EMR provides the control plane and cluster options, but S3 layout, partition sizing, shuffle pressure, and restart boundaries determine performance.
Define the workload in measurable units
Before choosing instances, capture five facts for a representative run:
- compressed bytes scanned and bytes generated;
- total CPU seconds and executor memory peak;
- shuffle read and write bytes;
- output file count and file-size distribution;
- elapsed time by job stage.
With those values, capacity becomes a calculation rather than a guess. A first executor count is usually constrained by max(input partitions, shuffle partitions, memory tasks), and a first memory budget must include Python worker overhead when using PySpark UDFs.
A useful target for Parquet files is 128 to 512 MiB. If 1 TiB of output is written, that implies roughly 2,048 to 8,192 files. A dataset with 100,000 tiny files will spend more time listing and opening objects than processing payloads.
Choose instance fleets around failure tolerance
Instance fleets let EMR draw from multiple instance types and subnets. Define a stable core fleet for HDFS and stateful executors, then a mixed task fleet for elastic compute. Avoid making the job depend on one discounted capacity pool. A ratio such as 50 to 70 percent On-Demand core capacity and the remainder Spot task capacity often balances restart cost and price, but the exact amount depends on the rerun window and Spot interruption history.
An example capacity profile for a 10 TiB daily job is:
| Fleet | Target | Allocation | Purpose |
|---|---|---|---|
| Primary | 1 | On-Demand | coordinates the cluster and job |
| Core | 10 | On-Demand or capacity-optimized Spot | persistent HDFS and minimum compute |
| Task | 20 to 40 | capacity-optimized Spot | scales scan, sort, and shuffle |
This is a starting hypothesis. Increase memory-optimized capacity for joins and stateful aggregations; increase compute-optimized capacity for decompression, filtering, or projection-heavy scans. Instance fleet settings should request capacity units, and the target should be converted into executor slots after reserving resources for the operating system and YARN.
Lay out S3 for the query pattern
Date partitions must match the common predicate:
s3://example-lake/raw/events/
dt=2020-10-21/region=us/
dt=2020-10-21/region=eu/
dt=2020-10-22/region=us/
Partition pruning only works when the query filters on these columns. Dynamic filtering on a high-cardinality order identifier is not a reason to create an ID partition. Keep user-facing output compact and columns sorted enough for dictionary encoding and predicate pushdown.
Write to a new, run-specific staging prefix:
s3://example-lake/silver/orders/run_date=2020-10-22/run_id=.../
After validation, publish a manifest or table partition. This keeps a failed job from presenting a mixture of old and new files as one successful result. S3 overwrite semantics must not be treated as a transactional table commit.
Size partitions and shuffle explicitly
Spark should begin with enough input partitions to keep executors busy, but each task should be large enough to amortize overhead. For 128 MiB files:
input partition tasks ~= input bytes / 128 MiB
shuffle partitions ~= max(2 x total executor cores, shuffle bytes / 128 MiB)
Round that value and validate with the Spark UI. A task count below available slots underutilizes the cluster. A task count far above available slots can be fine for skew tolerance, but excessive tiny tasks increase scheduling overhead.
Adaptive Query Execution can coalesce shuffle partitions, but it does not eliminate a fundamentally skewed key. Salting, pre-aggregation, or filtering the large side is still necessary when one account owns 70 percent of the events.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder \
.appName("daily-order-revenue") \
.config("spark.sql.adaptive.enabled", "true") \
.config("spark.sql.adaptive.coalescePartitions.enabled", "true") \
.config("spark.sql.shuffle.partitions", "800") \
.getOrCreate()
orders = spark.read.parquet("s3://example-lake/bronze/orders") \
.where("order_date = '2020-10-21'")
customers = spark.read.parquet("s3://example-lake/reference/customers") \
.select("customer_id", "country")
result = orders \
.filter(F.col("order_total_cents") >= 0) \
.groupBy("order_date", "customer_id") \
.agg(
F.sum("order_total_cents").alias("revenue_cents"),
F.countDistinct("order_id").alias("order_count")
) \
.join(F.broadcast(customers), "customer_id", "left") \
.select("order_date", "customer_id", "country",
"revenue_cents", "order_count") \
.coalesce(200)
result.write \
.mode("overwrite") \
.partitionBy("order_date", "country") \
.parquet("s3://example-lake/silver/revenue/stage/2020-10-21")
Broadcasting is deliberate here: the reference dimension must remain small enough to fit every executor. A 10 GiB broadcast limit with autoBroadcastJoinThreshold is not safe on an executor with 12 GiB of JVM heap. Join strategy should be fixed by measured size, and large dimensions should use sort-merge join.
Configure the cluster at the EMR layer
Set a Spark classification when creating the cluster or in the EMR Serverless application:
[
{
"Classification": "spark-defaults",
"Properties": {
"spark.serializer": "org.apache.spark.serializer.KryoSerializer",
"spark.sql.adaptive.enabled": "true",
"spark.sql.adaptive.skewJoin.enabled": "true",
"spark.sql.files.maxPartitionBytes": "134217728",
"spark.sql.shuffle.partitions": "800",
"spark.speculation": "false",
"spark.executor.memoryOverhead": "2048"
}
}
]
Speculation can mask a single slow task, but speculative writes to an external sink can duplicate results. Keep it disabled unless every sink path is idempotent. Kryo must be paired with testing for any unregistered custom type; the serializer setting is not a free performance guarantee.
Submit and recover a run
For a transient EMR cluster, submit the application through a step:
aws emr add-steps \
--cluster-id j-EXAMPLE \
--steps '[
{
"Type":"Spark",
"Name":"daily-revenue-2020-10-21",
"ActionOnFailure":"CONTINUE",
"Args":[
"--deploy-mode","cluster",
"--conf","spark.executor.instances=80",
"--conf","spark.executor.cores=4",
"--conf","spark.executor.memory=12g",
"s3://example-code/daily_revenue.py",
"--date","2020-10-21",
"--run-id","20201021-retry-02"
]
}
]'
An EMR Serverless job can use the same application code and decouple runtime capacity from a long-lived cluster:
aws emr-serverless start-job-run \
--application-id 00fexample \
--execution-role-arn arn:aws:iam::111122223333:role/emr-serverless-job \
--job-driver '{
"sparkSubmit":{
"entryPoint":"s3://example-code/daily_revenue.py",
"entryPointArguments":["--date","2020-10-21","--run-id","20201021-retry-02"],
"sparkSubmitParameters":"--conf spark.executor.instances=80"
}
}'
Serverless reduces cluster lifecycle work and can improve burst isolation. A persistent cluster is still attractive when bootstrap is frequent, large local data is reused, or specialized HDFS topology provides a meaningful benefit. Compare completed-job dollars, not hourly capacity, and include idle-cluster time in the persistent-cluster total.
Cost and reliability runbook
Set a fixed deadline before scaling. For a four-hour job, alert at two hours if less than half of the input bytes have completed. Alert on failed stage attempts, executor removals, and output write count. A job should fail loudly if:
- input row count differs by more than the accepted source variance;
- required partitions are absent;
- output is empty for a non-empty input;
- output files are outside the expected 64 MiB to 1 GiB range;
- aggregate totals fail a reconciled tolerance.
On failure, preserve logs and the Spark event log, then rerun only the failed date and run ID into a clean prefix. Delete or quarantine the incomplete prefix. Do not replay on top of a partially published partition. Once output counts and totals pass, atomically update the catalog partition or manifest pointer.
Track cost per successful TiB, executor loss rate, median and p95 completion time, and recovery time. A healthy system improves those values over time. If a larger cluster halves elapsed time but costs more because the job spent 40 percent of the run waiting for skewed tasks, the right fix is data design or join strategy, not additional nodes.