๐Ÿ“Š Data Engineering

Flink

Apache Flink

A real-time stream processing framework. Strong at event-time processing.

Detailed Explanation

Apache Flink is a distributed processing engine for stateful computations over unbounded and bounded data streams. It natively supports Event Time processing and Exactly-Once semantics.

Key Features of Flink

  • Event time processing: Handling of late data based on Watermarks
  • State management: Consistent management of large-scale state and checkpointing
  • Exactly-Once guarantee: Failure recovery based on distributed snapshots
  • Low latency: Real-time processing at the millisecond level
  • Unified batch/stream: Batch and stream processing with the same API

Flink vs Spark Streaming Comparison

ItemFlinkSpark Streaming
Processing ModelTrue StreamingMicro-batch
LatencyMillisecondsSeconds
Event TimeNative supportSupported in Structured Streaming
State ManagementBuilt-in state backendLimited
SQL SupportFlink SQLSpark SQL

Code Example

Python (PyFlink) stream processing

# PyFlink๋ฅผ ์‚ฌ์šฉํ•œ ์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import (
    KafkaSource, KafkaOffsetsInitializer, KafkaSink,
    KafkaRecordSerializationSchema
)
from pyflink.common import WatermarkStrategy, Types
from pyflink.common.serialization import SimpleStringSchema
from pyflink.datastream.window import TumblingEventTimeWindows
from pyflink.common.time import Time, Duration
from pyflink.datastream.functions import ProcessWindowFunction
import json

# ์‹คํ–‰ ํ™˜๊ฒฝ ์„ค์ •
env = StreamExecutionEnvironment.get_execution_environment()
env.set_parallelism(4)
env.enable_checkpointing(60000)  # 1๋ถ„๋งˆ๋‹ค ์ฒดํฌํฌ์ธํŒ…

# Kafka ์†Œ์Šค ์„ค์ •
kafka_source = KafkaSource.builder() \
    .set_bootstrap_servers("kafka:9092") \
    .set_topics("user-events") \
    .set_group_id("flink-consumer-group") \
    .set_starting_offsets(KafkaOffsetsInitializer.latest()) \
    .set_value_only_deserializer(SimpleStringSchema()) \
    .build()

# Watermark ์ „๋žต (์ด๋ฒคํŠธ ์‹œ๊ฐ„ ๊ธฐ๋ฐ˜)
watermark_strategy = WatermarkStrategy \
    .for_bounded_out_of_orderness(Duration.of_seconds(5)) \
    .with_timestamp_assigner(
        lambda event, timestamp: json.loads(event)['event_time']
    )

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

# ์ด๋ฒคํŠธ ํŒŒ์‹ฑ ๋ฐ ํ‚ค ์ถ”์ถœ
def parse_event(event_str):
    event = json.loads(event_str)
    return (event['user_id'], event)

parsed_stream = stream.map(
    parse_event,
    output_type=Types.TUPLE([Types.STRING(), Types.MAP(Types.STRING(), Types.STRING())])
)

# ์œˆ๋„์šฐ ์ง‘๊ณ„
class EventCountWindowFunction(ProcessWindowFunction):
    def process(self, key, context, elements):
        count = len(list(elements))
        window_start = context.window().start
        window_end = context.window().end
        yield {
            'user_id': key,
            'event_count': count,
            'window_start': window_start,
            'window_end': window_end
        }

# 5๋ถ„ ํ…€๋ธ”๋ง ์œˆ๋„์šฐ๋กœ ์‚ฌ์šฉ์ž๋ณ„ ์ด๋ฒคํŠธ ์ง‘๊ณ„
result_stream = parsed_stream \
    .key_by(lambda x: x[0]) \
    .window(TumblingEventTimeWindows.of(Time.minutes(5))) \
    .process(EventCountWindowFunction())

# ๊ฒฐ๊ณผ๋ฅผ Kafka๋กœ ์ „์†ก
kafka_sink = KafkaSink.builder() \
    .set_bootstrap_servers("kafka:9092") \
    .set_record_serializer(
        KafkaRecordSerializationSchema.builder()
            .set_topic("user-event-counts")
            .set_value_serialization_schema(SimpleStringSchema())
            .build()
    ) \
    .build()

result_stream.map(lambda x: json.dumps(x)).sink_to(kafka_sink)

# ์‹คํ–‰
env.execute("User Event Aggregation")

Real-time aggregation with Flink SQL

-- Flink SQL์„ ์‚ฌ์šฉํ•œ ์‹ค์‹œ๊ฐ„ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ

-- Kafka ์†Œ์Šค ํ…Œ์ด๋ธ” ์ƒ์„ฑ
CREATE TABLE user_events (
    user_id STRING,
    event_type STRING,
    event_time TIMESTAMP(3),
    properties MAP<STRING, STRING>,
    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-consumer',
    'scan.startup.mode' = 'latest-offset',
    'format' = 'json'
);

-- ๊ฒฐ๊ณผ ์‹ฑํฌ ํ…Œ์ด๋ธ” (Kafka)
CREATE TABLE user_event_metrics (
    user_id STRING,
    window_start TIMESTAMP(3),
    window_end TIMESTAMP(3),
    event_count BIGINT,
    unique_event_types BIGINT,
    PRIMARY KEY (user_id, window_start) NOT ENFORCED
) WITH (
    'connector' = 'upsert-kafka',
    'topic' = 'user-metrics',
    'properties.bootstrap.servers' = 'kafka:9092',
    'key.format' = 'json',
    'value.format' = 'json'
);

-- 5๋ถ„ ํ…€๋ธ”๋ง ์œˆ๋„์šฐ ์ง‘๊ณ„ ์ฟผ๋ฆฌ
INSERT INTO user_event_metrics
SELECT
    user_id,
    TUMBLE_START(event_time, INTERVAL '5' MINUTE) AS window_start,
    TUMBLE_END(event_time, INTERVAL '5' MINUTE) AS window_end,
    COUNT(*) AS event_count,
    COUNT(DISTINCT event_type) AS unique_event_types
FROM user_events
GROUP BY
    user_id,
    TUMBLE(event_time, INTERVAL '5' MINUTE);

-- ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋กœ ์‹ค์‹œ๊ฐ„ ์ด์ƒ ํƒ์ง€
SELECT
    user_id,
    HOP_START(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE) AS window_start,
    COUNT(*) AS event_count
FROM user_events
GROUP BY
    user_id,
    HOP(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE)
HAVING COUNT(*) > 100;  -- 5๋ถ„ ๋‚ด 100๊ฐœ ์ด์ƒ ์ด๋ฒคํŠธ๋Š” ์ด์ƒ ์ง•ํ›„

Java DataStream API

// Java๋ฅผ ์‚ฌ์šฉํ•œ Flink ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;

public class UserEventProcessor {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
            StreamExecutionEnvironment.getExecutionEnvironment();

        env.enableCheckpointing(60000);
        env.setParallelism(4);

        // Kafka ์†Œ์Šค
        KafkaSource<UserEvent> source = KafkaSource.<UserEvent>builder()
            .setBootstrapServers("kafka:9092")
            .setTopics("user-events")
            .setGroupId("flink-java-consumer")
            .setValueOnlyDeserializer(new UserEventDeserializer())
            .build();

        // Watermark ์ „๋žต
        WatermarkStrategy<UserEvent> watermarkStrategy =
            WatermarkStrategy.<UserEvent>forBoundedOutOfOrderness(
                Duration.ofSeconds(5))
            .withTimestampAssigner((event, ts) -> event.getEventTime());

        // ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ
        DataStream<UserEventCount> result = env
            .fromSource(source, watermarkStrategy, "Kafka Source")
            .keyBy(UserEvent::getUserId)
            .window(TumblingEventTimeWindows.of(Time.minutes(5)))
            .aggregate(new EventCountAggregator());

        result.sinkTo(kafkaSink);

        env.execute("User Event Processing");
    }
}

Practical Conversation Example

Data Engineer: "We need to build a real-time anomaly detection system. Which is better, Spark Streaming or Flink?"
Senior Engineer: "If latency matters, Flink is the better choice. Spark uses micro-batching, so it incurs latency on the order of seconds, whereas Flink can process at the millisecond level."
Data Engineer: "We also need event-time-based processing. How do you handle late-arriving data?"
Senior Engineer: "Flink handles it with Watermarks. For example, if you allow a 5-second delay, events that arrive 5 seconds late can still be included in the correct window. Anything later than that is handled separately with a Side Output."
Data Engineer: "How is state management handled? Is data lost if a failure occurs?"
Senior Engineer: "Flink periodically saves state with Checkpoints. With the RocksDB backend, you can manage state of several terabytes, and Exactly-Once is guaranteed during failure recovery."

Cautions

Cautions for State Management

  • As state size grows, checkpoint time increases - TTL configuration is essential
  • Disk I/O must be considered when using RocksDB
  • If key distribution is unbalanced, state concentrates on specific tasks (data skew)

Watermark Configuration

  • If the Watermark interval is too short, late data is lost
  • If it is too long, result output is delayed and memory usage increases
  • An appropriate Out-of-orderness setting suited to the data characteristics is required

Parallelism and Resources

  • Be careful with state redistribution when changing parallelism
  • TaskManager memory configuration - adjust the heap/off-heap ratio
  • Network buffer size affects throughput

Related Terms

Learn More