Engineer a streaming feature pipeline leveraging Flink, schema registry, and replayable…
- User
Engineer a streaming feature pipeline leveraging Flink, schema registry, and replayable audit logs.
Assistant
Engineer a streaming feature pipeline leveraging Flink, schema registry, and replayable audit logs.
The user wants an "engineering" solution for a streaming feature pipeline. Key components requested:
The request is high-level but technical. I need to provide a comprehensive architecture, key code snippets, and a discussion of the design choices to meet the specific requirements (especially the "replayable" aspect).
Plan:
High-Level Architecture:
Detailed Design Steps:
Code Structure (Python/Java/SQL):
Addressing "Replayable Audit Logs":
Drafting the Content:
Avro format + Registry integration.Refining the "Replayable" aspect:
Self-Correction/Refinement:
confluent-kafka + schema-registry client nuances.Final Output Structure:
(Self-Correction during drafting code): Standard Flink connectors for Kafka usually handle Schema Registry nicely. I will use the Table API for the Schema Registry parts because it abstracts away the painful serde logic nicely in PyFlink.
Let's write the Python code.
env = StreamExecutionEnvironment...
t_env = StreamTableEnvironment...
t_env.get_config().get_configuration().set_string("pipeline.name", "FeaturePipeline")
Source: Kafka table with format 'avro-registry'.
Sink: Kafka table (Audit) + Jdbc/Redis (Feature Server).
Actually, standard PyFlink doesn't always have the "avro-registry" format built-in without extra jars. I need to specify the Maven dependencies (JARs) required.
Replay Strategy Specifics:
The prompt asks for "Replayable Audit Logs".
This implies the Audit Log itself is the replay source? Or the pipeline supports replay to generate the audit logs?
Usually, "Audit Log" implies recording what happened. "Replayable" implies we can recompute state from this log.
I will design the Audit Log as the intermediate sink.
Flow: Raw Events -> Flink (Compute) -> Enriched Audit Log (Kafka) -> Flink (Sink) -> Online Store.
This allows us to truncate the Online Store and replay from the Audit Log if the serving layer breaks, OR replay from Raw Events if the logic breaks.
Let's stick to the simpler: Raw Events -> Flink -> Audit Log (History) + Online Store (Serving).
Let's go. This solution architects a robust streaming feature pipeline designed for real-time ML inference and high-integrity auditing. It uses Apache Flink for stateful computation, Confluent Schema Registry for contract enforcement, and Apache Iceberg (or Kafka Compacted Topics) for maintaining replayable audit logs.
The pipeline follows a Kappa-like architecture where raw events are immutable, and feature derivation is deterministic.
We use Schema Registry to prevent "poison pill" events from corrupting the feature logic.
topic-name-value (default).BACKWARD (allows deleting fields, but not adding non-nullable fields without a default).Example AVRO Schema (User Transaction):
{
"type": "record",
"name": "Transaction",
"namespace": "com.ml.features",
"fields": [
{"name": "user_id", "type": "string"},
{"name": "amount", "type": "double"},
{"name": "timestamp", "type": "long", "logicalType": "timestamp-millis"},
{"name": "merchant", "type": "string"}
]
}
We will use PyFlink to define the pipeline. This example computes a 30-minute rolling average transaction amount per user.
You need the following JARs in your Flink ./lib folder or submitted via --classpath:
flink-avroflink-connector-kafkakafka-schema-registry-clientThe requirement for replayability is handled via the Compacted Kafka Topic (feature-audit-log) or a Log-Structured Table (Iceberg/Hudi).
If a bug is found in the AVG calculation logic or a new feature (MAX(amount)) is needed:
raw-transactions (which might be huge), you can bootstrap the state by reading the feature-audit-log topic first (if the logic is additive) or, more commonly, reset the consumer group of the raw-transactions source to a specific timestamp.raw_event_payload context within the log, you can debug why a specific feature vector was generated without querying the raw source again.To ensure the pipeline is production-grade:
Schema Evolution Checks:
BACKWARD compatibility.currency field), Flink's Avro deserializer will handle it. If it breaks compatibility, the registry rejects the schema, protecting the pipeline.Exactly-Once Semantics:
Dead Letter Queue (DLQ):
[Producers]
|
v
[Apache Kafka: Raw Topic] <-- Schema Registry validates producer schemas
|
| (Flink Source)
v
[Apache Flink Cluster]
| - Deserialization (Avro)
| - Window Aggregation (State Backend: RocksDB)
| - Watermarking
|
+------------------------+
| |
v v
[Kafka: Audit Log] [Online Store: Redis/DynamoDB]
(Compact Topic) (Key: user_id, Val: Feature Vector)
|
| (Batch Replay Source)
v
[Offline Training Pipeline] (Re-compute features if logic changes)
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment, EnvironmentSettings
from pyflink.table.catalog import HiveCatalog
import json
def create_feature_pipeline():
# 1. Setup Environment
env = StreamExecutionEnvironment.get_execution_environment()
env.set_parallelism(3)
# Enable Checkpointing for Exactly-Once semantics (Crucial for Audit)
env.enable_checkpointing(60000) # 1 minute checkpoint
t_env = StreamTableEnvironment.create(env)
# 2. Define Kafka Source with Schema Registry
# We use the raw SQL DDL for clarity and robust connector options
source_ddl = f"""
CREATE TABLE raw_transactions (
-- Schema is derived automatically from Schema Registry
-- based on the 'topic' and 'properties.schema.registry.url'
`user_id` STRING,
`amount` DOUBLE,
`timestamp` BIGINT,
`merchant` STRING,
-- Metadata to capture Kafka timestamp for Watermarks
`event_time` TIMESTAMP(3) METADATA FROM 'timestamp',
WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH (
'connector' = 'kafka',
'topic' = 'raw-transactions',
'properties.bootstrap.servers' = 'kafka:9092',
'properties.group.id' = 'flink-feature-pipeline',
'format' = 'avro', -- Assumes Avro, schema registry handles fetching
'avro-confluent.schema-registry.url' = 'http://schema-registry:8081',
'scan.startup.mode' = 'latest-offset'
)
"""
# 3. Define Audit Log Sink (Replayable Source)
# Using Kafka Compact topic as a changelog/audit log
audit_sink_ddl = f"""
CREATE TABLE feature_audit_log (
`user_id` STRING,
`window_start` TIMESTAMP(3),
`window_end` TIMESTAMP(3),
`avg_amount` DOUBLE,
`tx_count` BIGINT,
`raw_event_payload` STRING, -- Store original context for replay
`processing_time` TIMESTAMP(3) METADATA -- Audit timestamp
) WITH (
'connector' = 'kafka',
'topic' = 'feature-audit-log',
'properties.bootstrap.servers' = 'kafka:9092',
'format' = 'json',
'key.format' = 'json',
'key.fields' = 'user_id',
-- Log Compaction ensures we keep the latest state per user for replay
'properties.cleanup.policy' = 'compact'
)
"""
# 4. Define Feature Logic
# Compute rolling metrics and construct the audit record
feature_logic = """
INSERT INTO feature_audit_log
SELECT
t.user_id,
TUMBLE_START(t.event_time, INTERVAL '30' MINUTE) as window_start,
TUMBLE_END(t.event_time, INTERVAL '30' MINUTE) as window_end,
AVG(t.amount) as avg_amount,
COUNT(*) as tx_count,
-- For audit/replay: Serialize original relevant data
FORMAT('User %s paid %.2f at %s', t.user_id, t.amount, t.merchant) as raw_event_payload,
CURRENT_TIMESTAMP as processing_time
FROM raw_transactions t
GROUP BY
TUMBLE(t.event_time, INTERVAL '30' MINUTE),
t.user_id
"""
# Execute
t_env.execute_sql(source_ddl)
t_env.execute_sql(audit_sink_ddl)
t_env.execute_sql(feature_logic)
if __name__ == '__main__':
create_feature_pipeline()