Events per hour
Oct 6, by source
Project 06 · Streaming + batch
Web events arrive through Kafka and mobile app events through Amazon Kinesis. A Flink job deduplicates and sessionizes both streams in real time and writes events and sessions to Apache Iceberg, so product dashboards run a few seconds behind users. Every night a Spark job recomputes the previous day from the raw events, including the ones that arrived late, and atomically replaces those partitions of the same tables. One set of tables, one definition of a session, and two engines that check each other.
Oct 6, by source
Sessions reaching each step, Oct 6
Session counts per day; the nightly batch is the reference
Delay from event time to arrival, log scale
Oct 6
Oct 6, web and app combined
State at 02:30 on Oct 7
The stream is fast, the batch is complete, and both write the same tables.
01 · Collect
Web and mobile SDKs
Page views, searches, cart changes and purchases, each with a client event id and timestamp.
02 · Ingest
Kafka · Kinesis
Web events land in Kafka. The mobile backend already runs on AWS, so app events arrive through Kinesis.
03 · Stream
Apache Flink
Reads both streams, drops duplicates by event id, groups events into sessions with a 30-minute gap and commits every 30 s.
04 · Store
Apache Iceberg
One set of tables for both engines: events, sessions and funnel steps, partitioned by day.
05 · Recompute
Apache Spark, nightly
Rebuilds yesterday from raw events, late arrivals included, and replaces just those partitions.
06 · Reconcile
Spark SQL
Compares the streaming and batch results per day and alerts above 0.1%.
event_id, a 30-minute inactivity gap and the same session id, so on-time data gives the same answer in Flink and Spark.Both engines write these Iceberg tables. The CSV download is the hourly rollup for the last 14 days.
clickstream.eventsIceberg · appended by Flink · days(event_ts)event_idstringanonymous_id / user_idstringplatform / sourcestringweb or ios/android; kafka or kinesisevent_typestringpage_view, search, add_to_cart, purchase and otherspagestring/p/{product}event_ts / ingest_tstimestampclickstream.sessionsIceberg · Flink writes, Spark replaces nightlysession_idstringanonymous_id and the session startanonymous_idstringplatform / channelstringstarted_at / ended_attimestampevents / page_viewsintconvertedbooleanevents_hourlyRollup · the CSV downloadhour_starttimestampweb_events / mobile_eventsbigintsessions / purchasesbigintlate_eventsbigintThe Flink sessionization job, the nightly Spark recompute, and the query that reconciles them.
Flink SQL: both sources unioned, deduplicated by event_id, and grouped into sessions with a 30-minute gap.
CREATE CATALOG lake WITH (
'type' = 'iceberg',
'catalog-impl' = 'org.apache.iceberg.aws.glue.GlueCatalog',
'io-impl' = 'org.apache.iceberg.aws.s3.S3FileIO',
'warehouse' = 's3://clickstream-lake/warehouse'
);
CREATE TEMPORARY TABLE web_events (
event_id STRING, anonymous_id STRING, user_id STRING, event_type STRING, page STRING,
event_ts TIMESTAMP_LTZ(3),
WATERMARK FOR event_ts AS event_ts - INTERVAL '5' MINUTE
) WITH (
'connector' = 'kafka',
'topic' = 'web.events',
'properties.bootstrap.servers' = 'kafka:9092',
'properties.group.id' = 'flink-sessionize',
'scan.startup.mode' = 'group-offsets',
'properties.auto.offset.reset' = 'latest',
'format' = 'json'
);
CREATE TEMPORARY TABLE mobile_events (
event_id STRING, anonymous_id STRING, user_id STRING, event_type STRING, page STRING, os STRING,
event_ts TIMESTAMP_LTZ(3),
WATERMARK FOR event_ts AS event_ts - INTERVAL '5' MINUTE
) WITH (
'connector' = 'kinesis',
'stream.arn' = 'arn:aws:kinesis:us-east-1:111122223333:stream/mobile-events',
'aws.region' = 'us-east-1',
'source.init.position' = 'LATEST',
'format' = 'json'
);
-- keep the first copy of each event (state expires after an hour)
SET 'table.exec.state.ttl' = '1 h';
CREATE TEMPORARY VIEW all_events AS
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY proc_time) AS rn
FROM (
SELECT event_id, anonymous_id, user_id, event_type, page, 'web' AS platform, event_ts, PROCTIME() AS proc_time FROM web_events
UNION ALL
SELECT event_id, anonymous_id, user_id, event_type, page, os AS platform, event_ts, PROCTIME() AS proc_time FROM mobile_events
)
) WHERE rn = 1;
INSERT INTO lake.clickstream.sessions
SELECT
MD5(CONCAT(anonymous_id, '|', DATE_FORMAT(window_start, 'yyyy-MM-dd HH:mm:ss.SSS'))) AS session_id,
anonymous_id,
FIRST_VALUE(platform) AS platform,
window_start AS started_at,
window_end AS ended_at,
COUNT(*) AS events,
COUNT(*) FILTER (WHERE event_type = 'page_view') AS page_views,
MAX(CASE WHEN event_type = 'purchase' THEN 1 ELSE 0 END) = 1 AS converted
FROM TABLE(
SESSION(TABLE all_events PARTITION BY anonymous_id, DESCRIPTOR(event_ts), INTERVAL '30' MINUTES)
)
GROUP BY window_start, window_end, anonymous_id;
Spark, nightly: rebuild one day of sessions from raw events, late arrivals included, and replace that day in one commit.
"""Recompute sessions for one day from raw events. Usage: recompute_day.py 2026-10-06"""
import sys
from pyspark.sql import SparkSession, Window, functions as F
day = sys.argv[1]
spark = SparkSession.builder.appName(f"recompute-sessions-{day}").getOrCreate()
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
events = (
spark.table("lake.clickstream.events")
.where(F.to_date("event_ts") == F.lit(day))
.dropDuplicates(["event_id"])
)
by_device = Window.partitionBy("anonymous_id").orderBy("event_ts")
gap_s = F.col("event_ts").cast("long") - F.lag(F.col("event_ts").cast("long")).over(by_device)
sessions = (
events
.withColumn("is_new", F.when(gap_s.isNull() | (gap_s >= 30 * 60), 1).otherwise(0))
.withColumn("session_n", F.sum("is_new").over(by_device))
.groupBy("anonymous_id", "session_n")
.agg(
F.min("event_ts").alias("started_at"),
F.max("event_ts").alias("last_event_at"),
F.first("platform", ignorenulls=True).alias("platform"),
F.count("*").alias("events"),
F.count(F.when(F.col("event_type") == "page_view", 1)).alias("page_views"),
F.max(F.col("event_type") == "purchase").alias("converted"),
)
# same id and end time as the streaming job
.withColumn("session_id", F.md5(F.concat_ws("|", "anonymous_id", F.date_format("started_at", "yyyy-MM-dd HH:mm:ss.SSS"))))
.withColumn("ended_at", F.col("last_event_at") + F.expr("INTERVAL 30 MINUTES"))
.select("session_id", "anonymous_id", "platform", "started_at", "ended_at", "events", "page_views", "converted")
)
# Replaces only the partitions present in `sessions` (this day), atomically.
sessions.writeTo("lake.clickstream.sessions").overwritePartitions()
Spark SQL with Iceberg time travel: the streaming result (before the overwrite) against the batch result (now).
WITH stream AS (
SELECT platform, count(*) AS sessions
FROM lake.clickstream.sessions TIMESTAMP AS OF '2026-10-07 01:39:00'
WHERE started_at >= '2026-10-06' AND started_at < '2026-10-07'
GROUP BY platform
),
batch AS (
SELECT platform, count(*) AS sessions
FROM lake.clickstream.sessions
WHERE started_at >= '2026-10-06' AND started_at < '2026-10-07'
GROUP BY platform
)
SELECT
b.platform,
s.sessions AS stream_sessions,
b.sessions AS batch_sessions,
round(abs(b.sessions - s.sessions) / b.sessions, 5) AS difference,
abs(b.sessions - s.sessions) / b.sessions > 0.001 AS over_limit
FROM batch AS b
JOIN stream AS s USING (platform)
ORDER BY difference DESC;
Flink was upgraded and restarted from a savepoint. Nine minutes of mobile events were processed after their sessions had closed, so the streaming count for that day was 0.14% low until the nightly recompute corrected it.
About 0.8% of events arrive after the 5-minute watermark, mostly from mobile apps that were offline. They are in the raw events table within seconds and in sessions after the nightly run.
Product dashboards read sessions about 4 seconds behind real time at p95, instead of waiting for a nightly job.
Recomputing one day takes about 38 minutes. A month-long backfill runs as one job per day, in parallel, and each day lands as its own commit.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as events_hourly.csv or read data.json.