Skip to main content
PYSPARK โ€ข LESSON 279

Custom Micro-Batch Writing with foreachBatch

How can we write streaming micro-batches to multiple destination tables or perform Delta Lake MERGE operations?

Productionโฑ 3 Minutesโญ 880 XP
๐Ÿค” THE QUESTION

How can we write streaming micro-batches to multiple destination tables or perform Delta Lake MERGE operations?

๐Ÿ’ก WHAT IS IT?

foreachBatch(process_batch_fn) executes custom programmatic logic on each micro-batch DataFrame as standard batch data.

๐ŸŽฏ WHAT IS IT USED FOR?

Upserting stream data into Lakehouse tables (MERGE INTO) and writing simultaneously to Redis cache and Parquet lake.

๐Ÿ’ป EXAMPLE
def process_batch(batch_df, batch_id):
    batch_df.persist()
    batch_df.write.mode("append").parquet("s3://lakehouse/silver/events/")
    batch_df.unpersist()

query = streaming_df.writeStream.foreachBatch(process_batch).option("checkpointLocation", "/tmp/cp/").start()

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Custom Micro-Batch Writing with foreachBatch.

  • โœ“ foreachBatch() custom sink
  • โœ“ Micro-batch processing function
  • โœ“ Multi-sink streaming publishing