Skip to main content

Declarative Stream Processing: Flink SQL & Table API

Module Duration: 6-7 hours Focus: Table API, SQL DDL/DML, dynamic tables, temporal joins, UDFs, MATCH_RECOGNIZE Prerequisites: SQL knowledge, Flink DataStream API, streaming concepts Hands-on Labs: 15+ SQL streaming applications

Introduction: Why SQL for Streaming?

The Paradigm Shift

Traditional Stream Processing (DataStream API):
SQL Stream Processing:

Why This Matters

Business Impact:
  • Democratization: Analysts can write streaming pipelines (not just engineers)
  • Productivity: 10x faster development (SQL vs Java/Scala)
  • Portability: Same SQL across batch and streaming
  • Optimization: Query planner optimizes execution automatically
Industry Adoption:
  • Uber: Migrated 60% of streaming jobs to Flink SQL
  • Netflix: Keystone platform built on Flink SQL
  • Alibaba: Largest Flink SQL deployment (10,000+ jobs)
  • LinkedIn: Real-time metrics pipelines in SQL

Part 1: The Relational Model for Streams

Dynamic Tables: The Core Abstraction

From the paper “Apache Flink: Stream and Batch Processing in a Single Engine”:
“A dynamic table is a table that changes over time. Queries on dynamic tables yield dynamic tables.”
Key Insight: Streams are unbounded tables, tables are materialized streams.

Stream-Table Duality

Example: Aggregation Creates Retractions:
Change Types:
  • +I: Insert (new row)
  • -U: Update retract (delete old version)
  • +U: Update insert (insert new version)
  • -D: Delete

Part 2: Table API Fundamentals

Creating Tables from Streams

Basic Table Operations


DDL: Creating Tables and Connectors

Kafka Source Table

JDBC Sink Table (MySQL)

Upsert Kafka Sink (Changelog Stream)

Filesystem Sink (Parquet)

DML: Querying Streams

Simple Filtering and Projection

Aggregations


Part 4: Windowed Aggregations (The Heart of Streaming SQL)

Tumbling Windows

Fixed-size, non-overlapping windows.
Output:

Sliding Windows (Hopping)

Fixed-size, overlapping windows.
Visualization:

Session Windows

Variable-size windows based on inactivity gap.
Example:

Cumulative Windows (Over Windows)

Running aggregations with bounded look-back.

Part 5: Joins in Streaming SQL

Regular Join (Cross-Product)

Warning: Both sides must be bounded (e.g., windowed) or this creates unbounded state!

Interval Join (Time-Bounded)

Flink optimizes this: Only keeps 1 hour of state per key!

Temporal Join (Versioned Tables)

Problem: Dimension tables change over time. Which version to use? Solution: Temporal join with versioned table.
Key Benefit: Correct historical lookups even if product price changed!

Lookup Join (External Database)

Performance: Flink caches lookups to minimize database queries.

Part 6: Advanced SQL Features

Deduplication

Top-N per Key

MATCH_RECOGNIZE (Pattern Detection in SQL!)

Use Case: Detect fraud patterns (3 declining transactions followed by 1 success).
Explanation:
  • A+: One or more declined transactions
  • B: Followed by an approved high-value transaction
  • Output: Only matched patterns (potential fraud!)
More Complex Pattern:

User-Defined Functions (UDFs)

Scalar UDF

Table Function (UDTF)

Aggregate Function (UDAF)


Part 7: Real-World Use Cases

Use Case 1: Real-Time Dashboard (Tumbling Windows)

Use Case 2: Fraud Detection (Stateful Aggregation)

Use Case 3: Sessionization (Session Windows)

Use Case 4: Feature Engineering for ML


Part 8: Performance Optimization

State Management in SQL

Problem: Unbounded State

Solution 1: Table State TTL

Solution 2: Windowed Aggregation

Mini-Batch Optimization

Trade-off: Higher throughput, slightly higher latency (5s max).

Local-Global Aggregation

Benefit: 2-5x faster for aggregations with skewed keys.

Part 9: Connectors Deep Dive

Kafka Connector Options

Filesystem Connector (S3/HDFS)

JDBC Connector


Part 10: Production Patterns

Pattern 1: End-to-End Pipeline

Pattern 2: Multi-Sink Fanout

Pattern 3: Late Data Handling


Part 11: Debugging & Monitoring

Query Execution Plan

Output:

Logging for Debugging

Common SQL Pitfalls

Pitfall 1: Unbounded Distinct

Pitfall 2: Cartesian Joins


Part 12: Exercises

Exercise 1: Real-Time Analytics Dashboard

Task: Build a minutely dashboard showing:
  • Total events
  • Unique users
  • Revenue
  • Top 5 products by sales

Exercise 2: Fraud Detection

Task: Detect users with >3 declining transactions within 10 minutes.

Exercise 3: Sessionization

Task: Compute session duration and page views per session (30-min inactivity).

Summary

What You’ve Mastered

✅ Dynamic tables and stream-table duality ✅ Table API and SQL DDL/DML ✅ Windowed aggregations (tumbling, sliding, session) ✅ Joins (regular, interval, temporal, lookup) ✅ Advanced features (MATCH_RECOGNIZE, UDFs, Top-N) ✅ Connectors (Kafka, JDBC, filesystem) ✅ Performance optimization (mini-batch, state TTL) ✅ Production patterns (multi-sink, late data handling)

Key Takeaways

  1. SQL Democratizes Streaming: Analysts can build real-time pipelines
  2. Windowing is Essential: Use tumbling/sliding/session windows to bound state
  3. Temporal Joins are Powerful: Correct historical lookups with versioned tables
  4. State Management Matters: Always consider state size and TTL
  5. Connectors are Production-Ready: Kafka, JDBC, S3 all have mature connectors

Next Module

Module 7: Complex Event Processing (CEP)

Pattern detection and sequencing with Flink CEP

Resources

Documentation

Papers

Practice: Build a complete real-time analytics pipeline: Kafka → Flink SQL (enrich, aggregate) → Multiple sinks (Kafka, MySQL, S3). Monitor state growth and optimize for production!