---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.0
alternate:
  - https://ytsaurus.tech/docs/en/flow/python/examples/wait_click_join.md
  - https://ytsaurus.tech/docs/ru/flow/python/examples/wait_click_join.md
  - href: https://ytsaurus.tech/docs/en/flow/python/examples/wait_click_join.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/en/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/en/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed

<!-- source: en/_includes/flow/python/examples/wait_click_join.md -->
# Wait Click Join in YTsaurus Flow (Python)

This is an example of a join-pipeline that merges hit and action streams by key, using timers and external state. It’s a Python implementation of a similar C++ example.

[Source code](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/python/wait_click_join)

## Structure

The pipeline includes a single transform computation called `join`, which:

- Receives messages from two input streams: `hit` and `action`.
- Accumulates data in the external state.
- Sets a timer for the end of the waiting window.
- When the timer triggers, it generates a join result or clears the state.

## `__main__.py`

```python
def main():
    log.info("Starting companion execution")

    pipeline = Pipeline()
    pipeline.add("join", JoinProcessFunction())

    log.info("Starting pipeline...")
    pipeline.run()
    log.info("Pipeline completed")
```

## `join_process_function.py`

This file holds the core join logic. The function processes two streams and uses timers for windowed aggregation:

### `on_message`

```python
    def on_message(self, message, output, ctx):
        stream_id = message.stream_id

        if stream_id == "hit":
            hit_id = message.payload["hit_id"]
            hit_time = message.payload["hit_time"]
            hit_payload = message.payload["hit_payload"]
        elif stream_id == "action":
            hit_id = message.payload["hit_id"]
            hit_time = message.payload["hit_time"]
        else:
            raise ValueError(f"Unknown streamId: {stream_id}")

        log.debug("Process message (Key: %s, HitId: %s, HitTime: %s)", message.key, hit_id, hit_time)

        wait_time = _parse_duration_seconds(ctx.parameters["wait_for_actions"])
        max_time = hit_time + wait_time

        # All messages out of wait range would be dropped.
        if message.event_timestamp >= max_time:
            log.warning(
                "Message is out of wait range, skip (HitId: %s, HitTime: %s, MaxTime: %s)",
                hit_id,
                hit_time,
                max_time,
            )
            return

        # Drop late data.
        if message.event_timestamp < ctx.min_watermark:
            log.warning(
                "Late message, skip (HitId: %s, EventTimestamp: %s, InputEventWatermark: %s)",
                hit_id,
                message.event_timestamp,
                ctx.min_watermark,
            )
            return

        state = ctx.external_state("/join-state", message)
        builder = state.to_builder()

        if stream_id == "hit":
            log.debug("Process hit message (HitId: %s, HitPayload: %s)", hit_id, hit_payload)
            builder.set("hit_payload", hit_payload)
        else:
            action_time = message.payload["action_time"]
            is_click = message.payload["is_click"]
            log.debug("Process action message (HitId: %s, ActionTime: %s)", hit_id, action_time)
            if is_click:
                builder.set("click_time", action_time)
            else:
                builder.set("show_time", action_time)

        state.set(builder.finish())
        log.debug("Add timer for Key (MaxTime: %s, HitTime: %s)", max_time, hit_time)
        output.add_timer(max_time, hit_time)
```

### `on_timer`

```python
    def on_timer(self, timer, output, ctx):
        hit_id = timer.key["hit_id"]
        log.debug("Process timer (KeyHitId: %s, Timer: %s)", hit_id, timer)

        state = ctx.external_state("/join-state", timer)

        log.debug("Process state (KeyHitId: %s, State: %s)", hit_id, state)

        if timer.stream_id == "timer":
            show_time = state.get("show_time")
            hit_payload = state.get("hit_payload")

            if show_time is not None and hit_payload is not None and show_time != 0:
                log.debug("Click join: %s", state)
                hit_time = timer.key["hit_time"]
                click_time = state.get("click_time")

                builder = ctx.message_builder("joined_action")
                builder.set("hit_id", hit_id)
                builder.set("hit_time", hit_time)
                builder.set("show_time", show_time)
                builder.set("hit_payload", hit_payload)

                if click_time is not None and click_time != 0:
                    builder.set("is_click", True)
                    builder.set("click_time", click_time)
                else:
                    builder.set("is_click", False)
                    builder.set("click_time", 0)

                output.add_message(builder.finish())

            state.clear()
        else:
            raise ValueError(f"Unknown streamId: {timer.stream_id}")
```

## Key patterns

- **External state** with `ctx.external_state("/join-state", message)`: use the `to_builder()` / `set()` / `clear()` pattern to accumulate data from multiple streams.
- **Timers** via `output.add_timer(max_time, hit_time)`: set a timer with `trigger_timestamp` (when it fires) and `event_timestamp` (linked to the event).
- **Late data filtering**: use `message.event_timestamp < ctx.min_watermark` to discard late data (learn more about watermarks).
- **Computation parameters**: read configuration from the spec with `ctx.parameters["wait_for_actions"]`.
- **MessageBuilder**: create output messages with a defined schema using `ctx.message_builder("joined_action")`.
- **Processing multiple streams**: branch on `message.stream_id` to apply different logic for handling hit and action streams.
<!-- endsource: en/_includes/flow/python/examples/wait_click_join.md -->

<!-- source: en/_includes/flow/python/examples/wait_click_join_also.md -->
## See also

- [Quick start (Python)](https://ytsaurus.tech/docs/en/flow/python/getting-started.md)
- [Timers](https://ytsaurus.tech/docs/en/flow/concepts/timers.md)
- [Stateful processing](https://ytsaurus.tech/docs/en/flow/concepts/stateful.md)
<!-- endsource: en/_includes/flow/python/examples/wait_click_join_also.md -->
