Trips completed per 5 minutes
Oct 6 against the same Tuesday last week
Project 01 · Real-time streaming
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.
Oct 6 against the same Tuesday last week
Completed trips, top ten zones
Event time to committed Iceberg row, p50 and p95
Highest lag per Kafka partition today
Average completed trips per hour, last four weeks
Completed trips by fare band
Snapshots retained for 24 hours; compaction targets 256 MB files
Airflow DAG iceberg_maintenance
From an app event to a queryable Iceberg row in about 10 seconds at p95.
01 · Produce
Rider and driver apps
Trip requests, state changes, payments and a driver location ping every 4 seconds, as Avro events.
02 · Ingest
Apache Kafka
Four topics with 12 partitions each and 7-day retention. Schema Registry blocks incompatible schema changes.
03 · Process
Spark Structured Streaming
10-second micro-batches, deduplication on event_id and a 10-minute watermark for late events.
04 · Store
Apache Iceberg on S3
Hidden hourly partitions and atomic snapshot commits, so readers never see half a batch.
05 · Maintain
Apache Airflow
Hourly compaction, snapshot expiry and orphan-file cleanup, with an alert when a table falls behind.
06 · Query
Trino and Athena
Analysts and this dashboard read the same tables, seconds behind the apps.
MERGE on trip_id, which is safe to run twice.event_ts with a 10-minute watermark. Events later than that go to rides.late_events, and a nightly job folds them in.rewrite_data_files runs compact them to about 256 MB.ingest_ts. The job records commit time minus event time per batch, which feeds the freshness chart and its alert.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_idstringtrip_idstringevent_typestringrequested, accepted, picked_up, completed, cancelledrider_id / driver_idstringzone_idintfare_usddecimal(8,2)completed eventsevent_tstimestampingest_tstimestamprides.tripsIceberg · MERGE · days(requested_ts)trip_idstringstatusstringrequested_tstimestamppickup_ts / dropoff_tstimestamppickup_zone / dropoff_zoneintdistance_kmdecimal(6,2)fare_usddecimal(8,2)updated_tstimestamprides.trips_5minIceberg · MERGE · the CSV downloadinterval_starttimestamptrips_requested / trips_completedbigintavg_fare_usd / avg_eta_mindoubleevents / late_eventsbigintfreshness_p50_s / freshness_p95_sdoubleThe 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()
Iceberg table definitions. Hidden partitioning means queries filter on event_ts and Iceberg prunes the files.
-- Raw events: append-only, partitioned by hour without a separate partition column.
CREATE TABLE IF NOT EXISTS lake.rides.trip_events (
event_id STRING NOT NULL,
trip_id STRING,
event_type STRING NOT NULL,
rider_id STRING,
driver_id STRING,
zone_id INT,
fare_usd DECIMAL(8, 2),
event_ts TIMESTAMP NOT NULL,
ingest_ts TIMESTAMP NOT NULL
)
USING iceberg
PARTITIONED BY (hours(event_ts))
TBLPROPERTIES (
'format-version' = '2',
'write.target-file-size-bytes' = '268435456',
'write.distribution-mode' = 'hash',
'history.expire.max-snapshot-age-ms' = '86400000', -- keep 24 hours of snapshots
'write.metadata.delete-after-commit.enabled' = 'true',
'write.metadata.previous-versions-max' = '50'
);
-- Current state of every trip, upserted each micro-batch. Merge-on-read keeps MERGE cheap.
CREATE TABLE IF NOT EXISTS lake.rides.trips (
trip_id STRING NOT NULL,
rider_id STRING,
driver_id STRING,
status STRING,
requested_ts TIMESTAMP,
pickup_ts TIMESTAMP,
dropoff_ts TIMESTAMP,
pickup_zone INT,
dropoff_zone INT,
distance_km DECIMAL(6, 2),
fare_usd DECIMAL(8, 2),
updated_ts TIMESTAMP NOT NULL
)
USING iceberg
PARTITIONED BY (days(requested_ts), bucket(16, trip_id))
TBLPROPERTIES (
'format-version' = '2',
'write.merge.mode' = 'merge-on-read',
'write.update.mode' = 'merge-on-read',
'history.expire.max-snapshot-age-ms' = '86400000'
);
Hourly Airflow DAG: compact small files, then expire old snapshots. Orphan files are removed once a night.
"""Hourly Iceberg upkeep for the rides tables."""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import ShortCircuitOperator
from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator
TABLES = ["rides.trip_events", "rides.driver_locations", "rides.trips", "rides.payments"]
COMPACT = """
CALL lake.system.rewrite_data_files(
table => '{table}',
strategy => 'binpack',
options => map(
'target-file-size-bytes', '268435456',
'min-input-files', '8',
'partial-progress.enabled', 'true'))
"""
EXPIRE = "CALL lake.system.expire_snapshots(table => '{table}', retain_last => 100)"
ORPHANS = "CALL lake.system.remove_orphan_files(table => '{table}')"
with DAG(
dag_id="iceberg_maintenance",
schedule="15 * * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
max_active_runs=1,
default_args={"retries": 2, "retry_delay": timedelta(minutes=5)},
tags=["iceberg", "maintenance"],
) as dag:
nightly = ShortCircuitOperator(
task_id="only_at_3am",
python_callable=lambda data_interval_end, **_: data_interval_end.hour == 3,
)
for table in TABLES:
name = table.split(".")[-1]
compact = SparkSqlOperator(task_id=f"compact_{name}", sql=COMPACT.format(table=table), conn_id="spark_lake")
expire = SparkSqlOperator(task_id=f"expire_{name}", sql=EXPIRE.format(table=table), conn_id="spark_lake")
orphans = SparkSqlOperator(task_id=f"orphans_{name}", sql=ORPHANS.format(table=table), conn_id="spark_lake")
compact >> expire
nightly >> orphans
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.
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.
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.
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.