Batch Processing Optimizer
Optimize batch data processing workloads using Spark, Polars, DuckDB, and pandas with focus on memory efficiency, parallelism, and cost reduction.
Activation Triggers
Activate on: "batch processing", "Spark optimization", "Polars", "DuckDB", "pandas performance", "data frame", "shuffle optimization", "partition skew", "memory optimization", "out of memory"
NOT for: Real-time streaming → streaming-pipeline-architect | Warehouse SQL tuning → data-warehouse-optimizer | Pipeline orchestration → airflow-dag-orchestrator
Quick Start
- Choose the right tool — DuckDB for single-node analytics, Polars for DataFrames, Spark for distributed
- Profile first — identify bottlenecks (shuffle, skew, memory) before optimizing
- Reduce data early — filter and select columns as early as possible in the pipeline
- Avoid shuffles — broadcast small tables, pre-partition data, use map-side joins
- Right-size resources — match executor memory/cores to actual data size
Core Capabilities
| Domain |
Technologies |
| Distributed |
Apache Spark 3.5+, Dask, Ray |
| Single-Node |
DuckDB 1.1+, Polars 1.x, pandas 2.2+ |
| File Formats |
Parquet, Arrow IPC, Delta Lake, Iceberg |
| Optimization |
AQE (Spark), lazy evaluation (Polars), columnar scans |
| Cloud |
Databricks, EMR, Dataproc, serverless Spark |
Architecture Patterns
Tool Selection Decision Tree
Data Size?
├─ < 10 GB → DuckDB (SQL) or Polars (DataFrame)
│ Single machine, zero setup, fastest iteration
│
├─ 10-100 GB → Polars (lazy) or DuckDB (out-of-core)
│ Still single machine with spill-to-disk
│
└─ > 100 GB → Spark (distributed)
Multi-node cluster, shuffle-based joins
Complexity?
├─ SQL-centric → DuckDB (fastest SQL engine for analytics)
├─ DataFrame → Polars (10x faster than pandas, lazy evaluation)
└─ Complex ML → Spark + MLlib or Spark + Ray
Spark Optimization Patterns
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
spark = SparkSession.builder \
.config("spark.sql.adaptive.enabled", "true") \
.config("spark.sql.adaptive.coalescePartitions.enabled", "true") \
.config("spark.sql.adaptive.skewJoin.enabled", "true") \
.getOrCreate()
# GOOD: broadcast small dimension table (< 100MB)
from pyspark.sql.functions import broadcast
result = large_df.join(broadcast(small_dim_df), "key")
# GOOD: predicate pushdown — filter before join
orders = spark.read.parquet("s3://data/orders/") \
.filter(F.col("order_date") >= "2026-01-01") \
.select("order_id", "customer_id", "amount") # column pruning
# BAD: collect() on large dataset — causes OOM on driver
# all_data = large_df.collect() # NEVER do this
# GOOD: write partitioned output
result.repartition(200) \
.write.mode("overwrite") \
.partitionBy("order_date") \
.parquet("s3://output/results/")
Polars Lazy Evaluation
import polars as pl
# Lazy mode: builds query plan, optimizes, then executes
result = (
pl.scan_parquet("data/orders/*.parquet") # lazy scan
.filter(pl.col("order_date") >= "2026-01-01")
.join(
pl.scan_parquet("data/customers/*.parquet"),
on="customer_id",
how="inner"
)
.group_by("region")
.agg([
pl.col("amount").sum().alias("total_revenue"),
pl.col("order_id").n_unique().alias("order_count"),
])
.sort("total_revenue", descending=True)
.collect() # executes optimized plan
)
# Polars optimizes: predicate pushdown, projection pushdown,
# join reordering — all automatically via lazy evaluation
Anti-Patterns
- pandas for >5GB — pandas loads everything into memory; use Polars (lazy) or DuckDB for medium data, Spark for large
- Collect to driver —
df.collect() or df.toPandas() on large Spark DataFrames causes OOM; aggregate first
- Ignoring partition skew — one partition with 10x more data than others bottlenecks the entire job; use AQE or salting
- Reading all columns — always select only needed columns; Parquet columnar format skips unused columns entirely
- Tiny output files — too many small output files (< 128MB) slow downstream reads; coalesce before writing
Quality Checklist
1---
2license: Apache-2.0
3name: batch-processing-optimizer
4description: 'Spark, pandas, polars, DuckDB optimization for batch data processing. Activate on: batch processing, Spark optimization, polars, DuckDB, pandas performance, data frame, shuffle, partition, memory optimization. NOT for: streaming pipelines (use streaming-pipeline-architect), warehouse queries (use data-warehouse-optimizer).'
5allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*,python:*,spark-submit:*)
6category: Backend & Infrastructure
7tags:
8 - batch-processing
9 - spark
10 - polars
11 - duckdb
12 - performance
13pairs-with:
14 - skill: data-warehouse-optimizer
15 reason: Batch outputs often load into warehouses
16 - skill: airflow-dag-orchestrator
17 reason: Airflow schedules batch processing jobs
18 - skill: lakehouse-architect
19 reason: Batch jobs read/write lakehouse tables
20metadata:
21 source: https://skillmd.com/skills/curiositech/batch-processing-optimizer
22---
23
24# Batch Processing Optimizer
25
26Optimize batch data processing workloads using Spark, Polars, DuckDB, and pandas with focus on memory efficiency, parallelism, and cost reduction.
27
28## Activation Triggers
29
30**Activate on:** "batch processing", "Spark optimization", "Polars", "DuckDB", "pandas performance", "data frame", "shuffle optimization", "partition skew", "memory optimization", "out of memory"
31
32**NOT for:** Real-time streaming → `streaming-pipeline-architect` | Warehouse SQL tuning → `data-warehouse-optimizer` | Pipeline orchestration → `airflow-dag-orchestrator`
33
34## Quick Start
35
361. **Choose the right tool** — DuckDB for single-node analytics, Polars for DataFrames, Spark for distributed
372. **Profile first** — identify bottlenecks (shuffle, skew, memory) before optimizing
383. **Reduce data early** — filter and select columns as early as possible in the pipeline
394. **Avoid shuffles** — broadcast small tables, pre-partition data, use map-side joins
405. **Right-size resources** — match executor memory/cores to actual data size
41
42## Core Capabilities
43
44| Domain | Technologies |
45|--------|-------------|
46| **Distributed** | Apache Spark 3.5+, Dask, Ray |
47| **Single-Node** | DuckDB 1.1+, Polars 1.x, pandas 2.2+ |
48| **File Formats** | Parquet, Arrow IPC, Delta Lake, Iceberg |
49| **Optimization** | AQE (Spark), lazy evaluation (Polars), columnar scans |
50| **Cloud** | Databricks, EMR, Dataproc, serverless Spark |
51
52## Architecture Patterns
53
54### Tool Selection Decision Tree
55
56```
57Data Size?
58 ├─ < 10 GB → DuckDB (SQL) or Polars (DataFrame)
59 │ Single machine, zero setup, fastest iteration
60 │
61 ├─ 10-100 GB → Polars (lazy) or DuckDB (out-of-core)
62 │ Still single machine with spill-to-disk
63 │
64 └─ > 100 GB → Spark (distributed)
65 Multi-node cluster, shuffle-based joins
66
67Complexity?
68 ├─ SQL-centric → DuckDB (fastest SQL engine for analytics)
69 ├─ DataFrame → Polars (10x faster than pandas, lazy evaluation)
70 └─ Complex ML → Spark + MLlib or Spark + Ray
71```
72
73### Spark Optimization Patterns
74
75```python
76from pyspark.sql import SparkSession
77import pyspark.sql.functions as F
78
79spark = SparkSession.builder \
80 .config("spark.sql.adaptive.enabled", "true") \
81 .config("spark.sql.adaptive.coalescePartitions.enabled", "true") \
82 .config("spark.sql.adaptive.skewJoin.enabled", "true") \
83 .getOrCreate()
84
85# GOOD: broadcast small dimension table (< 100MB)
86from pyspark.sql.functions import broadcast
87result = large_df.join(broadcast(small_dim_df), "key")
88
89# GOOD: predicate pushdown — filter before join
90orders = spark.read.parquet("s3://data/orders/") \
91 .filter(F.col("order_date") >= "2026-01-01") \
92 .select("order_id", "customer_id", "amount") # column pruning
93
94# BAD: collect() on large dataset — causes OOM on driver
95# all_data = large_df.collect() # NEVER do this
96
97# GOOD: write partitioned output
98result.repartition(200) \
99 .write.mode("overwrite") \
100 .partitionBy("order_date") \
101 .parquet("s3://output/results/")
102```
103
104### Polars Lazy Evaluation
105
106```python
107import polars as pl
108
109# Lazy mode: builds query plan, optimizes, then executes
110result = (
111 pl.scan_parquet("data/orders/*.parquet") # lazy scan
112 .filter(pl.col("order_date") >= "2026-01-01")
113 .join(
114 pl.scan_parquet("data/customers/*.parquet"),
115 on="customer_id",
116 how="inner"
117 )
118 .group_by("region")
119 .agg([
120 pl.col("amount").sum().alias("total_revenue"),
121 pl.col("order_id").n_unique().alias("order_count"),
122 ])
123 .sort("total_revenue", descending=True)
124 .collect() # executes optimized plan
125)
126
127# Polars optimizes: predicate pushdown, projection pushdown,
128# join reordering — all automatically via lazy evaluation
129```
130
131## Anti-Patterns
132
1331. **pandas for >5GB** — pandas loads everything into memory; use Polars (lazy) or DuckDB for medium data, Spark for large
1342. **Collect to driver** — `df.collect()` or `df.toPandas()` on large Spark DataFrames causes OOM; aggregate first
1353. **Ignoring partition skew** — one partition with 10x more data than others bottlenecks the entire job; use AQE or salting
1364. **Reading all columns** — always select only needed columns; Parquet columnar format skips unused columns entirely
1375. **Tiny output files** — too many small output files (< 128MB) slow downstream reads; coalesce before writing
138
139## Quality Checklist
140
141- [ ] Tool matches data size (DuckDB/Polars < 100GB, Spark > 100GB)
142- [ ] Columns pruned early (select only what is needed)
143- [ ] Filters pushed down to scan level (predicate pushdown)
144- [ ] Small tables broadcast in joins (< 100MB)
145- [ ] Spark AQE enabled (adaptive query execution)
146- [ ] No `collect()` on large datasets (aggregate before collecting)
147- [ ] Output files sized 128MB-1GB (coalesce/repartition before write)
148- [ ] Partition skew monitored and mitigated (salting or AQE)
149- [ ] Job profiled: Spark UI stages, Polars `.explain()`, DuckDB `EXPLAIN ANALYZE`
150- [ ] Memory sized appropriately: executor memory >= 2x largest partition