Streaming Data Pipelines with Kafka and Flink
Batch pipelines answer questions about yesterday. Streaming pipelines answer questions about the last five seconds â fraud scores before the card authorization clears, recommendations while the user is still scrolling, inventory decrements the moment an order lands. Moving from nightly batches to continuous streams changes nearly every engineering assumption: data arrives out of order, downstream consumers run at different speeds, state must live somewhere durable, and "exactly once" becomes a property you have to design for rather than take for granted.
This lesson builds a production-shaped streaming stack. You will learn how Kafka's partition model gives you durable, replayable event logs; how to aggregate with tumbling, sliding, and session windows; how Flink's watermarking handles late data with exactly-once state; and how to serve online features from Redis without melting your primary database.
What You'll Learn
- 1Design Kafka topics, partitions, and consumer groups for throughput and ordering
- 2Implement windowed aggregation with correct handling of late-arriving events
- 3Explain exactly-once semantics and where each processing engine provides them
- 4Compute and serve low-latency online features with Redis patterns
Prerequisites
- !Comfortable with Python and a relational database
- !Basic familiarity with Docker
- !Understanding of REST APIs and JSON
The anatomy of a streaming architecture
A reference streaming platform has five stages. Sources emit events (clicks, transactions, sensor readings). Ingestion durably buffers them (Kafka, Kinesis, Pub/Sub). Processing transforms and aggregates (Flink, Spark Structured Streaming, Kafka Streams). Serving materializes results into low-latency stores (Redis, feature stores, search indexes). Consumers read from the serving layer â models, dashboards, alerting.
The critical design choice is between stream-native and stream-processing layers. Kafka alone is a log: it stores and forwards events but does not aggregate them. Processing engines add windows, joins, and state. Treating Kafka as if it did aggregation is the most common architectural mistake â you end up with a dozen consumers each reinventing windowing with slightly different bugs.
| Component | Role | State | Ordering guarantee |
|---|---|---|---|
| Kafka topic/partition | Durable event log | Disk-backed, replayable | Total order within a partition |
| Consumer group | Parallel consumption | Offsets per group | Order within a partition, not across |
| Flink job | Stateful processing | Checkpoints to storage | Exactly-once with two-phase commit |
| Kafka Streams | Embedded processing | Changelog topics | Exactly-once within the broker |
| Redis | Online feature serving | In-memory, TTL | Single-threaded per key |
Kafka topics, keys, and consumer groups
Kafka's scalability model is the partition. A topic with 12 partitions can be consumed by up to 12 consumers in a group in parallel; each partition is owned by exactly one consumer at a time. Ordering is guaranteed within a partition, never across â so the key you choose determines what gets a consistent order.
import json
from kafka import KafkaProducer, KafkaConsumer
from kafka.admin import KafkaAdminClient, NewTopic
admin = KafkaAdminClient(bootstrap_servers="localhost:9092")
admin.create_topics([NewTopic(name="payments", num_partitions=6,
replication_factor=1)])
producer = KafkaProducer(
bootstrap_servers="localhost:9092",
key_serializer=lambda k: k.encode("utf-8"),
value_serializer=lambda v: json.dumps(v).encode("utf-8"),
acks="all", # wait for in-sync replicas
retries=5,
enable_idempotence=True, # safe retries, no duplicates
)
def publish_payment(payment):
# Key by account_id: all events for one account stay ordered in one partition
producer.send("payments", key=payment["account_id"], value=payment)
producer.flush()
consumer = KafkaConsumer(
"payments",
bootstrap_servers="localhost:9092",
group_id="fraud-detector",
auto_offset_reset="earliest",
enable_auto_commit=False, # commit only after processing succeeds
value_deserializer=lambda m: json.loads(m.decode("utf-8")),
)
for message in consumer:
handle(message.value)
consumer.commit() # offsets advance only after successful handling
The acks="all" and enable_idempotence=True settings trade latency for durability: the broker acknowledges only after all in-sync replicas persist the write, and the producer's idempotent mode makes retries safe. For payment-grade data this trade is non-negotiable; for clickstream telemetry you may relax it.
Windows: tumbling, sliding, session
Raw events are not the unit of analysis; aggregates over time windows are. Tumbling windows partition time into non-overlapping intervals (every 5 minutes). Sliding windows overlap (every minute, look back 5). Session windows close after a gap of inactivity, which is the right shape for user-behavior analytics.
from collections import defaultdict
from datetime import datetime, timedelta
class TumblingWindowAggregator:
"""Fixed-size, non-overlapping windows keyed by metric name."""
def __init__(self, window_seconds=60):
self.size = timedelta(seconds=window_seconds)
self.buckets = defaultdict(list)
def add(self, key, event_time: datetime, value: float):
# Align event to the start of its window
epoch = int(event_time.timestamp())
window_start = datetime.fromtimestamp(epoch - epoch % int(self.size.total_seconds()))
self.buckets[(key, window_start)].append((event_time, value))
def ready_windows(self, watermark: datetime):
"""Emit windows fully behind the watermark (safe from late data)."""
emitted = []
for (key, start), events in list(self.buckets.items()):
if start + self.size <= watermark:
values = [v for _, v in events]
emitted.append({
"key": key,
"window_start": start.isoformat(),
"count": len(values),
"sum": round(sum(values), 2),
"mean": round(sum(values) / len(values), 4),
"p95": round(float(np.percentile(values, 95)), 2)
if len(values) >= 5 else None,
})
del self.buckets[(key, start)]
return emitted
agg = TumblingWindowAggregator(window_seconds=300)
base = datetime(2026, 1, 1, 12, 0, 0)
for i in range(40):
agg.add("checkout_latency_ms", base + timedelta(seconds=i * 8), 120 + (i % 7) * 15)
print(agg.ready_windows(base + timedelta(seconds=400)))
The watermark â the maximum event time seen minus an allowed lateness â is what makes windowed output correct under out-of-order arrival. Emit a window when the watermark passes its end; events later than the allowed lateness are dropped or routed to a side output for correction. Without an explicit lateness policy, either you emit wrong aggregates or you hold windows open forever.
Flink SQL for exactly-once stream analytics
When aggregation logic outgrows a hand-rolled window map, a processing engine earns its operational cost. Flink provides event-time windows, watermarks, state, and checkpoints that together deliver exactly-once output semantics even through failures.
from pyflink.table import EnvironmentSettings, TableEnvironment
env_settings = EnvironmentSettings.in_streaming_mode()
tenv = TableEnvironment.create(env_settings)
tenv.execute_sql("""
CREATE TABLE orders (
order_id STRING,
user_id STRING,
amount DECIMAL(10, 2),
event_time TIMESTAMP(3),
WATERMARK FOR event_time AS event_time - INTERVAL '30' SECOND
) WITH (
'connector' = 'kafka',
'topic' = 'orders',
'properties.bootstrap.servers' = 'localhost:9092',
'format' = 'json',
'scan.startup.mode' = 'latest-offset'
)
""")
tenv.execute_sql("""
CREATE TABLE minute_revenue (
window_start TIMESTAMP(3),
user_id STRING,
orders BIGINT,
revenue DECIMAL(12, 2),
PRIMARY KEY (window_start, user_id) NOT ENFORCED
) WITH (
'connector' = 'upsert-kafka',
'topic' = 'minute-revenue',
'properties.bootstrap.servers' = 'localhost:9092',
'key.format' = 'json',
'value.format' = 'json'
)
""")
result = tenv.execute_sql("""
SELECT
window_start,
user_id,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM TABLE(
TUMBLE(TABLE orders, DESCRIPTOR(event_time), INTERVAL '1' MINUTE)
)
GROUP BY window_start, user_id
""")
Exactly-once here means effects are atomic with respect to checkpoints: Kafka's transactional producer commits output offsets and writes in the same two-phase commit Flink performs on checkpoint. The requirement on the source is read_committed isolation, and on the sink it is a transactional connector â get either wrong and you quietly reintroduce duplicates.
Online feature computation backed by Redis
Serving a model in real time means computing features at request time, often from the same event stream that trains the model. The pattern: consume events, update per-key aggregates in Redis with atomic commands, and read those keys during inference.
import json
from collections import deque
from kafka import KafkaConsumer
from redis import Redis
ACTION_WEIGHTS = {"view": 1.0, "click": 2.0, "add_to_cart": 3.0, "purchase": 5.0}
class OnlineFeatureStore:
def __init__(self):
self.redis = Redis(host="localhost", port=6379, decode_responses=True)
self.consumer = KafkaConsumer(
"user-actions",
bootstrap_servers="localhost:9092",
value_deserializer=lambda m: json.loads(m.decode("utf-8")),
group_id="feature-computer",
)
def update(self, event):
uid = event["user_id"]
action = event["action"]
pipe = self.redis.pipeline()
# Rolling 1-hour action counts with TTL cleanup
count_key = f"feat:{uid}:count:{action}"
pipe.incr(count_key)
pipe.expire(count_key, 3600)
# Sliding window of last 100 amounts for distribution features
amt_key = f"feat:{uid}:amounts"
pipe.lpush(amt_key, float(event.get("amount", 0)))
pipe.ltrim(amt_key, 0, 99)
pipe.expire(amt_key, 86400)
# Weighted engagement score
score_key = f"feat:{uid}:engagement"
pipe.incrbyfloat(score_key, ACTION_WEIGHTS.get(action, 0.0) * 0.1)
pipe.expire(score_key, 86400)
pipe.execute()
def read_features(self, uid):
amounts = [float(x) for x in self.redis.lrange(f"feat:{uid}:amounts", 0, -1)]
engagement = float(self.redis.get(f"feat:{uid}:engagement") or 0.0)
return {
"engagement_score": engagement,
"amount_mean": (sum(amounts) / len(amounts)) if amounts else 0.0,
"amount_max": max(amounts) if amounts else 0.0,
"recent_events": len(amounts),
}
def run(self):
for message in self.consumer:
self.update(message.value)
Two properties make this production-safe: every update is a pipeline of atomic commands (no read-modify-write races across workers), and every key carries a TTL so abandoned users do not accumulate forever. For stronger guarantees â exactly-once feature updates aligned with event offsets â write features from the same Flink job that computes aggregates, using Redis as a transactional sink.
Event-driven patterns: outbox, idempotency, replay
Microservices coupled by synchronous calls cascade failures. Decoupling through events improves resilience but introduces three problems you must design for: duplicate delivery (at-least-once is the norm), ordering across services (Kafka orders per partition, not globally), and dual writes (database and event log must not disagree).
The transactional outbox pattern solves dual writes: services write domain events to an outbox table inside the same database transaction as their state change, and a relay (CDC via Debezium, or a poller) publishes outbox rows to Kafka. Consumers must be idempotent â key on a deterministic event ID and skip repeats:
import hashlib
from typing import Dict, Optional
class IdempotentEventProcessor:
def __init__(self, redis: Redis, seen_ttl_seconds: int = 7 * 24 * 3600):
self.redis = redis
self.ttl = seen_ttl_seconds
def dedupe_key(self, event: dict) -> str:
payload = json.dumps(event, sort_keys=True)
return "evt:" + hashlib.sha256(payload.encode()).hexdigest()
def process_once(self, event: dict, handler) -> Optional[str]:
key = self.dedupe_key(event)
# SET NX: only the first worker across the fleet claims this event
claimed = self.redis.set(key, "1", nx=True, ex=self.ttl)
if not claimed:
return None
handler(event)
return key
processor = IdempotentEventProcessor(Redis())
sample = {"event_id": "e-991", "type": "payment.captured", "amount": 42.50}
print(processor.process_once(sample, lambda e: print("handled", e["event_id"])))
print(processor.process_once(sample, lambda e: print("never runs")))
Replay is the underrated payoff of the log architecture: because Kafka retains events, you can rebuild a broken consumer, backfill a new feature, or re-run an entire quarter of aggregates without touching producers. Design topics with retention in mind (compact topics for state changelogs, time-retention topics for event streams) and treat replay drills as routine operational practice.
Operational hygiene rounds out the design. Alert on consumer lag as the primary health signal â a growing lag means either a slow consumer or a traffic spike, and both need different responses. Snapshot streaming state periodically so a job restart does not require a full replay from the beginning of retention. Document which sinks are idempotent and which are not, because that determines whether a retry-after-crash is safe or double-charges a customer. Finally, keep a small, well-exercised runbook for the three incidents every stream eventually faces: a poison-pill event that crashes the parser, a schema change that breaks deserialization, and a downstream store outage that back-pressures the whole pipeline.
Common Mistakes
Keying Kafka events by a random UUID when per-entity ordering matters
Fix: Key by the entity whose order you need to preserve (account_id, order_id); UUID keys scatter one entity's events across all partitions and destroy ordering.
Committing consumer offsets before the record is fully processed
Fix: Disable auto-commit, process, then commit â the reverse order duplicates work on rebalance but never loses events.
Ignoring late data by using processing time instead of event time
Fix: Carry event timestamps in payloads, define watermarks, and set an explicit allowed-lateness policy; processing-time windows silently miscount anything delayed.
Treating Redis feature keys as eternal, then debugging memory exhaustion months later
Fix: Set TTLs on every key at write time and monitor keyspace size; abandoned users should expire, not accumulate.
Best Practices
- Partition by the entity that needs ordering; choose partition counts for consumer parallelism, not guessed throughput
- Use exactly-once only where it pays: payments, ledger writes; at-least-once plus idempotent consumers is fine for analytics
- Define watermark and lateness policies explicitly in every streaming job and document them
- Compute online and training features from the same definitions to avoid training-serving skew
- Budget for replay: retention windows, compaction strategy, and periodic replay drills should be part of the design review
Interview Questions
Q1: What does Kafka guarantee about ordering, and what does it not?
Total order of messages within a partition. Nothing across partitions of the same topic or across topics â per-entity ordering requires hashing that entity into a single partition key.
Q2: How do watermarks handle out-of-order events?
A watermark is a moving estimate of event-time progress, typically max-seen event time minus allowed lateness. Windows close when the watermark passes their end, bounding how long the engine waits for stragglers.
Q3: When is exactly-once processing worth the cost?
When side effects are non-idempotent and financially or legally material â payments, inventory decrements, ledger entries. For analytical aggregates, at-least-once with idempotent sinks is usually cheaper and sufficient.
Key Takeaways
- Kafka gives durable, replayable, partition-ordered logs; processing engines add windows, state, and exactly-once semantics on top
- Key choice determines ordering guarantees â key by the entity, never by random UUIDs, when sequence matters
- Event time, watermarks, and explicit lateness policies are mandatory for correct windowed aggregation
- Online features belong in Redis-style stores with atomic pipelines and TTLs, computed from the same definitions as training features
- Design for duplicates and replay from day one: idempotent consumers, transactional outbox, retention policies