Join hits, impressions, and clicks over a time window (YTsaurus Flow, C++)
Problem statement
Imagine a system with three types of events:
- hit — a user request event. It contains some hit_payload with useful data.
- action show — an event indicating that the user saw the response; it contains action_time.
- action click — an event indicating that the user clicked the response they saw; it contains action_time.
All events include hit_id and hit_time.
For simplicity, assume that within a user request, a hit must be present, and there can be no more than one show and no more than one click. The data arrives in two topics: hit and action.
The output will be a join of all three logs. In general, there are many possible join variants, but here we’ll focus on one specific approach:
- An action can occur several hours after a hit. However, this pipeline only considers actions where action_time < hit_time + wait_for_actions.
- The system ignores all events that happen after the hit is closed. In other words, it doesn’t allow any updates to previously emitted events.
- Hits without impressions are ignored.
- For each show, you get information about whether a click occurred and the hit_payload from the hit.
Points 1 and 2 can have other variants depending on business goals. The article The Dataflow Model covers various possible system behaviors quite well. We strongly recommend reading it.
You can find the code here.
Reading data
This part is pretty standard. Since the data is already in the required format in the input queue, you can use the combination TSwiftPassthroughOrderedSourceComputation + TQueueSource. You register action_reader, which generates the action stream, and hit_reader, which generates the hit stream.
However, for the pipeline to work correctly, you need to configure time handling properly. For both SourceComputation instances, you must set up watermark_strategy:
- You need to set
event_timestampto the appropriate time. Useevent_timestamp_assignerfor this. Foraction_reader, specify theaction_timecolumn; forhit_reader, usehit_time. - You explicitly set
watermark_generator/out_of_orderness_boundto10s. This is a key parameter for the heuristic that estimates the watermark. This value is only for tests; for real tasks, choose it based on the properties of the stream you’re reading.
You can read about all the settings in detail here.
Here’s an example spec for action_reader:
"spec" = {
"computations" = {
"action_reader" = {
"computation_class_name" = "NYT::NFlow::TSwiftPassthroughOrderedSourceComputation";
"input_stream_ids" = [];
"output_stream_ids" = ["action"];
"watermark_strategy" = {
"event_timestamp_assigner" = {
"column" = "action_time";
};
"watermark_generator" = {
"out_of_orderness_bound" = "10s";
};
};
"sources" = {
"source_stream" = {
"source_class_name" = "NYT::NFlow::TQueueSource";
"stream_id" = "injected_stream";
"parameters" = {
};
};
};
"parameters" = {};
};
};
"streams" = {
"action" = {
"schema" = [
{name = "hit_id"; type = "string";};
{name = "hit_time"; type = "uint64";};
{name = "is_click"; type = "boolean";};
{name = "action_time"; type = "uint64";};
];
};
};
};
Keep in mind that our watermark generator is heuristic, so errors are inevitable. That means that from time to time, some events will violate the watermark rules. These are usually called late data. Depending on your system’s requirements, you can handle these events in a special way. In this pipeline, they’re completely ignored, which inevitably leads to some data loss.
Joining streams
For convenience, the join is performed by the key (hit_id, hit_time). When the first event for this key arrives, a timer starts with max_time == hit_time + wait_for_actions. The system waits until all events with event_time < max_time are processed (allowing for the accuracy of our watermark, of course) and then permanently closes the corresponding hit. It generates the necessary output event and deletes the original hit profile.
Any data that arrives after the hit is closed is ignored.
First, let’s look more closely at the join spec:
{
"computations" = {
"join" = {
"computation_class_name" = "NYT::NFlow::TProcessFunctionComputation";
"processing_function" = "NYT::NFlow::NExample::TJoinFunction";
"processing_function_parameters" = {
"wait_for_actions" = "10s";
};
"group_by_schema" = [
{"name" = "hash"; "expression" = "farm_hash(hit_id)"; "type" = "uint64"};
{"name" = "hit_id"; "type" = "string"};
{"name" = "hit_time"; "type" = "uint64"};
];
"input_stream_ids" = ["action"; "hit"];
"output_stream_ids" = ["joined_action";];
"timers" = {
"timer" = {};
};
"sinks" = {
"queue" = {
"sink_class_name" = "NYT::NFlow::TAsyncQueueSink";
"input_stream_ids" = ["joined_action"];
"parameters" = {
};
};
};
};
};
streams = {
"joined_action" = {
"schema" = [
{name = "hit_id"; type = "string";};
{name = "hit_time"; type = "uint64";};
{name = "is_click"; type = "boolean";};
{name = "show_time"; type = "uint64";};
{name = "click_time"; type = "uint64";};
{name = "hit_payload"; type = "string";};
];
};
};
};
- In
group_by_schema, in addition tohit_idandhit_time, we includehash. This is for the correct operation of the partitioning algorithm. - The pipeline needs a timer to close the hit, so we register
timerintimers. We don’t specify extra settings because timers, by default, useevent_timeand the input streams. - To send the
joined_eventto an ordered dynamic table (which might be on another cluster), we use an asynchronousTAsyncQueueSink.
The join itself is implemented as a process function called TJoinFunction (a subclass of IProcessFunction that processes messages and timers element by element). It’s executed by the built-in TProcessFunctionComputation. In the spec, you set it via processing_function, and wait_for_actions is passed through processing_function_parameters. We recommend reading the code in the repository because it’s continuously improved.
Key ideas:
- When the first event for a key arrives, you create a timer to close it.
- The state for each key is described by an arbitrary type (in this example, a
TYsonStructsubclass). This object is stored in the internalFlowtables. You access the state viaTMutableStateKeyClient, which you initialize inInitusingIRuntimeInitContext::InitClient. - For each event, you record the necessary information from that event in the profile.
- When the timer fires, you generate an output event (if you have the required data) and clear the profile by calling
state.Clear(). - You get the current watermark with
context->GetInputEventWatermark()and discard all late-arriving events.
void TJoinFunction::ProcessMessage(
const TInputMessageConstPtr& message,
const IOutputCollectorPtr& output,
const IRuntimeContextPtr& context)
{
auto ysonKey = context->ConvertToYsonKey<TJoinKey>(message->Key);
auto state = JoinStateClient_.GetState(message->Key);
auto windowEnd = GetWindowEnd(ysonKey);
auto eventTimestamp = message->GetMeta().EventTimestamp;
// All messages out of the wait range are dropped.
if (eventTimestamp >= windowEnd) {
YT_TLOG_WARNING("Message is out of wait range, skip")
.With("HitId", ysonKey->HitId)
.With("WindowEnd", windowEnd);
return;
}
// Drop late data.
auto inputEventWatermark = context->GetInputEventWatermark();
if (eventTimestamp < inputEventWatermark) {
YT_TLOG_WARNING("Late message, skip")
.With("HitId", ysonKey->HitId)
.With("InputEventWatermark", inputEventWatermark);
return;
}
if (message->StreamId == "hit") {
auto hit = context->ConvertToYsonMessage<THitMessage>(message);
state->HitPayload = hit->HitPayload;
} else if (message->StreamId == "action") {
auto action = context->ConvertToYsonMessage<TActionMessage>(message);
if (action->IsClick) {
state->ClickTime = action->ActionTime;
} else {
state->ShowTime = action->ActionTime;
}
} else {
THROW_ERROR_EXCEPTION("Unknown stream %Qv", message->StreamId);
}
// Set a timer at the end of the wait window. With DeduplicateEqualTimestamps (on by
// default) timers are deduplicated by trigger timestamp; the timer fires once the event
// watermark reaches windowEnd, i.e. after (almost) all messages within the window.
output->AddTimer(windowEnd, TSystemTimestamp(ysonKey->HitTime));
}
void TJoinFunction::ProcessTimer(
const TInputTimerConstPtr& timer,
const IOutputCollectorPtr& output,
const IRuntimeContextPtr& context)
{
auto ysonKey = context->ConvertToYsonKey<TJoinKey>(timer->Key);
auto state = JoinStateClient_.GetState(timer->Key);
if (timer->StreamId != "timer") {
THROW_ERROR_EXCEPTION("Unknown stream %Qv", timer->StreamId);
}
if (state.IsEmpty()) {
return;
}
if (state->ShowTime && state->HitPayload) {
auto joinedAction = New<TJoinedActionMessage>();
joinedAction->HitId = ysonKey->HitId;
joinedAction->HitTime = ysonKey->HitTime;
joinedAction->ShowTime = *state->ShowTime;
if (state->ClickTime) {
joinedAction->IsClick = true;
joinedAction->ClickTime = *state->ClickTime;
} else {
joinedAction->IsClick = false;
joinedAction->ClickTime = 0;
}
joinedAction->HitPayload = *state->HitPayload;
output->AddMessage(context->ConvertToMessage(joinedAction));
}
state.Clear();
}
Managing objects in YTsaurus
The imaginary system described above includes the following objects:
action_queueandhit_queue— input queues.consumer— a consumer for reading the input queues and notifying the queue broker which messages are fully processed and no longer needed by the system.output_queue— the output queue with the joined input logs.producer— a producer for exactly-once writes to the output queue.state— a table for storing the key profile.pipeline— the pipeline itself, which is a collection of tables and files.
See also
You must create all these objects in YTsaurus before you start the pipeline.