Project 01 · Real-time streaming

Real-Time Streaming Lakehouse

Rider and driver apps publish trip requests, location pings, trip state changes and payments to Kafka. A Spark Structured Streaming job reads them in 10-second micro-batches, handles late events with a watermark and writes exactly once into Apache Iceberg tables on Amazon S3, so analysts can query a trip seconds after it happens. Airflow keeps the tables healthy with hourly compaction and snapshot expiry.

  • Apache Kafka
  • Spark Structured Streaming
  • Apache Iceberg
  • Amazon S3
  • Apache Airflow
Sample data Tuesday, Oct 6, 2026 · 24 hours, US Central Download data (CSV)

Trips completed per 5 minutes

Oct 6 against the same Tuesday last week

Busiest pickup zones

Completed trips, top ten zones

End-to-end freshness

Event time to committed Iceberg row, p50 and p95

Peak consumer lag by partition

Highest lag per Kafka partition today

Demand by weekday and hour

Average completed trips per hour, last four weeks

Fare distribution

Completed trips by fare band

Iceberg table health

Snapshots retained for 24 hours; compaction targets 256 MB files

Latest maintenance runs

Airflow DAG iceberg_maintenance

How it works

From an app event to a queryable Iceberg row in about 10 seconds at p95.

  1. 01 · Produce

    Rider and driver apps

    Trip requests, state changes, payments and a driver location ping every 4 seconds, as Avro events.

  2. 02 · Ingest

    Apache Kafka

    Four topics with 12 partitions each and 7-day retention. Schema Registry blocks incompatible schema changes.

  3. 03 · Process

    Spark Structured Streaming

    10-second micro-batches, deduplication on event_id and a 10-minute watermark for late events.

  4. 04 · Store

    Apache Iceberg on S3

    Hidden hourly partitions and atomic snapshot commits, so readers never see half a batch.

  5. 05 · Maintain

    Apache Airflow

    Hourly compaction, snapshot expiry and orphan-file cleanup, with an alert when a table falls behind.

  6. 06 · Query

    Trino and Athena

    Analysts and this dashboard read the same tables, seconds behind the apps.

  • Exactly once, end to end. Raw events use Iceberg's streaming sink, which records each batch's epoch in the snapshot, so a replayed batch is skipped. Trip state is upserted with MERGE on trip_id, which is safe to run twice.
  • Event time, not arrival time. Aggregations follow event_ts with a 10-minute watermark. Events later than that go to rides.late_events, and a nightly job folds them in.
  • Small files are expected, then fixed. Committing every 10 seconds creates many small files. Hourly rewrite_data_files runs compact them to about 256 MB.
  • Freshness is measured, not assumed. Every row carries ingest_ts. The job records commit time minus event time per batch, which feeds the freshness chart and its alert.

Data model

Three Iceberg tables in the rides namespace. The CSV download is the 5-minute aggregate behind the charts.

rides.trip_eventsIceberg · append · hours(event_ts)
event_idstring
Unique id from the app; used to drop duplicates
trip_idstring
Trip the event belongs to
event_typestring
requested, accepted, picked_up, completed, cancelled
rider_id / driver_idstring
Pseudonymous ids
zone_idint
Pickup zone
fare_usddecimal(8,2)
Set on completed events
event_tstimestamp
When it happened in the app
ingest_tstimestamp
When the row was committed
rides.tripsIceberg · MERGE · days(requested_ts)
trip_idstring
Primary key
statusstring
Latest state of the trip
requested_tstimestamp
Request time
pickup_ts / dropoff_tstimestamp
Null until the trip reaches that state
pickup_zone / dropoff_zoneint
Zone ids
distance_kmdecimal(6,2)
Trip distance
fare_usddecimal(8,2)
Final fare
updated_tstimestamp
Event time of the latest change; MERGE keeps the newest
rides.trips_5minIceberg · MERGE · the CSV download
interval_starttimestamp
Start of the 5-minute window
trips_requested / trips_completedbigint
Counts in the window
avg_fare_usd / avg_eta_mindouble
Averages over completed trips
events / late_eventsbigint
Events processed, and how many arrived after their window
freshness_p50_s / freshness_p95_sdouble
Event time to commit, in seconds

Key code

The streaming job, the table definitions and the Airflow DAG that maintains the tables.

Reads trip events from Kafka, appends them to rides.trip_events and upserts trip state into rides.trips every 10 seconds.

"""Kafka -> Iceberg. Raw events are appended; trip state is upserted with MERGE."""
from pyspark.sql import SparkSession, Window, functions as F
from pyspark.sql.avro.functions import from_avro

CHECKPOINTS = "s3://rides-lakehouse/checkpoints"
SCHEMA = open("schemas/trip_event.avsc").read()

spark = (
    SparkSession.builder.appName("stream-trips")
    .config("spark.sql.extensions", "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")
    .config("spark.sql.catalog.lake", "org.apache.iceberg.spark.SparkCatalog")
    .config("spark.sql.catalog.lake.catalog-impl", "org.apache.iceberg.aws.glue.GlueCatalog")
    .config("spark.sql.catalog.lake.warehouse", "s3://rides-lakehouse/warehouse")
    .getOrCreate()
)

events = (
    spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", "broker-1:9092,broker-2:9092,broker-3:9092")
    .option("subscribe", "rides.trip-events")
    .option("maxOffsetsPerTrigger", 400_000)
    .load()
    # Confluent wire format: skip the magic byte and 4-byte schema id
    .select(from_avro(F.expr("substring(value, 6, length(value) - 5)"), SCHEMA).alias("e"))
    .select("e.*")
    .withColumn("event_ts", F.expr("timestamp_millis(event_time_ms)"))
    .withColumn("ingest_ts", F.current_timestamp())
    .withWatermark("event_ts", "10 minutes")
    .dropDuplicatesWithinWatermark(["event_id"])
)

# 1) Raw events: the Iceberg sink commits each epoch once, even after a restart.
raw = (
    events.drop("event_time_ms").writeStream.format("iceberg")
    .outputMode("append")
    .trigger(processingTime="10 seconds")
    .option("checkpointLocation", f"{CHECKPOINTS}/trip_events")
    .toTable("lake.rides.trip_events")
)


# 2) Trip state: keep the newest event per trip, then MERGE (idempotent on retry).
def upsert_trips(batch, batch_id):
    newest = Window.partitionBy("trip_id").orderBy(F.col("event_ts").desc())
    (batch.where("trip_id IS NOT NULL")
          .withColumn("rn", F.row_number().over(newest))
          .where("rn = 1")
          .createOrReplaceTempView("updates"))
    batch.sparkSession.sql("""
        MERGE INTO lake.rides.trips t
        USING updates u ON t.trip_id = u.trip_id
        WHEN MATCHED AND u.event_ts > t.updated_ts THEN UPDATE SET
            status = u.event_type,
            pickup_ts = coalesce(t.pickup_ts, CASE WHEN u.event_type = 'picked_up' THEN u.event_ts END),
            dropoff_ts = CASE WHEN u.event_type = 'completed' THEN u.event_ts ELSE t.dropoff_ts END,
            fare_usd = coalesce(u.fare_usd, t.fare_usd),
            updated_ts = u.event_ts
        WHEN NOT MATCHED THEN INSERT (trip_id, rider_id, status, requested_ts, pickup_zone, updated_ts)
            VALUES (u.trip_id, u.rider_id, u.event_type, u.event_ts, u.zone_id, u.event_ts)
    """)


state = (
    events.writeStream.foreachBatch(upsert_trips)
    .trigger(processingTime="10 seconds")
    .option("checkpointLocation", f"{CHECKPOINTS}/trips")
    .start()
)

spark.streams.awaitAnyTermination()

Engineering notes

A broker restart, absorbed

At 08:20, during the morning peak, Kafka broker 2 restarted. Lag on its four partitions passed 40K events and p95 freshness broke the 15 s SLA for two intervals. The job caught up in about six minutes with no lost or duplicated rows.

Small files under control

Ten-second commits create about 8,600 snapshots a day per table. Hourly compaction keeps average files near the 256 MB target. driver_locations is flagged because its compaction is running long and needs more executors.

Late data has a home

About 0.4% of events arrive late but inside the 10-minute watermark, and are merged normally. The rare events beyond it go to rides.late_events and are folded in by a nightly batch job.

Readers never see half a batch

Each micro-batch is one Iceberg commit. Queries read the last committed snapshot, and MERGE on trip_id keeps rides.trips correct when a batch is retried.

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 trips_5min.csv or read data.json.