If your function contains logic that is time-consuming, resource-intensive, or error-prone, you can use asynchronous invocations to allow your programs to respond to traffic spikes in a more efficient and reliable manner. When you invoke a function in asynchronous mode, you do not need to wait for the function to respond. Requests are persistently stored in the internal queue of Function Compute before they are reliably processed. This topic describes the scenarios and common features of asynchronous invocations.
Scenarios
The following items list common scenarios of asynchronous invocations:
Audio and video processing
You can use Function Compute to process audio and video files. During the process, time-consuming tasks such as encoding, decoding, and transcoding are involved. You can trigger these tasks in asynchronous mode so that the tasks run in the backend and the frontend can proceed without waiting. This improves user experience. In addition, you can invoke multiple functions in asynchronous mode to implement concurrent processing and reduce the task processing time. For example, you can split your audio and video project into multiple tasks and process these tasks in parallel if your project size is large. You can also convert a video to multiple formats in parallel.
Data ETL processing
In an extract, transform, and load (ETL) process, multiple independent operations, such as database querying, file reading and writing, and data cleansing, are involved. You can use asynchronous invocations to allow these operations to be performed in parallel, reducing the processing time and improving system performance. For time-consuming tasks, such as processing of large-scale data sets and transformations of complex data, asynchronous invocations allow these tasks to run in the backend without waiting in the frontend. This improves user experience.
Web application development
Function Compute can be used with other cloud services to quickly build web applications. Asynchronous invocations can be used to prevent page freezing caused by lengthy backend response times when users submit forms, perform queries, and load a large amount of data. In this case, users can continue to interact with other parts of the page without experiencing delays. In high-concurrency scenarios, for example, when a large number of users access an application at the same time, asynchronous invocations can distribute request loads and prevent services from being overloaded.
Deferred invocation
In specific scenarios, you may want Function Compute to defer a function invocation after you submit an asynchronous invocation request. In this case, you can use the Function Compute API or SDK to defer the function invocation.
You can add the HTTP request header x-fc-async-delay
to the code. Valid values: (0,3600). Unit: seconds. Function Compute invokes the function when the period specified by x-fc-async-delay
elapses.
Retry policy
Error handling and retry mechanisms are supported in asynchronous invocations. A task can be rescheduled without affecting the entire process if the task fails. Function Compute automatically retries an asynchronous invocation if the invocation fails.
Retry mechanism
The following table describes the default retry mechanism for common errors.
Error type | Server behavior | Billed | Solution |
| By default, Function Compute retries the function up to three times. You can change the number of retries based on your business requirements. | Billed based on the number of invocations. For more information, see Billing overview. | Check your code. |
Execution concurrency upper limit exceeded | Function Compute retries the function execution for up to 5 hours in binary exponential backoff mode. If your function execution fails, retries start 0.5 seconds later. Subsequent retry intervals are calculated in binary exponential backoff mode, such as 1 second, 2 seconds, 4 seconds, and 8 seconds. The retries last up to 5 hours. | No | By default, each Alibaba Cloud account can run up to 100 instances in each region. The actual quota displayed on the General Quotas page in the Quota Center console prevails. You can increase the quota in the Quota Center console. |
Internal error | No | Join the DingTalk group (ID: 64970014484) for technical support. | |
Insufficient Function Compute resources | No |
Configure a retry policy
You can specify the maximum number of retries and the maximum time to live (TTL) for messages in Function Compute.
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Configurations tab. In the left-side navigation pane, click Asynchronous Mode Configurations. In the Asynchronous Mode Configurations section, click Modify.
In the Asynchronous Mode Configurations panel, configure the following parameters and click Deploy.
Parameter
Description
Task Mode
Specifies whether to enable the asynchronous task mode. For more information, see Asynchronous tasks.
Maximum Retries
The maximum number of retries for messages in asynchronous invocations. Valid values: [0,8].
By default, Function Compute retries three times for messages that fail to be asynchronously triggered. You can reduce or increase the number of asynchronous invocation retries based on your business requirements.
Maximum Message Lifetime
The maximum lifetime of messages in asynchronous invocations. Valid values: [1,604800]. Default value: 86400. Unit: seconds.
This duration is calculated from the time when an asynchronous invocation is triggered. If the maximum message lifetime elapses, the message is discarded. Discarded messages are tracked by the Asynchronous Invocation Trigger Events metric in CloudMonitor. For more information, see Monitoring metrics.
Result callback
After receiving an asynchronous invocation request, Function Compute persists the request and immediately returns a response without waiting for the request to complete. If you want to retain a request that fails to be executed after it is retried for the specified maximum number of times or if you want to notify downstream applications of the asynchronous invocation results, you can configure result callbacks. After you configure a destination service for asynchronous invocations, Function Compute automatically triggers a callback to the corresponding service based on the execution result.
How it works
The following figure shows the process of a result callback.
Scenarios
Save discarded events for later use
If an asynchronous request fails to be executed after the system retries the request based on the retry policy, Function Compute discards the request. If a destination is configured for failed invocations, Function Compute pushes the context information of the failed request to the destination service such as ApsaraMQ for RocketMQ for subsequent processing. You can also set the destination service to another function. Function Compute automatically pushes the context information of the failed request to this function to execute custom error handling logic.
Notify downstream services of execution results
You can configure a destination for successful invocations. After a request is successfully executed, Function Compute pushes the context information of the request to the downstream destination service. For example, if you use Function Compute to automatically decompress ZIP files that are uploaded to Object Storage Service (OSS), you can configure result callbacks for the decompression function if you want to receive notifications after decompression.
Supported destination services for asynchronous invocations
If you configure a destination for asynchronous invocations of a function, Function Compute sends the context and data of the request to the specified service when the result of the asynchronous invocation meets the specified conditions. You can configure different destination services for different functions, aliases, and versions. The following destination services are supported for asynchronous invocations:
Simple Message Queue (formerly MNS)
Function Compute
EventBridge
ApsaraMQ for RocketMQ
If you select ApsaraMQ for RocketMQ, only an ApsaraMQ for RocketMQ 4.x instance can be configured as the destination service. ApsaraMQ for RocketMQ 5.x instances cannot be configured as destination services. For more information, see Differences between ApsaraMQ for RocketMQ 4.x and 5.x and compatibility description.
Take note of the following items when you configure the destination service for asynchronous invocations:
Event content sent to the destination for the asynchronous invocation
The following sample code provides an example of event content when the destination for the asynchronous invocation is Simple Message Queue (formerly MNS), Function Compute, or ApsaraMQ for RocketMQ.
{ "timestamp": 1660120276975, "requestContext": { "requestId": "xxx", "functionArn": "acs:fc:{regionid}:{accountid}:functions/xxxx", "condition": "FunctionResourceExhausted", "approximateInvokeCount": 3 }, "requestPayload": "", "responseContext": { "statusCode": 200, "functionError": "" }, "responsePayload": "" }
Table 1. Parameter description
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 execution times of the asynchronous invocation. A value greater than 1 indicates that Function Compute retried the execution.
requestPayload
The original payload of the function request.
responseContext
The response context.
responseContext.statusCode
The returned system status code. 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.
The following sample code provides an example of event content when the destination for asynchronous invocations is EventBridge. For more information, see Overview.
{ "datacontenttype": "application/json", "aliyunaccountid": "143xxxx", "data": { "requestContext": { "condition": "", "approximateInvokeCount": 1, "requestId": "0fcb7f0c-xxxx", "functionArn": "acs:fc:{regionid}:{accountid}:functions/xxxx" }, "requestPayload": "", "responsePayload": "", "responseContext": { "functionError": "", "statusCode": 200 }, "timestamp": 1660120276975 }, "subject": "acs:fc:{regionid}:{accountid}: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 following items list the limits of payload sizes for different destination services:
Simple Message Queue (formerly MNS): 64 KB
Function Compute: 128 KB
EventBridge: 64 KB
ApsaraMQ for RocketMQ: 4 MB
Loop avoidance
When you configure a destination for asynchronous invocations, make sure that loop invocations do not occur. For example, a loop occurs if you configure Function B as the destination for successful asynchronous invocations of Function A and configure Function A as the destination for successful asynchronous invocations of Function B. An asynchronous invocation and execution of Function A may begin an infinite loop in which Function A and Function B continuously invoke each other.
Configure the destination service for asynchronous invocations
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Configurations tab. In the left-side navigation pane, click Asynchronous Mode Configurations.
Configure the destination for successful invocations
In the Destination for Successful Invocations section, click Modify.
In the Destination for Successful Invocations panel, set Invoke Other Services upon Success to Enable and configure the Destination Service parameter. The following table describes the parameters.
Parameter
Description
Destination Service
Function Compute. If you select Function Compute from the Destination Service drop-down list, you must configure the following parameters:
Function Name: the name of a function.
Version or Alias: the alias or version of the function.
Simple Message Queue (formerly MNS). If you select Simple Message Queue (formerly MNS) from the Destination Service drop-down list, you must configure the following parameters:
Destination Type: the type of the destination that receives results of successful invocations. Valid values:
Queue
A queue-based messaging model provides highly reliable and concurrent message consumption services. Each message in a queue can be consumed by only one client.
Topic
A topic-based messaging model is used to send messages from one publisher client to multiple subscriber clients. SMQ topics can be pushed as messages by using multiple methods.
Queue: the name of a Simple Message Queue (formerly MNS) queue. This parameter is required if you set the Destination Type parameter to Queue.
Topic: the name of a Simple Message Queue (formerly MNS) topic. This parameter is required if you set the Destination Type parameter to Topic.
ApsaraMQ for RocketMQ. If you select ApsaraMQ for RocketMQ from the Destination Service drop-down list, you must configure the following parameters:
Instances: the destination instance.
Topic: the destination topic.
EventBridge. If you select EventBridge from the Destination Service drop-down list, you must configure the Custom Event Bus parameter.
Click Deploy.
Configure the destination for failed invocations
In the Destination for Failed Invocations section, click Modify.
In the Destination for Failed Invocations panel, set Invoke Other Services upon Failure to Enable. Then, configure the Destination Service parameter.
For more information about the parameters of the destination for failed invocations, see the preceding table.
Click Deploy.
Handle a callback failure
If the role configured for the function does not have the permissions on the destination services or the destination services are unavailable, the callback to the destination services may fail. You can handle such failures based on the metrics and logs provided by Function Compute. The following table describes the common errors and corresponding system actions.
HTTP status code | Description | System action |
5xx | Requests are throttled or a content error occurs. | Function Compute automatically retries the callback in exponential backoff mode. The initial retry interval is 500 milliseconds, and the maximum retry duration is 30 minutes. |
4xx | You do not have the required permissions, the request parameter is incorrect, or the request message body exceeds the limit of the destination service. An example of an incorrect request parameter is that the resources for the destination service specified by the request parameter have been deleted. | The system returns an error and records the error message. |
Callback metrics
When the callback fails, Function Compute records the corresponding metrics and displays the metrics in the console. You can log on to the Function Compute console. In the left-side navigation pane, choose . In the Function Name column, click the name of the function that you want to manage.
Metric | Description |
FunctionDestinationErrors | The number of requests that fail to trigger the specified destination during the function execution. The statistics are collected every minute or every hour. |
FunctionDestinationSucceed | The number of requests that successfully trigger the specified destination during the function execution. The statistics are collected every minute or every hour. |
For more information about metrics, see Monitoring metrics.
FAQ
How do I trigger an asynchronous invocation of a function?
You can use one of the following methods to asynchronously invoke a Function Compute function:
Log on to the Function Compute console, find the desired function and select Invoke the function in asynchronous mode on the Tests tab.
Call the InvokeFunction operation and set the value of the
x-fc-invocation-type
parameter to Async.Use Serverless Devs to configure asynchronous invocations. Set the value of the
invocation-type
parameter to Async. For more information, see Invoke a function.Create a trigger that supports asynchronous invocations. For more information, see Trigger tasks by using events.
What to do next
If you want to obtain the status information of each phase of asynchronous requests, you can enable the task mode. For more information, see Asynchronous tasks.