Design and Optimize a PySpark Job for Time-Series Data Aggregation

Instruction: Given a dataset containing timestamps and metrics from various sensors, design a PySpark job to aggregate this data into hourly averages. Detail the steps you would take to optimize this job for efficiency and performance.

Context: This question assesses the candidate's ability to work with time-series data in PySpark, requiring knowledge of data transformation, efficient aggregation methods, and optimization techniques. Candidates should demonstrate their understanding of PySpark's capabilities to process time-series data efficiently, considering aspects like time window partitioning, handling time zones, and optimizing for minimal data shuffling.

Updated

First decide whether the metric is an average of observations or a time-weighted average. This example computes the former, independently for each sensor, in half-open UTC hour windows: a reading at 01:00 belongs to the next hour. Hours with no readings are absent.

With an existing session named spark:

from pyspark.sql import functions as F

previous_zone = spark.conf.get('spark.sql.session.timeZone')
try:
    spark.conf.set('spark.sql.session.timeZone', 'UTC')
    readings = spark.createDataFrame([
        ('a', '2026-01-01T00:00:00Z', 2.0),
        ('a', '2026-01-01T00:59:59Z', 4.0),
        ('a', '2026-01-01T01:00:00Z', 8.0),
        ('b', '2026-01-01T00:30:00Z', 10.0),
    ], 'sensor string, time_text string, value double')
    typed = readings.withColumn('event_time', F.to_timestamp('time_text'))
    assert typed.filter(F.col('event_time').isNull()).count() == 0
    hourly = typed.groupBy('sensor', F.window('event_time', '1 hour')).agg(
        F.avg('value').alias('mean'), F.count('value').alias('observations')
    )
    result = hourly.select('sensor',
        F.date_format('window.start', 'HH:mm').alias('hour'),
        'mean', 'observations').orderBy('sensor', 'hour')
    assert [tuple(r) for r in result.collect()] == [
        ('a', '00:00', 3.0, 2), ('a', '01:00', 8.0, 1), ('b', '00:00', 10.0, 1)
    ]
finally:
    spark.conf.set('spark.sql.session.timeZone', previous_zone)

The fixture uses valid offset-bearing timestamps and finite metrics. Production parsing needs an explicit invalid-input policy, including whether malformed timestamps raise under the runtime's ANSI settings. Quarantine null/nonfinite metrics, reject missing sensor IDs, resolve duplicate event IDs and retain rejected counts. Do not assign UTC to naive local times without knowing their source zone; daylight-saving ambiguity needs an explicit rule. Join a sensor/hour calendar if missing hours must be reported, and distinguish missing readings from measured zero.

Read only required columns and time ranges, use appropriate columnar files and inspect the plan and Spark UI. The grouped aggregation normally needs an exchange; a blind pre-repartition may add one. Cache only if the same expensive result is reused, and measure task skew, spill and output-file size. In a streaming variant, add event-time state/watermark, output-mode and late-correction policies rather than assuming the batch job's semantics automatically carry over.

Time windows, SQL tuning

Related Questions