Asynchronous invocation can be configured in Function Compute. This allows you to send the results of successful or failed function executions to destinations. You can also set the number of retries for asynchronous invocation and the validity period of messages. This topic describes the terms, configuration items, configuration methods, and monitoring metrics of asynchronous invocation.

What is asynchronous invocation?

Functions can be invoked asynchronously or synchronously. When you call the InvokeFunction operation to invoke a function, you can specify the invocation method. In addition, if the following triggers are configured, your function is asynchronously invoked:

When an event triggers asynchronous invocation of a function, Function Compute places the event in an internal queue and returns the request ID. The status of the invocation and that of the function execution are not returned. To obtain the result of the asynchronous invocation, you can configure destinations for the asynchronous invocation.

The following figure shows the asynchronous invocation process.invoke_process

Configuration items for asynchronous invocation

Asynchronous invocation configurations include the following two parts:

  • Destination for asynchronous invocation: the cloud service or resource to which the result of the asynchronous invocation is sent. It corresponds to the destinationConfig parameter in the data structure.
    Note Destinations for asynchronous invocation do not support time triggers. Specifically, if a function is asynchronously invoked by a time trigger, Function Compute cannot invoke the configured destination for asynchronous invocation. For more information about time triggers, see Overview.
  • Asynchronous invocation policy: the maximum validity period of messages and the number of retries for asynchronous invocation. They correspond to the maxAsyncEventAgeInSeconds and maxAsyncRetryAttempts parameters in the data structure.

Destinations for asynchronous invocation

If a destination for asynchronous invocation is configured for a function and the result of the asynchronous invocation meets the condition, Function Compute sends the context and data of the asynchronous invocation to the specified service or resource. This allows cloud services or resources to interact with each other. You can configure different destinations for different functions, aliases, and versions. The following types of destinations for asynchronous invocation are supported:
  • MNS queue
  • MNS topic
  • Function Compute
  • EventBridge
    Note You can set EventBridge as the destination for asynchronous invocation in the following regions: China (Hangzhou), China (Shanghai), US (Silicon Valley), US (Virginia), China (Beijing), and China (Hong Kong).

Take note of the following points when you configure destinations for asynchronous invocation:

  • Event content sent to the destinations for asynchronous invocation
    {
        "timestamp": "2020-08-20T12:00:00.000Z",
        "requestContext": {
            "requestId": "xxx",
            "functionArn": "acs:fc:::services/{serviceName}/functions/{functionName}",
            "condition": "FunctionResourceExhausted", 
            "approximateInvokeCount": 3
        },
        "requestPayload": "",
        "responseContext": {
            "statusCode": 200,
            "functionError": ""
        },
        "responsePayload": ""
    }
    Parameter Description
    timestamp The timestamp of the invocation.
    requestContext The context of the request.
    requestContext.requestId The request ID of the asynchronous invocation.
    requestContext.functionArn The Alibaba Cloud Resource Name (ARN) of the function that is asynchronously invoked.
    requestContext.condition The error code of the invocation.
    requestContext.approximateInvokeCount The number of times that the function is asynchronously invoked. A value greater than 1 indicates that Function Compute has retried your function.
    requestPayload The original payload of the function request.
    responseContext The context of the response.
    responseContext.statusCode The system status code that is returned for the invoked function. A status code other than 200 indicates that a system error occurred.
    responseContext.functionError The error message of the invocation.
    responsePayload The original payload that is returned after the function is executed.

    If the destination for asynchronous invocation is EventBridge, the event content includes more parameters. For more information about these parameters, see Overview. The following part shows an example of the event content:

    {
        "datacontenttype": "application/json",
        "aliyunaccountid": "143xxxx",
        "data": {
            "requestContext": {
                "condition": "",
                "approximateInvokeCount": 1,
                "requestId": "0fcb7f0c-xxxx",
                "functionArn": "acs:fc:::services/xxxx.LATEST/functions/xxxx"
            },
            "requestPayload": "",
            "responsePayload": "",
            "responseContext": {
                "functionError": "",
                "statusCode": 200
            },
            "timestamp": 12345
        },
        "subject": "acs:fc:::services/xxxx.LATEST/functions/xxxx",
        "source": "acs:fc",
        "type": "fc:AsyncInvoke:succeeded",
        "aliyunpublishtime": "2021-01-03T09:44:31.233Asia/Shanghai",
        "specversion": "1.0",
        "aliyuneventbusname": "xxxxxxx",
        "id": "ecc4865xxxxxx",
        "time": "2021-01-03T01:44:31Z",
        "aliyunregionid": "cn-shanghai-vpc",
        "aliyunpublishaddr": "199.99.xxx.xxx"
    }
  • Payload limits

    The payload that is supported by a destination for asynchronous invocation cannot exceed the following limits:

    • MNS queue or topic: 64 KB
    • Function Compute: 128 KB
    • EventBridge: 64 KB
    Note The default data sent to a destination for asynchronous invocation, except the values of the requestPayload and responsePayload parameters, must be less than 1 KB in size. Make sure that the total size of the input parameters, function response, and default data of your asynchronous invocation does not exceed the payload limit.
  • Loop avoidance

    When you configure a destination for asynchronous invocation, make sure that you do not create a loop. Assume that you configure Function B as the destination for successful asynchronous invocation of Function A and Function A as the destination for successful asynchronous invocation of Function B. Asynchronous invocation and execution of Function A may begin an infinite loop where Function A and Function B continuously invoke each other.

Asynchronous invocation policy

In some scenarios, high invocation payload may result in a backlog of messages. You can modify the following asynchronous invocation configurations to ignore messages that exist for a long period of time:

  • Maximum validity period of messages

    The maxAsyncEventAgeInSeconds parameter in the asynchronous invocation configurations specifies the maximum validity period of messages. Valid values: [1,2592000]. Unit: seconds. The period starts when asynchronous invocation is triggered and ends when the message is removed from the queue for processing. If this period of time is longer than the value of the maxAsyncEventAgeInSeconds parameter, the message is discarded. Discarded messages are tracked by the Asynchronous Invocation Requests Discarded Due to Timeout metric in Cloud Monitor. For more information about the metric, see the following section View asynchronous invocation metrics provided by Cloud Monitor.

  • Number of retries

    You can configure the number of retries by setting the maxAsyncRetryAttempts parameter in the asynchronous invocation configurations in Function Compute. Valid values: [0,8]. By default, Function Compute retries a failed asynchronous invocation for three times. You can adjust the number of retries based on your business needs.

Data structure of asynchronous invocation configurations

The asynchronous invocation configurations use the following data structure:

{
  "destinationConfig": {
        "onSuccess": {
          "destination": "acs:fc:{region}:{account}:services/{service_name}.{ Qualifier}/functions/{function_name}}",
        },
        "onFailure": {
          "destination": "acs:mns:{region}:{account}:/queues/{queue_name}/messages"
        }
  }
  "maxAsyncEventAgeInSeconds": 100,
  "maxAsyncRetryAttempts": 1
}
Table 1. Parameters in asynchronous invocation configurations
Parameter Description
destinationConfig The destination for asynchronous invocation.
onSuccess The destination that Function Compute invokes when the function is executed.
onFailure The destination that Function Compute invokes when the function fails to be executed due to a system error or an error of the function.
destination The destination for asynchronous invocation. Valid values:
  • mns/queues: an MNS queue. The ARN format is acs:mns:{region}:{account}:/queues/{queue_name}/messages.
  • mns/topics: an MNS topic. The ARN format is acs:mns:{region}:{account}:/topics/{topic_name}/messages.
  • fc: Function Compute. The ARN format is acs:fc:{region}:{account}:services/{service_name}.{ Qualifier}/functions/{function_name}.
  • eventbridge: EventBridge. The ARN format is acs:eventbridge:{region}:{accountId}:eventbus/{busName}.
The ARNs include the following parameters:
  • {region}: the region ID. For more information, see Endpoints.
  • {account}: the account ID. For more information, see Obtain your Alibaba Cloud account ID.
  • {queue_name}: the name of the MNS queue.
  • {topic_name}: the name of the MNS topic.
  • {service_name}: the name of the service in Function Compute.
  • {Qualifier}: the alias of the service in Function Compute.
  • {function_name}: the name of the function.

A sample ARN for an MNS queue is acs:mns:cn-hangzhou:1111******:/queues/myqueue/messages.

maxAsyncEventAgeInSeconds Specifies the maximum validity period of messages. Valid values: [1,2592000]. Unit: seconds. The period starts when asynchronous invocation is triggered and ends when the message is removed from the queue for processing. If this period of time is longer than the value of the maxAsyncEventAgeInSeconds parameter, the message is discarded.
maxAsyncRetryAttempts You can configure the number of retries by setting the maxAsyncRetryAttempts parameter in the asynchronous invocation configurations in Function Compute. Valid values: [0,8]. By default, Function Compute retries a failed asynchronous invocation for three times. You can adjust the number of retries based on your business needs.

Configuration methods

For all configuration methods of asynchronous invocation, make sure that the service role of the function has the required permissions on the destination.

Destination Minimum permission
MNS queue mns:SendMessage
MNS topic mns:PublishMessage
Function Compute fc:InvokeFunction
EventBridge eventbridge:PutEvents

For more information, see Permissions.

Use the console

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Services and Functions. In the Services pane, click the service that you require.
  4. On the Functions tab, click the name of the function that you require.
  5. Click the Async Config tab.
  6. On the Async Config tab, set the following parameters.
    Set parameters
    Parameter Example Description
    Asynchronous Invocation Policy Configuration
    Maximum Retries 1 You can configure the number of retries by setting the maxAsyncRetryAttempts parameter in the asynchronous invocation configurations in Function Compute. Valid values: [0,8]. By default, Function Compute retries a failed asynchronous invocation for three times. You can adjust the number of retries based on your business needs.
    Maximum Validity Period of Invocation Requests (Seconds) 1 Specifies the maximum validity period of messages. Valid values: [1,2592000]. Unit: seconds. The period starts when asynchronous invocation is triggered and ends when the message is removed from the queue for processing. If this period of time is longer than the value of the maxAsyncEventAgeInSeconds parameter, the message is discarded.
    Destination Configuration - Condition: On Success
    Resource Type fc The destination for asynchronous invocation. This option affects the destination configuration. Valid values:
    • fc: Function Compute.
    • mns/queues: an MNS queue.
    • mns/topics: an MNS topic.
    • eventbridge: EventBridge.
    Service fnf-demo The service in Function Compute.
    Note This parameter is required only when the Resource Type parameter is set to fc.
    Version/Alias 2 The version or alias of the service in Function Compute.
    Note This parameter is required only when the Resource Type parameter is set to fc.
    Function Operation The name of the function.
    Note This parameter is required only when the Resource Type parameter is set to fc.
    Queue Name MyQueue The name of the MNS queue.
    Note This parameter is required only when the Resource Type parameter is set to mns/queues.
    Topic Name MyTopic The name of the MNS topic.
    Note This parameter is required only when the Resource Type parameter is set to mns/topics.
    Resource acs:fc:cn-hangzhou:188077086902****:services/fnf-demo.2/functions/Operation The Alibaba Cloud Resource Name (ARN) of the destination service.
    Destination Configuration - Condition: On Failure

    The parameters are the same as those for the success condition.

  7. Click Save Configurations.
    The The configurations are saved message appears.

Other operations

  • To modify an asynchronous invocation configuration that has been saved, modify the parameters as needed and click Save Configurations on the Async Config tab.
    Notice Asynchronous invocation configurations are incrementally updated. If you want to remove a specific setting, delete the original configuration and create a configuration without the setting.
  • To delete an asynchronous invocation configuration that has been saved, click Delete Configurations on the Async Config tab.
  • For more information about the monitoring metrics for asynchronous invocation, see the following section View asynchronous invocation metrics provided by Cloud Monitor.

Use SDKs

For more information, see Supported SDKs.

Use API operations

You can call the FunctionAsyncInvokeConfig API operations to configure asynchronous invocation for a function in a service in Function Compute. Versions and aliases of services are supported.

API Description
PutFunctionAsyncInvokeConfig Creates or modifies an asynchronous invocation configuration for a specific function in a service.
GetFunctionAsyncInvokeConfig Queries an asynchronous invocation configuration of a specific function in a service.
ListFunctionAsyncInvokeConfigs Queries all asynchronous invocation configurations of a specific function in a service.
DeleteFunctionAsyncInvokeConfig Deletes an asynchronous invocation configuration of a specific function in a service.

View asynchronous invocation metrics provided by Cloud Monitor

The destination for asynchronous invocation may fail to be called in the following situations: the service role of the function does not have the permissions to call the destination service or resource, the response is too large in size, or the destination is abnormal. You can find more information by viewing the metrics that are provided by Cloud Monitor.

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Services and Functions. In the Services pane, click the service that you require.
  4. On the Functions tab, click the name of the function that you require.
  5. Click the Metrics tab.
  6. On the Metrics tab, set the Time Range parameter as needed to view the metrics.
    timespan
    The following figure shows sample metrics. The metrics framed in the box are those related to asynchronous invocation.metrics-result

    The following metrics are used to monitor asynchronous invocation:

    • Error Rate: the total number of times that Function Compute attempts to send asynchronous invocation events to the destination, and the rate of errors that occurred due to server, client, and function issues. The error rate metric may be displayed due to invalid permissions, invalid resource configurations, and violations of size limits.
    • Invocation Record Sending Metrics: the number of times that Function Compute successfully sent and failed to send asynchronous invocation events to the destination.
    • Asynchronous Invocation Requests Discarded Due to Timeout: the number of messages that are discarded because their lifecycle exceeded the value of the maxAsyncEventAgeInSeconds parameter.