For a Python solution, you can use Apache Beam, since it offers a Python SDK and can work with streaming data, leveraging runners such as Google Dataflow, Apache Flink, and Apache Spark. Apache Beam uses a model which allows the same code to run both in batch and streaming modes.
Here is a high-level Python solution using Apache Beam to calculate the average time for each step:
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from datetime import datetime
from apache_beam.transforms.window import SlidingWindows
# Options for the Beam pipeline
options = PipelineOptions(
runner='YourChosenRunner', # e.g., DirectRunner, DataflowRunner, FlinkRunner etc.
streaming=True,
)
# A parsing function to convert raw event to a tuple (user_id, step_num, event_timestamp)
def parse_event(line):
user_id, step_num, timestamp_str = line.split(',')
event_timestamp = datetime.strptime(timestamp_str.strip(), '%Y-%m-%d %H:%M:%S')
return user_id, int(step_num), event_timestamp.timestamp()
# A function that generates tuples for time elapsed between steps
def compute_time_difference(element):
(user_id, events) = element
steps = list(events)
steps.sort(key=lambda e: e[1]) # Sort by step_num
for i in range(len(steps) - 1):
current_step = steps[i]
next_step = steps[i+1]
time_diff = next_step[2] - current_step[2]
yield (user_id, next_step[1], time_diff)
# The main pipeline
with beam.Pipeline(options=options) as p:
# Read the events from your source e.g., Pub/Sub, Kafka topic, etc.
events = (p
| 'ReadEvents' >> beam.io.ReadFromPubSub(subscription='your-subscription')
| 'ParseEvents' >> beam.Map(parse_event))
# Add timestamps to use in windowing
timestamped_events = (events
| 'AddEventTimestamps' >> beam.Map(lambda x: beam.window.TimestampedValue(x, x[2])))
# Assign the events to windows of a certain duration
windowed_events = (timestamped_events
| 'WindowInto' >> beam.WindowInto(SlidingWindows(60, 5))) # For instance, 1-minute windows with 5-second slides
# Group events by user_id
grouped_events = (windowed_events
| 'GroupByUserId' >> beam.GroupByKey())
# Calculate the average difference in timestamps for consecutive steps
step_durations = (grouped_events
| 'ComputeTimeDifferences' >> beam.FlatMap(compute_time_difference)
| 'GroupByStep' >> beam.GroupByKey()
| 'CalculateAverages' >> beam.Map(lambda x: (x[0], sum(x[1]) / len(x[1]))))
# Write the output to a sink, e.g., BigQuery, or console for debugging
output = (step_durations | 'WriteToSink' >> beam.io.WriteToText('output.txt'))
Some specifics, like the source of the input data (ReadFromPubSub in this case), would have to be adapted based on where and how your data is ingested.
Please note that computing averages for variable-length windows isn't straightforward because you would normally emit a result for a window upon its closure. Assuming events aren't late beyond the allowed lateness for the window, you would get an updated average every time a new event is accounted for in a window.
Always be sure to test extensively and tune your watermarks, windows, and triggers according to your data's specific patterns and lateness.