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.
1Spark splits data into partitions and runs the same code on every partition in parallel across a cluster.
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.
3Spark keeps working sets in executor memory and rebuilds lost partitions from lineage instead of replicating them.
4Transformations only build a DAG; an action triggers execution, which lets Spark optimise the whole plan first.
5SQL/DataFrames, Structured Streaming, MLlib and GraphX share one engine that runs on Standalone, YARN or Kubernetes — or managed on EMR, Glue and Databricks.
6If the data fits comfortably on one machine, pandas, Polars or DuckDB is usually faster and simpler than Spark.
1Transformations are lazy and only extend the plan; every action submits at least one job.
2Narrow transformations (filter, select, withColumn) are pipelined inside one stage; wide ones (groupBy, join, distinct, orderBy, repartition) need a shuffle.
3The DAGScheduler ends a stage at every shuffle — an Exchange in the physical plan — and a stage starts only after its parent stages finish.
4A stage runs one task per partition: input splits for scan stages, spark.sql.shuffle.partitions (200) after a shuffle unless AQE coalesces them.
5Tasks run in waves of executors × cores slots — ⌈tasks ÷ slots⌉ waves — so a nearly empty last wave leaves cores idle.
6In the Spark UI jobs contain stages and stages contain tasks; a skipped stage reused shuffle output computed by an earlier job.
1An RDD is defined by its partitions, a compute function, dependencies on parents, and optionally a partitioner and preferred locations.
2DataFrame queries execute as RDDs (FileScanRDD, MapPartitionsRDD, ShuffledRowRDD…), so partitions and lineage still drive performance.
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.
4Narrow operations keep the partition count; shuffles and repartition() set a new one; coalesce() merges partitions without a shuffle.
5Lost partitions are recomputed from lineage rather than restored from replicas; checkpoint() truncates lineage that has grown too long.
6The scheduler prefers PROCESS_LOCAL, then NODE_LOCAL, RACK_LOCAL and ANY, waiting spark.locality.wait (3 s) before each fallback.
1A shuffle co-locates rows with the same key by sending every map task's rows to the reduce partition that owns each key.
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.
3DataFrame shuffles produce spark.sql.shuffle.partitions (200) partitions regardless of data size; AQE can coalesce small ones at runtime.
4When execution memory runs out, sorts and aggregations spill sorted runs to disk — slower, but the task survives.
5Shuffle files die with their executor unless an external shuffle service, shuffle tracking or decommissioning keeps them available.
6A FetchFailedException makes the DAGScheduler re-run the lost map outputs and retry the stage, up to spark.stage.maxConsecutiveAttempts (4) times.
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.
2Unified memory is (heap − 300 MB) × spark.memory.fraction (0.6), shared by execution and storage; the remaining 40% is user memory.
3Execution can evict cached blocks down to spark.memory.storageFraction (0.5) of unified memory; storage can never evict execution.
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.
5DataFrame cache() uses MEMORY_AND_DISK_DESER, is filled lazily by actions, and should be released with unpersist().
6Broadcast variables ship read-only data once per executor; accumulator updates are exactly-once only inside actions.
1A PySpark driver is a Python process controlling a JVM driver through Py4J; Python objects like DataFrame are proxies for JVM objects.
2DataFrame transformations only build a plan inside the JVM, so code made of built-in functions executes as JVM code on the executors.
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.
4Pandas UDFs exchange Arrow batches instead of pickled rows; regular Python UDFs are Arrow-optimised by default since Spark 4.2.
5Python worker memory lives outside the JVM heap and must fit in the executor memory overhead unless spark.executor.pyspark.memory is set.
6Spark Connect (Spark 3.4+) sends unresolved plans over gRPC from a thin client with no JVM, but drops the SparkContext and RDD APIs.
1SparkSession is the entry point to DataFrames and SQL; getOrCreate() reuses an existing session, and resource settings must be fixed before the application starts.
2A DataFrame is an immutable, distributed table of Rows with a StructType schema that Spark checks before anything runs.
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.
4PERMISSIVE mode silently turns unparseable fields into nulls; add a _corrupt_record column, then count and quarantine the bad rows.
5Parquet is the default format; partitionBy writes one folder per value, and overwrite in the default static mode deletes every existing partition.
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 ~.
2Transformations return a new immutable DataFrame and only extend the plan; nothing runs until an action such as show, count, collect or write.
3explain() prints the optimised physical plan — pushed filters, pruned columns and Exchange (shuffle) nodes — without running the query.
4collect() and toPandas() move every row into the driver; bring back counts, aggregates, take(n) or a limit() instead.
5Every action recomputes the DataFrame from its source unless you cache one you reuse — and unpersist it afterwards.
6Add many columns with withColumns or one select, never with a loop of withColumn calls.
1A Python UDF runs your function once per row in a Python worker, with every value serialised across and back.
2UDFs are black boxes to the optimizer — no filter pushdown, no reordering, no code generation — so reach for built-in functions first.
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.
4applyInPandas shuffles and loads each whole group into one worker's memory; mapInPandas works partition by partition without a shuffle.
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.
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.
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.
2explode creates one row per element and silently drops rows whose array is empty or null — use explode_outer to keep them.
3Higher-order functions (transform, filter, exists, aggregate) work inside arrays as JVM expressions, without exploding and regrouping.
4from_json needs a schema and doesn't fail on bad input by default — check a required field for null, or use FAILFAST.
5Flatten nested data into one table per grain: structs into prefixed columns, each array into its own child table keyed by the parent id.
6Parquet reads take the schema from a single file unless mergeSchema is on; explicit schemas ignore new source fields until you add them.
1A streaming query is a normal DataFrame query over an unbounded input table; Spark runs it incrementally, by default as micro-batches.
2Streaming file sources need an explicit schema; Kafka delivers binary key and value columns that you cast and parse with from_json.
3The output mode decides what each trigger writes: append for rows that are final, update for changed rows, complete for the whole aggregate result.
4availableNow processes everything currently available in rate-limited batches and then stops — an incremental batch job with streaming bookkeeping.
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.
6withWatermark bounds lateness and state for event-time aggregations; without one, stateful queries keep growing.
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.
2ROW_NUMBER, RANK and DENSE_RANK differ only on ties: 1-2-3-4, 1-2-2-4 and 1-2-2-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.
4Filter window results in an outer query (rn = 1) for top-N per group and latest-record dedupe, with a tie-breaker for determinism.
5CTEs name intermediate results and are inlined into one plan; in PySpark the equivalent is a DataFrame variable.
6Prefer NOT EXISTS over NOT IN — a single NULL in the subquery makes NOT IN return no rows.
1SQL strings and DataFrame calls both become a logical plan that Catalyst optimises, so they run identically.
2The analyzer resolves names against the catalog — unknown tables and columns fail with an AnalysisException before any data is read.
3Rule-based optimisation pushes filters toward the scan, prunes unused columns, folds constants and infers extra filters such as isnotnull on join keys.
4The physical planner picks operators such as HashAggregate, BroadcastHashJoin or SortMergeJoin and inserts an Exchange wherever data must move.
5Whole-stage codegen fuses the operators between Exchanges into one compiled function (the *(n) markers) that runs on Tungsten's compact binary rows.
6In explain output, FileScan's PushedFilters and ReadSchema show what pushdown and pruning saved, and every Exchange is a shuffle.
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.
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.
3repartition(n) shuffles into n even partitions, repartition(col) groups rows by key, and coalesce(n) merges partitions without a shuffle.
4coalesce lowers the parallelism of the stage it sits in, so coalesce(1) can turn a whole stage into a single task.
5Every write task creates one file per partition value it holds: repartition by the partition columns before partitionBy and cap file size with maxRecordsPerFile.
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.
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).
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.
4Only the non-preserved side of an outer join can be broadcast; a full outer join can never use a broadcast hash join.
5Joins without an equality condition run as BroadcastNestedLoopJoin or CartesianProduct, so add an equality key such as a day bucket.
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.
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).
3It converts a sort-merge join to a broadcast hash join when one side turns out small, and splits skewed sort-merge join partitions.
4It never splits ordinary partitions or changes the first scan stage, so file layout and the initial partition count still matter.
5Dynamic partition pruning (Spark 3.0) pushes a dimension filter into a partitioned fact table's scan: look for dynamicpruningexpression in PartitionFilters.
6The SQL tab's plan with isFinalPlan=true is what actually ran.
1Columnar formats decode only the columns a query uses and carry statistics for skipping data; CSV and JSON must be parsed in full.
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.
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.
4partitionBy on a low-cardinality column that queries filter on gives directory-level pruning (PartitionFilters) before any file is opened.
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.
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.
2checkpoint() writes to reliable storage and truncates the lineage; localCheckpoint() is faster but lost with its executor.
3Never collect() or toPandas() big data: aggregate, limit or write it out; spark.driver.maxResultSize (1g) guards the driver.
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.
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.
6Speculation re-runs tasks slowed down by a bad node, not skewed ones; Kryo mainly helps RDD-heavy code.
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.
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.
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.
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.
5On tables with many partitions, a partition index (up to 3 per table) lets GetPartitions fetch only matching partitions instead of loading them all.
6Protect metadata with catalog encryption (KMS) and protect data access with IAM plus Lake Formation grants on databases, tables and columns.
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.
2The first classifier that returns certainty 1.0 wins; if none does, the highest certainty wins, and 0.0 everywhere gives the classification UNKNOWN.
3Hive-style key=value folders become named partition columns; other folder levels become partition_0, partition_1 and so on.
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”.
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.
6If you already own the schema, define tables yourself and register partitions explicitly; use crawlers for discovery and drift detection.
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.
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.
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.
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.
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.
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.
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).
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.
3When a node fails you fix it and resume the workflow run from that node — successful nodes are not re-run.
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.
5Retries re-run the whole script, so every job must be idempotent — overwrite the partitions you produce instead of appending.
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.
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.
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.
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.
5Store database credentials in Secrets Manager and reference the secret from the connection; never pass passwords as job arguments.
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.
1A Glue Spark job is a Python script: resolve parameters, build SparkContext → GlueContext → SparkSession, init the Job, do the ETL, commit.
2Custom parameters are passed as --name value and read with getResolvedOptions(sys.argv, ["name"]) — underscores only, no leading dashes in the script.
3GlueContext wraps the SparkContext and adds Glue I/O (create_dynamic_frame, write_dynamic_frame); glueContext.spark_session is a normal SparkSession.
4job.init() loads bookmark state and job.commit() saves it — skip either and incremental processing silently stops working.
5Special parameters such as --job-bookmark-option, --enable-spark-ui, --additional-python-modules, --TempDir and --conf configure the run without touching code.
6Log with glueContext.get_logger() and re-raise exceptions so a broken run is marked FAILED instead of SUCCEEDED.
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.
2JDBC reads run as one query unless you set hashfield or hashexpression plus hashpartitions (default 7) to split them into parallel queries.
3write_dynamic_frame.from_options with partitionKeys writes Hive-style key=value folders; it adds files and has no overwrite mode.
4getSink(..., enableUpdateCatalog=True, partitionKeys=[...]) + setCatalogInfo + setFormat + writeFrame registers new partitions and schema without a crawler.
5Use df.write with dynamic partition overwrite when a rerun must replace partitions instead of appending to them.
6--datalake-formats iceberg (or hudi, delta) adds the table-format libraries; you still configure the Spark catalog with --conf.
1A job bookmark is persisted state per job, with one entry per transformation_ctx, saved atomically by job.commit().
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.
3S3 sources are tracked by object last-modified time, so a file rewritten in place is read again.
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.
5Resetting or rewinding a bookmark never cleans the target — reruns append duplicates unless the write is idempotent.
6Make writes idempotent: overwrite the partitions a run owns, dedupe on a business key, or MERGE into an Iceberg table.
1Find the bottleneck first: Spark UI for stages and tasks, job run insights for failures, observability metrics for utilisation and skew.
2push_down_predicate prunes catalog partitions before S3 is listed; catalogPartitionPredicate does it server-side with partition indexes for tables with very many partitions.
3groupFiles/groupSize fix many small JSON or CSV inputs; repartition or coalesce before the write decides how many output files you get.
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.
5Pass Spark settings with --conf key=value --conf key2=value2; AQE is on by default from Glue 4.0 (Spark 3.3).
6collect(), toPandas() and count() in loops pull work onto the single driver — aggregate in Spark and bring back only small results.
1A Glue streaming job (job type gluestreaming) is Spark Structured Streaming that runs continuously against Kinesis Data Streams, Kafka or Amazon MSK.
2Read the stream through a Data Catalog table or with connection options; you get a streaming DataFrame.
3glueContext.forEachBatch(frame, batch_function, options) calls your function for every micro-batch; windowSize (100 seconds by default) and checkpointLocation are required options.
4Streaming jobs track progress with checkpoints, not job bookmarks — a restarted job resumes where it stopped, and deleting the checkpoint reprocesses.
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.
6You pay for every hour the job runs; G.025X workers (0.25 DPU) keep low-volume streams cheap.
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.
2Put transformation logic in plain DataFrame functions with no awsglue imports, so pytest can test them on a local SparkSession.
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.
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.
5EvaluateDataQuality runs DQDL rules such as IsComplete "order_id" and ColumnValues "amount" > 0 inside the job — fail the run before bad data lands.
6Route Glue Job State Change events (FAILED, TIMEOUT, STOPPED) through EventBridge to your on-call channel and alarm on CloudWatch metrics.