Function Compute supports asynchronous invocation. 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, scenarios, limits, configuration items, configuration methods, and 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.

Scenarios

This section describes the applicable scenarios of stateless asynchronous invocation and stateful asynchronous invocation:
  • Applicable scenarios of stateless asynchronous invocation
    • The execution duration of a function is short.
    • The result of each execution does not need to be frequently viewed.
    • The execution of a function does not need to be interrupted.
  • Applicable scenarios of stateful asynchronous invocation
    • The execution duration of a function is long.
    • The result of each execution needs to be viewed.
    • The execution of a function needs to be interrupted.
    Note If stateful asynchronous invocation is enabled, an additional latency exists for invoking and executing a function because status information needs to be saved. The latency does not cause additional fees. For more information about billing, see Billing.

Limits

This section describes the limits of stateless asynchronous invocation and stateful asynchronous invocation.
  • Stateless asynchronous invocation

    N/A

  • Stateful asynchronous invocation
    • You can query only execution information within seven days.
    • The following regions support stateful asynchronous invocation: China (Hangzhou), China (Shanghai), China (Beijing), China (Shenzhen), China (Hong Kong), Singapore (Singapore), UK (London), US (Silicon Valley), US (Virginia), and India (Mumbai).

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.
  • 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).
  • Message Queue for Apache RocketMQ
    Note You can set Message Queue for Apache RocketMQ as the destination for asynchronous invocation in the China (Hangzhou) and China (Qingdao) regions.

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
    • Message Queue for Apache RocketMQ: 4 MB
    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. For example, 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 Bcontinuously 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 CloudMonitor. For more information about the metric, see the following section View asynchronous invocation metrics provided by CloudMonitor.

  • 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

This section describes the data structures of asynchronous invocation configurations.
  • Stateless 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
    }
  • Stateful asynchronous invocation configurations use the following data structure:
    {
      "statefulInvocation": true,
      "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
statefulInvocation Indicates whether stateful asynchronous invocation is enabled.
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}:{accountId}:/queues/{queue_name}/messages.
  • mns/topics: an MNS topic. The ARN format is acs:mns:{region}:{accountId}:/topics/{topic_name}/messages.
  • fc: Function Compute. The ARN format is acs:fc:{region}:{accountId}:services/{service_name}.{Qualifier}/functions/{function_name}.
  • eventbridge: EventBridge. The ARN format is acs:eventbridge:{region}:{accountId}:eventbus/{busName}.
  • mq: Message Queue for Apache RocketMQ. The ARN format is cs:mq:{region}:{accountId}:{mq_instance_id}%{topic_name}.
The ARNs include the following parameters:
  • {region}: the region ID. For more information, see Endpoints.
  • {accountId}: 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 or Message Queue for Apache RocketMQ 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.
  • {mq_instance_Id}: the ID of the Message Queue for Apache RocketMQ instance.

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

maxAsyncEventAgeInSeconds
maxAsyncRetryAttempts

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
Message Queue for Apache RocketMQ AliyunMQPubOnlyAccess

For more information, see Grant permissions to a RAM user by using an Alibaba Cloud account.

Use the Function Compute 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 Asyn Invocation tab.
  6. Click Configure Async Invocation.
    Note If you have configured asynchronous invocation, skip this step.
  7. In the upper-right corner of the details page of the function, select the version that you want to configure and view from the version drop-down list.
  8. On the Asyn Invocation tab, set the parameters that are described in the following table.
    Set parameters
    Parameter Example Description
    Asynchronous Invocation Policy Configuration
    Max Retries 1
    Max Message effecti 1
    Enable Stateful Async Invocation N/A If stateful asynchronous invocation is enabled, Function Compute records detailed status transition information of each invocation, such as the invocation input, execution result, and error message.
    Note If you fail to enable stateful asynchronous invocation, submit a ticket.
    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.
    • rocketmq: Message Queue for Apache RocketMQ.
    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.

  9. 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 Asyn Invocation 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 Asyn Invocation tab.
  • For more information about the metrics for asynchronous invocation, see the following section View asynchronous invocation metrics provided by CloudMonitor.

Use SDKs

For more information, see Supported SDKs.

Use API operations

Operation Description
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.
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.
You can call the StatefulAsyncInvocation API operations to view specific execution information, asynchronous invocations that meet a specific condition, and terminate an asynchronous invocation.
GetStatefulAsyncInvocation Queries the information about a stateful asynchronous invocation.
ListStatefulAsyncInvocations Queries all stateful asynchronous invocations that meet a specific condition. Examples:
  • Queries a specified number of stateful asynchronous invocations.
  • Queries stateful asynchronous invocations whose status is Failed.
  • Queries stateful asynchronous invocations whose start time is in a specific execution period.
StopStatefulAsyncInvocation Terminates a stateful asynchronous invocation.

View asynchronous invocation metrics provided by CloudMonitor

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 CloudMonitor.

  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 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.