Configure Managed Service for Prometheus
The PAI-Rec engine supports collecting metric data through Prometheus. This topic describes how to enable this feature, explains the metrics, and shows how to add custom metrics.
Background
A recommendation pipeline consists of many stages. In addition to the overall running status of the engine, you usually need more fine-grained data to observe each stage.
The PAI-Rec engine supports collecting metric data through Prometheus, which achieves the following goals:
Enhanced system visibility: Collecting and analyzing multi-dimensional metric data helps development and O&M teams gain a clearer understanding of the running status and performance bottlenecks of the system.
Rapid troubleshooting: Observability enables teams to quickly identify and locate the source of problems in the system. This shortens the time to resolve faults and improves system reliability and availability.
Improved response efficiency: With real-time monitoring and alerting mechanisms, teams can take action before problems affect users, which reduces the losses caused by system failures.
Enable metric collection
To enable metric collection, add the corresponding configuration to the engine configuration list. The following sample shows the configuration:
{
"PrometheusConfig": {
"Enable": true,
"PushGatewayURL": "https://your_pushgateway_url",
"PushIntervalSecs": 15
}
}The following table describes the configuration parameters:
Field | Type | Required | Description |
Enable | bool | Yes | Specifies whether to enable metric collection. This feature is disabled by default. |
PushGatewayURL | string | No | The address of the Prometheus Push Gateway: After this field is configured, metric data is pushed to this address. |
PushIntervalSecs | int | No | The interval at which metrics are pushed, in seconds. To push metrics, you must set this field to a value greater than 0. |
PushGatewayToken | string | No | If token protection is enabled for Prometheus, you must specify the token. |
PushGatewayUseAliyunCredential | bool | No | Specifies whether to use an Alibaba Cloud credential to access the Push Gateway. This feature is disabled by default. After it is enabled, the engine automatically obtains a credential through the Alibaba Cloud default credential chain (the RAM role of the EAS instance) and completes authentication. Requires engine version 2.1.7 or later |
After you modify the configuration, restart the engine for the configuration to take effect.
Two collection methods
The PAI-Rec engine supports two metric collection methods: Pull and Push.
Collection method | Description | Scenarios |
Pull (enabled by default) | The engine exposes a metrics endpoint, which Prometheus actively scrapes. | Scenarios where Prometheus can access the engine instances directly and the instance addresses are fixed. |
Push | The engine periodically pushes metrics to the Prometheus Push Gateway. You must set PushGatewayURL and PushIntervalSecs in the engine configuration and complete the authentication configuration. | The engine is deployed in an environment where instances scale dynamically, such as PAI-EAS. |
In Pull mode, the engine exposes the following two endpoints, which correspond to built-in metrics and custom metrics respectively:
Built-in metrics:
http://${your_service_host}/metricsCustom metrics:
http://${your_service_host}/custom_metrics
Important: When the engine service is deployed on PAI-EAS, instances are dynamically scheduled and accessed through a gateway. The Pull method cannot correctly obtain the metrics of all instances. Use the Push method instead.
Observe metrics
The following example uses Alibaba Cloud Managed Service for Prometheus (CloudMonitor) to describe how to observe metrics.
Resource preparation
Managed Service for Prometheus in CloudMonitor is activated.
A Prometheus instance is created: In the console sidebar, choose Prometheus Monitoring > Instances > Create Prometheus Instance.
The Prometheus instance is integrated into a non-shared Grafana workspace. If the current region has no non-shared Grafana workspace, create one: In the console sidebar, choose Grafana Service > Workspace Management > Cloud Service Integration, select the Prometheus instance, and click Integrate.
Integration procedure
Obtain the Push Gateway address: On the Instances page of the CloudMonitor console, in the Actions column of the target instance, click Settings. In the Push Gateway Address section, obtain the URL. Select the public endpoint or the internal endpoint based on the actual network environment of the engine service.
Configure authentication: Complete the authentication configuration based on the instance version. For details, see "CloudMonitor Push Gateway authentication" below. Taking a V2 instance as an example, you must grant the AliyunPrometheusMetricWriteAccess permission to the RAM role AliyunPAIRecEASRole.
Enable metric pushing for the engine: Add the PrometheusConfig configuration to the engine configuration list and restart the engine.
Verify metric pushing: Check the engine service logs to confirm that no
Error sending to push gatewayerror is reported. Alternatively, on the metric management page of the Prometheus monitoring instance, query built-in metrics such aspairec_rec_totalto confirm that data is present.Import the metrics dashboard: Visit the Grafana public (or private) endpoint and log on. In the sidebar, click Dashboards. In the upper-right corner, click New and select Import. Upload the dashboard configuration JSON file (download link: PAI-Rec Grafana dashboard configuration JSON), set the datasource to the corresponding Prometheus instance, and click Import.
After you complete the preceding steps, you can view the metrics dashboard. In addition to the preconfigured metrics dashboard, you can refer to the metric descriptions below and add your own dashboards for observation.
CloudMonitor Push Gateway authentication
By default, the Push Gateway of a CloudMonitor Prometheus instance does not allow anonymous writes. Push requests that fail authentication return a 401 error. Select the corresponding integration method based on the instance version and the password-free configuration:
Scenario | Authentication method | Engine-side configuration |
Instances with password-free access enabled | Password-free (IP address whitelist) | No additional configuration is required. |
CloudMonitor V1 Prometheus instances | Token authentication | PushGatewayToken |
CloudMonitor V2 Prometheus instances | Alibaba Cloud credential authentication Requires engine version 2.1.7 or later | PushGatewayUseAliyunCredential |
Password-free access
After you enable password-free writes and configure a client IP address whitelist on the Prometheus instance, clients in the whitelist do not need to carry authentication information when they push data. No additional configuration is required on the engine side. For instructions, see Configure and use password-free access for a Prometheus V2 instance.
Important: After you enable password-free access, do not specify PushGatewayToken or enable PushGatewayUseAliyunCredential in the engine configuration. Otherwise, the server still performs RAM authentication based on the identity that is carried, which may cause access to be denied.
Token authentication (CloudMonitor V1 instances)
Push Gateway data protection for V1 instances is based on a token generated in the console. After you enable Token protection, you must carry the token in the engine configuration.
Log on to the CloudMonitor console and go to the Settings page of the target instance. In the Token section, click Generate Token and copy the token value.
Specify PushGatewayToken in the engine configuration and restart the engine.
{
"PrometheusConfig": {
"Enable": true,
"PushGatewayURL": "https://your_pushgateway_url",
"PushIntervalSecs": 15,
"PushGatewayToken": "your_token"
}
}Alibaba Cloud credential authentication (CloudMonitor V2 instances)
V2 instances authenticate based on the Alibaba Cloud RAM system and do not support the token method. After PushGatewayUseAliyunCredential is enabled, the engine automatically obtains a credential through the Alibaba Cloud default credential chain to complete authentication, and supports automatic refresh of STS temporary credentials. When the engine is deployed on PAI-EAS, it automatically uses the RAM role (AliyunPAIRecEASRole) associated with the EAS instance to obtain temporary credentials, so you do not need to configure a plaintext AccessKey.
Grant the metric write permission to the RAM role.
Use your Alibaba Cloud root account or a RAM administrator to log on to the RAM console. In the left-side navigation pane, choose Permission Management > Grant Permission.
On the Grant Permission page, click Add Permissions and configure the following parameters.
Parameter
Description
Resource Scope
Select the resource scope as needed.
Principal
Select the RAM role AliyunPAIRecEASRole.
Access policy
Select AliyunPrometheusMetricWriteAccess or AliyunCloudMonitorFullAccess.
Click Confirm New Authorization, and then click Close.
Enable PushGatewayUseAliyunCredential in the engine configuration and restart the engine.
{
"PrometheusConfig": {
"Enable": true,
"PushGatewayURL": "https://your_pushgateway_url",
"PushIntervalSecs": 15,
"PushGatewayUseAliyunCredential": true
}
}Metrics dashboards
System overview

API request volume shows the number of requests per second (QPS) of the API, displayed along two dimensions: status code and API URI.
API response time shows the T99, T95, and T90 response times of the API, which reflect the API response speed.
Memory usage reflects how the memory occupied by PAI-Rec engine instances changes over time. Each instance corresponds to one curve.
Go goroutines reflects how the number of goroutines of PAI-Rec engine instances changes over time. Each instance corresponds to one curve.
Insufficient recommendation count errors shows the number of errors in which the engine cannot return enough recommended items.
Recall metrics

Recall count proportion reflects the proportion of recommended items obtained by each recall channel in the total recommended items.
Recall latency reflects how fast the recall stage is. Like the API request response time, it shows T99, T95, and T90 data separately.
Filter metrics

Filtering latency reflects how fast the filtering stage is. Like the API request response time, it shows T99, T95, and T90 data separately.
Pre-ranking metrics

Pre-ranking latency reflects how fast the pre-ranking stage is. Like the API request response time, it shows T99, T95, and T90 data separately.
Fine-ranking metrics

Fine-ranking latency reflects how fast the fine-ranking stage is. Like the API request response time, it shows T99, T95, and T90 data separately.
Re-ranking metrics

Re-ranking latency reflects how fast the re-ranking stage is. Like the API request response time, it shows T99, T95, and T90 data separately.
FAQ
Prometheus cannot receive the metrics
Check the engine service logs to see whether the Error sending to push gateway or Error push gateway error is reported, and handle each case accordingly:
The error indicates that the response code is 401: Authentication failed. Based on the instance version and the password-free configuration, check the corresponding settings described in "CloudMonitor Push Gateway authentication" earlier in this topic:
V1 instances: Confirm that
PushGatewayTokenis specified in the engine configuration and that the token is the same as the one generated in the console.V2 instances: Confirm that
PushGatewayUseAliyunCredentialis enabled and that the RAM role AliyunPAIRecEASRole is granted the AliyunPrometheusMetricWriteAccess permission.Instances with password-free access enabled: Confirm that the client IP address is within the password-free whitelist and that no authentication fields are specified in the engine configuration. When authentication information is carried, the server still performs RAM authentication based on that identity.
The error indicates a timeout: The connection timeout limit for reporting metrics is currently 10 seconds. Check whether the network between the engine service and Prometheus is working properly. Also verify that the Push Gateway address in the configuration is correct, and note the difference between the public endpoint and the internal endpoint.
No error is reported: Confirm whether the engine service was restarted after the engine configuration was updated.
Some metrics on the Grafana dashboard have no data
Check the filter settings in the upper-left corner of the dashboard: The environment filter drop-down list is labeled env, and the scenario filter drop-down list is labeled scene. Confirm that the correct environment (such as prepub) and the correct scenario (such as home_feed) are selected.
The API latency metrics are inaccurate
Quantiles such as T99 and T95 of the API latency are estimated based on Histogram buckets, and an actual value can only fall within a bucket range. If the bucket settings do not match the actual latency distribution, the estimated quantiles are significantly distorted. For example, this happens when most request latencies fall within the same bucket or exceed the boundary of the largest bucket. When values exceed the boundary of the largest bucket, the quantile always equals that boundary value.
By default, the API latency metrics use the standard Prometheus buckets (0.005 seconds to 10 seconds), where the bucket intervals are relatively sparse. You can configure custom buckets through ReqDurBuckets to make the buckets denser within the range where the actual latencies are concentrated. For example, if the API latencies are concentrated between 20 milliseconds and 500 milliseconds, refer to the following configuration:
{
"PrometheusConfig": {
"Enable": true,
"ReqDurBuckets": [0.01, 0.02, 0.03, 0.05, 0.08, 0.1, 0.15, 0.2, 0.3, 0.5, 1, 2.5]
}
}Note:
Buckets are measured in seconds and must be arranged in ascending order.
(Recommended) Set the bucket range to cover the minimum to the maximum of the actual latencies, and make the buckets denser in the quantile range that you care about, such as around T99. A moderate number of buckets is enough, because too many buckets increase the metric storage overhead.
After you modify the configuration, restart the engine for the configuration to take effect.
Built-in metric descriptions
Metric name | Type | Meaning | Dimension labels |
pairec_rec_total | Counter | Total number of recommendations | scene (scenario) |
pairec_size_not_enough_total | Counter | Total number of times when recommended items are insufficient | scene (scenario) |
pairec_recall_items_percentage (deprecated in new versions) | Gauge | The proportion of items from each recall source | recall_name (recall name) |
pairec_recall_count | Counter | Number of recalled items | scene, recall_name (scenario and recall name) |
pairec_recall_count_total | Counter | Total number of recalled items | scene (scenario) |
pairec_rec_duration_seconds | Histogram | Latency distribution of the entire recommendation process | scene (scenario) |
pairec_recall_duration_seconds | Histogram | Recall latency distribution | scene (scenario) |
pairec_filter_duration_seconds | Histogram | Filtering latency distribution | scene (scenario) |
pairec_general_rank_duration_seconds | Histogram | Pre-ranking latency distribution | scene (scenario) |
pairec_load_feature_duration_seconds | Histogram | Feature loading latency distribution | scene (scenario) |
pairec_rank_duration_seconds | Histogram | Fine-ranking latency distribution | scene (scenario) |
pairec_sort_duration_seconds | Histogram | Re-ranking latency distribution | scene (scenario) |
pairec_requests_total | Counter | Total number of HTTP requests | code, method, host, url |
pairec_request_duration_seconds | Histogram | Processing time distribution of HTTP requests | code, method, host, url |
pairec_request_size_bytes | Histogram | Size of the HTTP request body | code, method, host, url |
pairec_response_size_bytes | Histogram | Size of the HTTP response body | code, method, host, url |
pairec_fallback_total | Counter | Number of times the fallback is triggered | scene (scenario) |
pairec_recall_duration_by_name_seconds | Histogram | The latency distribution of a single recall channel, which can be used to locate slow recall channels | scene, recall_name (scenario and recall name) |
pairec_recall_empty_total | Counter | The number of times each recall channel returns an empty result (also counted when the recall execution is abnormal), which can be used to detect failing recall channels | scene, recall_name (scenario and recall name) |
The preceding metrics of the Histogram type reflect the total number of records of the current metric (with the _count suffix), the total sum of their values (with the _sum suffix), and the distribution ranges (with the _bucket suffix).
In addition to these metrics, PAI-Rec also collects the metric data of the Go process itself.
The metric data also carries instance and job information. instance indicates which instance the data comes from, and job indicates which environment the data comes from (product for the production environment and prepub for the staging environment).
Custom metrics
To obtain and push custom metrics, you must register them in the pairec engine code. The following sample code shows how:
package main
import (
"log"
"time"
"github.com/alibaba/pairec/v2"
"github.com/alibaba/pairec/v2/service/metrics"
"github.com/prometheus/client_golang/prometheus"
)
func main() {
// Define the metric
m := prometheus.NewCounter(prometheus.CounterOpts{
Name: "abc",
})
// Register the metric in pairec
err := metrics.CustomRegister.Register(m)
if err != nil {
log.Fatalln(err)
}
go func() {
for {
time.Sleep(time.Second * 5)
m.Inc() // Collect the metric data
}
}()
// ...
pairec.Run()
}After you register custom metrics in CustomRegister, you can obtain the custom metric data from the /custom_metrics endpoint.
If the push configuration is enabled, the custom metric data is also pushed to the Prometheus gateway.
For simplicity, the sample code only starts a goroutine that sets the metric data at regular intervals. In practice, you can set the metric data in the API controller logic or at any other location.