Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 27

Optimizing Spark Queries with Partitioning

This lesson is built with resources from bigdataperformance.substack.com and python.plainenglish.io.

Hello! Welcome back.

In our last lesson, we explored how caching and persistence allow you to optimize Spark jobs by keeping data in memory, avoiding costly re-computations. This was a key strategy for optimizing your cluster's memory and CPU usage. Today, we'll tackle another fundamental performance pillar: optimizing how data is physically distributed across the cluster.

Your learning outcome for this lesson is to apply partitioning strategies to optimize Spark query performance. As a data architect, mastering partitioning is non-negotiable. It's the primary lever you have to control parallelism, manage data skew, and minimize I/O, directly impacting the speed and cost of your data pipelines.

What is a Partition?

Before we dive into strategies, let's solidify the core concept. In Spark, a partition is a logical chunk of your DataFrame. Each partition is processed as a single unit (a task) by an executor core. The number of partitions determines the degree of parallelism your job can achieve.

Let's begin with a quick reading to formalize this concept.

Mastering Apache Spark Partitioning: Coalesce vs. Repartition

The article 'Mastering Apache Spark Partitioning' from Big Data Performance provides a great introduction to what partitions are and why they matter.

Please read the first two sections, 'Understanding Partitions in Apache Spark'. It clearly defines a partition and its role in determining parallelism.

From an architectural standpoint, think of partitions as the threads of your data processing application. Too few, and you leave expensive cluster resources idle. Too many, and the overhead of scheduling and managing tasks can slow things down. Your goal is to find the right balance.


Controlling In-Memory Partitions: repartition() vs. coalesce()

Spark gives you two main functions to control the number of in-memory partitions for a DataFrame: repartition() and coalesce(). While they can both change the partition count, they work very differently and have profound performance implications.

Let's look at a visual representation first.

Spark coalesce() vs. repartition() Visual Comparison
This diagram illustrates the fundamental difference between `coalesce()` and `repartition()`. `coalesce()` performs a 'narrow' transformation, combining existing partitions to reduce their number without a full data shuffle. `repartition()` performs a 'wide' transformation, triggering a full shuffle to redistribute data evenly across new partitions.

As you can see:

  • coalesce() is a "narrow" transformation. It combines existing partitions, often on the same machine, minimizing data movement.
  • repartition() is a "wide" transformation. It triggers a full shuffle, moving data across the network to create new, roughly equal-sized partitions.

Now, let's dive into the specifics of how they work and, more importantly, the performance trade-offs.

Mastering Apache Spark Partitioning: Coalesce vs. Repartition

Let's return to the 'Mastering Apache Spark Partitioning' article. It does an excellent job of explaining the mechanics and the hidden performance drawbacks of each function.

Please read the sections titled 'Coalesce: The Narrow Transformation', 'Repartition: The Wide Transformation', and especially 'The Hidden Drawbacks: Performance Implications'. The last section contains a critical insight for any architect regarding the risk of using coalesce() too early in a pipeline.

The key takeaways from the reading are crucial for design decisions:

  1. repartition() is expensive but powerful. The full shuffle costs network I/O and serialization overhead, but it's the only way to increase partitions or to fix data skew by rebalancing data evenly.
  2. coalesce() is cheap but risky. It avoids a shuffle, making it efficient for reducing partitions. However, as the article highlights, using it too early can cripple parallelism for an entire stage, forcing a 100-core cluster to run on only 10 cores, for example. This is a classic performance trap.

Architect's Playbook: Applying Partitioning Strategies

Now for the practical application. When do you use which strategy, and how do you determine the right number of partitions?

When to repartition()

  • After heavy filtering: When a filter() operation removes a large percentage of your data, you are often left with many small or even empty partitions. This leads to inefficient processing. Use repartition() to rebalance the remaining data into a smaller number of evenly-sized partitions.
  • To increase parallelism: If you are reading from a source that creates too few partitions (e.g., a single large JSON file), you can repartition() to a larger number to fully utilize your cluster's cores.
  • Before a join on a skewed key: If you know a join key is unevenly distributed, repartitioning both DataFrames by the join key can co-locate the data and optimize the join performance.

When to coalesce()

  • Right before writing to disk: This is the classic use case. After all your wide transformations (join, groupBy, etc.) are done, you might have 200 partitions. Writing these out would create 200 small files, which is inefficient for future reads. You can use df.coalesce(10).write.parquet(...) to reduce the number of output files without incurring the cost of a final shuffle.

How Many Partitions?

There's no single magic number, but a good rule of thumb is to aim for partitions that are between 128MB and 256MB in size.

  • Too small: The overhead of the Spark scheduler managing thousands of tiny tasks can become a bottleneck.
  • Too large: You might underutilize your cluster or, worse, cause OutOfMemory errors if a single partition doesn't fit in an executor's memory.

You can dynamically calculate a reasonable number of partitions. The following reading provides a simple but effective approach.

From Minutes to Seconds: The Complete Guide to PySpark ...

The guide 'From Minutes to Seconds' offers several practical code-based strategies. Let's look at how to calculate an optimal number of partitions.

Read the subsections 'Repartition vs. Coalesce' under 'Partitioning Strategies' and 'Avoiding Over-partitioning' under 'Cost Optimization in the Cloud'. The code snippets show how to use the functions and how to calculate a target partition count.

Test your understanding!

You have a 500GB DataFrame with 2000 partitions. Your first step is a filter() operation that keeps only 1% of the records, corresponding to about 5GB of data. You then need to perform an expensive groupBy() aggregation on this filtered data. What is the best partitioning strategy to apply after the filter but before the groupBy?

  1. Do nothing and let the groupBy run on the 2000 partitions.
  2. Use filtered_df.coalesce(40)
  3. Use filtered_df.repartition(40)

Explain your choice. (Assume a target partition size of ~128MB).

Show answer

The correct answer is 3. Use filtered_df.repartition(40).

Reasoning:

  • The filter() operation will leave most of the 2000 partitions empty or very small, while a few might still contain data. This is classic data skew.
  • Option 1 is bad: Running the groupBy on 2000 mostly empty partitions is extremely inefficient. Spark will waste time scheduling and managing thousands of tasks that do almost no work.
  • Option 2 is bad: coalesce(40) would just collapse the 2000 partitions into 40 without rebalancing the data. You would likely end up with a few very large partitions and many empty ones, which does not solve the skew problem for the upcoming groupBy.
  • Option 3 is correct: repartition(40) will trigger a shuffle, which is exactly what you need here. It will take the 5GB of scattered data, ignore all the empty space, and redistribute it evenly across 40 new, right-sized partitions (5000MB / 40 partitions ≈ 125MB/partition). This ensures the subsequent groupBy operation runs with maximum parallelism and efficiency.

Partitioning on Disk: partitionBy() for Predicate Pushdown

So far, we've discussed partitioning data in memory during a Spark job. There's another, equally important type of partitioning: partitioning data on disk when you write it. This is done using the partitionBy() method.

daily_sales_df.write.partitionBy("year", "month", "day").parquet("s3://bucket/sales/")

This doesn't change the number of files written (that's still controlled by the number of in-memory partitions). Instead, it creates a directory structure like this:

/sales/
  └── year=2024/
      ├── month=01/
      │   ├── day=20/
      │   │   └── part-00001.snappy.parquet
      │   └── day=21/
      │       └── part-00002.snappy.parquet
      └── month=02/
          └── ...

The architectural benefit here is Partition Pruning (or Predicate Pushdown). If you later query this data with a filter, Spark is smart enough to read only the directories that match the filter.

# Spark will only scan the files inside /sales/year=2024/month=01/
spark.read.parquet("s3://bucket/sales/").where("year = 2024 AND month = '01'")

For huge datasets, this can change a query from scanning terabytes to scanning megabytes, providing a massive performance boost. Always choose partition columns that you filter on frequently (e.g., dates, regions, customer segments).


Conclusion

You've now seen how partitioning is a multi-faceted tool for a data architect. It's not just about one function call; it's a series of strategic decisions to balance workload, manage I/O, and control data layout both in memory and on disk.

Key Takeaways:

  • Partitions dictate parallelism. The goal is to have enough partitions to keep the cluster busy, but not so many that scheduling overhead becomes a problem.
  • repartition() shuffles data. It's expensive but essential for increasing parallelism and fixing data skew. Use it after heavy filters or before shuffle-heavy operations like joins.
  • coalesce() avoids a shuffle. It's efficient for reducing partitions, but should typically only be used right before writing data to avoid killing parallelism in preceding stages.
  • partitionBy() organizes data on disk. This enables partition pruning, a critical optimization technique that allows Spark to skip reading irrelevant data entirely.

This lesson concludes our module on Apache Spark. You've learned about its architecture, how to transform data, and how to optimize performance through file formats, caching, and partitioning.

In our next lesson, we will zoom out from the processing engine and begin Module 5: Building the Data Lakehouse. We will start by describing the concept of a data lake, its common challenges, and how the principles we've just learned help address them.