PySpark Architecture
Section 7 • Real-Time Streaming, Message Queues & CDC

Apache Kafka, AWS Kinesis & Debezium CDC Streaming

Understand how Spark Structured Streaming distributes continuous data streams. Learn why topic partitions dictate maximum parallel executor tasks, how to manage consumer lag spikes, and how RocksDB state store prevents GC crashes in stateful stream joins.

1. Interactive Streaming & CDC Hardware Stress Simulator

Simulate Kafka Consumer Lag, Shards & RocksDB Memory Stress
Cluster Worker Nodes: (Scale workers to verify topic partition thread distribution & consumer lag relief)
Topic Partitions / Shards: 16 Partitions
Max concurrent consumer threads in Spark
Message Ingestion Velocity: 50,000 msgs/sec
Incoming event throughput per second
Active Consumer Tasks 16 Tasks
Ingestion Throughput 195.3 MB/s
Consumer Lag 0 Msgs (Healthy)
End-to-End P99 Latency 142 ms
RocksDB State Memory 1.4 GB / Worker

Cluster Node Telemetry Under Streaming & CDC Load

Balanced Topic Partitions • Zero Lag Backlog
Driver / Master STREAM COORDINATOR
CPU Load22%
JVM Heap Buffer2.4 / 8.0 GB
WAL Commit: 24ms Active

2. The Golden Rule of Streaming: Topic Partitions & Executor Cores

Interactive Animated Simulator: More Data & Less Cores vs. Less Data & More Cores

The Immutable Law: Exactly 1 Spark Task per Kafka Topic Partition

In Spark Structured Streaming, Spark does NOT hash or re-partition incoming Kafka data on read. Instead, it enforces a strict 1-to-1 mapping: 1 Kafka Topic Partition is read by at most 1 Spark Task thread. Understanding this rule reveals why adding cores to an under-partitioned topic wastes 100% of your cloud spend, and why under-provisioning cores triggers catastrophic lag spikes!

16 Partitions
2 (Under-partitioned) 8 (Balanced) 16 (High Throughput)
4 Cores
2 Cores (Small) 8 Cores 16 Cores (Large)
200,000 msgs/s
10k msgs/s (Light) 100k msgs/s 250k msgs/s (Flood)
Core Saturation 4 / 4 (100% Active) 0 Idle Cores
Task Waves per Batch 4 Waves (16 ÷ 4) 12 Partitions Waiting
Batch Duration vs Trigger 3,850ms / 1,000ms FALLING BEHIND!
Consumer Lag Growth +150k msgs/sec Runaway Lag Spike
Cloud Cost Efficiency 100% Silicon Used 0% Waste
Live Topology: Kafka Topic Partitions → Persistent TCP Sockets → Spark Cores
Kafka Cluster (Port 9092)
Topic: txn_events (16 Parts)
TCP Fetch Sockets
Spark Worker Cores
Cluster: 4 Cores Available
Scenario Strategy Topic Partitions vs Cores Hardware Impact Production Failure Mode & Solution
⚠️ More Data, Less Cores Partitions (16) >> Cores (4) Cores overloaded at 100% CPU. Tasks process in 4 sequential waves. Memory buffers fill up. Disaster: Batch duration exceeds trigger window → Runaway Consumer Lag → Driver OOM crash. Fix: Scale up Spark executor cores or partition batch intervals.
💸 Less Data, More Cores Partitions (4) << Cores (16) Only 4 cores consume data. The remaining 12 cores sit 100% idle at 0% CPU. Starvation: Adding nodes yields 0% speedup because 1 partition cannot be split across 2 consumers! Fix: Increase Kafka topic partitions to match cluster cores.
⭐️ The Golden Ratio (Balanced) Partitions ≥ Cores (e.g. 8 : 8 or 16 : 8) 100% Core saturation. Each core handles 1 or 2 partitions in parallel. CPU load steady at 65-75%. Optimal: Sub-second micro-batch execution, zero consumer lag, 100% cloud spend ROI.

3. Change Data Capture (CDC) with Debezium WAL Streaming

Real-time database replication into Delta Lake & Iceberg

Debezium reads the transaction write-ahead log (WAL) from PostgreSQL, MySQL, or Oracle and emits row-level change events (INSERT, UPDATE, DELETE) into Kafka. PySpark consumes the CDC stream and merges changes into Delta Lake or Iceberg tables using MERGE INTO operations.

python • cdc_delta_merge.py
# PySpark CDC Micro-Batch MERGE INTO Delta Lake
def merge_cdc_batch(batch_df, batch_id):
    from delta.tables import DeltaTable
    delta_table = DeltaTable.forPath(spark, "s3://lakehouse/customers_gold/")
    
    delta_table.alias("tgt").merge(
        batch_df.alias("src"),
        "tgt.customer_id = src.customer_id"
    ).whenMatchedUpdate(
        condition = "src.op = 'u'",
        set = { "name": "src.after.name", "email": "src.after.email", "updated_at": "src.ts_ms" }
    ).whenMatchedDelete(
        condition = "src.op = 'd'"
    ).whenNotMatchedInsert(
        condition = "src.op = 'c'",
        values = { "customer_id": "src.after.customer_id", "name": "src.after.name", "email": "src.after.email" }
    ).execute()