SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Batch vs Stream Processing
  • Change Data Capture (CDC)
  • MapReduce
  • ETL Pipelines
  • Data Lakes
  • Data Warehousing
  • Data Lakehouse
  • Lambda Architecture
  • Kappa Architecture
  • Streaming Engines
  • Spark and Hadoop
  • Workflow Orchestration (Airflow)
  • Parquet and Columnar File Formats
  • Data Governance and Feature Stores
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Big Data Processing

Spark and Hadoop

The big data toolbox: HDFS to store, YARN to schedule, MapReduce and Spark to compute.

โฑ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Hadoop and Spark are the two names you meet first in big data. Hadoop is a toolbox: HDFS to store files, YARN to share the machines, and MapReduce to compute. Spark is a faster compute engine that keeps data in memory between steps.

  • Storage: HDFS spreads big files over many machines (or you use cloud object storage instead).
  • Scheduling: YARN (or Kubernetes) decides which machine runs which task.
  • Compute: MapReduce writes to disk between steps. Spark plans the whole job as a graph and keeps results in memory.
  • Today most new work uses Spark on object storage. Hadoop ideas live on inside it.

02Concept: What is it?

One machine cannot hold or scan a few terabytes quickly. The big data answer is to split the data across many cheap machines and to send the code to the data, instead of dragging the data to the code. Apache Hadoop (2006) packaged this idea. It has three layers that work together.

The Hadoop stack, layer by layer
๐ŸงฎCompute: MapReduce, Spark, Hivethe code that processes data
โ†“
๐ŸŽ›๏ธScheduling: YARNshares CPU and memory between jobs
โ†“
๐Ÿ—„๏ธStorage: HDFSbig files in replicated blocks
Each layer can be swapped. Spark keeps the same shape but replaces the top layer.

Spark (2014 as a top-level project) came from a simple complaint: MapReduce writes to disk after every step, which makes chains of steps and repeated passes slow. Spark describes your whole job first, as a graph of steps, and then runs it. Between steps it keeps data in memory where it can.

The key ideas of Spark's model: you build a dataset by chaining transformations (filter, map, join). These are lazy: nothing runs. Only an action (count, write, show) triggers the work. Spark then turns the chain into a DAG, cuts it into stages at every shuffle, and sends the tasks to executors on the cluster.

๐Ÿง Spark is not a database or a file system
Spark only computes. It does not store data by itself. It reads from HDFS, S3, a database or Kafka, and writes the result back.

03Real-Life Example

๐ŸตThe Team Marking Exams
A teacher has 10,000 exam papers to mark and total by class. She splits the papers into piles and gives one pile to each of 50 helpers (this is HDFS: the data is already spread out). A manager hands out helpers and rooms (YARN). With the MapReduce style, each helper marks, writes the marks on paper and files it in a cabinet before the next step starts. With the Spark style, helpers keep the marks in their head and only meet once, at the shuffle, to add up the totals by class.
Exam marking
Hadoop and Spark
Piles of papers spread over helpers
HDFS blocks on DataNodes
The manager giving out helpers and rooms
YARN ResourceManager
The teacher who plans the work
Spark driver
Each helper marking their own pile
Executors running tasks
Helpers meeting to total marks by class
A shuffle (a stage boundary)
Filing every step in a cabinet
MapReduce writing to disk each step
Remembering marks for the next round
Spark cache in memory

04Why Do We Need It?

๐Ÿ“ฆData too big for one machine
Terabytes and petabytes need many disks and many CPUs working together.
๐ŸššMove code, not data
Tasks run on the machines that already hold the blocks, so the network is not flooded.
๐Ÿ’ธCheap hardware
Failures are expected, so the system retries tasks and re-copies blocks instead of needing special servers.
โšกSpeed for repeated work
Spark keeps data in memory, which helps machine learning and any job that loops over the same data.
๐ŸงฐOne engine, many jobs
SQL, streaming, machine learning and graphs all run on the same Spark core.
๐Ÿ”ŒOpen and portable
Runs on YARN, Kubernetes or a cloud service, reading open files such as Parquet.
Hadoop showed how to store and process data at scale on cheap machines. Spark made that processing fast and pleasant to write.

05Where Do We Use It?

๐Ÿ”„ETL and ELT
Clean and join huge tables nightly and write the result to a lake or warehouse.
๐Ÿค–Machine learning
Train models and build features on data far bigger than one machineโ€™s memory.
๐Ÿ“ŠInteractive SQL
Spark SQL, Hive and Presto/Trino answer questions over files in a lake.
๐ŸŒŠStream processing
Spark Structured Streaming treats a stream as a table that keeps growing.
๐ŸงพLog and event analysis
Scan days of logs for patterns, counts and anomalies.
๐Ÿ—ƒ๏ธLakehouse tables
Delta Lake, Iceberg and Hudi are read and written mostly by Spark.

06Types / Parts / How It Works

The pieces and what each one does

PieceJobRemember
HDFSStores big files as replicated blocks. NameNode keeps the map, DataNodes keep the blocks.Details on the Distributed File Systems page
YARNGives containers (CPU and memory) to applications. ResourceManager plus a NodeManager on each machine.Spark can also run on Kubernetes or standalone
MapReduceMap, shuffle, reduce, with disk between jobs.Details on the MapReduce page
HiveWrites SQL and turns it into jobs over files. The metastore keeps table definitions.Now often runs on Tez or Spark
Spark coreDriver plans the job. Executors run tasks and hold cached data.The compute engine
Spark SQL / DataFramesTables with columns. An optimizer (Catalyst) picks a good plan.Prefer this over raw RDDs
Structured StreamingRuns the same query on small batches of new data again and again.See Streaming Engines

How Spark runs one job

From your code to tasks on executors
Driver
๐Ÿ“Your codetransformations are lazy
โ†“an action runs it
๐Ÿ•ธ๏ธDAG, then stagescut at each shuffle
Executors
๐ŸงฑStage 1 tasksone per partition (filter, map)
โ†“shuffle: data moves over the network
๐ŸงฑStage 2 tasksgroup, join, aggregate
The driver plans. The executors work. A shuffle cuts the job into stages.

Narrow and wide steps

KindExamplesData movementCost
Narrowfilter, map, select, unionEach output partition needs one input partition. No shuffle.Cheap, pipelined inside one stage
WidegroupBy, join, distinct, repartition, sortRows with the same key must meet. Data is shuffled between machines.Expensive: disk, network, a new stage
Driver (plans) Executors (work) Shuffle
VisualizerDisk between steps vs memory between stepsAdd passes over the data and switch between MapReduce and Spark. Turn the cache off in Spark to see why caching matters. The outlined block is the shuffle: the stage boundary.
Engine
Pass 1
Read
Map
Shuffle
Reduce
Write
Pass 2
Read
Map
Shuffle
Reduce
Write
Pass 3
Read
Map
Shuffle
Reduce
Write
diskcomputecompute on cached datashuffle (stage boundary)
Total time
45
illustrative units
Disk steps
6
reads + writes
Spark would take
27
same job, same passes
MapReduce runs 3 separate job(s). Each one reads its input from disk and writes its result back to disk before the next job starts. That is 6 disk steps. Switch to Spark to see the same work keep its data in memory.

The time units are made up to show the shape of the cost (disk and network are slow, memory is fast). They are not benchmarks. Real speed depends on data size, cluster, caching and the job. The white outline marks the shuffle: in Spark it splits the job into two stages.

07How to Use It / Steps / Implementation

Writing a good Spark job

  1. 1
    Choose where data lives
    Cloud object storage (S3, GCS, ADLS) is the common choice. HDFS is fine if you already run Hadoop.
  2. 2
    Use DataFrames and SQL
    Spark can optimise them. Raw RDDs with custom functions skip most of the optimiser.
  3. 3
    Store data as Parquet
    Columnar and compressed, so Spark reads only the columns and row groups it needs.
  4. 4
    Filter and select early
    Reduce rows and columns before a join or group by, so less data is shuffled.
  5. 5
    Cache only what you reuse
    Call cache or persist on a dataset used many times. Release it when done.
  6. 6
    Size partitions sensibly
    Aim for partitions of roughly 100 to 200 MB. Too many tiny tasks or too few giant ones both hurt.
  7. 7
    Watch the Spark UI
    Look for long stages, huge shuffles and a few tasks that take far longer than the rest (skew).
๐Ÿ’กA word count in spirit
spark.read.text(path).groupBy("word").count().write.parquet(out). Nothing runs until the write. The group by is the shuffle.
โš ๏ธcollect() is a trap
Calling collect on a big dataset pulls everything into the driver's memory and crashes it. Write results to storage, or take a small sample.

08Key Terms to Know

TermMeaning in easy words
HDFSHadoop Distributed File System. Big files split into replicated blocks
YARNYet Another Resource Negotiator. Shares cluster CPU and memory between jobs
DriverThe Spark process that plans the job and coordinates the work
ExecutorA Spark process on a worker that runs tasks and holds cached data
RDDResilient Distributed Dataset. The low-level Spark collection, rebuilt from its recipe if lost
DataFrameA Spark table with named columns, planned by an optimiser
TransformationA lazy step such as filter or join. Nothing runs yet
ActionA step that runs the job and returns or saves a result, such as count or write
ShuffleMoving rows between machines so the same key lands together
StageA group of tasks that can run without a shuffle in the middle
PartitionOne slice of a dataset. One task works on one partition
Data skewOne key has far more rows than the others, so one task is very slow

09Pros, Cons and Trade-offs

โœ… Pros
  • Handles data far larger than one machine
  • Spark is fast for chains of steps and repeated passes
  • One engine for SQL, streaming and machine learning
  • Recovers from failed tasks by re-running them
  • Works with open file formats and many storage systems
โš ๏ธ Cons
  • A cluster to run, tune and pay for
  • Shuffles are costly and easy to cause by accident
  • Memory errors and skew need real tuning skill
  • Overkill for data that fits on one machine
  • Startup time makes it poor for tiny, instant queries

Trade-offs

ChoiceWe gainWe lose
MapReduceVery robust, simple modelSlow for multi-step and iterative jobs
Spark in memorySpeed on repeated passesNeeds enough memory, or spills to disk
HDFS storageData next to compute, no cloud feesYou run and repair the cluster
Object storage + SparkSeparate storage and compute, scale eachNetwork reads, slower listing and renames
Spark SQL / DataFrameOptimiser helpsLess control than hand-written code

10Common Problems and Mistakes

Common mistakes

  1. Ignoring shuffles. Every join and group by moves data over the network. Filter first, and avoid needless wide steps.
  2. Data skew. One hot key (for example a null or a huge customer) makes one task run for an hour while the rest wait.
  3. Too many small files. Thousands of tiny files make the job spend more time opening files than reading them.
  4. Caching everything. Memory fills up, and Spark has to evict or spill. Cache only reused data.
  5. Calling collect on big data. The driver runs out of memory.
  6. Python functions per row. Plain Python UDFs are slow. Use built-in functions where you can.
  7. Using a cluster for small data. A single machine with a good database or pandas is often faster and cheaper.

Things to watch

๐Ÿ’ฅOut of memory
Executors die when partitions are too big. Raise partitions or memory, or fix the skew.
๐Ÿ”Recomputing
A dataset used twice without cache is rebuilt both times from the source.
๐Ÿ—‚๏ธPartitioning by the wrong column
Writing a file per user floods the lake with tiny files.
โ˜๏ธObject store quirks
Renames and listings are slow on S3. Use a committer or a table format built for it.

11Real-World Examples

๐ŸŒYahoo and Facebook
Ran some of the first huge Hadoop clusters for search, ads and analytics.
๐ŸงฑDatabricks
Created by the makers of Spark. Runs Spark as a managed cloud service.
โ˜๏ธAWS EMR, Google Dataproc, Azure HDInsight
Managed clusters that run Spark and Hadoop tools on demand.
๐Ÿš—Uber and Netflix
Process huge event and trip data with Spark and keep it as open table files in lakes.
โ˜ธ๏ธSpark on Kubernetes
Drivers and executors run as pods, and clusters are created only for the job.
๐ŸHive metastore
Still the common place to keep table definitions for many engines.
๐Ÿ“Note
Many companies have moved off self-run HDFS to cloud storage. The ideas (blocks, partitions, shuffles, DAGs) remain the same.
Mini case: a slow nightly job
๐ŸŒStage 2: 1 task takes 50 minkey = null has 40% of rows
โ†’โ†“filter nulls, or salt the key
โš–๏ธRows spread evenlyevery task finishes in about 3 min
Skew was the problem. Fixing one hot key fixed the whole stage.

12Related Topics to Read Next

MapReduceโ†’

The model that Spark improved on.

Distributed File Systemsโ†’

How HDFS stores and heals its blocks.

Data Lakesโ†’

Where Spark usually reads and writes data.

Parquet and Columnar File Formatsโ†’

The file format Spark likes best.

Workflow Orchestration (Airflow)โ†’

Schedules Spark jobs as part of a pipeline.

Batch vs Stream Processingโ†’

Spark does both with the same engine.

Streaming Enginesโ†’

Spark Structured Streaming compared with other engines.

ETL Pipelinesโ†’

The usual job Spark runs.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Hadoop: HDFS (store) + YARN (schedule) + MapReduce (compute).
  • โœ”Spark: a compute engine that plans a DAG and keeps data in memory.
  • โœ”Lazy: transformations plan, actions run.
  • โœ”Stage: a group of tasks with no shuffle inside. A shuffle ends a stage.
  • โœ”Wide steps (group by, join) cost a shuffle. Filter first.
  • โœ”Common traps: skew, small files, collect, caching everything.
  • โœ”Today: Spark + Parquet on object storage is the usual pattern.
  • โœ”One line: โ€œStore it in pieces, plan the whole job, and move as little data as you can.โ€
โ† Previous
Streaming Engines
Next โ†’
Workflow Orchestration (Airflow)