Showing posts with label PySpark. Show all posts
Showing posts with label PySpark. Show all posts

How to Fix the Kafka Small File Problem in Amazon S3 & GCS



1. Introduction

When building real-time streaming architectures with Apache Kafka, streaming directly into cloud storage (like Amazon S3 or Google Cloud Storage) seems straightforward. However, high-throughput topics written with low batch timeouts quickly create millions of micro-files—often under 1 MB each.

This "Small File Problem" leads to two massive issues:

  1. Exploding Cloud Costs: AWS charges per 1,000 PUT requests ($0.005 per 1,000 requests adds up fast when writing 100 files/second).

  2. Abysmal Query Speeds: Query engines like AWS Athena, Trino, and Snowflake must open, read, and close thousands of separate file footers, slowing down analytical queries from seconds to minutes.

In this guide, we’ll explore how to configure Kafka Connect (S3 Sink Connector) and PySpark Structured Streaming to batch, compress, and optimize real-time data before it hits long-term storage.

2. Solution Strategy 1: Tuning Kafka Connect S3 Sink

If you are using Kafka Connect, the key is balancing Latency vs. File Size. You should target file sizes between 128 MB and 512 MB per object.

Modify your connect-s3-sink.json configuration with these three parameters:

{
"name": "s3-sink-telemetry-optimized",
"config": {
"connector.class": "io.confluent.connect.s3.S3SinkConnector",
"tasks.max": "4",
"topics": "telemetry-events",
"s3.bucket.name": "datatipss-analytics-lake",
"s3.part.size": "67108864",
"flush.size": "100000",
"rotate.interval.ms": "300000",
"storage.class": "io.confluent.connect.s3.storage.S3Storage",
"format.class": "io.confluent.connect.s3.format.parquet.ParquetFormat",
"parquet.compression": "SNAPPY",
"schema.compatibility": "NONE"
}
}

Why these settings matter:

  • s3.part.size = 67108864 (64 MB): Sets the minimum upload buffer part size for multi-part uploads.

  • flush.size = 100000: Forces a file write only after accumulating 100,000 records.

  • rotate.interval.ms = 300000 (5 minutes): Guarantees files are committed at least every 5 minutes so low-volume topics don't leave data stuck in memory forever.

3. Solution Strategy 2: Dynamic Repartitioning in PySpark

If you consume Kafka with PySpark Structured Streaming, simply saving the stream using .writeStream without repartitioning will create one file per Kafka partition for every trigger interval.

To avoid thousands of micro-partitions, use .repartition() or configure Trigger Intervals combined with Snappy-compressed Parquet:

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, from_json
from pyspark.sql.types import StructType, StringType, TimestampType

spark = SparkSession.builder \
.appName("KafkaToS3BatchOptimizer") \
.config("spark.sql.parquet.compression.codec", "snappy") \
.getOrCreate()

# 1. Read from Kafka
kafka_stream = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092") \
.option("subscribe", "user-clicks") \
.option("startingOffsets", "latest") \
.load()

# 2. Process Data Payload
schema = StructType().add("user_id", StringType()).add("action", StringType())

processed_df = kafka_stream \
.selectExpr("CAST(value AS STRING) as json_payload") \
.select(from_json(col("json_payload"), schema).alias("data")) \
.select("data.*")

# 3. Write with Trigger Processing Time to enforce batching
query = processed_df.repartition(2) \
.writeStream \
.format("parquet") \
.option("path", "s3a://datatipss-data-lake/user-clicks/") \
.option("checkpointLocation", "s3a://datatipss-data-lake/checkpoints/user-clicks/") \
.trigger(processingTime="5 minutes") \
.start()

query.awaitTermination()

4. Production Best Practices: Compaction Jobs

Even with batching, spike traffic can occasionally produce sub-optimal file sizes. Implement an automated Compaction Job (using Delta Lake OPTIMIZE or PySpark) that runs overnight to rewrite micro-files into uniform 512 MB Parquet files.

The Silent Pipeline Killer: Handling Real-Time Schema Drift in Apache Spark



In modern data engineering, the only constant is change—and nowhere is that more true than in source data schemas. Upstream application teams release new features, modify API payloads or rename database columns without giving data teams a heads-up. 

When your ETL or ELT pipeline expects a rigid schema and encounters an unexpected field or a modified data type, the result is usually a catastrophic failure: broken jobs at 3:00 AM, corrupted data warehouses, and inaccurate executive dashboards.

This phenomenon—Schema Drift—is one of the most common causes of silent pipeline failures. In this guide, we’ll explore how to handle real-time schema drift in Apache Spark using Delta Lake, showing you how to implement Schema Evolution, enforce data quality gates, and route un-parseable records to a Dead Letter Queue (DLQ) without bringing down your entire data infrastructure.

1. The Nightmare: "Column 'user_id' Not Found"

Imagine waking up to a broken production pipeline at 3:00 AM because an upstream team changed user_id to userId or added a new JSON field to their API response. Traditional rigid schemas break instantly when source data changes.

2. The Strategy: Schema Enforcement vs. Schema Evolution

  • Schema Enforcement (Gatekeeper): Rejects any data that doesn't strictly match the target schema to protect warehouse integrity.

  • Schema Evolution (Adaptability): Automatically updates the target Delta table schema when new columns are introduced in the source.

3. The Implementation: PySpark & Delta Lake

from pyspark.sql import SparkSession

spark = SparkSession.builder \
.appName("SchemaDriftHandler") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.getOrCreate()

# Read streaming or batch data with schema inference
df_incoming = spark.readStream \
.format("json") \
.option("cloudFiles.schemaLocation", "/path/to/schema/checkpoint") \
.load("/path/to/incoming/data/")

# Write with Schema Evolution enabled (.option("mergeSchema", "true"))
df_incoming.writeStream \
.format("delta") \
.option("mergeSchema", "true") \
.option("checkpointLocation", "/path/to/checkpoint") \
.start("/path/to/delta/table")

4. Handling Bad Data: The "Dead Letter Queue" (DLQ) Pattern

When schema changes are destructive (e.g., changing a data type from Integer to String), mergeSchema isn't enough. The professional best practice is routing malformed records to a Corrupt Record Path / Dead Letter Queue so valid records keep processing uninterrupted.


Conclusion

Handling schema drift isn't about blocking changes—it's about building resilient, self-healing pipelines that gracefully adapt to evolving business logic. By combining Delta Lake’s mergeSchema capabilities with proactive schema tracking and Dead Letter Queue (DLQ) patterns,you transform pipeline-breaking schema changes into manageable, automated background workflows.

How to Prevent SQL Injection & Bulk Data Exfiltration in Production Databases

  Defending Production Databases: Preventing SQL Injection and Bulk Data Exfiltration 1. Introduction If you inspect the raw access logs or ...