PUse the traffic control module in PAI-Rec

Updated at:

This topic walks you through the complete traffic control workflow in PAI-Rec, from preparation to engine-side configuration.

Prerequisites

Note

When a traffic control task is created, PAI-Rec generates a Flink SQL job for real-time statistics. This SQL job is deployed to the Flink platform when the task is published. You must upload the JAR package manually before you begin.

Complete the following one-time setup before you create a traffic control task:

  1. Download the traffic control JAR package (Traffic control JAR package) and the FeatureStore JAR package. For the required versions, see Configure Flink Connector.

  2. Go to the Flink Realtime Compute console. If you do not have an instance, purchase one first. Select a workspace. Make sure that the primary account holder or the instance purchaser has added you to the workspace; otherwise, you will not have access. In the left-side navigation pane, choose Connectors, and then click Create Custom Connector. Upload the traffic control JAR package that you downloaded to register the connectors. The traffic control JAR package contains multiple connectors (traffic-ctrl-sink, traffic-ctrl-lookup, traffic-lookup, http-sink, and rest-lookup). Upload and create each connector one by one. If a connector has a Lookup option, enable it. Do not change any other parameters.

  3. In the left-side navigation pane, choose ETL > Functions. Click the + icon and upload the traffic control JAR package to register the UDF. In the Register UDF JAR dialog box, set UDF Name to traffic-ctrl, and then click OK. After the system scans the JAR package, the UDF function list appears: ConditionMatch, DynamicTarget, and ExplodeSplit. Click Create Function to confirm.

PAI-Rec configuration

1. Create a traffic control task

Go to the PAI-Rec console. In the left-side navigation pane, choose Operations > Traffic Control, and then click Create Task.

1.1 Configure basic information

When you create a traffic control task, specify the task name, description, target scenarios, and engine services. Configure the Flink data source and execution duration (a specific time range or permanent). In the dependent data source configuration, select the behavior table, item table, and user table. At the bottom of the page, select the experiment group and experiment for both the staging and production environments.

Parameter

Description

Task Name

A custom name for the traffic control task.

Task Description

A brief description of the task.

Target Scenarios

The scenarios where traffic control takes effect. The first scenario is the primary scenario. All report data is aggregated under this scenario.

Engine Services

The engine services where traffic control applies. You can deploy multiple engine services and limit traffic control to specific ones.

Flink Data Source

The Flink data source registered on the cloud product configuration page.

Execution Duration

A specific time range, or permanent execution.

Dependent Data Sources

The three tables registered on the data registration page: behavior table, item table, and user table.

Staging Experiment

The experiment to control in the staging environment.

Production Experiment

The experiment to control in the production environment.

1.2 Select the target audience

Parameter

Description

Example

Target Audience

Filters which user requests are subject to traffic control. If this parameter is not configured, all users are included.

gender='man': only requests from male users are subject to traffic control. Multiple conditions in array format are combined with AND logic.

Behavior Filter

Filters real-time behavior logs by behavior type. If your target is impressions, enter the impression event value here. Do not leave this empty — an empty value causes all logs to participate in the calculation, which is illogical.

event_type=expose. Note that event_type and expose depend on your field names and values. This is only an example. Multiple conditions in array format are combined with AND logic.

Custom expressions support multiple operator types: arithmetic, logical, comparison, and set operators.

  • Arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and modulo (%).

  • Logical operators: AND (&&), OR (||), and NOT (!).

  • Comparison operators: equal (==), not equal (!=), less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=).

  • Set operators: for example, in checks whether an element is in a set.

1.3 Configure control targets

Parameter

Description

Control Type

  • Proportional: controls the ratio of traffic allocated to the control pool relative to the total task traffic. The total task traffic is defined as the total traffic of the item set associated with the task. If no item set is associated, the total traffic of the current control scenario is used.

  • Absolute volume: guarantees a specific amount of traffic for the control pool.

Granularity

  • When the control type is proportional, only global granularity is available.

  • When the control type is absolute volume, both global and per-item granularity are available:

    • Global: the total traffic across all items in the control pool.

    • Per-item: the target traffic for each individual item in the control pool.

Control Logic

  • Guarantee: the task ensures that the current metric meets or exceeds the target. If the current metric already exceeds the target, subsequent control logic is skipped.

  • Approach: the task drives the current metric toward the target. If the current metric exceeds the target, items in the control pool are suppressed. If the current metric falls below the target, items are boosted. Note: when multiple "Approach" tasks share the same item subset, conflicting targets may prevent all goals from being met.

Item Scope

All active items currently online. For proportional control tasks, the traffic of the items in this scope serves as the denominator for calculating the control ratio.

Control targets: A traffic control task can contain multiple control targets. Each control target defines the item subset to control and sets the target values.

Parameter

Description

Target Name

A custom name for the control target.

Target Time Window

Select a time range. Use a longer window for more stable results.

Controlled Item Set

Filters the control pool based on item attributes.

Target Value

For proportional control, this is the target percentage.

For absolute volume control, this is the total volume or per-item volume.

Tolerance Range

The acceptable deviation from the target. For example, a value of 10 means the target is considered met if the actual value falls within [x, x×(1+10%)]. A value of -10 means the target is met if the actual value falls within [x×(1-10%), x]. For proportional "Approach" tasks, setting a tolerance range avoids reverse control when overshooting occurs, which helps reduce interference with overall metrics.

New Item Control

This parameter is not in effect. Ignore it. New item control is a cold-start scenario where new items cannot be produced from existing recall pipelines and require a separate recall pipeline.

Enabled

Whether this control target is active.

After you configure the settings, click Save to go to the publish page.

1.4 Publish the Flink task

Two Flink SQL scripts are generated.

The Flink task performs real-time counting of the controlled target items.

  1. Reset the offset of the Datahub/Kafka behavior data to 00:00 of the current day. Resetting the offset calibrates the consumption start point to eliminate interference from historical state, ensuring strict alignment of data within the time window and processing logic, and guaranteeing complete and accurate statistical results.

    A prompt dialog box may appear when you publish the task. Follow the on-screen instructions to complete the Datahub and Debug configurations.

    The dialog box shows the completion status of the Datahub and Debug configurations. Click Go to Configure to navigate to the corresponding configuration page.

  2. The generated statistics SQL requires AccessKey credentials at runtime. For the first traffic control task, click Create Flink Project Variable, and then configure your AccessKey credentials on the Flink platform before you publish the task. The red prompt area on the page indicates that ACCESS_KEY_ID and ACCESS_KEY_SECRET must be configured.

    After the variable is created, the following two variables appear in the variable management section of the Flink console. Set your AccessKey credentials.

    The two variables are ACCESS_KEY_ID and ACCESS_KEY_SECRET, both of type Ciphertext. Enter your AccessKey credentials here.

  3. After the preceding steps, click Publish Flink Task. Publish the staging environment first, and then publish the production environment. Publishing takes some time. Click View Flink Publish Status to monitor the deployment progress. On the Flink platform, go to ETL > Job Drafts to view the SQL drafts (suffixed with the task ID). In Operations, check the job status (Starting => Running).

    On the traffic control task page, switch to the Staging environment and click Publish Flink Task. The system displays a message: "Deployment triggered. Wait approximately 3 minutes." You can check the deployment status of each Flink job in the task list. A successful publish is shown as follows:

    On the Flink platform, go to ETL > Operations. The deployed Flink job appears with a status of RUNNING, which indicates that the task is running normally.

    In the task list, use the Start switch to control the start and stop status of the traffic control task.

    If an error occurs during the Flink task publish, follow the error message to adjust the configuration, and then click Retry to continue, or go to the Flink platform to investigate the root cause and deploy the corresponding Flink job.

2. Publish and start the task

After a traffic control task is published, you cannot modify the task parameters. You can only add or disable control targets.

After the task is published, start the task. Start the staging traffic control task first. After the entire pipeline runs correctly, start the production task.

Use the environment switch in the upper-left corner to publish or start tasks in different environments.

Engine configuration

Add the following configurations to your existing engine configuration based on your business requirements.

1. Traffic control configuration

Apply this configuration to both the staging and production environments.

  • DefaultKp, DefaultKi, and DefaultKd are the three default PID algorithm parameters: Kp, Ki, and Kd. You can override these values through A/B experiment configurations.

  • DiversityRuleSort is the Diversity re-ranking (DiversityRuleSort).

    "SortConfs": [
        {
            "Name": "TrafficControlSort",
            "SortType": "TrafficControlSort",
            "PIDConf": {
                "DefaultKp": 5,
                "DefaultKi": 1,
                "DefaultKd": 1
            }
        },
        {
            "Name": "TrafficDiversityRuleSort",
            "SortType": "DiversityRuleSort",
            "DiversitySize": 20,
            "DiversityRules": [
                {
                    "Dimensions": [
                        "__traffic_control_id__"
                    ],
                    "WindowSize": 10,
                    "FrequencySize": 2
                }
            ]
        }
    ],
    "SortNames": {
        "home_feed": [
            "TrafficControlSort",
            "TrafficDiversityRuleSort"
        ]
    },
  • TrafficControlSort is the traffic control module in the engine. After this module runs, it adds a special field to each item: __traffic_control_id__.

    • The __traffic_control_id__ field indicates whether an item's position was "moved forward." If the item was moved forward, the field value is set to 0. Otherwise, the field value is set to the item's original position in the list.

    • "Moved forward" means the following: in an item array, if an item was originally positioned beyond the requested size (meaning it had no chance of being displayed), and traffic control promoted it within the size limit so that it now has a display opportunity, the item is marked with __traffic_control_id__=0. If an item was already within the size limit before control and remains within the limit after control, it is not marked as 0. This is because the item was already in the display list before and after control, so it is attributed to organic traffic rather than traffic control.

  • DiversityRuleSort is the diversification module in the engine. You can configure diversification constraints on the __traffic_control_id__ field. For example, in the output list, allow at most 2 "moved forward" items per 10 positions.

    • Without DiversityRuleSort, users may see a screen full of items that were promoted from lower-ranked positions. These items typically have lower relevance, which degrades personalization, harms user experience, and negatively affects overall metrics.

2. Advanced configuration

2.1 Proportional control

No additional configuration is required.

2.2 Absolute volume control

Apply this configuration to both the staging and production environments. After you configure traffic control, add the following configuration. Directly recalling all controlled items places significant pressure on the ranking system. To address this, define a custom PipelineConfs that retrieves RetainNum: 300 items per request from the recall table for ranking, and then merges them into the main pipeline. For configuration details, see Customize pipelines.

"PipelineConfs": {
    "home_feed": [
        {
            "Name": "newitem",
            "FilterNames": [
                "UniqueFilter",
                "UserExposureFilter15Min",
                "UserExposureFilterReal",
                "adjust_count_filter"
            ],
            "RecallNames": [
                "new_item_1500_recall"
            ],
            "RankConf": {
                "RankAlgoList": [
                    "fs_dbmtl_v4"
                ],
                "RankScore": "${fs_dbmtl_v4_probs_is_click}+${fs_dbmtl_v4_probs_is_collect_like_comment}",
                "BatchCount": 400,
                    "Processor": "EasyRec"
                },
                FeatureLoadConfs": [
                    {
                        "FeatureDaoConf": {
                        "AdapterType": "hologres",
                        "HologresName": "holo_info",
                        "ItemFeatureKeyName": "item_id",
                        "FeatureKey": "item:id",
                        "HologresTableName": "xxx_home_feed_new_item_1500_v2_online",
                        "ItemSelectFields": "item_id,is_1500_new_item",
                        "FeatureStore": "item"
                    },
                    "Features": []
                }
            ]
        }
    ]
},
"RecallConfs": [
    {
        "Name": "new_item_1500_recall",
        "RecallType": "ColdStartRecall",
        "RecallCount": 1500,
        "ColdStartDaoConf": {
            "AdapterType": "hologres",
            "HologresName": "holo_info",
            "HologresTableName": "xxx_home_feed_new_item_1500_v2_online",
            "WhereClause": "is_complated='1'",
            "PrimaryKey": "\"item_id\""
        }
    }
],
"FilterConfs": [
    {
        "Name": "adjust_count_filter",
        "FilterType": "AdjustCountFilter",
        "ShuffleItem": true,
        "RetainNum": 300
    }
]

FAQ

1. Why must TrafficControlSort and DiversityRuleSort be used together?

TrafficControlSort is the traffic control module in the PAI-Rec engine. After this module runs, it adds a special field to each item: __traffic_control_id__.

  • The __traffic_control_id__ field indicates whether an item's position was "moved forward." If the item was moved forward, the field value is set to 0. Otherwise, the field value is set to the item's original position in the list.

DiversityRuleSort is the diversification module in the PAI-Rec engine. You can configure diversification constraints on the __traffic_control_id__ field. For example, in the output list, allow at most 3 "moved forward" items per 10 positions.

Without DiversityRuleSort, users may see a screen full of items that were promoted from lower-ranked positions. These items typically have lower relevance, which degrades personalization, harms user experience, and negatively affects overall metrics.

2. How do I tune PID parameters?

Reference: Traffic Control PID Parameter Tuning Guide

Link: https://zhuanlan.zhihu.com/p/643275184

3. What is the algorithm behind traffic control?

Reference: https://pai-vision-data-hz.oss-cn-zhangjiakou.aliyuncs.com/pairec/docs/pairec/html/traffic_control/traffic_control.html