🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Streaming Analytics: Windowing, Watermarks, Exactly-Once

Data EngineeringStream Processing⭐ Premium

Streaming Analytics: Windowing, Watermarks, Exactly-Once

Difficulty: Senior Level | Companies: Netflix, Uber, Lyft, DoorDash, Stripe

Batch processing hides its hardest decisions inside a schedule: you choose a date, you load a date, and everything arrives roughly together. A stream removes that luxury. Events arrive late, duplicated, out of order and sometimes not at all, and the aggregation you publish must still be correct for the person watching the number move. This lesson works through the four decisions that determine whether a streaming pipeline is trustworthy: which time you aggregate on, how you window it, how long you wait for stragglers, and what guarantee you are actually willing to claim.

Prerequisites

  • !Kafka topics, partitions and consumer offsets
  • !Spark or Flink batch aggregation basics
  • !Checkpointing and durable storage

What You'll Learn

  • 1Explain why event time beats processing time for analytics
  • 2Choose tumbling, sliding or session windows for a metric
  • 3Tune a watermark against observed lateness
  • 4State precisely what exactly-once does and does not cover

Event time, processing time, and why the gap matters

Event time is when something happened in the world: the user clicked, the card was charged, the sensor reported. Processing time is when your cluster got around to reading it. The gap between them is not a rounding error. A mobile client offline for an hour, a rebalance that pauses consumers, or a replay from the dead letter queue can all push an event minutes or hours past its true moment.

Aggregate on processing time and every one of those events lands in the wrong bucket, so a session that ran from 09:00 to 09:15 is partly reported under 10:00. The dashboard will look plausible and be quietly wrong, which is worse than obviously broken. Aggregate on event time and you need a mechanism to decide when a bucket is finished, because you can never be certain another straggler is not on its way. That mechanism is the watermark, and it is the single most consequential parameter in the whole job.

Late data is not an edge case, it is the normal case. Design as though a few percent of events will arrive after their window has been announced, and decide explicitly whether to drop them, correct the result, or route them to a side output for reconciliation.

Window shapes and when each one fits

Three window shapes cover almost every streaming metric. A tumbling window is fixed length and non-overlapping, so five-minute buckets tile the timeline exactly once each. A sliding window has a length and a slide interval, so each event belongs to several overlapping windows, which suits metrics like "events in the last ten minutes, refreshed every minute." A session window has no fixed boundaries at all: it opens on the first event and closes once a gap of the session timeout passes, which is what you want for per-user activity.

Choosing wrong produces metrics that are internally consistent but useless. A sliding window over a high-volume topic multiplies state by the ratio of length to slide, so a sixty-minute window sliding every minute holds sixty copies of each key's partial aggregate. Sessions are cheap until a user leaves a tab open overnight, at which point one key can hold an unbounded amount of state. Pick the shape from the question the business is asking, not from the syntax you find convenient.

WindowBoundariesState costTypical use
TumblingFixed, non-overlappingOne bucket per key per intervalPer-minute counters, hourly rollups
SlidingFixed length, overlappingLength divided by slide buckets per keyRolling rates, moving averages
SessionGap-triggered, per keyOne session per active keyUser journeys, idle-timeout activity
GlobalEverything, no boundaryOne key totalCumulative totals, sessionization input

Watermarks and late arrivals

A watermark is a moving assertion that no event older than a timestamp will arrive. In Spark you declare it with a tolerance, in Flink you define an out-of-orderness bound, and in both cases the engine uses it to decide when a window can be emitted and when its state can be discarded. The tolerance is a trade-off you can measure: too short and you drop real data, too long and you hold state you cannot afford and publish results that arrive late anyway.

python
from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder.appName("StreamingAnalytics").getOrCreate()

events = (
    spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", "kafka:9092")
    .option("subscribe", "user_events")
    .load()
    .select(F.from_json(F.col("value").cast("string"), EVENT_SCHEMA).alias("data"))
    .select("data.*")
)

per_minute = (
    events.withWatermark("event_timestamp", "10 minutes")
    .groupBy(F.window("event_timestamp", "5 minutes"), "event_type")
    .count()
)

Set the tolerance from data rather than from a blog post. Log the observed lateness distribution for a week, pick a percentile you can accept losing, and round up. Revisit it whenever you add a new mobile client or a new upstream partner, because those are the usual sources of a shifted distribution.

Where state lives and who expires it

Every aggregation over a stream is stateful, and state needs a home. Managed state inside the engine is the default and the right starting point: it lives in a checkpointed backend, is restored on failure, and is expired by the watermark automatically. Move to an external store only when you need the value outside the job, such as serving a feature to a model or exposing a counter to an API.

python
import json
import redis


class WindowStateStore:
    def __init__(self, host="redis", ttl_seconds=3600):
        self.client = redis.Redis(host=host, port=6379)
        self.ttl = ttl_seconds

    def bump(self, window_key: str, event: dict) -> None:
        pipe = self.client.pipeline()
        pipe.hincrby(f"window:{window_key}", "count", 1)
        pipe.rpush(f"window:{window_key}:events", json.dumps(event))
        pipe.expire(f"window:{window_key}", self.ttl)
        pipe.execute()

    def read(self, window_key: str) -> dict:
        data = self.client.hgetall(f"window:{window_key}")
        return {"count": int(data.get(b"count", 0)), "key": window_key}

Whatever you choose, give the state a time to live. State that only grows is the most common cause of a streaming job that is healthy for three months and then dies at four in the morning, and an explicit expiry converts that failure into a slow degradation you can plan for.

Exactly-once without lying to yourself

Exactly-once is a property of a boundary, not of a job. Inside the engine you can get it with checkpointed offsets and idempotent sinks, so that a restart replays from the last consistent point and writes results that converge. Across the boundary into a system with no idempotent write, you cannot. Claiming end-to-end exactly-once over a sink that appends is simply false, and the honest engineering answer is to say which guarantee applies where.

python
class DeduplicatingProcessor:
    def __init__(self, seen_store, window_seconds=300):
        self.seen = seen_store
        self.window_seconds = window_seconds

    def process(self, event: dict) -> dict | None:
        event_id = event["event_id"]
        if self.seen.add_if_absent(event_id, ttl=self.window_seconds):
            return None
        return self.handle(event)

    def handle(self, event: dict) -> dict:
        return {
            "event_id": event["event_id"],
            "user_id": event["user_id"],
            "amount": event.get("amount", 0),
        }

A deduplication store is a pragmatic middle ground: it does not give a mathematical guarantee, but with a time-to-live matched to your maximum replay horizon it removes the duplicates that actually appear in practice. Combine it with idempotent upserts keyed on the natural identifier and the remaining risk becomes rounding error rather than double-counted revenue.

Serving a live dashboard from a stream

The final hop is where many streaming designs quietly turn back into batch. A dashboard that refreshes every few seconds needs its numbers pushed, not polled, and it needs only the rows that changed. Use update output mode so the engine emits modified rows instead of recomputing entire windows, and write to a low-latency store the front end can read directly.

python
metrics = (
    events.withWatermark("event_timestamp", "5 minutes")
    .groupBy(F.window("event_timestamp", "1 minute"), "page")
    .agg(
        F.count("*").alias("views"),
        F.countDistinct("user_id").alias("unique_users"),
        F.sum(F.when(F.col("event_type") == "purchase", 1).otherwise(0)).alias("purchases"),
    )
)

query = (
    metrics.writeStream.outputMode("update")
    .option("checkpointLocation", "s3://checkpoints/dashboard")
    .format("redis")
    .start()
)

Two operational details decide whether this survives contact with production. The checkpoint location must be durable and unique per job, because two jobs sharing a checkpoint corrupt each other's offsets. And you need a lag alert: consumer lag and checkpoint age degrade long before throughput visibly drops, and by the time the dashboard is visibly wrong the underlying backlog may take hours to drain.

💡Measure lateness before tuning

Emit the difference between event time and processing time as a histogram on day one. Every later decision about watermark tolerance, checkpoint interval and state size becomes an argument about a number instead of a guess.

Common Mistakes

Aggregating on processing time because it is simpler

Fix: Aggregate on event time and accept the cost of managing watermarks

Setting the watermark tolerance as a round number with no data behind it

Fix: Log the observed lateness distribution and choose a percentile you can defend

Claiming end-to-end exactly-once across an append-only sink

Fix: State the guarantee per boundary and add idempotent upserts or a dedup store

Unbounded state with no expiry

Fix: Give every key a time to live and alert on state size growth

Best Practices

  • Emit event-to-processing lag as a histogram before tuning anything
  • Prefer managed checkpointed state until you have a concrete reason not to
  • Use update output mode for dashboards so only changed rows are recomputed
  • Give each streaming job a unique durable checkpoint location
  • Alert on consumer lag and checkpoint age, not only on failure

Interview Questions

Q1: Event time or processing time, and why?

Event time, because analytics must describe when things happened. Processing time misplaces any event that arrives late, and late arrival is normal once mobile clients, rebalances and replays are in play.

Q2: How do you choose a watermark tolerance?

Measure the distribution of lateness over a representative period, pick an acceptable percentile of data to sacrifice, round up, and revisit whenever a new producer or partner changes the distribution.

Q3: Design a real-time fraud detection path for 100K events per second.

Kafka partitions by account for ordering, a stateful stream engine computes per-account windows with checkpoints, a low-latency store holds recent features, and a synchronous decision service reads it with a strict latency budget plus an async fallback.

Q4: What breaks when two jobs share a checkpoint?

Offsets and state are restored incorrectly, so one job can skip events the other expected or double-apply them. Checkpoint locations must be unique and durable per job.

Q5: How would you monitor a streaming pipeline?

Consumer lag, checkpoint age, event-to-processing latency, state store size, watermark delay and output throughput, with alerts sized to the drain time you can tolerate rather than to zero.

Key Takeaways

  • Aggregate on event time and treat late data as normal, not exceptional
  • The window shape should come from the business question, not the syntax
  • Watermark tolerance is a measured trade-off between lost data and held state
  • State needs a time to live or the job dies after a few months of growth
  • Exactly-once is a boundary property; say which guarantee applies where
  • Dashboards want update mode, unique checkpoints and lag alerting
🔒

Premium Content

Streaming Analytics: Windowing, Watermarks, Exactly-Once

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement