Library

Volume 1 · System Architecture & Distributed Systems

Notebook
Sign in

Section 6

Real-Time Data Processing

1,402 words · about 6 min

6.1 Lambda Architecture

Combines an immutable batch layer (for comprehensive, fault-tolerant historical calculation) with a speed layer (for low-latency streaming aggregations), unified at query time by a serving layer.

flowchart TD
    Source["Data Source\n(IoT Events / App Telemetry)"]

    subgraph BatchLayer["Batch Layer (Accuracy & Completeness)"]
        RawStore[("Immutable Master Dataset\n(HDFS / S3 Data Lake)")]
        BatchCompute["Batch Compute\n(Apache Spark / MapReduce)"]
        BatchViews[("Precomputed Batch Views")]
        RawStore --> BatchCompute --> BatchViews
    end

    subgraph SpeedLayer["Speed Layer (Low Latency / Delta)"]
        StreamEngine["Stream Processor\n(Apache Flink / Storm)"]
        RealtimeViews[("Real-time Views\n(Fast Key-Value / In-Memory)")]
        StreamEngine --> RealtimeViews
    end

    subgraph ServingLayer["Serving Layer (Consolidated Queries)"]
        QueryEngine["Query Engine\n(Merges Batch Views + Real-time Delta)"]
        ClientUI["Analytics Dashboard / Client API"]
        BatchViews --> QueryEngine
        RealtimeViews --> QueryEngine
        QueryEngine --> ClientUI
    end

    Source --> RawStore
    Source --> StreamEngine

Major Trade-Off:

  • Maintaining dual pipelines (batch in Spark and streaming in Flink) creates significant code synchronization overhead, since identical business logic must be authored and debugged across two divergent processing engines.

6.2 Kappa Architecture

A deliberate simplification of Lambda: everything is treated as an unbounded event stream. A single stream-processing engine handles both real-time ingestion and historical recalculation.

flowchart LR
    Source["Data Source"]
    Kafka[("Durable Event Log\n(Kafka / Redpanda)\nLong Retention")]
    Processor["Single Stream Processor\n(Apache Flink / Kafka Streams)"]
    Serving[("Serving Layer Store\n(ClickHouse / Elasticsearch)")]
    Client["Analytics Client / API"]

    Source --> Kafka
    Kafka -->|Live Tail| Processor
    Kafka -.->|Reprocess: Reset Consumer Offset\nReplay Historical Events| Processor
    Processor --> Serving
    Serving --> Client

Reprocessing in Kappa:

  • When business logic or aggregation schemas change, developers update the streaming job, deploy a new consumer group, and replay historical partitions from offset zero. Once caught up, the new serving view replaces the legacy view.

When to Choose Kappa over Lambda:

  • Identical transformation logic applies to historical records and real-time streams.
  • The underlying log store supports cost-effective long-term retention (e.g., Kafka Tiered Storage backed by AWS S3).

When to prefer Kappa over Lambda: when your batch and streaming business logic would be nearly identical anyway (so maintaining two codebases has no benefit), and when your event log retention is long enough to support full reprocessing from history.

6.3 Stream Processing Framework Comparison

Feature Kafka Streams Apache Flink Spark Structured Streaming
Processing Model Record-at-a-time Record-at-a-time Micro-batch
State Management RocksDB-backed local state stores Managed, checkpointed state Stateful via DataFrames/DStreams
Exactly-once Yes Yes Yes (with limitations)
Latency Low (milliseconds) Very low (milliseconds) Medium (seconds, micro-batch interval)
Deployment Library — embeds in your app, no separate cluster Requires a dedicated cluster Requires a Spark cluster
Best fit Lightweight stream processing tightly coupled to Kafka Complex event-time processing, large stateful jobs Teams already using Spark for batch, unified batch+stream API

6.4 Windowing Concepts (used across all stream processors)

  • Tumbling window: fixed-size, non-overlapping (e.g., every 1 minute, independently).
  • Sliding window: fixed-size, overlapping, advances by a smaller step than its size (e.g., 5-minute window sliding every 1 minute).
  • Session window: dynamically sized based on activity gaps — closes after a period of inactivity (e.g., user session ends after 30 minutes idle).

6.5 Reference Design: 1M Events/Second IoT Ingestion Pipeline

Data Ingestion Layer:

  • A distributed log (Kafka-class system) with 100+ partitions across brokers as the central event bus.
  • Lightweight MQTT broker for IoT devices, bridging into the event bus; API Gateway with rate limiting for HTTP-based devices.

Stream Processing Layer:

  • A low-latency stream processor (Flink-class) for windowed aggregation (tumbling, sliding, session windows).
  • Pre-aggregate metrics (counts, averages, percentiles) at 1-second, 1-minute, and 1-hour granularities.
  • Exactly-once semantics via checkpointing for data integrity.

Storage Layer (hot/warm/cold tiering):

  • Hot (last 24h): A columnar OLAP store (Druid/ClickHouse-class) for sub-second query response.
  • Warm (last 30 days): A time-series database for time-windowed queries.
  • Cold (archive): Object storage in a columnar file format (Parquet), queryable via a federated query engine.

Analytics & Serving Layer:

  • Pre-computed dashboards served directly from the hot OLAP store.
  • WebSocket connections for real-time dashboard push updates.
  • A query API that federates across hot/warm stores transparently for historical queries.

Scalability considerations: partition the event bus by device ID for per-device ordering; match stream-processor parallelism to partition count; auto-scale processing workers based on consumer lag; consider geo-distributed clusters (with mirroring) for globally distributed IoT deployments.

Reliability considerations: replication factor of 3 across availability zones for the event bus; periodic savepoints/checkpoints in the stream processor for safe upgrades and recovery; a dead-letter queue for malformed events; a circuit breaker between ingestion and processing layers so a processing slowdown doesn’t back-pressure ingestion into data loss.

6.6 Section 6 — Interview Q&A

Q1: Compare Lambda and Kappa architecture. Which would you choose for a new real-time analytics platform?

A: Lambda maintains two parallel pipelines — a batch layer for complete, accurate historical results and a speed layer for low-latency approximate results — merged at query time by a serving layer. Its main weakness is dual maintenance: the same business logic often needs to be implemented twice, once in the batch framework and once in the streaming framework, and keeping them logically consistent as requirements evolve is a real ongoing cost. Kappa collapses this to a single stream-processing pipeline, treating “batch” reprocessing as simply replaying the event log from an earlier offset through the same code path. For a new platform, I’d default to Kappa if the durable log’s retention window can reasonably cover the reprocessing needs (which modern tiered-storage log systems make increasingly feasible) — it’s simpler to build, test, and reason about with one codebase. I’d only reach for Lambda if there’s a hard requirement for a fundamentally different, more resource-intensive batch algorithm (e.g., a full historical ML feature backfill) that genuinely doesn’t belong in the low-latency streaming path.

Q2: How do exactly-once semantics work in a stream processing system, and why does it matter?

A: Exactly-once semantics guarantee that even in the presence of failures and retries, each input record affects the output state exactly one time — not zero times (data loss) and not more than once (duplication). It’s achieved through a combination of idempotent writes and coordinated checkpointing: the stream processor periodically snapshots its internal state and its consumption offset together as one atomic unit, so on recovery from a failure it can roll back to a consistent checkpoint and resume from exactly the right offset, and downstream sinks are written to transactionally (or made idempotent) so a replayed batch doesn’t double-apply. This matters enormously for anything involving counts, money, or aggregations — without it, a transient failure and automatic retry could silently double-count a metric or double-charge a transaction, and these bugs are extremely hard to detect after the fact because the data just looks slightly, plausibly wrong rather than obviously broken.

Q3: What’s the difference between a tumbling window and a session window, and give an example of when you’d use each?

A: A tumbling window is fixed-size and non-overlapping — every event falls into exactly one window based purely on time, e.g., “aggregate metrics every 60 seconds,” which is ideal for regular periodic reporting like a per-minute dashboard tile. A session window is dynamically sized based on actual activity — it stays open as long as events keep arriving within a gap threshold and closes once that gap is exceeded, which is the right model when the meaningful unit isn’t a fixed time slice but a burst of related activity, like a user’s browsing session on an e-commerce site (the session should end when the user goes idle for 30 minutes, not at an arbitrary clock boundary that might split one continuous shopping trip into two disconnected windows).

Q4: How do you design a stream processing pipeline to be resilient to a downstream sink outage without losing data?

A: The event bus itself is the safety net — as long as it’s durable and has sufficient retention, the stream processor can simply stop advancing its consumer offset while the sink is down, back-pressuring naturally without losing anything, and resume exactly where it left off once the sink recovers. I’d pair this with a circuit breaker around the sink write so the processor doesn’t hammer a failing sink with retries that waste resources without making progress, alerting so the team knows about the outage immediately, and a dead-letter path for records that fail repeatedly for reasons other than sink unavailability (e.g., a malformed record that will never successfully write) so those don’t block the entire pipeline indefinitely behind one bad record. The key design principle is that the durable log decouples ingestion rate from processing rate, so a slow or temporarily down consumer is an operational issue to monitor and recover from, not a data-loss event.