Module 3 ยท Lecture 12

Apache Spark: The Engine Behind Big Data Streaming

Technology literacy ยท Decision frameworks ยท MBA case studies

โฑ 90 minutes ๐Ÿ“ Prerequisites: Lecture 11 (Windowing) ๐ŸŽ“ Approach: Technology literacy โ€” not Spark development

Contents

  1. Learning Objectives
  2. Session Timeline
  3. The Story of Apache Spark
  4. The Micro-Batch Model
  5. Faculty Demo โ€” Spark in Action
  6. The Decision Framework
  7. Case Studies
  8. Group Exercise
  9. Key Takeaways

Learning Objectives

Session Timeline

TimeSegmentActivity
0โ€“10 minRecapL11 windowing โ€” which window type would you use for fraud?
10โ€“30 minThe Story of SparkWhy it was built, what problem it solved, who uses it
30โ€“45 minMicro-Batch ModelHow Spark Streaming works โ€” trigger intervals explained
45โ€“60 minFaculty DemoLive spark_consumer.py โ€” observe output, understand structure
60โ€“70 minDecision FrameworkWhen Spark is right, when it is overkill
70โ€“82 minCase Study DiscussionFlipkart, Swiggy โ€” why did they choose Spark?
82โ€“88 minGroup Exercise"Which tool?" โ€” match 5 scenarios to the right framework
88โ€“90 minWrap-UpKey takeaways + preview of L13 (Flink)

Section 1: The Story of Apache Spark

The Problem Spark Solved

Before Spark, the dominant big data technology was Hadoop MapReduce (circa 2006โ€“2012). MapReduce was revolutionary โ€” it let you process petabytes of data across thousands of machines. But it had one painful limitation: it read from disk and wrote back to disk between every step of a multi-step job.

MapReduce workflow:
Step 1: Read from disk โ†’ process โ†’ write to disk
Step 2: Read those results from disk โ†’ process โ†’ write to disk again
...
A 10-step ML job = 10 disk reads + 10 disk writes. ~4 hours.

Spark workflow:
Step 1: Read from disk โ†’ keep in memory
Step 2: Process (in memory) โ†’ keep in memory
...
Final: Write result to disk

The same 10-step job: 10โ€“100ร— faster.

Spark's Rise

YearMilestone
2009Created at UC Berkeley AMPLab
2013Donated to Apache Software Foundation
2016Spark 2.0: Structured Streaming API (DataFrame-native)
2021Databricks (Spark's commercial backer) valued at $43 billion
2024~80% of Fortune 500 companies run Spark workloads

Career context: Understanding Spark is the difference between being able to read a data architecture diagram and being confused by one. Even if you never write a Spark job yourself, you will encounter it in vendor proposals, system design documents, and hiring decisions throughout your career.

Section 2: How Spark Streaming Works โ€” The Micro-Batch Model

The Fundamental Design

Spark Structured Streaming collects events for a short interval (the trigger interval), then processes that chunk as a mini-batch, emits results, and repeats. The trigger interval controls the latency vs cost balance:

Trigger IntervalLatencyCostWhen to Use
50ms~50msVery HighNear-real-time financial systems
200ms (default)~200msHighMost production streaming
1 second~1sMediumDashboards, moderate freshness
10 seconds~10sLowAggregations, batch-ish workloads
1 minute~1minVery LowPeriodic summaries

The DataFrame Mental Model

The most important concept: a stream looks like an infinite table. You write almost the same code for batch analysis and live streaming. Your team doesn't need to learn a completely different paradigm.

Traditional table (static): fixed number of rows, same result every query.

Spark Streaming DataFrame (live):
Row 1: arrived 10:01:00
Row 2: arrived 10:01:01
Row 3: arriving right now...
Row 4: arriving in 2 seconds...
  โ†ณ infinite rows; query result changes every trigger interval

What "Distributed" Actually Means

Spark splits your stream across multiple workers (executors), each handling a portion of the load in parallel. On a laptop: one machine, multiple threads. In production: 10โ€“100 machines, each handling a partition of the Kafka topic.

Section 3: Faculty Demo โ€” Spark in Action

This is an observation exercise. Do not install Spark. The goal is to read and understand the code structure.

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, from_json, window, sum as spark_sum, count, avg
from pyspark.sql.types import StructType, StructField, StringType, DoubleType

# 1. Start the Spark engine
spark = SparkSession.builder.appName("SDA-Demo").getOrCreate()

# 2. Read a live Kafka topic โ€” creates an "infinite DataFrame"
raw_stream = spark.readStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", "localhost:9092") \
    .option("subscribe", "transactions-topic") \
    .load()

# 3. Parse JSON payload into typed columns
parsed = raw_stream.select(from_json(col("value").cast("string"), schema).alias("d")).select("d.*")

# 4. Group by 1-minute tumbling windows โ€” same syntax as batch SQL
windowed = parsed.groupBy(window("timestamp", "1 minute")) \
    .agg(count("*").alias("transactions"), spark_sum("amount").alias("total_spend"))

# 5. Write results every 10 seconds
query = windowed.writeStream.outputMode("update").format("console") \
    .trigger(processingTime="10 seconds").start()
query.awaitTermination()

Discussion questions during demo:

  1. The stream is an "infinite table." Why is that useful to a data engineer?
  2. Point at window("timestamp", "1 minute") โ€” What type of window is this? What happens to events that span two windows?
  3. Point at outputMode("update") โ€” What's the alternative? When would you use "complete" mode?

Section 4: The Spark Decision Framework

Three Questions Before Recommending Spark

Question 1 โ€” How much data?

Question 2 โ€” How fresh must the data be?

Question 3 โ€” What does your team know?

The Organisational Cost โ€” Often Underestimated

CostWhat It Means
InfrastructureCluster or Databricks/EMR โ€” โ‚น15,000โ€“โ‚น5,00,000/month
ExpertiseSpark engineers are 2โ€“3ร— more expensive than general Python engineers
ComplexityDebugging a distributed job is harder than debugging a Python script
Setup timeInitial cluster setup + CI/CD integration: 2โ€“6 weeks engineering time

Section 5: Case Study Discussion

Case A: Flipkart โ€” Big Billion Days

~500 million events/hour during peak. Latency required: <2 minutes for seller dashboards and inventory alerts. Team already Spark-native on Databricks/Azure. Python consumer would be overwhelmed immediately at this scale.

Discussion: At what point in Flipkart's growth would you have made the switch to Spark?

Case B: Swiggy โ€” Delivery ETA Prediction

Multiple simultaneous streams: restaurant POS, driver GPS (every 10s), traffic API data. Spark's MLlib lets the prediction model run in the same pipeline as data processing. Latency required: <30 seconds for ETA updates.

Discussion: What window type would you use for the GPS ping stream โ€” tumbling (every 30s) or sliding (rolling 2 min)?

Case C: Small FinTech โ€” The Counter-Example

200,000 transactions/day = ~2 events/second. Existing Python consumer handles this at 5% CPU utilisation. Spark would add โ‚น40,000/month in Databricks costs + 1 engineer to maintain it. Latency requirement: within 5 minutes.

The right answer: Keep the Python consumer. Revisit Spark when volume exceeds 10M events/day. The mistake is copying what large companies do without scaling the context.

Group Exercise: "Which Tool?"

Work in pairs. For each scenario, select the right tool and justify in 2 sentences.

Options: Manual Python Consumer | Apache Spark | Apache Flink | ksqlDB

#ScenarioYour ChoiceWhy (2 sentences)
1EdTech startup, 5,000 students, real-time quiz score aggregation
2HDFC Bank, 10M transactions/hour, fraud must be flagged < 200ms
3Zepto, order fulfilment metrics per dark store per 5-min window
4Small logistics company, "live" delivery dashboard updated every 10 min
5Stock exchange, trade volume per symbol per second for regulatory reporting

Key Takeaways

โœ“ Key Takeaways โ€” Lecture 12

  1. Spark solved the Hadoop disk I/O problem by keeping data in memory โ€” 10โ€“100ร— faster for multi-step jobs
  2. Structured Streaming = a stream that looks like an infinite DataFrame โ€” same code style as batch SQL
  3. Micro-batch model: events collected for a trigger interval (~200ms default), then processed as a mini-batch
  4. Spark is right when: volume > 10M events/day, latency > 200ms acceptable, team knows Python/SQL
  5. Spark is NOT right when: small scale, latency < 100ms needed, no infra/expertise, simple use case
  6. Organisational cost is real โ€” infrastructure, hiring, and complexity are often underestimated

Preview โ€” Lecture 13: Apache Flink & True Streaming

Where Spark's micro-batch model falls short, and when the extra cost of Flink is actually justified. Think about: NPCI processes ~4 billion UPI transactions/month. Fraud must be flagged in <300ms. Is Spark's micro-batch sufficient?