devHọc Dev

Week 1 - Day 4: Transformation and Orchestration (Glue ETL, EMR, Lambda, Step Functions, MWAA)

Week 1 – Day 4

This lesson combines 5 topics: Glue ETL in depth — Spark and DynamicFrame, Glue Job Tuning and performance optimization, Amazon EMR and EMR Serverless, Lambda for lightweight ETL, Orchestration — Step Functions, MWAA, Glue Workflows, EventBridge.

Learning Objectives

  • Review the Spark execution model: driver, executor, partition, lazy evaluation
  • Understand DynamicFrame vs DataFrame and Glue's characteristic transforms
  • Handle inconsistent schemas: ResolveChoice, Relationalize
  • Write output correctly: partitionKeys, catalog updates, formats
  • Diagnose slow/OOM jobs with metrics and the Spark UI
  • Know the tuning levers: worker type/count, partitions, small files, skew
  • Handle small files and optimize writes
  • Know the Glue cost optimization checklist
  • Understand the EMR architecture: node types, EMRFS, cluster lifecycle
  • Optimize EMR costs: Spot, instance fleets, transient clusters, auto-termination
  • Know EMR Serverless and EMR on EKS
  • Compare Glue vs EMR — the classic selection question
  • Know the Lambda limits that decide "usable for ETL or not"
  • Event-driven ETL patterns: S3 event → Lambda; Kinesis/SQS → Lambda
  • Error handling: retry, DLQ, destination, idempotency
  • Recognize when Lambda is the wrong tool (move to Glue/EMR/Flink)
  • Understand Step Functions: Standard vs Express, error handling, Map/Distributed Map
  • Know MWAA (managed Airflow) and when to choose it over Step Functions
  • Know Glue Workflows and EventBridge (rules + Scheduler)
  • Pick the right orchestrator based on the signals in the question

Part 1: Glue ETL in depth — Spark and DynamicFrame

1. Spark in 10 lines (the foundation for understanding Glue)

DRIVER(coordinates,buildstheDAG)│splitsjob→stages→tasks┌───────────┼───────────┐▼▼▼EXECUTOREXECUTOREXECUTOR←Glueworkers(G.1X...)(tasksprocessdataPARTITIONSinparallel)
  • Lazy evaluation: transformations (filter, map, join) are only recorded in the DAG; an action (write, count) triggers execution
  • Shuffle: join/groupBy require moving data between executors — the most expensive part; skew (lopsided keys) makes 1 task run forever
  • Number of partitions ~ degree of parallelism; too few/too large files → few tasks; too many small files → overhead

2. DynamicFrame vs DataFrame

DynamicFrame is Glue's own abstraction on top of Spark, designed for data with unclean/inconsistent schemas:

Spark DataFrameGlue DynamicFrame
SchemaFixed, must be known up frontInferred, each record is self-describing — tolerates mixed schemas
Inconsistent types (a column that is sometimes int, sometimes string)Error or nullChoice type — keeps both, resolve later
Glue integration—Job bookmarks, catalog, Glue sinks
APIRich SQL/DataFrameETL-specific transforms
ConversionfromDF()toDF()
# Convert back and forth when you need both APIs
df = dynamic_frame.toDF()              # DynamicFrame → DataFrame (Spark SQL)
dyf = DynamicFrame.fromDF(df, glueContext, "dyf")

In practice: read/write + resolve schema with DynamicFrame, do complex transforms with DataFrame/Spark SQL.

3. Frequently tested DynamicFrame transforms

TransformPurpose
ApplyMappingRename/retype/select columns (explicit mapping)
ResolveChoiceResolve choice types: cast:long, make_cols (split into col_int, col_string), make_struct, project
RelationalizeFlattens nested JSON into multiple flat tables (root + child tables for arrays) — loadable into a relational warehouse
Filter, Map, Join, SplitFieldsAs the names say
DropNullFieldsDrops all-null columns
UnboxParses a column holding a JSON string into a struct
# Example: the "price" column is sometimes int, sometimes string in the source JSON
resolved = raw_dyf.resolveChoice(specs=[("price", "cast:double")])

# Nested JSON → flat tables for Redshift
flat = Relationalize.apply(frame=raw_dyf, staging_path=tmp_dir, name="root")

Exam cue: "deeply nested JSON needs to be loaded into Redshift" → Relationalize. "Column with inconsistent data types" → ResolveChoice.

4. Reading and writing data in a Glue job

Reading

# From the catalog (recommended — enables bookmarks, partition pushdown)
dyf = glueContext.create_dynamic_frame.from_catalog(
    database="sales_db", table_name="orders",
    push_down_predicate="year='2026' AND month='07'",   # read only the partitions you need!
    transformation_ctx="src")
  • push_down_predicate: filters partitions before reading S3 — drastically cuts time/cost (unlike filtering after reading)

Writing

sink = glueContext.getSink(
    connection_type="s3", path="s3://lake/curated/orders/",
    updateBehavior="UPDATE_IN_DATABASE",     # update the schema in the catalog
    partitionKeys=["year", "month"],
    enableUpdateCatalog=True,
    transformation_ctx="sink")
sink.setFormat("glueparquet")               # Glue's write-optimized parquet
sink.writeFrame(transformed_dyf)
  • enableUpdateCatalog + partitionKeys: new partitions land in the catalog automatically — no crawler needed after the job
  • Writing Iceberg/Hudi/Delta: use the Spark DataFrame writer with the table format configuration (Glue 4.0/5.0 ship the libraries)

5. Small job with a JDBC source — watch out for parallel reads

Reading a large JDBC table: by default 1 connection → slow. Configure hashfield/hashpartitions (DynamicFrame) or partitionColumn/lowerBound/upperBound/numPartitions (Spark) to read in parallel.

Part 2: Glue Job Tuning and performance optimization

1. Observe first, optimize later

Diagnostic tools

  • Job metrics (--enable-metrics): CPU/memory per executor, bytes read/written, data shuffle
  • Spark UI (--enable-spark-ui + S3 event logs): view stages/tasks, durations, shuffle, skew — the main tool for finding bottlenecks
  • Continuous logging to CloudWatch Logs
  • Glue job run insights: automatic error and tuning hints in the error message

Classic symptoms

SymptomCommon causeFix
Driver OOM (OutOfMemoryError)Listing too many small files / collecting to the driverGroup files, drop collect, use useS3ListImplementation
Executor OOMPartitions too large, skew, unnecessary cachingRepartition, salt keys, larger worker size (G.2X+)
1 task runs forever, the rest finish earlyData skew (lopsided keys)Salt keys, broadcast join the small table, AQE (Spark 3 handles most of it)
Slow job on readMillions of small files; uncompressed, non-columnar JSON/CSVCompaction; convert to Parquet; push_down_predicate
Slow job on writeToo many small output partitionsrepartition/coalesce before writing

2. Main tuning levers

Choosing workers and count

  • Increase the number of workers when the job is limited by parallelism (many partitions waiting to be processed)
  • Increase the worker size (G.1X → G.2X/G.4X/G.8X) when individual tasks need more memory (large joins, heavy aggregation)
  • Auto Scaling (--enable-auto-scaling): Glue adds/removes executors per job stage — avoids paying for idle workers

Number of Spark partitions

  • Rule of thumb: partitions ~ 2-3× the total number of cores; each partition ~128MB of data
  • spark.sql.shuffle.partitions (default 200) — tune according to shuffle volume
  • AQE (Adaptive Query Execution) — Spark 3 (Glue 3.0+) automatically coalesces small partitions after a shuffle and handles skew joins in most cases

Small files problem

Millions of KB-sized files on S3 → slow driver listing, one tiny task per file, enormous overhead:

  • At the source: batch upstream (larger Firehose buffer, Kinesis aggregation)
  • In the job: read with groupFiles: inPartition + groupSize (groups many small files into one read task)
  • Periodically: a compaction job (read → repartition → rewrite as ~128MB-1GB files); with Iceberg use OPTIMIZE ... REWRITE DATA (Athena) or the automatic compaction of S3 Tables

Join tuning

  • Broadcast join: the small table (< a few hundred MB) is sent to every executor — avoids shuffling the large table
  • Filter early (predicate pushdown, column selection) before joining
  • Skew: salt keys or let AQE handle it

3. Glue cost optimization (checklist)

  1. Right job type: Python shell for small work; Spark for large data
  2. Flex execution for batches without an SLA (-~34%)
  3. Auto Scaling instead of a fixed max worker count
  4. Bookmarks + push_down_predicate: process only the data you need
  5. Reduce data read: Parquet + partitioning + compaction
  6. Set a sensible timeout (default 48h — a hung job burns money)
  7. Interactive sessions for development (billed per minute, idle timeout) instead of running the whole job to test
  8. Latest Glue version (5.0 is faster → fewer DPU-hours)

4. Combined scenario example

A Glue job with 10 G.1X workers runs for 3h, reading 2M small JSON files (200GB total) from S3, joining with a 50MB reference table, writing Parquet. How do you optimize it?

Sample solution:

  1. Convert/consolidate the source: larger Firehose buffer or compaction beforehand — or read with groupFiles
  2. push_down_predicate if only some partitions are needed
  3. Broadcast join the 50MB table
  4. Write: coalesce to a sensible file count (~200GB/512MB ≈ 400 files)
  5. Enable Auto Scaling + consider Flex for a nightly batch → Less time, fewer DPU-hours — "faster" and "cheaper" at the same time.

Part 3: Amazon EMR and EMR Serverless

1. Amazon EMR (on EC2)

Architecture

┌──────────────────────EMRCLUSTER──────────────────────┐│PRIMARYnode(1or3forHA):resourcemanager,driver││COREnodes:runtasks+HDFSstorage││TASKnodes:runtasksonly(noHDFS)→goodforSPOT│└─────────────────────────────────────────────────────────┘Frameworks:Spark,Hive,Presto/Trino,Flink,HBase,Hudi/Iceberg...Storage:EMRFS→read/writeS3(decouplescomputeandstorage,recommended)HDFS→local,lostwhentheclustershutsdown
  • EMRFS: the S3 connector — data is durable outside the cluster, shutting the cluster down loses no data → today's standard model
  • Transient cluster: start a cluster, run steps, then auto-terminate — cheap batch; long-running for ad-hoc/interactive work
  • Deep administration: choose AMIs, bootstrap actions, per-framework configuration — powerful but operationally heavy

EMR cost optimization (frequently tested)

TechniqueDetails
Spot for TASK nodesTask nodes hold no HDFS → losing a node loses no data; core/primary should be On-Demand
Instance fleetsMix multiple instance types + purchasing options, allocation strategy
Transient + auto-terminationDon't pay for an idle cluster
Managed scalingAdds/removes nodes based on load
Graviton instances~20% cheaper for the same performance
S3 instead of HDFSNo need for large core node storage

2. EMR Serverless

  • Runs Spark/Hive jobs without managing a cluster: declare an application → submit jobs, AWS provisions workers on demand, scales to zero
  • Pay for the vCPU-seconds + GB-seconds actually used; pre-initialized capacity (warm) if you need fast starts
  • No SSH, no instance choice; limited frameworks (Spark, Hive) compared with full EMR
  • Exam cue: "Spark jobs, intermittent/unpredictable, don't want to manage clusters" → EMR Serverless

3. EMR on EKS

  • Runs Spark jobs on an existing EKS cluster — leverages the organization's shared Kubernetes infrastructure, shares capacity with other services
  • Choose it when the question says "standardized on Kubernetes / existing EKS cluster"

4. Glue vs EMR — decision table

AWS GlueEMR (EC2)EMR Serverless
ModelServerless ETL jobSelf-managed clusterServerless job
FrameworksSpark (+Python shell, Ray)Everything: Spark, Hive, Trino, Flink, HBase...Spark, Hive
Infrastructure controlNoneFull (AMI, bootstrap, system libraries)None
ETL integration (catalog, bookmarks, crawlers, visual)DeepestCatalog usableCatalog usable
CostDPU-hour (higher unit price)Cheapest at large scale (Spot/RI)vCPU/GB-seconds
OperationsLowestHighLow

Selection rules

  • Standard ETL pipeline into the lake, low operations → Glue
  • Need frameworks beyond Spark/Hive (Trino, HBase, custom), specific system libraries, or deep cost optimization (Spot, large always-on clusters) → EMR
  • Pure Spark, intermittent workload, no cluster wanted → EMR Serverless
  • Migrating on-prem Hadoop/Spark while keeping the stack → EMR ("lift and shift")

5. Operational details worth remembering

  • Steps: the unit for submitting work to a cluster (CLI/API/Step Functions can all submit steps)
  • EMR Studio / notebooks: managed IDE for data scientists on EMR
  • S3DistCp: copies/merges large files between S3 ↔ HDFS (also the classic compaction tool)
  • Security: Kerberos, Lake Formation integration, security configuration (at-rest/in-transit encryption)

Part 4: Lambda for lightweight ETL

1. Lambda limits you must know

LimitValueConsequence for ETL
Timeout15 minutes maxLonger jobs → Glue/EMR/split up with Step Functions
Memory128MB - 10GB (CPU scales proportionally)Data must be processed as a stream/in chunks, don't load huge files
/tmp storage512MB - 10GBLimited temp files
Sync payload6MB (response/request)Pass large data via S3, not the payload
Concurrency1,000 per region by default (can be raised)Large fan-out needs to watch for throttling
Deployment250MB unzipped (container image: 10GB)Heavy libraries (pandas, pyarrow) → layer/container image

Exam rule: if you see "processing takes ~30 minutes" or "hundreds of GB per run" → Lambda is WRONG; choose Glue/EMR. Lambda fits: small-to-medium files, per-event, < 15 minutes.

2. Event-driven ETL patterns with Lambda

S3 event → Lambda (per-file processing)

CSV file arrives at s3://raw/incoming/
      │ S3 Event Notification (or via EventBridge)
      ▼
   Lambda: validate → light transform → write s3://curated/
      │ error?
      ▼
   Retry (async: 2 times) → On-failure destination / DLQ (SQS)
  • Async invocation (S3 event): retries 2 times automatically; configure an on-failure destination (SQS/SNS/EventBridge/Lambda) or a DLQ so failed events aren't lost
  • Large files: use Lambda only as a router/trigger (e.g. start a Glue job), not to process them itself

SQS → Lambda (buffering + throttle control)

  • SQS sits in the middle to absorb bursts, batch (up to 10 msgs), and control concurrency (maximum concurrency per event source)
  • Partial batch response (ReportBatchItemFailures): retry only the failed messages in a batch, not the whole batch
  • Poison message → SQS DLQ (maxReceiveCount)

Kinesis → Lambda

Covered in Week 1 Day 3: batch size/window, parallelization factor, bisect on error, on-failure destination; errors block the shard if not configured — unlike SQS.

Lambda in a larger pipeline

  • Glue-code step in Step Functions (call APIs, validate, decide branches)
  • Firehose transform (already covered)
  • Triggers: EventBridge schedules instead of a cron server

3. Idempotency — a golden DEA topic

Every event source (S3, SQS standard, Kinesis) is at-least-once → Lambda may receive duplicates. Code must be idempotent:

  • Write output deterministically (same input → same S3 key, overwrite instead of append)
  • Conditional write: DynamoDB attribute_not_exists / S3 precondition to skip already-processed records
  • Store a processed marker (idempotency key = event id) in DynamoDB with a TTL
  • With SQS FIFO: the deduplication ID helps on the queue side, but the consumer should still be idempotent

4. When Lambda IS the right tool (summary)

ScenarioLambda?
Validate/convert each small file on upload✅
Call an API to enrich data per event✅
Route/filter events, trigger other jobs✅
Transform records in Firehose✅
Batch join of two 500GB tables❌ Glue/EMR
Stateful 30-minute windowed aggregation❌ Flink
Job running 45 minutes❌ Glue (or split up with Step Functions)
Loading a warehouse with row-by-row INSERTs❌ COPY batch

Part 5: Orchestration — Step Functions, MWAA, Glue Workflows, EventBridge

1. AWS Step Functions

Concepts

A state machine (defined in ASL — JSON) coordinates steps: calls over 220 services directly (Glue, Lambda, EMR, Athena, ECS...), branching, parallelism, retries — serverless, no infrastructure.

{Start}→ValidateInput(Lambda)→RunGlueJob(glue:startJobRun.sync)←.sync=waitforthejobtofinish→Choice:DQpass?├─yes→RunCrawler→AthenaCTAS→Success└─no→SNSPublish(alert)→Fail(eachstatehasitsownRetry/Catch)

Standard vs Express

StandardExpress
Run durationUp to 1 yearUp to 5 minutes
SemanticsExactly-once workflowAt-least-once
PricingPer state transitionPer execution + duration
Use caseETL pipelines, waiting on long jobsHigh-volume, short event processing

Features for data pipelines

  • .sync integration: start a job and wait for completion (Glue, EMR steps, Athena...) — no polling of your own
  • Retry/Catch per state: backoff, max attempts, error-handling branches — the strongest point
  • Map state: iterates in parallel over an input array; Distributed Map: fans out to millions of items (e.g. one run per S3 object) with controllable concurrency
  • Wait / callback (task token): wait for approval/a human step

2. MWAA — Managed Workflows for Apache Airflow

  • Managed Airflow: DAGs written in Python, a huge library of operators (AWS, GCP, Snowflake, dbt, Spark...), a familiar monitoring UI
  • AWS manages the scheduler/workers/webserver (scaled by environment class); DAGs live in S3; supports Airflow 2.x and 3.x (MWAA supports Airflow 3.0 since 10/2025)
  • Cost: the environment runs continuously (billed hourly) — no scale-to-zero
  • Choose it when: you already have Airflow DAGs (migration), need cross-platform/hybrid orchestration, the team is used to Python-as-code
  • Step Functions vs MWAA: serverless + deep AWS integration + pay-per-use vs the Airflow ecosystem + portability

3. Glue Workflows

  • Orchestration inside Glue: chains of crawlers + jobs + triggers (schedule/event/conditional), passing run properties
  • The graph is visible in the console; can be started by an EventBridge event (e.g. an S3 file arriving)
  • Limitation: only coordinates Glue crawlers/jobs — cannot call Lambda/EMR/other services
  • Choose it when: a simple, pure-Glue pipeline, and you don't want to add another service

4. EventBridge — triggers and schedules

  • Rules: event pattern matching (e.g. s3:ObjectCreated via EventBridge, Glue job state change FAILED → SNS)
  • EventBridge Scheduler: managed cron/rate, time zones, one-time schedules — replaces a cron server; can invoke most AWS APIs
  • Pipes: point-to-point source (SQS, Kinesis, DynamoDB streams) → target, with filtering/enrichment
  • EventBridge is not an orchestrator — it is an event router/scheduler; combine them: EventBridge triggers → Step Functions orchestrates

5. Choosing an orchestrator — decision table

Signal in the questionChoose
Serverless, retry/branching, calls many AWS services, waits on long jobsStep Functions (Standard)
"Existing Airflow DAGs", "Python-based workflows", multi-platformMWAA
Pipeline made only of Glue crawlers + jobsGlue Workflows
Run X on a simple cron scheduleEventBridge Scheduler (+ a job/SFN as the target)
Process millions of S3 files in parallel with controlStep Functions Distributed Map
High event volume, each workflow < 5 minutesStep Functions Express

End-to-end reference architecture

(filearrives)(nightly02:00)S3──►EventBridgeruleEventBridgeScheduler││▼▼┌─────────────────────────────────┐│StepFunctions(Standard)││Gluejob→DQcheck→Choice││├─pass→Crawler→dbt/CTAS││└─fail→SNS+Fail│└─────────────────────────────────┘

Review Questions

  1. A JSON source has a user_id column that is sometimes a number and sometimes a string. How does Glue handle it?

    Show answer

    DynamicFrame keeps that column as a choice type (it doesn't fail). Use ResolveChoice to settle it: cast:string (force one type), make_cols (split into user_id_int, user_id_string), make_struct, or project. This is the main advantage of DynamicFrame over DataFrame, which requires a consistent schema.

  2. You need to load nested JSON (orders containing an items array) into relational tables in Redshift. Which Glue transform?

    Show answer

    Relationalize — flattens the nested structure into a root table + child tables for each array, linked by auto-generated keys. The result is a set of flat tables that load straight into Redshift (COPY) and can be joined back together.

  3. A job only needs the current month's data from a table partitioned by year/month, but it reads the whole bucket and then filters. How do you fix it?

    Show answer

    Use push_down_predicate in create_dynamic_frame.from_catalog (e.g. "year='2026' AND month='07'") — Glue only lists and reads the matching partitions on S3 instead of reading everything and filtering in Spark. For tables with very many partitions you can also use catalogPartitionPredicate (server-side). Cuts both runtime and DPU-hours.

  4. After a job writes new partitions to S3, Athena doesn't see the new data. How do you fix it inside the job (without adding a crawler)?

    Show answer

    Write with a sink that has enableUpdateCatalog=True plus partitionKeys (and updateBehavior) — Glue adds the new partitions/schema to the Data Catalog as it writes. Alternatives: run MSCK REPAIR TABLE/ALTER TABLE ADD PARTITION via Athena, or use partition projection.

  5. When should you convert a DynamicFrame to a DataFrame in a job?

    Show answer

    When you need the full Spark API: Spark SQL, window functions, complex joins, UDFs, ML libraries — DataFrame is richer and usually faster (Catalyst optimizer). The standard pattern: DynamicFrame for reading + resolving schema + bookmarks, toDF() for heavy transforms, fromDF() to go back and write with a Glue sink (catalog update).

  6. Reading a 500GB PostgreSQL table over JDBC is very slow even though the job has many workers. Why?

    Show answer

    By default JDBC reads over a single connection — every other worker sits waiting. Configure parallel reads: hashfield/hashpartitions with DynamicFrame (or partitionColumn, lowerBound, upperBound, numPartitions with Spark) on an evenly distributed column (numeric key/timestamp). Also consider the load on the source database.

  7. A job fails with Driver OutOfMemory when reading a bucket containing 5 million small files. Why does the driver (not an executor) die, and how do you fix it?

    Show answer

    The driver is responsible for listing files and planning tasks — 5 million objects create huge metadata in driver memory. Fix: consolidate small files (compaction), read with groupFiles: inPartition/groupSize so Glue groups files during planning, enable useS3ListImplementation to list in batches, and solve the root cause upstream (larger Firehose buffer).

  8. A stage has 200 tasks: 199 tasks finish in 1 minute, 1 task runs for 50 minutes. What is happening and how do you fix it?

    Show answer

    Data skew: one join/groupBy key holds most of the data and piles into 1 partition. Fixes: (1) Spark 3 AQE (Glue 3.0+) is on by default and handles skew joins automatically in most cases; (2) salt the key — add a random suffix to split the hot key into several sub-keys; (3) broadcast join if one table is small; (4) filter out junk keys (null, default values) that cause skew before joining.

  9. When do you add more workers, and when do you switch to larger workers (G.2X/G.4X)?

    Show answer

    Add workers when the job parallelizes well but lacks slots (many partitions queued, all executors evenly busy on CPU). Larger workers when individual tasks lack memory (executor OOM, heavy spill to disk) — joins/aggregations holding lots of data in RAM. Read the metrics: high executor memory usage + spill → larger; even CPU and a long queue → more.

  10. How do you consolidate small files when WRITING output in Spark/Glue? Compare repartition and coalesce.

Show answer

Before writing, reduce the number of partitions: coalesce(n) — merges partitions without a shuffle, cheap, can only reduce the partition count; repartition(n) — full shuffle, more expensive but redistributes evenly (and can increase the partition count, partition by column). When writing a table partitioned by a column: repartition(col) makes each output partition get a few large files instead of every task writing a fragment into every partition.

  1. Name 4 ways to reduce the cost of a nightly Glue job currently running 20 DPUs × 2h.
Show answer

(1) Flex execution — nightly with no SLA, ~34% lower unit price; (2) Auto Scaling — when the job has light phases, it doesn't hold all 20 workers; (3) reduce the data processed: bookmarks (incremental) + push_down_predicate + Parquet sources; (4) tune it to run faster (broadcast join, consolidate small files) — DPU-hours = workers × hours, so faster is cheaper. Also: upgrade to a newer Glue version, set a short timeout.

  1. You run a 2-hour nightly Spark batch on EMR and want the lowest cost without risking data loss when Spot instances are reclaimed. Design?
Show answer

A transient cluster (auto-terminates after the steps) + primary & core: On-Demand, task nodes: Spot (instance fleets with diverse types to reduce the chance of simultaneous reclamation). Task nodes hold no HDFS, so losing a node only slows things down without losing data; input/output data lives in S3 (EMRFS).

  1. Why shouldn't all core nodes be Spot?
Show answer

Core nodes hold HDFS — simultaneous Spot reclamation can lose HDFS blocks (below the replication factor), breaking the job and even losing intermediate data. Standard: core On-Demand (minimum count), task nodes on Spot for elasticity. If all data is on S3 and the shuffle is small the risk is lower, but the exam best practice is still core = On-Demand.

  1. A team runs a Spark job a few times a day, 20 minutes each, and doesn't want to manage clusters. Glue or EMR Serverless — which criteria decide?
Show answer

Both are serverless Spark. Choose Glue if you want the ETL ecosystem: bookmarks, crawlers, Glue Studio, DQ — a standard data lake pipeline. Choose EMR Serverless if you need pure Spark/deeper Spark configuration customization, or to run existing Spark/Hive code from EMR/on-prem without adapting it to the Glue API, or to optimize the unit price per vCPU/GB-second. Questions usually distinguish them with "existing Spark applications" (→ EMR Serverless) vs "ETL with catalog/bookmarks" (→ Glue).

  1. An ad-hoc analytics cluster running Trino (Presto) for analysts — can Glue do it? Solution?
Show answer

Glue cannot run Trino — Glue only does Spark/Python/Ray. Options: EMR (install Trino/Presto) if you want a self-managed cluster, or — usually more correct for ad-hoc SQL on S3 — Athena (essentially a serverless Trino engine). Question stresses "ad-hoc SQL on S3, serverless" → Athena; "self-managed Trino with custom configuration" → EMR.

  1. An on-prem Hadoop cluster (Hive + Spark + HBase) needs to move to AWS quickly, keeping the applications as they are. Solution?
Show answer

EMR on EC2 — supports the full Hadoop stack (Hive, Spark, HBase...), a re-platform migration that keeps the code. HDFS → gradually move to S3/EMRFS (DataSync supports HDFS). Glue/EMR Serverless don't run HBase and don't offer an equivalent level of control.

  1. A pipeline uses Lambda to process files on S3 upload; occasionally a 20GB file makes Lambda time out. How do you fix the architecture?
Show answer

Lambda's 15 minutes/10GB don't suit large files. Fix: Lambda acts only as a trigger — it receives the S3 event and starts a Glue job (or Step Functions/EMR Serverless) to process the large file; or drop Lambda and use EventBridge → Glue workflow directly. Keep Lambda for small files by branching on size (taken from the event) if you want to optimize cost.

  1. A Lambda reading SQS: one bad message makes the whole batch retry forever. Which two configurations fix it?
Show answer

(1) Partial batch response (ReportBatchItemFailures) — Lambda reports the failed messages individually, so successful messages in the batch aren't retried; (2) a DLQ on SQS with maxReceiveCount — a bad (poison) message is moved to the DLQ after N receives for analysis, without blocking the queue.

  1. S3 events may be delivered more than once; Lambda writes results to DynamoDB. How do you avoid double processing?
Show answer

Design for idempotency: use a unique key from the event (bucket/key/versionId or event id) as the idempotency key; write to DynamoDB with a conditional write (attribute_not_exists(pk)) — the duplicate fails the condition and is skipped; or check a "processed" marker table with a TTL before running. Principle: never assume exactly-once from an event source.

  1. What is the difference in error handling between Lambda reading Kinesis and Lambda reading SQS?
Show answer

Kinesis: by default an error blocks the shard (the same batch is retried until retention runs out) because ordering must be preserved — you need to configure maximumRetryAttempts, bisectBatchOnFunctionError, and an on-failure destination to make progress. SQS: a failed message returns to the queue after the visibility timeout, is retried independently, and goes to the DLQ after exceeding maxReceiveCount — it doesn't block other messages (standard queue).

  1. You need to run a lightweight Python transform (pandas, ~50MB file) every hour. Lambda or Glue Python shell?
Show answer

Both are valid; choose by constraints: Lambda — event-driven/EventBridge schedule, finishes in minutes, lightweight integration, very low per-invocation cost; use a layer/container if you need pandas. Glue Python shell — lives alongside the Glue pipeline (workflow, catalog), can run longer than 15 minutes, small 0.0625 DPU. If processing time risks exceeding 15 minutes or you want it inside a Glue workflow → Python shell; otherwise Lambda is usually the cheapest and simplest.

  1. Pipeline: Glue job A → if successful, run jobs B and C in parallel → finally a crawler; each step needs retries and an alert on failure. What is the leanest orchestrator?
Show answer

Step Functions Standard: Task states with glue:startJobRun.sync (wait for the job to finish), a Parallel state for B+C, Retry/Catch per state, a Catch branch → SNS. Fully serverless, no orchestration code. Glue Workflows can do it too (pure Glue) but lack flexible alerting/integration outside Glue; MWAA is overkill for one pipeline.

  1. A company migrating from on-prem already has 200 Airflow DAGs. Which orchestration solution on AWS needs the least conversion effort?
Show answer

MWAA — managed Airflow, the Python DAGs stay almost unchanged (upload to S3, adjust connections/AWS operators if needed). Rewriting 200 DAGs into Step Functions ASL is a large, unnecessary cost — contrary to "minimal migration effort".

  1. A workflow must wait for a 3-hour Glue job and then continue. Standard or Express? Why?
Show answer

Standard — runs for up to 1 year and is billed per state transition, so waiting a long time costs nothing extra; use .sync to wait for the Glue job. Express maxes out at 5 minutes — it cannot wait for a 3-hour job. Express is for short, high-volume event processing.

  1. You need to process 2 million S3 objects, one transform per object, with controlled concurrency and per-item retries. Solution?
Show answer

Step Functions Distributed Map: list objects from S3 (or a manifest/CSV), fan out each item into a child execution (Lambda/ECS...), set MaxConcurrency, tolerated failure, per-item retry, with aggregated results written to S3. This is exactly the use case Distributed Map was built for, replacing a hand-written queue + workers.

  1. When a Glue job FAILS, you want to automatically send a Slack/SNS notification and create a ticket — without changing the job. How?
Show answer

An EventBridge rule that matches the Glue Job State Change event with state: FAILED → target SNS (or a Lambda calling the ticketing API). Glue already emits events to EventBridge — no need to modify the job or add polling. The "react to service events" pattern is EventBridge's home turf.

  1. What is the difference between EventBridge Scheduler and a Glue trigger schedule / MWAA cron?
Show answer

EventBridge Scheduler is an independent, universal scheduling service: cron/rate/one-time, timezone-aware, able to call most AWS APIs (including Step Functions, Glue, Lambda) with retry/DLQ — use it when you need a shared "clock". A Glue trigger schedule only starts Glue jobs/workflows; an Airflow schedule is tied to a DAG in MWAA. Choose based on the system in use; "replace cron server" → EventBridge Scheduler.

Hands-on Exercises

Part 1: Glue ETL in depth — Spark and DynamicFrame

  • Write a Glue job that reads sample nested JSON, run Relationalize and inspect the output tables
  • Create a file with a mixed-type column, observe the choice type and try 3 ResolveChoice strategies
  • Enable enableUpdateCatalog in the sink, write new partitions, verify Athena sees them immediately without a crawler
  • Read Glue PySpark transforms reference

Part 2: Glue Job Tuning and performance optimization

  • Enable --enable-spark-ui for a job, open the Spark UI and look at the stages and shuffle read/write
  • Experiment: a job reading 1000 files of 100KB vs 10 files of 10MB — compare the durations
  • Write a compaction job: read a prefix of many small files → coalesce → rewrite as ~256MB files
  • Read Best practices for performance tuning AWS Glue for Apache Spark jobs

Part 3: Amazon EMR and EMR Serverless

  • Create an EMR Serverless application (Spark), submit 1 PySpark job that reads/writes S3, look at the per-vCPU-second billing
  • Simulate decisions: 5 workloads (catalog ETL, ad-hoc Trino, HBase, intermittent Spark, Hadoop migration) → choose Glue/EMR/EMR Serverless/Athena
  • Read up on the structure of instance fleets and allocation strategies
  • Read EMR best practices — cost

Part 4: Lambda for lightweight ETL

  • Create a Lambda triggered by an S3 event: read a small CSV, add a column, write Parquet (pyarrow layer) to the curated bucket
  • Configure an on-failure destination to SQS, upload a broken file to see the failed event land in the queue
  • Write an idempotency check using a DynamoDB conditional write in the Lambda above
  • Read Lambda event source mappings

Part 5: Orchestration — Step Functions, MWAA, Glue Workflows, EventBridge

  • Create a state machine: Lambda validate → Glue job (.sync) → Choice → SNS fail branch; also run the failure branch
  • Create an EventBridge rule matching Glue Job State Change FAILED → SNS email
  • Create an EventBridge Scheduler cron at 02:00 that invokes the state machine above
  • Read Distributed Map

References


Next lesson →