SparkLab/ modules 0/39 lessons
The whole course

Every lesson, briefly.

6 modules and 39 lessons in one scroll: what each lesson covers, what you'll be able to do and the takeaways worth remembering. Open any lesson to replay it on the dashboard.

MODULE 01

Spark Architecture

Module quiz

Driver, executors and the cluster manager; how a job becomes stages and tasks; partitions, the shuffle and executor memory.

lesson 01

Why Spark: from MapReduce to in-memory

10 min 9 stepsBeginner
Replay lesson

MapReduce paid a trip through disk for every job; Spark keeps data in memory and plans the whole pipeline as a DAG.

You'll learn
  • Why big data needs data-parallel processing
  • What made MapReduce slow for pipelines and iterative jobs
  • How in-memory working sets and a DAG remove disk round-trips
  • Lazy evaluation: transformations plan, actions run
  • One engine for SQL, streaming and ML — and where it runs
  • When pandas or DuckDB is the better tool
Takeaways
  1. 1Spark splits data into partitions and runs the same code on every partition in parallel across a cluster.
  2. 2MapReduce writes each job's output to replicated HDFS, so chained and iterative jobs spend most of their time on disk and network I/O.
  3. 3Spark keeps working sets in executor memory and rebuilds lost partitions from lineage instead of replicating them.
  4. 4Transformations only build a DAG; an action triggers execution, which lets Spark optimise the whole plan first.
  5. 5SQL/DataFrames, Structured Streaming, MLlib and GraphX share one engine that runs on Standalone, YARN or Kubernetes — or managed on EMR, Glue and Databricks.
  6. 6If the data fits comfortably on one machine, pandas, Polars or DuckDB is usually faster and simpler than Spark.
lesson 02

Anatomy of a Spark application

12 min 9 stepsBeginner
Replay lesson

One driver, many executors and a cluster manager in between — follow a job from spark-submit to results.

You'll learn
  • The three roles: driver, cluster manager and executors
  • How spark-submit and the deploy mode decide where the driver runs
  • What the driver does: DAG, scheduling and the Spark UI
  • How executors run tasks in parallel slots
  • What happens when an executor dies
Takeaways
  1. 1Every Spark application has exactly one driver, which runs your main program, plans the work and schedules tasks.
  2. 2Executors are JVM processes on worker nodes; each core is a slot that runs one task (one partition) at a time.
  3. 3The cluster manager — Standalone, YARN or Kubernetes — only hands out resources; it never runs your code.
  4. 4In client mode the driver runs where you submitted from; in cluster mode it runs inside the cluster.
  5. 5Only small results should come back to the driver: collect() on big data is the classic driver out-of-memory.
  6. 6If an executor dies, the driver re-runs its tasks elsewhere, recomputing lost partitions from lineage.
lesson 03

Jobs, stages and tasks

13 min 9 stepsIntermediate
Replay lesson

Follow one action from the DAG to stages cut at shuffles to one task per partition — and find it in the Spark UI.

You'll learn
  • Transformations vs actions, and why nothing runs before an action
  • Narrow vs wide dependencies
  • How the DAGScheduler cuts a job into stages at shuffles
  • One task per partition, run in waves over the slots
  • Finding jobs, stages and tasks in the Spark UI
Takeaways
  1. 1Transformations are lazy and only extend the plan; every action submits at least one job.
  2. 2Narrow transformations (filter, select, withColumn) are pipelined inside one stage; wide ones (groupBy, join, distinct, orderBy, repartition) need a shuffle.
  3. 3The DAGScheduler ends a stage at every shuffle — an Exchange in the physical plan — and a stage starts only after its parent stages finish.
  4. 4A stage runs one task per partition: input splits for scan stages, spark.sql.shuffle.partitions (200) after a shuffle unless AQE coalesces them.
  5. 5Tasks run in waves of executors × cores slots — ⌈tasks ÷ slots⌉ waves — so a nearly empty last wave leaves cores idle.
  6. 6In the Spark UI jobs contain stages and stages contain tasks; a skipped stage reused shuffle output computed by an earlier job.
lesson 04

RDDs, partitions and lineage

12 min 8 stepsIntermediate
Replay lesson

An RDD is partitions plus a recipe — how input splits form, how lineage rebuilds lost data, and why locality matters.

You'll learn
  • The five properties that define an RDD
  • How DataFrames run as RDDs, and getNumPartitions()
  • How file splits decide the number of input partitions
  • How Spark rebuilds lost partitions from lineage
  • Data locality levels and spark.locality.wait
Takeaways
  1. 1An RDD is defined by its partitions, a compute function, dependencies on parents, and optionally a partitioner and preferred locations.
  2. 2DataFrame queries execute as RDDs (FileScanRDD, MapPartitionsRDD, ShuffledRowRDD…), so partitions and lineage still drive performance.
  3. 3File scans cut input into partitions of at most spark.sql.files.maxPartitionBytes (128 MB), packing small files and splitting smaller when data is small; non-splittable files are one partition each.
  4. 4Narrow operations keep the partition count; shuffles and repartition() set a new one; coalesce() merges partitions without a shuffle.
  5. 5Lost partitions are recomputed from lineage rather than restored from replicas; checkpoint() truncates lineage that has grown too long.
  6. 6The scheduler prefers PROCESS_LOCAL, then NODE_LOCAL, RACK_LOCAL and ANY, waiting spark.locality.wait (3 s) before each fallback.
lesson 05

Inside the shuffle

14 min 9 stepsAdvanced
Replay lesson

Map tasks sort and write blocks to local disk, reducers fetch them over the network — the costliest step in most jobs.

You'll learn
  • Why grouping and joining force an all-to-all shuffle
  • What map tasks write to local disk, and how reducers fetch it
  • How spark.sql.shuffle.partitions sizes every reduce task
  • Spill, and why shuffles dominate runtime
  • External shuffle service, shuffle tracking and fetch-failure retries
Takeaways
  1. 1A shuffle co-locates rows with the same key by sending every map task's rows to the reduce partition that owns each key.
  2. 2Map tasks write one sorted data file plus an index file to executor-local disk; reduce tasks fetch their block from every map output over the network.
  3. 3DataFrame shuffles produce spark.sql.shuffle.partitions (200) partitions regardless of data size; AQE can coalesce small ones at runtime.
  4. 4When execution memory runs out, sorts and aggregations spill sorted runs to disk — slower, but the task survives.
  5. 5Shuffle files die with their executor unless an external shuffle service, shuffle tracking or decommissioning keeps them available.
  6. 6A FetchFailedException makes the DAGScheduler re-run the lost map outputs and retry the stage, up to spark.stage.maxConsecutiveAttempts (4) times.
lesson 06

Executor memory, caching and shared variables

15 min 9 stepsAdvanced
Replay lesson

Inside an executor: heap regions, overhead and Python workers, cache levels, broadcast variables and accumulators.

You'll learn
  • How an executor container splits into heap and overhead
  • Reserved, user and unified memory — with the numbers
  • How execution and storage borrow and evict
  • Why a task spills, and when it runs out of memory instead
  • cache(), persist() and unpersist()
  • Broadcast variables and accumulators, and their gotchas
Takeaways
  1. 1An executor's container is its heap plus spark.executor.memoryOverhead (default max(384 MB, 10% of heap)), plus off-heap and PySpark memory when configured.
  2. 2Unified memory is (heap − 300 MB) × spark.memory.fraction (0.6), shared by execution and storage; the remaining 40% is user memory.
  3. 3Execution can evict cached blocks down to spark.memory.storageFraction (0.5) of unified memory; storage can never evict execution.
  4. 4Sorts, aggregations and shuffles spill to disk when execution memory runs out; OOMs come from what can't spill — huge records, user objects, collect(), broadcasts and Python or native memory.
  5. 5DataFrame cache() uses MEMORY_AND_DISK_DESER, is filled lazily by actions, and should be released with unpersist().
  6. 6Broadcast variables ship read-only data once per executor; accumulator updates are exactly-once only inside actions.
MODULE 02

PySpark in Depth

Module quiz

How Python drives the JVM, the DataFrame API end to end, UDFs vs pandas UDFs, nested data and Structured Streaming.

lesson 07

How PySpark talks to the JVM

12 min 8 stepsIntermediate
Replay lesson

Your Python code steers a JVM through Py4J — see when data stays in the JVM and when it crosses into Python.

You'll learn
  • How the Python driver controls a JVM driver through Py4J
  • Why built-in DataFrame functions run at JVM speed
  • When executors start Python workers, and what crosses over
  • Pickle vs Arrow serialisation, and how to avoid both
  • How Python memory fits into executor memory overhead
  • What Spark Connect changes for Python clients
Takeaways
  1. 1A PySpark driver is a Python process controlling a JVM driver through Py4J; Python objects like DataFrame are proxies for JVM objects.
  2. 2DataFrame transformations only build a plan inside the JVM, so code made of built-in functions executes as JVM code on the executors.
  3. 3Executors start Python workers only for Python UDFs, pandas UDFs, pandas function APIs and RDD lambdas — and every row involved is serialised across and back.
  4. 4Pandas UDFs exchange Arrow batches instead of pickled rows; regular Python UDFs are Arrow-optimised by default since Spark 4.2.
  5. 5Python worker memory lives outside the JVM heap and must fit in the executor memory overhead unless spark.executor.pyspark.memory is set.
  6. 6Spark Connect (Spark 3.4+) sends unresolved plans over gRPC from a thin client with no JVM, but drops the SparkContext and RDD APIs.
lesson 08

SparkSession, schemas and I/O

13 min 8 stepsBeginner
Replay lesson

Start a session, give your data a real schema, survive broken records and write Parquet without wiping the table.

You'll learn
  • Creating and configuring a SparkSession
  • What a DataFrame, a Row and a StructType schema are
  • Why schema inference costs an extra pass — and how to avoid it
  • Handling malformed records with read modes and _corrupt_record
  • Writing Parquet with save modes and partitionBy safely
Takeaways
  1. 1SparkSession is the entry point to DataFrames and SQL; getOrCreate() reuses an existing session, and resource settings must be fixed before the application starts.
  2. 2A DataFrame is an immutable, distributed table of Rows with a StructType schema that Spark checks before anything runs.
  3. 3Schema inference on CSV and JSON costs an extra pass over the data and can drift between runs — declare an explicit schema for production reads.
  4. 4PERMISSIVE mode silently turns unparseable fields into nulls; add a _corrupt_record column, then count and quarantine the bad rows.
  5. 5Parquet is the default format; partitionBy writes one folder per value, and overwrite in the default static mode deletes every existing partition.
lesson 09

Transformations, actions and expressions

13 min 8 stepsBeginner
Replay lesson

Build column expressions, chain immutable transformations, and know exactly which call makes Spark do the work.

You'll learn
  • Referencing columns: names, F.col, df[...], expr and selectExpr
  • Chaining immutable transformations: filter, withColumn, drop, dropDuplicates
  • Conditional logic, literals, casts and string/date functions
  • Lazy evaluation and reading a plan with explain()
  • What each action returns, and which ones hit the driver
  • Why loops of withColumn are slow and what to use instead
Takeaways
  1. 1A Column is an unevaluated expression tree; build it with F.col, F.expr, F.when, F.lit and built-in functions, and wrap conditions in parentheses when combining with &, | and ~.
  2. 2Transformations return a new immutable DataFrame and only extend the plan; nothing runs until an action such as show, count, collect or write.
  3. 3explain() prints the optimised physical plan — pushed filters, pruned columns and Exchange (shuffle) nodes — without running the query.
  4. 4collect() and toPandas() move every row into the driver; bring back counts, aggregates, take(n) or a limit() instead.
  5. 5Every action recomputes the DataFrame from its source unless you cache one you reuse — and unpersist it afterwards.
  6. 6Add many columns with withColumns or one select, never with a loop of withColumn calls.
lesson 10

Aggregations, joins and window functions

15 min 9 stepsIntermediate
Replay lesson

groupBy, every join type and window functions — the patterns behind most pipelines, and which of them shuffle.

You'll learn
  • Grouped aggregations with agg, alias and pivot
  • Every join type, including left_semi and left_anti
  • Avoiding duplicate-column ambiguity after a join
  • Window functions: ranking, lag/lead and running totals
  • The dedupe-latest-record pattern
  • Predicting which operations shuffle
Takeaways
  1. 1groupBy().agg() takes several aliased aggregates and runs as one shuffle after a per-partition partial aggregation.
  2. 2Pass the list of values to pivot, or Spark runs an extra job just to discover them.
  3. 3left_semi keeps left rows that have a match and left_anti keeps those that don't — both return only the left side's columns.
  4. 4Join on column names to get a single key column; joining on an expression keeps both copies and makes later references ambiguous.
  5. 5Window functions keep every row; row_number over partitionBy/orderBy with a tie-breaker is the standard way to keep the latest record per key.
  6. 6Aggregations, distinct, non-broadcast joins, windows and sorts all shuffle — and a window without partitionBy funnels everything into one partition.
lesson 11

UDFs, pandas UDFs and Arrow

14 min 8 stepsIntermediate
Replay lesson

Why a Python UDF is slow, when a built-in or a pandas UDF is the fix, and how Arrow moves data to pandas.

You'll learn
  • How a Python UDF executes, row by row in a Python worker
  • Why UDFs are opaque to the optimizer and block pushdown
  • Replacing UDFs with built-in functions
  • Vectorised pandas UDFs with type hints and Arrow batches
  • applyInPandas and mapInPandas for group- and partition-level logic
  • Arrow-backed toPandas and createDataFrame, and their limits
Takeaways
  1. 1A Python UDF runs your function once per row in a Python worker, with every value serialised across and back.
  2. 2UDFs are black boxes to the optimizer — no filter pushdown, no reordering, no code generation — so reach for built-in functions first.
  3. 3Pandas UDFs exchange Arrow batches (10,000 rows by default) and run vectorised pandas code once per batch; the type hints choose the kind of UDF.
  4. 4applyInPandas shuffles and loads each whole group into one worker's memory; mapInPandas works partition by partition without a shuffle.
  5. 5spark.sql.execution.arrow.pyspark.enabled makes toPandas and createDataFrame fast (on by default since Spark 4.2), but toPandas still collects every row to the driver.
  6. 6Declare the exact return type and handle None inside the function — a classic UDF silently returns NULL on a type mismatch, and F.when won't shield it from null rows.
lesson 12

Nested and semi-structured data

14 min 9 stepsIntermediate
Replay lesson

Structs, arrays, maps and JSON strings — query them in place, explode them safely and flatten them for the lake.

You'll learn
  • Structs, arrays and maps, and what JSON inference turns into
  • Dot access, struct expansion and withField
  • explode, explode_outer and posexplode — and the rows explode drops
  • Array higher-order functions: transform, filter, exists, aggregate
  • Parsing JSON strings with from_json, get_json_object and to_json
  • Flattening nested data for a lake and handling schema evolution
Takeaways
  1. 1Structs hold named fields (reach them with dot paths), arrays hold ordered elements and maps hold dynamic keys; JSON inference produces structs and arrays, never maps.
  2. 2explode creates one row per element and silently drops rows whose array is empty or null — use explode_outer to keep them.
  3. 3Higher-order functions (transform, filter, exists, aggregate) work inside arrays as JVM expressions, without exploding and regrouping.
  4. 4from_json needs a schema and doesn't fail on bad input by default — check a required field for null, or use FAILFAST.
  5. 5Flatten nested data into one table per grain: structs into prefixed columns, each array into its own child table keyed by the parent id.
  6. 6Parquet reads take the schema from a single file unless mergeSchema is on; explicit schemas ignore new source fields until you add them.
lesson 13

Structured Streaming in PySpark

16 min 9 stepsIntermediate
Replay lesson

Treat a stream as a table that never ends: micro-batches, output modes, checkpoints, watermarks and foreachBatch.

You'll learn
  • The unbounded-table model and micro-batch execution
  • Reading from files and Kafka with readStream
  • Output modes, sinks and triggers, including availableNow
  • How checkpoints give exactly-once with replayable sources
  • Event-time windows, watermarks and late data
  • foreachBatch and the cost of stateful operators
Takeaways
  1. 1A streaming query is a normal DataFrame query over an unbounded input table; Spark runs it incrementally, by default as micro-batches.
  2. 2Streaming file sources need an explicit schema; Kafka delivers binary key and value columns that you cast and parse with from_json.
  3. 3The output mode decides what each trigger writes: append for rows that are final, update for changed rows, complete for the whole aggregate result.
  4. 4availableNow processes everything currently available in rate-limited batches and then stops — an incremental batch job with streaming bookkeeping.
  5. 5Exactly-once needs a replayable source, a dedicated durable checkpointLocation and an idempotent sink; foreachBatch is at-least-once unless you make writes idempotent with batch_id.
  6. 6withWatermark bounds lateness and state for event-time aggregations; without one, stateful queries keep growing.
MODULE 03

Spark SQL with PySpark

Module quiz

SQL basics you run from PySpark — SELECT, GROUP BY, joins, windows and CTEs — and how Catalyst turns both into one plan.

lesson 14

Tables, views and spark.sql

12 min 9 stepsBeginner
Replay lesson

Give a DataFrame a name, query it with SQL, and learn where Spark keeps tables, views and their metadata.

You'll learn
  • Register a DataFrame as a temp view and query it with spark.sql
  • Why spark.sql returns a lazy DataFrame, not rows
  • Session-scoped temp views vs global temp views
  • Managed vs external tables, and what DROP TABLE deletes
  • Where table metadata lives: a Hive metastore or the Glue Data Catalog
  • Mixing SQL and DataFrame code in one pipeline
Takeaways
  1. 1createOrReplaceTempView gives a DataFrame's plan a name that spark.sql can query — no data is copied or cached.
  2. 2spark.sql returns a lazy DataFrame: nothing runs until an action, except DDL/DML statements, which execute immediately.
  3. 3Temp views belong to one SparkSession; global temp views live in the global_temp database until the application stops.
  4. 4Managed tables keep their files under the warehouse directory and DROP TABLE deletes them; external tables (LOCATION / path) keep their files.
  5. 5Persistent table definitions live in a metastore — a Hive metastore, or on EMR and Glue usually the AWS Glue Data Catalog.
  6. 6SQL and DataFrame code compile to the same plans, so mix them wherever each reads best.
lesson 15

SELECT, WHERE and ORDER BY

14 min 8 stepsBeginner
Replay lesson

Pick columns, filter rows, sort and limit — in SQL and the DataFrame API — without tripping over NULL.

You'll learn
  • The logical order in which SQL clauses run
  • SELECT expressions, aliases and DISTINCT
  • WHERE with AND/OR/NOT, IN, BETWEEN, LIKE and IS NULL
  • The DataFrame twin of every clause
  • Three-valued logic and NULL-safe comparisons
  • CASE WHEN, ORDER BY … NULLS LAST and LIMIT
Takeaways
  1. 1SQL clauses run in the order FROM, WHERE, SELECT, DISTINCT, ORDER BY, LIMIT — which is why a SELECT alias works in ORDER BY but not in WHERE.
  2. 2WHERE keeps only rows whose condition is TRUE; AND binds tighter than OR, so parenthesise mixed conditions (and every comparison in Python).
  3. 3Any comparison with NULL is NULL, so != silently drops NULL rows — use IS NULL, the null-safe <=> or coalesce.
  4. 4CASE WHEN returns the first matching branch and NULL when nothing matches and there is no ELSE; its DataFrame twin is F.when(...).otherwise(...).
  5. 5ASC puts NULLs first and DESC puts them last by default; a full ORDER BY is a global sort, ORDER BY + LIMIT is a cheap top-N.
lesson 16

GROUP BY, HAVING and aggregates

13 min 8 stepsBeginner
Replay lesson

Count, sum and average per group, filter before and after aggregating — and see why every GROUP BY shuffles.

You'll learn
  • How GROUP BY turns rows into one row per group
  • COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)
  • The groupBy().agg() DataFrame twin
  • WHERE vs HAVING: filtering before or after aggregation
  • Why aggregation shuffles: partial and final HashAggregate
  • Subtotals with ROLLUP, CUBE and GROUPING SETS
Takeaways
  1. 1Every column in a grouped SELECT must be a grouping key or wrapped in an aggregate function.
  2. 2count(*) counts rows, count(col) counts non-NULL values and count(DISTINCT col) counts distinct non-NULL values; the other aggregates skip NULLs too.
  3. 3WHERE filters rows before grouping and HAVING filters groups after it — put every non-aggregate condition in WHERE.
  4. 4A GROUP BY runs as partial HashAggregate → Exchange → final HashAggregate: one shuffle and a new stage, kept small by partial aggregation.
  5. 5ROLLUP and CUBE are shorthands for GROUPING SETS; grouping(col) tells subtotal rows apart from real NULLs.
lesson 17

Joins in SQL and the DataFrame API

15 min 9 stepsBeginner
Replay lesson

Inner, outer, semi, anti and cross joins on orders and customers — and the NULL and duplicate traps that skew totals.

You'll learn
  • INNER JOIN in SQL and with join(other, on, how)
  • LEFT, RIGHT and FULL OUTER joins
  • LEFT SEMI and LEFT ANTI joins
  • Why NULL keys never match and duplicate keys multiply rows
  • Filtering in ON vs WHERE for outer joins
  • Broadcast vs sort-merge, in one sentence
Takeaways
  1. 1INNER JOIN keeps only matching pairs; LEFT, RIGHT and FULL OUTER also keep unmatched rows and fill the other side with NULLs.
  2. 2LEFT SEMI and LEFT ANTI return only left-side rows that do or don't have a match — no duplicates, no right-side columns.
  3. 3NULL keys never match (NULL = NULL is NULL) and duplicate keys multiply rows — check your keys before trusting totals.
  4. 4In an outer join, a filter on the optional side belongs in ON; in WHERE it quietly turns the join back into an inner join.
  5. 5join(other, on="key") keeps one key column; joining on an expression keeps both, so alias your DataFrames.
  6. 6A side estimated under 10 MB is broadcast; larger equi-joins become sort-merge joins that shuffle both sides.
lesson 18

Window functions, CTEs and subqueries

16 min 9 stepsIntermediate
Replay lesson

Rank, compare and running-total rows without collapsing them — then structure long queries with CTEs and subqueries.

You'll learn
  • Window functions vs GROUP BY
  • ROW_NUMBER, RANK and DENSE_RANK on ties
  • LAG / LEAD and running totals with window frames
  • Top-N per group and latest-record dedupe
  • CTEs with WITH … AS
  • IN, EXISTS and scalar subqueries
Takeaways
  1. 1A window function adds a per-row result computed over related rows — PARTITION BY groups them, ORDER BY sorts them, the frame picks which ones count.
  2. 2ROW_NUMBER, RANK and DENSE_RANK differ only on ties: 1-2-3-4, 1-2-2-4 and 1-2-2-3.
  3. 3With ORDER BY and no explicit frame the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — write ROWS BETWEEN … for a row-by-row running total.
  4. 4Filter window results in an outer query (rn = 1) for top-N per group and latest-record dedupe, with a tie-breaker for determinism.
  5. 5CTEs name intermediate results and are inlined into one plan; in PySpark the equivalent is a DataFrame variable.
  6. 6Prefer NOT EXISTS over NOT IN — a single NULL in the subquery makes NOT IN return no rows.
lesson 19

How Spark SQL runs a query: Catalyst and Tungsten

15 min 8 stepsIntermediate
Replay lesson

Follow one query from SQL text to generated code: parse, analyze, optimise, plan — and learn to read explain().

You'll learn
  • Why SQL and DataFrame code produce the same plan
  • Parsing and analysis against the catalog
  • Logical optimisation: pushdown, pruning, folding, filter inference
  • Physical planning, join selection and statistics
  • Whole-stage codegen and Tungsten's binary rows
  • Reading explain(mode="formatted") output
Takeaways
  1. 1SQL strings and DataFrame calls both become a logical plan that Catalyst optimises, so they run identically.
  2. 2The analyzer resolves names against the catalog — unknown tables and columns fail with an AnalysisException before any data is read.
  3. 3Rule-based optimisation pushes filters toward the scan, prunes unused columns, folds constants and infers extra filters such as isnotnull on join keys.
  4. 4The physical planner picks operators such as HashAggregate, BroadcastHashJoin or SortMergeJoin and inserts an Exchange wherever data must move.
  5. 5Whole-stage codegen fuses the operators between Exchanges into one compiled function (the *(n) markers) that runs on Tungsten's compact binary rows.
  6. 6In explain output, FileScan's PushedFilters and ReadSchema show what pushdown and pruning saved, and every Exchange is a shuffle.
MODULE 04

Performance & Optimisation

Module quiz

Read plans and the Spark UI, tune partitions, pick join strategies, beat skew, use AQE, lay out data and size executors.

lesson 20

Reading plans and the Spark UI

14 min 9 stepsIntermediate
Replay lesson

A nightly job got 13× slower. Read the physical plan and the Spark UI to find out why before touching a config.

You'll learn
  • Print a physical plan with explain and read it bottom-up
  • What PartitionFilters, PushedFilters and ReadSchema tell you
  • Spot shuffles: Exchange with partial and final HashAggregate
  • Tell BroadcastHashJoin from SortMergeJoin, and find AQE's final plan
  • Use the Spark UI tabs and the history server
  • Read task-metric distributions for skew, spill and GC
Takeaways
  1. 1explain("formatted") prints the physical plan without running it; read it from the scans at the bottom up to the root.
  2. 2In every scan check PartitionFilters (directories pruned), PushedFilters (sent to the reader) and ReadSchema (columns decoded).
  3. 3Each Exchange is a shuffle and a stage boundary; an aggregation shows a partial HashAggregate before it and a final one after it.
  4. 4A BroadcastExchange under a BroadcastHashJoin means the big side is never shuffled; SortMergeJoin means both sides were shuffled and sorted.
  5. 5With AQE, trust the plan marked isFinalPlan=true, shown after the run in explain() or the SQL tab.
  6. 6In a stage, compare max with median task time and shuffle read, look for spill and GC time, and use the history server for finished apps.
lesson 21

Partition tuning and the small-files problem

14 min 9 stepsIntermediate
Replay lesson

Too few partitions spill, too many drown in overhead, and a careless write leaves 98,000 tiny files behind.

You'll learn
  • How read partitions are sized: maxPartitionBytes and openCostInBytes
  • Why the default 200 shuffle partitions spill on big data
  • Size shuffle partitions: ~100–200 MB each, a multiple of total cores
  • repartition(n) vs repartition(col) vs coalesce(n)
  • Why writes create thousands of small files, and how to fix it
Takeaways
  1. 1Read tasks come from file splits of up to spark.sql.files.maxPartitionBytes (128 MB); each file also counts as openCostInBytes (4 MB) so tiny files get packed together.
  2. 2spark.sql.shuffle.partitions (200) ignores data size: size it so each shuffle partition is roughly 100–200 MB, in a multiple of the total core count.
  3. 3repartition(n) shuffles into n even partitions, repartition(col) groups rows by key, and coalesce(n) merges partitions without a shuffle.
  4. 4coalesce lowers the parallelism of the stage it sits in, so coalesce(1) can turn a whole stage into a single task.
  5. 5Every write task creates one file per partition value it holds: repartition by the partition columns before partitionBy and cap file size with maxRecordsPerFile.
lesson 22

Join strategies: broadcast, sort-merge, shuffle hash

15 min 9 stepsIntermediate
Replay lesson

A 40 MB lookup table is making Spark shuffle 2 TB of orders. Learn how Spark picks a join and how to overrule it.

You'll learn
  • How a sort-merge join works and what it costs
  • When Spark broadcasts automatically, and how to force it
  • The risks of broadcasting a table that is too big
  • Which side can be broadcast for each join type
  • Shuffled hash join and the MERGE / SHUFFLE_HASH hints
  • Why non-equi joins turn into nested loops
Takeaways
  1. 1Sort-merge join is the default for large equi-joins: both sides are shuffled and sorted (two Exchanges, two Sorts), and it scales to any size.
  2. 2Broadcast hash join copies the small side to every executor so the big side is never shuffled; Spark picks it below spark.sql.autoBroadcastJoinThreshold (10 MB, -1 disables).
  3. 3F.broadcast() or /+ BROADCAST(t) / overrides the threshold, but the driver collects that table and every executor holds a copy, so a hint on a growing table is an OOM waiting to happen.
  4. 4Only the non-preserved side of an outer join can be broadcast; a full outer join can never use a broadcast hash join.
  5. 5Joins without an equality condition run as BroadcastNestedLoopJoin or CartesianProduct, so add an equality key such as a day bucket.
lesson 23

Data skew and salting

15 min 9 stepsAdvanced
Replay lesson

One task runs for 38 minutes while 199 finish in seconds. Find the hot key and spread it out.

You'll learn
  • Recognise skew: max vs median task time and shuffle read
  • Find the hot keys, including NULL and placeholder keys
  • Why more partitions, executors or speculation don't fix skew
  • Let AQE split skewed sort-merge join partitions
  • Salt a join: random salt on the big side, exploded small side
  • Broadcast, split off NULL keys, or aggregate in two phases
Takeaways
  1. 1Skew shows up as one straggler: max task time and shuffle read far above the median, with spill on that task only.
  2. 2Every row with the same key goes to the same shuffle partition, so more partitions, executors or speculation don't help.
  3. 3AQE (on by default since Spark 3.2) splits a sort-merge join partition larger than 5× the median and 256 MB into smaller tasks.
  4. 4Salting adds F.floor(F.rand() * N) on the big side and explodes N copies of the other side, spreading a hot key over N tasks.
  5. 5Broadcast the small side when you can, keep NULL keys out of outer-join shuffles, and aggregate in two phases when Spark can't pre-aggregate.
lesson 24

Adaptive Query Execution

14 min 9 stepsAdvanced
Replay lesson

Spark plans with guesses. AQE re-plans at every shuffle with real sizes, and DPP skips partitions a join rules out.

You'll learn
  • Why static plans go wrong: estimates made before data is read
  • How AQE re-plans at query-stage boundaries with runtime statistics
  • Coalescing shuffle partitions, and the parallelismFirst catch
  • The runtime switch from sort-merge to broadcast join
  • What AQE can't fix
  • Dynamic partition pruning for star-schema joins
Takeaways
  1. 1AQE (spark.sql.adaptive.enabled, on by default since Spark 3.2) re-optimises the rest of a query each time a shuffle or broadcast stage finishes, using measured sizes.
  2. 2It merges small post-shuffle partitions; start from a high partition count, and set parallelismFirst=false if you want it to target advisoryPartitionSizeInBytes (64 MB).
  3. 3It converts a sort-merge join to a broadcast hash join when one side turns out small, and splits skewed sort-merge join partitions.
  4. 4It never splits ordinary partitions or changes the first scan stage, so file layout and the initial partition count still matter.
  5. 5Dynamic partition pruning (Spark 3.0) pushes a dimension filter into a partitioned fact table's scan: look for dynamicpruningexpression in PartitionFilters.
  6. 6The SQL tab's plan with isFinalPlan=true is what actually ran.
lesson 25

File formats, pruning and pushdown

15 min 9 stepsIntermediate
Replay lesson

The same query reads 3 TB of gzip CSV or 160 MB of partitioned Parquet. The difference is how the data is laid out.

You'll learn
  • Row formats (CSV, JSON, Avro) vs columnar formats (Parquet, ORC)
  • Inside a Parquet file: row groups, column chunks, min/max stats
  • Compression codecs, and which files can be split
  • Predicate pushdown and column pruning in the scan
  • Partition pruning from the directory layout, and bucketing
  • What Iceberg, Delta Lake and Hudi add on top of Parquet
Takeaways
  1. 1Columnar formats decode only the columns a query uses and carry statistics for skipping data; CSV and JSON must be parsed in full.
  2. 2Parquet files hold row groups of column chunks with min/max statistics; pushed filters skip row groups whose range can't match, which works best on clustered data.
  3. 3Snappy is Spark's default Parquet codec and zstd usually compresses better; a gzip-compressed CSV or JSON file can't be split and is read by a single task.
  4. 4partitionBy on a low-cardinality column that queries filter on gives directory-level pruning (PartitionFilters) before any file is opened.
  5. 5Bucketing two tables the same way on the join key removes the join's shuffle; table formats add atomic commits, compaction and file-level data skipping.
lesson 26

Caching, UDF costs and executor sizing

16 min 9 stepsAdvanced
Replay lesson

A DataFrame recomputed three times, a slow Python UDF and one giant executor per node: three fixes for one job.

You'll learn
  • When cache()/persist() pays off, and when it hurts
  • Cut long lineage with checkpoint and localCheckpoint
  • Why collect() and toPandas() take down drivers
  • What a Python UDF really costs vs built-ins and pandas UDFs
  • Size executors: ~5 cores, room for the OS and memory overhead
  • Dynamic allocation, Kryo and speculation
Takeaways
  1. 1Cache a DataFrame only when several actions reuse it, and unpersist() it when done; caching something used once, or too big to fit, just costs memory.
  2. 2checkpoint() writes to reliable storage and truncates the lineage; localCheckpoint() is faster but lost with its executor.
  3. 3Never collect() or toPandas() big data: aggregate, limit or write it out; spark.driver.maxResultSize (1g) guards the driver.
  4. 4Built-in functions stay in the JVM; Python UDFs ship every row to Python workers and block optimisations, and pandas UDFs batch rows with Arrow.
  5. 5Size executors at about 5 cores, leave a core and some memory per node, and budget memory overhead (max(384 MB, 10%)); giant heaps mean long GC pauses.
  6. 6Speculation re-runs tasks slowed down by a bad node, not skewed ones; Kryo mainly helps RDD-heavy code.
MODULE 05

AWS Glue Architecture

Module quiz

Serverless Spark on AWS: the Data Catalog, crawlers, what happens when a job runs, orchestration and security.

lesson 27

AWS Glue at a glance

12 min 8 stepsBeginner
Replay lesson

Catalog, crawlers, serverless Spark jobs and triggers — follow raw S3 files all the way to an Athena query.

You'll learn
  • Why a data lake needs metadata, ETL and orchestration — not just S3
  • The Glue building blocks: Data Catalog, crawlers, jobs, Studio, triggers, Data Quality
  • The four job types: Spark, Spark Streaming, Python shell and Ray
  • The reference flow: raw S3 → crawler → catalog → job → curated Parquet
  • What “serverless Spark” really means for you
  • How Athena, Redshift Spectrum and EMR share the same tables
Takeaways
  1. 1AWS Glue is a serverless data integration service: a metadata catalog, schema-discovery crawlers, managed Spark jobs and triggers to run them.
  2. 2The Data Catalog holds only metadata (schemas, locations, partitions) — the data itself stays in S3 or the source database.
  3. 3A typical lake flow is raw S3 → crawler → catalog table → Glue job → partitioned Parquet in a curated bucket → catalog → query engines.
  4. 4You choose the Glue version, worker type and number of workers; Glue provisions the Spark cluster for each run and releases it afterwards.
  5. 5Athena, Redshift Spectrum, EMR and Glue jobs all read the same catalog tables, so a table defined once is queryable everywhere.
lesson 28

The Glue Data Catalog

14 min 9 stepsIntermediate
Replay lesson

One Hive-compatible metastore per account and Region: databases, tables and partitions every AWS engine shares.

You'll learn
  • How the catalog is organised: databases → tables → partitions
  • What a table definition contains: location, formats, SerDe, parameters, versions
  • How engines prune partitions by asking the catalog
  • Four ways to register partitions, and when partition projection replaces them
  • Partition indexes for tables with many partitions
  • Encrypting the catalog and controlling access with Lake Formation
Takeaways
  1. 1Each AWS account has one Data Catalog per Region; databases group tables, and tables and partitions are metadata pointing at data in S3 or a database.
  2. 2A table stores columns, partition keys, S3 location, input/output format, SerDe and parameters such as classification; every UpdateTable archives the previous version by default.
  3. 3Because the catalog is a drop-in replacement for the Hive metastore, Athena, Redshift Spectrum, EMR and Glue jobs share one set of table definitions.
  4. 4A partition that exists in S3 but not in the catalog is invisible — register it with a crawler, MSCK REPAIR TABLE, ALTER TABLE ADD PARTITION or the job's enableUpdateCatalog, or use Athena partition projection.
  5. 5On tables with many partitions, a partition index (up to 3 per table) lets GetPartitions fetch only matching partitions instead of loading them all.
  6. 6Protect metadata with catalog encryption (KMS) and protect data access with IAM plus Lake Formation grants on databases, tables and columns.
lesson 29

Crawlers and classifiers

14 min 9 stepsIntermediate
Replay lesson

How a crawler classifies files, groups folders into tables and partitions, and handles schema drift on every run.

You'll learn
  • The crawl flow from include path to catalog tables
  • Classifier order and certainty: custom first, then built-in
  • How folders become partition columns (key=value vs partition_0)
  • Why a crawler sometimes creates one table per folder — and how to stop it
  • Schema change, delete and recrawl policies
  • When to skip crawlers entirely
Takeaways
  1. 1A crawler runs your custom classifiers in order, falls back to the built-in ones, infers a schema and writes tables and partitions into a catalog database.
  2. 2The first classifier that returns certainty 1.0 wins; if none does, the highest certainty wins, and 0.0 everywhere gives the classification UNKNOWN.
  3. 3Hive-style key=value folders become named partition columns; other folder levels become partition_0, partition_1 and so on.
  4. 4When schemas under one include path aren't similar enough, the crawler creates separate tables — give each dataset its own include path or enable “Create a single schema for each S3 path”.
  5. 5Schema change policy (update vs log), delete behaviour and recrawl policy (everything, new folders only, S3 events) decide how much each run touches the catalog.
  6. 6If you already own the schema, define tables yourself and register partitions explicitly; use crawlers for discovery and drift detection.
lesson 30

What happens when a Glue job runs

15 min 9 stepsIntermediate
Replay lesson

From StartJobRun to SUCCEEDED: provisioning, driver and executors, worker types, logs, Spark UI and the bill.

You'll learn
  • What a job definition contains and which defaults bite
  • How a run starts, provisions a Spark cluster and moves through its states
  • Worker types (G.1X … G.8X, R.*) and Glue versions
  • Auto scaling and the Flex execution class
  • Where logs, metrics and Spark UI event logs go
  • How to calculate the cost of a run in DPU-hours
Takeaways
  1. 1A job definition is a script in S3 plus an IAM role, Glue version, worker type, number of workers, parameters, timeout, retries and max concurrency.
  2. 2Each run goes STARTING → RUNNING → SUCCEEDED, FAILED, TIMEOUT or STOPPED; Glue builds a fresh Spark cluster (one driver, executors on workers) for it and tears it down afterwards.
  3. 3G.1X = 1 DPU = 4 vCPU + 16 GB with one executor per worker; G.2X, G.4X and G.8X double each step; R types are memory-optimised.
  4. 4Auto scaling (Glue 3.0+) treats the number of workers as a maximum; Flex (Glue 3.0+, G.1X/G.2X) trades start-time guarantees for a lower price.
  5. 5Logs go to CloudWatch (/aws-glue/jobs/output and /aws-glue/jobs/error), metrics to CloudWatch, and Spark UI event logs to an S3 path every 30 seconds.
  6. 6Cost = DPUs × hours × price per DPU-hour, billed per second with a 1-minute minimum: 10 × G.1X for 12 minutes is 2 DPU-hours.
lesson 31

Triggers, workflows and orchestration

14 min 9 stepsIntermediate
Replay lesson

Chain crawlers and jobs with triggers and workflows — or Step Functions, Airflow and EventBridge — and make reruns safe.

You'll learn
  • Why time-based chains break and what conditional triggers fix
  • The four trigger types and their rules
  • Workflows: start triggers, the DAG, run properties and resuming
  • When to use Step Functions, MWAA or EventBridge instead
  • Retries, max concurrency and idempotent writes
Takeaways
  1. 1Glue triggers are scheduled (cron, UTC), conditional (watch job and crawler end states, combined with AND or ANY), on-demand, or EventBridge events (workflow start only).
  2. 2A workflow is a DAG of triggers, crawlers and jobs with one start trigger; run properties are name/value pairs every job in the run can read and update.
  3. 3When a node fails you fix it and resume the workflow run from that node — successful nodes are not re-run.
  4. 4Use Step Functions (glue:startJobRun.sync) when the pipeline spans other AWS services or needs rich retry/catch logic, MWAA when you already run Airflow, and EventBridge rules on “Glue Job State Change” for alerts and event fan-out.
  5. 5Retries re-run the whole script, so every job must be idempotent — overwrite the partitions you produce instead of appending.
lesson 32

Security, IAM and networking

15 min 9 stepsAdvanced
Replay lesson

The job role, Lake Formation, VPC connections with ENIs and self-referencing security groups, secrets and encryption.

You'll learn
  • What the job or crawler IAM role must trust and allow
  • Where Lake Formation and cross-account catalog access fit
  • How a Glue connection puts ENIs into your subnet
  • The self-referencing security group rule and S3 access from private subnets
  • Keeping credentials in Secrets Manager
  • Encrypting outputs, logs and bookmarks with a security configuration
Takeaways
  1. 1Every job and crawler runs as an IAM role that trusts glue.amazonaws.com; start from AWSGlueServiceRole and add scoped S3, KMS and secret permissions — and give users iam:PassRole on it.
  2. 2Lake Formation adds database, table, column and row-level grants on top of IAM and vends scoped credentials to Glue, Athena, Redshift Spectrum and EMR.
  3. 3A Glue connection makes Glue create ENIs with private IPs in your subnet; the attached security group needs a self-referencing inbound rule for all TCP ports.
  4. 4From a private subnet, the job reaches S3 only through your routing — add an S3 gateway VPC endpoint or a NAT gateway, plus routes for KMS and other services it calls.
  5. 5Store database credentials in Secrets Manager and reference the secret from the connection; never pass passwords as job arguments.
  6. 6A security configuration encrypts S3 output (SSE-S3 or SSE-KMS), CloudWatch logs and job bookmarks; catalog metadata encryption is a separate Data Catalog setting.
MODULE 06

PySpark on AWS Glue

Module quiz

Write real Glue jobs: script anatomy, DynamicFrames, sources and sinks, job bookmarks, performance, streaming and the dev workflow.

lesson 33

Anatomy of a Glue PySpark script

12 min 9 stepsBeginner
Replay lesson

Every Glue Spark job is the same skeleton: parameters, contexts, Job, extract–transform–load, commit.

You'll learn
  • The boilerplate every Glue PySpark script starts with
  • Passing and reading custom job parameters with getResolvedOptions
  • SparkContext, GlueContext and the SparkSession — what each one is for
  • Why job.init() and job.commit() bracket the work
  • The special job parameters worth knowing
  • Logging from the script and failing loudly
Takeaways
  1. 1A Glue Spark job is a Python script: resolve parameters, build SparkContext → GlueContext → SparkSession, init the Job, do the ETL, commit.
  2. 2Custom parameters are passed as --name value and read with getResolvedOptions(sys.argv, ["name"]) — underscores only, no leading dashes in the script.
  3. 3GlueContext wraps the SparkContext and adds Glue I/O (create_dynamic_frame, write_dynamic_frame); glueContext.spark_session is a normal SparkSession.
  4. 4job.init() loads bookmark state and job.commit() saves it — skip either and incremental processing silently stops working.
  5. 5Special parameters such as --job-bookmark-option, --enable-spark-ui, --additional-python-modules, --TempDir and --conf configure the run without touching code.
  6. 6Log with glueContext.get_logger() and re-raise exceptions so a broken run is marked FAILED instead of SUCCEEDED.
lesson 34

DynamicFrames vs DataFrames

14 min 9 stepsIntermediate
Replay lesson

Self-describing records, choice types and Glue transforms for messy data — and when to drop down to DataFrames.

You'll learn
  • What a DynamicFrame is: self-describing DynamicRecords, schema on demand
  • How choice types capture inconsistent data, and how ResolveChoice fixes them
  • Renaming and casting with ApplyMapping
  • SelectFields, DropNullFields, Filter and Map
  • Flattening nested JSON with Relationalize
  • Converting with toDF() / fromDF() and when to use each API
Takeaways
  1. 1A DynamicFrame is a distributed collection of self-describing DynamicRecords; Glue computes the schema only when it needs it.
  2. 2When one field holds different types across records, the schema shows a choice type instead of failing or silently picking one.
  3. 3ResolveChoice turns choices into one type: cast:type, project:type, make_cols, make_struct, or MATCH_CATALOG against a catalog table.
  4. 4ApplyMapping renames, casts and selects in one declarative step — fields you don't list are dropped.
  5. 5Relationalize flattens nested JSON into a root table plus child tables for arrays, linked by generated join keys.
  6. 6Use DataFrames for joins, aggregations, windows and built-in functions; convert with toDF() and DynamicFrame.fromDF(df, glueContext, name).
lesson 35

Reading and writing in Glue

15 min 9 stepsIntermediate
Replay lesson

S3, catalog and JDBC sources; partitioned Parquet sinks that update the catalog; DataFrame writes and Iceberg.

You'll learn
  • Reading S3 with format options and grouping small files
  • Reading catalog tables and JDBC databases in parallel
  • Writing partitioned Parquet with partitionKeys
  • Adding partitions and schema to the catalog from the job
  • Writing DataFrames directly, to S3 and JDBC
  • Using Iceberg, Hudi or Delta with --datalake-formats
Takeaways
  1. 1S3 sources take connection_options (paths, recurse, groupFiles, groupSize) plus a format and format_options; grouping only works for row formats like JSON and CSV.
  2. 2JDBC reads run as one query unless you set hashfield or hashexpression plus hashpartitions (default 7) to split them into parallel queries.
  3. 3write_dynamic_frame.from_options with partitionKeys writes Hive-style key=value folders; it adds files and has no overwrite mode.
  4. 4getSink(..., enableUpdateCatalog=True, partitionKeys=[...]) + setCatalogInfo + setFormat + writeFrame registers new partitions and schema without a crawler.
  5. 5Use df.write with dynamic partition overwrite when a rerun must replace partitions instead of appending to them.
  6. 6--datalake-formats iceberg (or hudi, delta) adds the table-format libraries; you still configure the Spark catalog with --conf.
lesson 36

Job bookmarks and incremental loads

14 min 9 stepsIntermediate
Replay lesson

Let Glue remember what it already processed — and learn the five ways that memory goes wrong.

You'll learn
  • The four things a script needs for bookmarks to work
  • What a job bookmark stores and when it is saved
  • How S3 sources are tracked by modification time
  • JDBC bookmark keys and why they must be monotonic
  • Pausing, disabling, resetting and rewinding bookmarks
  • Failure modes and idempotent writes
Takeaways
  1. 1A job bookmark is persisted state per job, with one entry per transformation_ctx, saved atomically by job.commit().
  2. 2Bookmarks need --job-bookmark-option job-bookmark-enable, job.init(), a transformation_ctx on each source and job.commit() — miss one and old data is reprocessed.
  3. 3S3 sources are tracked by object last-modified time, so a file rewritten in place is read again.
  4. 4JDBC sources compare bookmark keys (the primary key by default, or jobBookmarkKeys) that must be strictly monotonic; rows updated in place are not re-read.
  5. 5Resetting or rewinding a bookmark never cleans the target — reruns append duplicates unless the write is idempotent.
  6. 6Make writes idempotent: overwrite the partitions a run owns, dedupe on a business key, or MERGE into an Iceberg table.
lesson 37

Tuning Glue jobs

15 min 9 stepsAdvanced
Replay lesson

Read less, group small files, size workers to the work, keep the driver idle — and measure before you tune.

You'll learn
  • Where to look first: Spark UI, job run insights and metrics
  • Partition pruning with push_down_predicate and catalogPartitionPredicate
  • Grouping small input files and controlling output file counts
  • Choosing worker type and count, auto scaling and Flex
  • Spark settings with --conf and AQE
  • Keeping heavy work off the driver
Takeaways
  1. 1Find the bottleneck first: Spark UI for stages and tasks, job run insights for failures, observability metrics for utilisation and skew.
  2. 2push_down_predicate prunes catalog partitions before S3 is listed; catalogPartitionPredicate does it server-side with partition indexes for tables with very many partitions.
  3. 3groupFiles/groupSize fix many small JSON or CSV inputs; repartition or coalesce before the write decides how many output files you get.
  4. 4Scale out with more workers for wide scans; move to G.2X/G.4X/G.8X or R types when tasks spill or run out of memory; use auto scaling and Flex to cut cost.
  5. 5Pass Spark settings with --conf key=value --conf key2=value2; AQE is on by default from Glue 4.0 (Spark 3.3).
  6. 6collect(), toPandas() and count() in loops pull work onto the single driver — aggregate in Spark and bring back only small results.
lesson 38

Streaming ETL on Glue

13 min 8 stepsAdvanced
Replay lesson

An always-on Spark Structured Streaming job: Kinesis or Kafka in, forEachBatch micro-batches out to S3.

You'll learn
  • What a Glue streaming job is and how it differs from a batch job
  • Reading Kinesis Data Streams, Kafka or MSK via a catalog table or options
  • Processing micro-batches with glueContext.forEachBatch
  • Windows, checkpoints and restarts
  • Schema detection and writing each batch to S3 and the catalog
  • Sizing with G.025X and the always-on cost model
Takeaways
  1. 1A Glue streaming job (job type gluestreaming) is Spark Structured Streaming that runs continuously against Kinesis Data Streams, Kafka or Amazon MSK.
  2. 2Read the stream through a Data Catalog table or with connection options; you get a streaming DataFrame.
  3. 3glueContext.forEachBatch(frame, batch_function, options) calls your function for every micro-batch; windowSize (100 seconds by default) and checkpointLocation are required options.
  4. 4Streaming jobs track progress with checkpoints, not job bookmarks — a restarted job resumes where it stopped, and deleting the checkpoint reprocesses.
  5. 5Inside the batch function you have a normal DataFrame: map it, convert to a DynamicFrame and write it to S3 or a catalog table like any batch job.
  6. 6You pay for every hour the job runs; G.025X workers (0.25 DPU) keep low-volume streams cheap.
lesson 39

Developing, testing and deploying Glue jobs

14 min 9 stepsIntermediate
Replay lesson

Notebooks for exploring, pure functions and pytest for testing, IaC for deploying, data quality and alarms for running.

You'll learn
  • Exploring data with interactive sessions and their magics
  • Keeping transformation logic in pure, testable DataFrame functions
  • Running pytest locally in the official AWS Glue Docker image
  • Deploying jobs with CloudFormation, CDK or Terraform from CI
  • Gating loads with Glue Data Quality rules in DQDL
  • Alerting on failures with EventBridge and CloudWatch
Takeaways
  1. 1Use interactive sessions or Glue Studio notebooks to explore; set %glue_version, %worker_type, %number_of_workers and a short %idle_timeout in the first cell.
  2. 2Put transformation logic in plain DataFrame functions with no awsglue imports, so pytest can test them on a local SparkSession.
  3. 3The official image public.ecr.aws/glue/aws-glue-libs (tag 5 for Glue 5.0, 5.1 and 6.0 for newer versions) runs Glue scripts and tests locally, minus features such as bookmarks and Data Quality.
  4. 4Define jobs as code (AWS::Glue::Job, CDK or Terraform) and let CI test, upload the script to S3 and deploy the same definition to every environment.
  5. 5EvaluateDataQuality runs DQDL rules such as IsComplete "order_id" and ColumnValues "amount" > 0 inside the job — fail the run before bad data lands.
  6. 6Route Glue Job State Change events (FAILED, TIMEOUT, STOPPED) through EventBridge to your on-call channel and alarm on CloudWatch metrics.