๐Ÿ“ŠData Engineering

Apache Flink

A stream and batch processing framework

Detailed Explanation

Apache Flink is a distributed processing engine that handles unbounded streams and bounded streams (batch) in a unified way. It adopts a "stream-first" architecture and treats batch processing as a special form of streaming. This allows real-time and batch processing to be performed with the same API and runtime.

Flink's key strengths are event-time processing and exactly-once guarantees. Through the watermark mechanism, it accurately processes late-arriving events, and through checkpointing, it can recover without data loss even when failures occur.

It also excels at stateful processing. It supports keyed state and operator state, and with the RocksDB backend it can manage state larger than memory. Through savepoints, state can be preserved even when upgrading an application.

It provides Flink SQL and the Table API, so stream processing is also possible with SQL queries. Through the dynamic table concept, stream data can be handled like a table, and through CDC (Change Data Capture) connectors, database changes can be captured and processed in real time.

Code Example

Python Click to copy
# PyFlink ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ ์˜ˆ์ œ

from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import (
    KafkaSource, KafkaOffsetsInitializer, KafkaSink, KafkaRecordSerializationSchema
)
from pyflink.datastream.functions import MapFunction, KeyedProcessFunction, RuntimeContext
from pyflink.datastream.state import ValueStateDescriptor
from pyflink.common import Types, WatermarkStrategy, Duration
from pyflink.common.serialization import SimpleStringSchema
import json

# ์‹คํ–‰ ํ™˜๊ฒฝ ์„ค์ •
env = StreamExecutionEnvironment.get_execution_environment()
env.set_parallelism(4)

# ์ฒดํฌํฌ์ธํŒ… ์„ค์ • (exactly-once ๋ณด์žฅ)
env.enable_checkpointing(60000)  # 60์ดˆ๋งˆ๋‹ค ์ฒดํฌํฌ์ธํŠธ
env.get_checkpoint_config().set_min_pause_between_checkpoints(30000)

# ==========================================
# 1. Kafka Source ์„ค์ •
# ==========================================

kafka_source = KafkaSource.builder() \
    .set_bootstrap_servers("kafka:9092") \
    .set_topics("user-events") \
    .set_group_id("flink-processor") \
    .set_starting_offsets(KafkaOffsetsInitializer.earliest()) \
    .set_value_only_deserializer(SimpleStringSchema()) \
    .build()

# ์›Œํ„ฐ๋งˆํฌ ์ „๋žต (์ด๋ฒคํŠธ ์‹œ๊ฐ„ ๊ธฐ๋ฐ˜)
watermark_strategy = WatermarkStrategy \
    .for_bounded_out_of_orderness(Duration.of_seconds(10)) \
    .with_timestamp_assigner(lambda event, ts: json.loads(event)['timestamp'])

# ์†Œ์Šค ์ŠคํŠธ๋ฆผ ์ƒ์„ฑ
events = env.from_source(
    kafka_source,
    watermark_strategy,
    "Kafka Source"
)

# ==========================================
# 2. ์‚ฌ์šฉ์ž ์„ธ์…˜ ๋ถ„์„ (Stateful Processing)
# ==========================================

class SessionAggregator(KeyedProcessFunction):
    """์‚ฌ์šฉ์ž๋ณ„ ์„ธ์…˜ ์ง‘๊ณ„ (์ƒํƒœ ์œ ์ง€)"""

    def open(self, runtime_context: RuntimeContext):
        # ์ƒํƒœ ์ดˆ๊ธฐํ™”
        self.session_state = runtime_context.get_state(
            ValueStateDescriptor("session", Types.STRING())
        )
        self.event_count = runtime_context.get_state(
            ValueStateDescriptor("count", Types.INT())
        )

    def process_element(self, event, ctx):
        data = json.loads(event)
        user_id = data['user_id']

        # ํ˜„์žฌ ์ƒํƒœ ๊ฐ€์ ธ์˜ค๊ธฐ
        current_session = self.session_state.value()
        count = self.event_count.value() or 0

        # ์„ธ์…˜ ํƒ€์ž„์•„์›ƒ ํƒ€์ด๋จธ ๋“ฑ๋ก (30๋ถ„)
        ctx.timer_service().register_event_time_timer(
            ctx.timestamp() + 30 * 60 * 1000
        )

        # ์ƒํƒœ ์—…๋ฐ์ดํŠธ
        self.event_count.update(count + 1)

        if current_session is None:
            # ์ƒˆ ์„ธ์…˜ ์‹œ์ž‘
            self.session_state.update(data.get('session_id'))
            yield json.dumps({
                'user_id': user_id,
                'event': 'session_start',
                'timestamp': data['timestamp']
            })

        yield json.dumps({
            'user_id': user_id,
            'event_type': data['event_type'],
            'session_events': count + 1
        })

    def on_timer(self, timestamp, ctx):
        # ์„ธ์…˜ ์ข…๋ฃŒ
        count = self.event_count.value()
        yield json.dumps({
            'user_id': ctx.get_current_key(),
            'event': 'session_end',
            'total_events': count,
            'timestamp': timestamp
        })
        # ์ƒํƒœ ํด๋ฆฌ์–ด
        self.session_state.clear()
        self.event_count.clear()

# ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ ํŒŒ์ดํ”„๋ผ์ธ
processed = events \
    .map(lambda x: json.loads(x)) \
    .key_by(lambda x: x['user_id']) \
    .process(SessionAggregator())

# ==========================================
# 3. Flink SQL๋กœ ์‹ค์‹œ๊ฐ„ ์ง‘๊ณ„
# ==========================================

from pyflink.table import StreamTableEnvironment, EnvironmentSettings

# Table ํ™˜๊ฒฝ ์„ค์ •
settings = EnvironmentSettings.new_instance().in_streaming_mode().build()
t_env = StreamTableEnvironment.create(env, settings)

# Kafka ํ…Œ์ด๋ธ” ์ •์˜
t_env.execute_sql("""
    CREATE TABLE user_events (
        user_id STRING,
        event_type STRING,
        amount DECIMAL(10, 2),
        event_time TIMESTAMP(3),
        WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
    ) WITH (
        'connector' = 'kafka',
        'topic' = 'user-events',
        'properties.bootstrap.servers' = 'kafka:9092',
        'properties.group.id' = 'flink-sql',
        'format' = 'json',
        'scan.startup.mode' = 'latest-offset'
    )
""")

# ์œˆ๋„์šฐ ์ง‘๊ณ„ ์ฟผ๋ฆฌ
t_env.execute_sql("""
    SELECT
        user_id,
        TUMBLE_START(event_time, INTERVAL '1' MINUTE) AS window_start,
        COUNT(*) AS event_count,
        SUM(amount) AS total_amount
    FROM user_events
    WHERE event_type = 'purchase'
    GROUP BY
        user_id,
        TUMBLE(event_time, INTERVAL '1' MINUTE)
""")

# ์‹คํ–‰
env.execute("User Session Analysis")

How It's Used in Practice

Data Engineer: "We currently process with Spark Streaming, but we get about a minute of latency. Can we reduce it further?"

Tech Lead: "If you switch to Flink, millisecond-level latency is possible. It's true stream processing, so there's no micro-batch overhead."

Data Engineer: "How about state management? We currently store intermediate state in Redis."

Tech Lead: "Flink has built-in state management, so you don't need an external store. With the RocksDB backend, it can even handle terabyte-scale state."

Interviewer: "How is Flink's exactly-once guarantee implemented?"

Candidate: "It is based on Chandy-Lamport, a distributed snapshot algorithm. Checkpoint barriers propagate through the stream, and each operator snapshots its state. In case of failure, processing restarts from the last checkpoint."

Interviewer: "What happens if the watermark doesn't advance?"

Candidate: "If no events arrive from a particular partition, the watermark stalls. You can detect idle partitions with the Idleness setting, or configure a Processing Time fallback."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "The checkpoint interval is 10 seconds, but if the state size is large, backpressure can occur."

Developer: "What's an appropriate interval?"

Reviewer: "It depends on state size and throughput, but 1-5 minutes is usually reasonable. Also, enabling incremental checkpointing greatly reduces checkpoint time."

Cautions

Related Terms

Learn More