The user wants a streaming ETL (Extract, Transform, Load) system with two specific constraints:
Exactly-once semantics: Every record is processed exactly once. No duplicates, no data loss due to retries.
Late data: The system must handle events that arrive after a certain processing window has technically closed.
Technology Stack Selection:
Apache Kafka is the industry standard for the transport layer (Source and Sink). It supports transactions, which are crucial for exactly-once processing.
Apache Flink is the best fit for the processing engine. It has native support for exactly-once semantics via checkpointing/snapshots and handles event time processing (watermarks) for late data gracefully (side outputs, allowed lateness).
Language: Python (PyFlink) or Java/Scala. I'll use Python (PyFlink) because it's widely accessible for data engineering tasks, though Java is often preferred for high-performance production systems. I will stick to the PyFlink Table API or DataStream API. The DataStream API gives more control over the specific requirements (late data handling).
Key Concepts to Implement:
Source: A Kafka topic.
Watermarks & Event Time: Essential for handling late data. We need to define how late is "too late."
Windowing: Grouping data to aggregate it (a common ETL task).
Late Data Handling: What to do with data arriving after the watermark? Flink allows "allowed lateness" (re-triggering the window) or "side outputs" (collecting late data separately).
Sink: Another Kafka topic or a database.
Exactly-Once Transaction: This requires configuration in Kafka producers and Flink's checkpointing.
Drafting the Code Structure (Mental or Scratchpad):
Setup: Environment settings, Kafka connections.
Checkpointing: Enable checkpointing in Flink. This is the heart of exactly-once state consistency.
Source: Read from Kafka. Assign timestamps and watermarks (e.g., BoundedOutOfOrdernessTimestampExtractor).
Transformation:
KeyBy some ID.
Window (e.g., TumblingEventTimeWindows).
Allowed Lateness (e.g., 1 minute).
ProcessWindowFunction (to aggregate).
Side Output tag for data that is still late after the allowed lateness.
Sink: Write to Kafka. Enable transactional writes (Semantic.EXACTLY_ONCE).
Output Late Data: Sink the side output to a separate storage (e.g., "late_events" topic).
Refining the Logic:
Scenario: Let's say we are processing user clicks.
Source: clicks-topic
Key: user_id
Window: 1 minute.
Allowed Lateness: 1 minute (updates the result).
Late Data Side Output: Anything later than 1 minute late goes to late-clicks-topic.
Sink: aggregated-clicks-topic.
Code Specifics (PyFlink):
python
env = StreamExecutionEnvironment.get_execution_environment()
# 1. Exactly-Once Checkpointing
env.enable_checkpointing(1000) # 1 second
env.get_checkpoint_config().set_checkpointing_mode(CheckpointingMode.EXACTLY_ONCE)
# 2. Kafka Source
kafka_source = KafkaSource.builder() ...
# 3. Watermarks (Handling late data logic start)
# We need to extract the timestamp from the JSON payload.
# 4. Window & Late Data Handling
windowed = stream.key_by(...).window(TumblingEventTimeWindows.of(Time.minutes(1))) \
.allowed_lateness(Time.minutes(1)) \
.side_output_late_data(late_output_tag)
# 5. Sink
# Use Kafka Sink with EXACTLY_ONCE delivery guarantee.
Explanation: Break down why this achieves exactly-once and handles late data.
Self-Correction/Edge Cases:
Issue: Flink's exactly-once sink to Kafka requires specific Kafka version support (Kafka 0.11+).
Issue: Two-phase commit (2PC) is the mechanism. Flink coordinates this.
Late Data: I need to show both "Allowed Lateness" (updating the window) and "Side Outputs" (catching the hopeless stragglers). This shows a robust understanding.
Final Plan:
Define the architecture.
Provide the PyFlink implementation.
Explain the "Exactly-Once" mechanism (Checkpointing + 2PC).
Explain the "Late Data" mechanism (Watermarks + Allowed Lateness + Side Outputs).
Let's write the Python code.
Import necessary classes.
Define StreamExecutionEnvironment.
Set checkpointing interval.
Set CheckpointingMode.EXACTLY_ONCE.
Define Kafka Source (Source 1).
Define Deserialization schema (SimpleStringSchema or JSON).
Let's double-check the PyFlink syntax for KafkaSink and KafkaSource as it changed in recent versions (Flink 1.13/1.14+ unified Source/Sink API). I will use the modern API.
Wait, for a Python user, they might need PyFlink installed via pip.
This looks solid. I will present this with explanations.
One specific detail: To guarantee end-to-end exactly-once, the Sink must support transactions. Kafka does. The external system reading from Kafka must also handle transactions properly (read_committed), but usually, that's outside the scope of the ETL code itself, though worth mentioning.
Let's refine the late data explanation.
Watermark: Defines "current time" based on event timestamps. Allows for out-of-order data within a bound (e.g., 5 seconds).
Window: Collects data.
Fire: When watermark passes window_end.
Allowed Lateness: Even after firing, if late data arrives within this grace period, the window re-fires with updated results.
Side Output: If data arrives after the allowed lateness, it goes to the side output so it's not dropped silently.
This is a complete solution. I will write the response now.
This implementation uses Apache Flink (PyFlink).
Flink is the industry standard for this requirement because it natively supports:
Exactly-once semantics via Checkpointing and Two-Phase Commits (Sink).
Event Time processing using Watermarks to handle late data correctly.
Architecture
Source: Kafka (Raw JSON events).
Processing: Flink (Aggregates by Window).
Sink: Kafka (Processed results).
Late Data Handling:
Allowed Lateness: Windows stay open for an extra grace period.
Side Outputs: Data arriving after the grace period is redirected to a "dead letter" queue (late events topic) so it isn't dropped silently.
Prerequisites
You need a running Kafka instance and the PyFlink library.
bash
pip install apache-flink
The Implementation
python
Explanation of Key Components
1. Exactly-Once Semantics
This is achieved through a combination of configuration:
Checkpointing (env.enable_checkpointing): Flink takes snapshots of the state (windows, offsets) periodically.
Source: The Kafka Source commits offsets to the checkpoint.
Sink (DeliveryGuarantee.EXACTLY_ONCE): The Kafka Sink utilizes Two-Phase Commit (2PC).
Phase 1 (Pre-commit): During a checkpoint, Flink writes data to Kafka but marks the transaction as "pending."
Phase 2 (Commit): Once the checkpoint is globally successful (all operators acknowledge), Flink commits the transaction, making the data visible to consumers. If a failure occurs mid-way, the transaction is rolled back.
2. Event Time & Watermarks
assign_timestamps_and_watermarks: We tell Flink to use the timestamp field inside the JSON event, not the system clock.
for_bounded_out_of_orderness(Duration.of_seconds(5)): This sets the "Wait Time." If an event arrives with a timestamp of 12:00:00, Flink waits until 12:00:05 (system time) before closing the window for 12:00:00. This handles mild delays.
3. Late Data Strategy
We implemented a two-tier strategy for data arriving after the watermark has passed:
Allowed Lateness (allowed_lateness): Even after the window fires (results are emitted), we keep the window state in memory for an extra 5 seconds. If a late record arrives within this grace period, the window re-fires with the updated total.
Side Outputs (side_output_late_data): If data arrives after the grace period, the window state is cleared. The standard approach is to drop it, but in robust ETL, we use get_side_output to redirect these specific events to a quarantine-late-events topic. This ensures no data loss; you can manually reprocess the quarantine topic later.
from pyflink.datastream import StreamExecutionEnvironment, TimeCharacteristic
from pyflink.datastream.connectors.kafka import KafkaSource, KafkaSink, KafkaRecordSerializationSchema
from pyflink.datastream.connectors import DeliveryGuarantee
from pyflink.common import Types, SimpleStringSchema, WatermarkStrategy, Duration
from pyflink.datastream.window import TumblingEventTimeWindows
from pyflink.datastream.functions import ProcessWindowFunction, KeySelector
from pyflink.common.typeinfo import Types
import json
import datetime
# ------------------------------------------------------------------------
# 1. Setup Environment
# ------------------------------------------------------------------------
env = StreamExecutionEnvironment.get_execution_environment()
# CRITICAL: Set Time Characteristic to Event Time (for late data handling)
env.set_stream_time_characteristic(TimeCharacteristic.EventTime)
# CRITICAL: Enable Checkpointing (for Exactly-Once semantics)
# Checkpoint every 5000ms (5 seconds)
env.enable_checkpointing(5000)
# Ensure the checkpointing mode is EXACTLY_ONCE
env.get_checkpoint_config().set_checkpointing_mode(org.apache.flink.streaming.api.CheckpointingMode.EXACTLY_ONCE)
# ------------------------------------------------------------------------
# 2. Define Kafka Source (Exactly-Once Starts Here)
# ------------------------------------------------------------------------
# We read from a 'transactions' topic
kafka_source = KafkaSource.builder() \
.set_bootstrap_servers("localhost:9092") \
.set_topics("transactions") \
.set_group_id("flink-etl-group") \
.set_starting_offsets(org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer.earliest()) \
.set_value_only_deserializer(SimpleStringSchema()) \
.build()
# Create the DataStream
stream = env.from_source(kafka_source, WatermarkStrategy.no_watermarks(), "Kafka Source")
# ------------------------------------------------------------------------
# 3. Define Logic: Parsing, Watermarks, and Windowing
# ------------------------------------------------------------------------
def parse_json(record):
"""Extracts event time and data from JSON string."""
try:
data = json.loads(record)
# Example: {"user": "alice", "amount": 10, "timestamp": 1678888888}
return (data['user'], data['amount'], data['timestamp'] * 1000) # Convert to ms
except:
return None
# Map to Tuple and assign Timestamps/Watermarks
# Watermark = MaxTimestamp - 5 seconds (Out of orderness tolerance)
# This means we wait 5s for late data before closing the window logically.
parsed_stream = stream.map(parse_json, Types.TUPLE([Types.STRING(), Types.INT(), Types.LONG()])) \
.filter(lambda x: x is not None) \
.assign_timestamps_and_watermarks(
WatermarkStrategy.for_bounded_out_of_orderness(Duration.of_seconds(5))
.with_timestamp_assigner(lambda event, timestamp: event[2])
)
# ------------------------------------------------------------------------
# 4. Define Window Aggregation and Late Data Handling
# ------------------------------------------------------------------------
# Define a tag for late data
late_data_tag = "late-data-side-output"
class MyWindowFunction(ProcessWindowFunction):
def process(self, key, context, elements):
# Simple aggregation: sum amounts
total = sum([e[1] for e in elements])
return [f"User: {key}, Total: {total}, WindowEnd: {context.window.end}"]
# KeyBy User, Tumbling Window of 10 seconds
result_stream = parsed_stream \
.key_by(lambda e: e[0]) \
.window(TumblingEventTimeWindows.of(datetime.timedelta(seconds=10))) \
.allowed_lateness(datetime.timedelta(seconds=5)) \
.side_output_late_data(late_data_tag) \
.process(MyWindowFunction(), Types.STRING())
# ------------------------------------------------------------------------
# 5. Define Kafka Sink (Exactly-Once Ends Here)
# ------------------------------------------------------------------------
# Serialize the main result stream back to string for Kafka
# Flink's Kafka Sink uses Two-Phase Commit to ensure data is written
# only when the checkpoint completes successfully.
kafka_sink = KafkaSink.builder() \
.set_bootstrap_servers("localhost:9092") \
.set_record_serializer(KafkaRecordSerializationSchema.builder()
.set_topic("processed-results")
.set_value_serialization_schema(SimpleStringSchema())
.build()
) \
.set_delivery_guarantee(DeliveryGuarantee.EXACTLY_ONCE) \
.build()
result_stream.sink_to(kafka_sink)
# Handle the Late Data (Side Output) -> Write to separate topic for reprocessing
late_stream = result_stream.get_side_output(late_data_tag)
# Sink late data to a 'quarantine' topic
late_sink = KafkaSink.builder() \
.set_bootstrap_servers("localhost:9092") \
.set_record_serializer(KafkaRecordSerializationSchema.builder()
.set_topic("quarantine-late-events")
.set_value_serialization_schema(SimpleStringSchema())
.build()
) \
.set_delivery_guarantee(DeliveryGuarantee.AT_LEAST_ONCE) \
.build()
late_stream.sink_to(late_sink)
# ------------------------------------------------------------------------
# 6. Execute
# ------------------------------------------------------------------------
env.execute("Streaming ETL with Exactly-Once and Late Data")