AWS Glue makes it easier to build and run data processing pipelines without managing Spark clusters manually. It provides a managed Apache Spark environment that can read data from sources such as Amazon S3, relational databases, and other supported services, transform that data, and write the results to a target location.
However, managed infrastructure does not automatically make every ETL job efficient. A job can still take longer than expected, consume unnecessary resources, create too many small files, or fail because of memory pressure. These problems often come from how the Spark application reads, processes, and writes data rather than from the number of workers assigned to the job.
Optimizing AWS Glue ETL jobs requires understanding both AWS Glue features and Apache Spark execution. You need to reduce unnecessary data scans, choose an appropriate partitioning strategy, control expensive shuffle operations, and monitor the job before changing its configuration.
This article explains practical ways to improve AWS Glue ETL performance with Spark, including PySpark examples, configuration choices, common mistakes, and production considerations.
Understanding AWS Glue ETL Jobs and Spark
AWS Glue is a serverless data integration service. It provides managed infrastructure for discovering, preparing, transforming, and moving data. For Spark-based ETL workloads, AWS Glue runs Apache Spark in a managed environment.
A typical AWS Glue ETL pipeline follows this process:
Read data from a source such as Amazon S3 or a JDBC database.
Apply transformations such as filtering, joining, cleaning, and aggregation.
Write the processed data to a target such as Amazon S3, a data warehouse, or another supported destination.
Update the AWS Glue Data Catalog when the pipeline needs to maintain table metadata.
Spark divides a large dataset into partitions and processes those partitions through distributed tasks. A Spark application normally has a driver that coordinates execution and executors that perform the work. AWS Glue manages the underlying resources, but the Spark execution plan still determines how efficiently the job uses them.
For example, consider a job that reads 500 GB of application logs from Amazon S3 but only needs records from the previous day. Reading every file and filtering afterward wastes time and resources. Filtering the relevant partitions before reading the data can reduce the amount of work significantly.
The goal is not simply to make Spark use more workers. The goal is to make each worker perform useful work with as little unnecessary data movement and processing as possible.
Start With Performance Metrics
Before changing worker counts or Spark settings, establish a baseline. Run the job with a representative dataset and record its execution time, data volume, worker usage, and failure rate.
AWS Glue provides job metrics, CloudWatch integration, and Spark UI support. These tools help identify whether the job is limited by data reading, CPU processing, memory, shuffle operations, or output writing.
Some useful indicators include:
Metric or observation | What it can indicate |
|---|
Long time spent reading data | Large scans, slow source access, or too many files |
High shuffle read and write | Expensive joins, aggregations, or repartitioning |
Tasks with very different durations | Data skew or uneven partition sizes |
High memory usage | Large partitions, caching, or memory-intensive transformations |
Many very short tasks | Excessive partition or small-file overhead |
Low executor utilization | Insufficient parallelism or time spent waiting for I/O |
Long output stage | Too many output files, slow writes, or expensive partitioning |
A useful tuning process is to measure the job, identify the slowest stage, make one meaningful change, and measure again. Changing several settings at once makes it difficult to determine which change actually helped.
Enable the Spark UI for the job when deeper investigation is required. It provides information about stages, tasks, execution plans, shuffle operations, and executor activity.
Reduce the Amount of Data Read
One of the most effective ways to improve ETL performance is to avoid reading data that the job does not need.
If a job processes only a specific date range, filter the source before loading all records into Spark. For data stored in Amazon S3 and registered in the AWS Glue Data Catalog, partition pruning and pushdown predicates can reduce unnecessary file access.
Use partition pruning
Suppose application events are stored in S3 using this directory structure:
s3://company-data/events/
year=2026/
month=11/
day=28/
month=11/
day=29/
month=11/
day=30/
If the job only needs records from November 30, it should not read every date directory.
The following example uses a pushdown predicate while reading from the Data Catalog:
from awsglue.context import GlueContext
from pyspark.context import SparkContext
sc = SparkContext.getOrCreate()
glue_context = GlueContext(sc)
events_dyf = glue_context.create_dynamic_frame.from_catalog(
database="analytics",
table_name="application_events",
push_down_predicate="year='2026' and month='11' and day='30'"
)
The predicate filters catalog partitions before the job reads the underlying S3 files. This is more efficient than loading every partition and applying a DataFrame filter afterward.
Partition columns should reflect common query patterns. Date-based partitioning is useful for event and transaction data, while other datasets may benefit from tenant, region, or business-unit partitions.
Avoid creating a very large number of tiny partitions. A partitioning design that creates excessive directories can increase metadata and planning overhead.
Use catalog partition indexes for large partition catalogs
The push_down_predicate option can still require AWS Glue to retrieve and evaluate partition metadata. When a table has a very large number of partitions, this metadata operation can become expensive.
AWS Glue Data Catalog partition indexes can help with server-side partition filtering. The catalogPartitionPredicate option can use these indexes to narrow the partition list before the job processes it.
Use this approach when partition listing itself is a measurable bottleneck. It is not necessary for every table, and the index must be designed around the partition fields used by the workload.
Select only required columns
Avoid reading every column when the transformation uses only a few fields. Columnar formats such as Parquet and ORC support projection pushdown, allowing Spark to read only the required columns where the source and execution plan support it.
For example:
events_df = events_dyf.toDF()
selected_df = events_df.select(
"event_id",
"user_id",
"event_type",
"event_timestamp"
)
Reducing the number of columns can lower data transfer, memory usage, and processing overhead.
Choose the Right Data Format
The data format used by an ETL pipeline affects both read and write performance.
CSV and JSON are useful for data exchange and human-readable exports, but they often require more parsing work. They also do not provide the same column-oriented storage benefits as formats such as Parquet and ORC.
For analytical workloads, Parquet is often a practical choice because it stores data in a columnar format and supports compression and column-level reads.
Format | Common use | Performance considerations |
|---|
CSV | Simple exports and data exchange | Text parsing can be expensive; limited type information |
JSON | Semi-structured data and API exports | Flexible schema, but parsing can require more CPU and memory |
Parquet | Analytical datasets | Columnar reads, compression, and predicate pushdown |
ORC | Analytical and warehouse workloads | Columnar storage with compression and statistics |
Avro | Data exchange and schema-oriented pipelines | Row-oriented format with schema support |
For a pipeline that repeatedly processes analytical data, consider converting raw CSV or JSON files into Parquet during an initial transformation. Downstream jobs can then read the optimized dataset instead of repeatedly parsing the original files.
For example:
from awsglue.dynamicframe import DynamicFrame
output_dyf = DynamicFrame.fromDF(
selected_df,
glue_context,
"output_dyf"
)
glue_context.write_dynamic_frame.from_options(
frame=output_dyf,
connection_type="s3",
connection_options={
"path": "s3://company-data/processed/events/"
},
format="glueparquet"
)
Choose compression based on the workload and the consumers of the data. Compression can reduce storage and I/O, but it also requires CPU resources. Test the available options with representative data rather than assuming that the highest compression level is always the best choice.
Avoid the Small Files Problem
A large number of small files is a common performance problem in Spark-based data pipelines.
For example, a dataset containing 100 GB of data stored in thousands of small files can be slower to process than the same data stored in a smaller number of reasonably sized files. Spark must discover files, create tasks, schedule work, and manage metadata. These operations add overhead even when the files contain very little data.
Small files can also increase pressure on the Spark driver because it must coordinate a large number of input tasks.
Group small input files
AWS Glue supports file grouping for DynamicFrame-based reads. The groupFiles and groupSize options can combine small files into larger processing groups.
For example:
source_dyf = glue_context.create_dynamic_frame.from_options(
connection_type="s3",
connection_options={
"paths": ["s3://company-data/raw/events/"],
"recurse": True,
"groupFiles": "inPartition",
"groupSize": "134217728"
},
format="json"
)
The example uses a 128 MiB grouping target. Choose a suitable value based on file sizes, worker capacity, and the structure of the dataset. File grouping reduces task overhead; it does not physically merge the original files in S3.
Compact output files
Output partitioning also needs attention. Writing a large number of tiny files can make later jobs slower.
You can use coalesce() when reducing the number of output partitions without requiring a full shuffle:
output_df = selected_df.coalesce(20)
output_df.write \
.mode("overwrite") \
.parquet("s3://company-data/processed/compacted-events/")
This example is appropriate only when reducing the existing partition count is sufficient. If the data is unevenly distributed or needs to be redistributed across executors, repartition() may be more suitable, but it introduces a shuffle.
Do not choose a fixed output partition count without considering the dataset size and the number of logical output partitions. Test the resulting file sizes and task distribution.
Optimize Spark Partitioning and Parallelism
Spark partitions determine how data is divided into tasks. Too few partitions can leave workers underused, while too many partitions can create scheduling overhead and small output files.
A job that reads data from a source with limited parallelism may need to repartition after loading. For example:
events_df = events_dyf.toDF()
parallel_df = events_df.repartition(100)
The value 100 is only an example. The correct number depends on input size, worker capacity, transformation complexity, and the number of available cores.
AWS guidance describes using approximately two or three times the available core count as an initial consideration for some workloads. It is not a universal rule. Measure task duration and resource utilization before choosing a partition count.
Repartition by useful columns
When writing partitioned output, repartitioning by the output partition columns can help organize data before writing:
partitioned_df = events_df.repartition(
80,
"year",
"month"
)
partitioned_df.write \
.mode("append") \
.partitionBy("year", "month") \
.parquet("s3://company-data/processed/events/")
Be careful when using this approach. If one partition value contains most of the records, the workload can become unbalanced. This is known as data skew.
Handle data skew
Data skew occurs when some Spark partitions contain much more data than others. Most tasks may finish quickly while a few tasks continue running for a long time.
For example, a join on country may be uneven if one country accounts for most of the records. The tasks processing that value can become much slower than the others.
Possible approaches include:
Review the distribution of join keys before selecting a partitioning strategy.
Filter unnecessary records before the join.
Use broadcast joins when one side of the join is genuinely small enough.
Consider salting heavily skewed keys when the workload justifies the additional complexity.
Avoid repartitioning by a column with very few distinct values.
The Spark UI is useful for confirming skew because it exposes differences in task duration and input size.
Optimize Joins and Shuffle Operations
A shuffle moves data between executors so that records with related keys can be processed together. Joins, aggregations, sorting, and repartitioning can trigger shuffles.
Shuffle operations involve network transfer, serialization, disk I/O, and memory management. They can become a major performance bottleneck when the job processes large datasets.
Use broadcast joins for small datasets
When one side of a join is small enough to fit comfortably in executor memory, a broadcast join can avoid shuffling the larger dataset.
from pyspark.sql.functions import broadcast
transactions_df = spark.read.parquet(
"s3://company-data/transactions/"
)
customers_df = spark.read.parquet(
"s3://company-data/customers/"
)
result_df = transactions_df.join(
broadcast(customers_df),
on="customer_id",
how="inner"
)
Broadcasting sends the smaller dataset to the executors so that the larger dataset does not need to be shuffled for that join.
Do not broadcast a dataset simply because it is smaller than the other input. It must also be small enough for the available executor memory. An oversized broadcast can cause memory pressure or job failures.
Avoid unnecessary transformations
Repeated repartition(), distinct(), groupBy(), and orderBy() operations can introduce expensive data movement.
Review the execution plan when a transformation behaves unexpectedly:
result_df.explain("formatted")
The plan can help identify exchanges, scans, joins, and other operations that affect execution. Combine compatible transformations and remove operations that do not contribute to the required output.
Tune shuffle partitions carefully
The Spark setting spark.sql.shuffle.partitions controls the number of partitions used for many shuffle operations. The default may not match every workload.
You can set it through job parameters or Spark configuration:
--conf spark.sql.shuffle.partitions=200
A larger value can create more parallel tasks, but it can also increase scheduling overhead. A smaller value may reduce overhead but create large tasks that require more memory. Tune this setting using Spark UI metrics rather than copying a value from another job.
Use DynamicFrames and DataFrames Appropriately
AWS Glue provides DynamicFrames, which are designed for ETL workflows involving data with inconsistent or evolving schemas. They support Glue-specific features such as job bookmarks and certain Glue transformations.
Spark DataFrames provide the standard Spark SQL API. They are often more convenient for operations such as complex joins, aggregations, SQL expressions, and built-in Spark functions.
A common approach is to read the source through a DynamicFrame and convert it to a DataFrame for transformations:
source_dyf = glue_context.create_dynamic_frame.from_catalog(
database="analytics",
table_name="application_events",
transformation_ctx="source_events"
)
events_df = source_dyf.toDF()
filtered_df = events_df.filter(
events_df.event_type == "purchase"
)
result_df = filtered_df.select(
"event_id",
"user_id",
"event_timestamp"
)
This approach combines Glue's source integration with Spark's DataFrame operations.
However, there is an important consideration when using job bookmarks. Bookmark support depends on the supported Glue source and how it is read. For supported bookmark-based sources, use the appropriate Glue DynamicFrame read path and a stable transformation_ctx. Converting the resulting DynamicFrame to a DataFrame for downstream transformations is different from replacing the bookmark-aware source read with a direct Spark read.
Choose the API based on the source, schema requirements, and transformations. Converting between DynamicFrames and DataFrames repeatedly can add complexity without providing a performance benefit.
Use Job Bookmarks for Incremental Processing
Many ETL pipelines do not need to process the entire dataset every time they run. Job bookmarks allow AWS Glue to track previously processed data for supported sources and process new or changed data during later runs.
For example, a daily pipeline that processes incoming files can use bookmarks to avoid reading the same eligible files repeatedly.
A basic bookmark-aware job structure looks like this:
import sys
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
args = getResolvedOptions(
sys.argv,
["JOB_NAME"]
)
sc = SparkContext.getOrCreate()
glue_context = GlueContext(sc)
job = Job(glue_context)
job.init(args["JOB_NAME"], args)
source_dyf = glue_context.create_dynamic_frame.from_catalog(
database="analytics",
table_name="incoming_events",
transformation_ctx="incoming_events_source"
)
events_df = source_dyf.toDF()
# Apply the required transformations here.
job.commit()
The job must be configured to enable bookmarks. The job.init() call initializes the bookmark state, and job.commit() saves the state at the end of a successful run.
Keep the transformation_ctx value stable when updating the job. Changing it can affect how Glue identifies the source or transformation state.
Bookmarks are not a replacement for application-level idempotency. A job can fail after writing output but before committing bookmark state. A retry may therefore encounter records that were already written. Design the output process so that repeated processing does not create duplicate or inconsistent results.
Select Suitable AWS Glue Worker Resources
AWS Glue provides worker types with different resource capacities. Selecting a worker type and worker count that match the workload can improve performance, but adding more workers is not always the best solution.
Consider the following factors:
Data volume and expected growth.
Memory required by joins, aggregations, and sorting.
CPU demand from parsing and transformations.
Number of tasks that can run in parallel.
Time spent waiting for source and destination systems.
For example, a memory-intensive job may benefit from a worker type with more memory, while a job that is limited by insufficient parallelism may benefit from additional workers.
AWS Glue also supports auto scaling for supported ETL jobs. With auto scaling enabled, Glue can add or remove workers based on workload parallelism, subject to the configured maximum.
The managed scaling profile is another option for supported Spark ETL jobs on AWS Glue 6.0 and later. It adjusts the cluster size during execution using the selected profile and maximum worker capacity. Check the current Glue version and feature requirements before enabling it.
Do not increase the worker count just because a job is slow. If the bottleneck is a full table scan, an inefficient join, or a large number of small files, adding workers may increase cost without solving the underlying issue.
Monitor Jobs With Spark UI and CloudWatch
Performance optimization should be based on evidence from actual job runs.
AWS Glue integrates with Amazon CloudWatch for job logs and metrics. The Spark UI provides a more detailed view of distributed execution.
Use these tools to investigate:
Which stage takes the most time.
Whether tasks are evenly distributed.
Whether executors are frequently running out of memory.
How much data is read and written during shuffle operations.
Whether the job spends too much time listing or reading files.
Whether the number of tasks is appropriate for the available resources.
For production jobs, keep useful logging around major pipeline stages. Record input counts, output counts, processing dates, and validation results. Avoid logging sensitive record values or credentials.
You can also enable Glue job observability metrics and continuous logging where appropriate. These features make it easier to compare runs and identify performance regressions after code or configuration changes.
A Practical PySpark ETL Optimization Example
The following example combines several of the techniques discussed above. It reads a partitioned source through the Glue Data Catalog, uses a pushdown predicate, converts the DynamicFrame to a DataFrame, selects required columns, filters records, and writes Parquet output.
import sys
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from pyspark.sql.functions import col
args = getResolvedOptions(
sys.argv,
["JOB_NAME", "PROCESS_DATE"]
)
sc = SparkContext.getOrCreate()
glue_context = GlueContext(sc)
spark = glue_context.spark_session
job = Job(glue_context)
job.init(args["JOB_NAME"], args)
process_date = args["PROCESS_DATE"]
year, month, day = process_date.split("-")
source_dyf = glue_context.create_dynamic_frame.from_catalog(
database="analytics",
table_name="raw_events",
push_down_predicate=(
f"year='{year}' and month='{month}' and day='{day}'"
),
transformation_ctx="raw_events_source"
)
source_df = source_dyf.toDF()
filtered_df = (
source_df
.select(
"event_id",
"user_id",
"event_type",
"event_timestamp",
"year",
"month",
"day"
)
.filter(col("event_id").isNotNull())
)
# Apply additional business transformations here.
output_path = (
f"s3://company-data/processed/events/"
f"year={year}/month={month}/day={day}/"
)
filtered_df.write \
.mode("overwrite") \
.format("parquet") \
.save(output_path)
job.commit()
Pass the job name and processing date as job parameters. The job can then process a specific date without changing the script.
This example uses overwrite for a date-specific output path. That is suitable only when the pipeline owns that output location and a rerun is expected to replace the complete date partition. For shared datasets or partial updates, use a carefully designed write strategy, such as a controlled merge or transactional table format, to avoid replacing unrelated data.
For production use, also add input validation, schema checks, data-quality rules, error handling, and monitoring. Validate the output before considering the run complete.
Common Mistakes to Avoid
Increasing workers before investigating the bottleneck
More workers can help when the job has enough parallel tasks but insufficient compute capacity. They do not automatically fix inefficient transformations, excessive file listing, or poor partitioning.
Reading all data and filtering afterward
Applying a filter after loading a large dataset can waste I/O and memory. Use partition pruning and source-supported pushdown wherever possible.
Creating too many output files
Using a very high partition count can produce many small files. This increases metadata overhead and can slow down future jobs.
Broadcasting large datasets
Broadcast joins are useful for genuinely small lookup datasets. Broadcasting a large dataset can create memory pressure and cause executor failures.
Changing several Spark settings together
Changing worker counts, shuffle partitions, file grouping, and join strategies in one release makes it difficult to identify the reason for a performance change. Tune one area at a time and compare results.
Treating job bookmarks as a complete duplicate-prevention system
Bookmarks track processing state for supported sources. They do not guarantee that every output operation is exactly once. Design writes to tolerate retries and partial failures.
Caching every intermediate DataFrame
Caching can help when the same expensive DataFrame is reused multiple times. It can also consume memory and create unnecessary overhead when the data is used only once. Cache selectively and release cached data when it is no longer needed.
Best Practices for Production AWS Glue ETL Jobs
A production-ready Glue pipeline should be designed for predictable performance, reliable recovery, and manageable cost.
Start with a measurable performance baseline for each important job.
Use the latest compatible AWS Glue version after testing dependencies and behavior.
Filter data as early as possible, preferably at the source.
Select only the columns required by the transformation.
Use Parquet or ORC for analytical datasets when appropriate.
Keep input and output file sizes within a practical range.
Use file grouping when reading large numbers of small files.
Choose partition columns based on real access patterns.
Monitor data skew before increasing parallelism.
Use broadcast joins only when the smaller dataset fits safely in memory.
Enable job bookmarks for supported incremental workloads.
Make output operations safe to retry.
Use auto scaling or managed scaling when the job and Glue version support them.
Review Spark UI stages and CloudWatch metrics after significant changes.
Keep credentials and sensitive values out of logs.
Test schema changes and late-arriving records before deploying pipeline updates.
Advantages and Disadvantages of AWS Glue With Spark
Advantages | Disadvantages |
|---|
Managed Spark infrastructure reduces cluster administration | Performance still depends on Spark application design |
Integrates with Amazon S3 and the Glue Data Catalog | Large catalogs and small files can introduce overhead |
Supports distributed processing for large datasets | Shuffle-heavy operations can be expensive |
Provides job monitoring and scaling features | More workers can increase cost |
Supports incremental processing through job bookmarks for supported sources | Bookmark behavior requires careful source and retry handling |
Supports multiple data formats and connectors | Connector capabilities and pushdown support vary |
AWS Glue is a strong option for managed ETL workloads, especially when the data pipeline already uses AWS services. However, it is important to evaluate the workload, required runtime, operational requirements, and cost before choosing it for every data-processing task.
Summary
Optimizing AWS Glue ETL jobs with Spark is mainly about reducing unnecessary work and making distributed processing more efficient. Start by measuring the job and identifying its slowest stages. Then focus on reducing data scans, using partition pruning, selecting suitable file formats, controlling small files, and improving Spark partitioning.
Joins and shuffle operations deserve particular attention because they can move large amounts of data between executors. DynamicFrames, DataFrames, and job bookmarks should also be used according to their capabilities and limitations.
Finally, choose worker resources based on observed workload behavior rather than guesswork. Use Spark UI and CloudWatch to verify every important change. A well-designed ETL pipeline should not only run faster but also remain reliable when data volume grows, schemas change, or a job needs to be retried.
Join the conversation! Your thoughts help the community grow.