Asynchronous tasks
When you asynchronously invoke a function, enable task mode if you need to track and retain the state of each stage and gain richer task control and observability. This topic describes the background information, limits, and common features of asynchronous tasks.
Background information
After you enable asynchronous tasks, you can use the following features:
-
Each function invocation records detailed state transition information about the invocation process, such as queued and waiting to be processed (Enqueued), invocation executed successfully (Succeeded), and invocation failed (Failed).
-
Function request lifecycle management is available, so you can proactively terminate an asynchronous task that is being executed.
Asynchronous tasks retain state information. As a result, function invocations and executions incur some additional latency, which is not billed separately. For more information about Function Compute billing, see Billing overview.
Limits
-
Scenario limits
Although asynchronous tasks provide richer features, they also incur higher system overhead. Disable task mode in the following scenarios:
-
You are highly sensitive to the latency of the request processing path and require an average latency of less than 100 milliseconds.
-
You need to initiate asynchronous invocations at a rate of thousands or even more per second.
-
-
Region limits
Asynchronous tasks are supported in the China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Chengdu), China (Hong Kong), Singapore, UK (London), US (Silicon Valley), US (Virginia), Germany (Frankfurt), Malaysia (Kuala Lumpur), Indonesia (Jakarta), Thailand (Bangkok), Japan (Tokyo), and South Korea (Seoul) regions.
-
Retention limits
Task state information can be queried only for tasks within the past 7 days.
Comparison between asynchronous tasks and the Jobs feature
If you need to run asynchronous tasks, you can use the Function Compute asynchronous task feature or the Jobs feature of Kubernetes. Function Compute asynchronous tasks provide a ready-to-use asynchronous task execution platform that is more efficient, more controllable, and easier to observe. The following is a detailed feature comparison.
|
Item |
Function Compute asynchronous tasks |
Jobs feature of Kubernetes |
|
Scenarios |
Suitable for real-time tasks whose execution takes tens of milliseconds and offline tasks whose execution takes tens of hours. |
Suitable for offline tasks that do not require a high task submission rate, have a relatively fixed workload, and do not have high real-time requirements. |
|
Task observability |
Supported. Provides rich observability features, such as metrics including logs and the number of queued tasks, as well as task path latency and task state queries. |
You must integrate open-source software on your own to implement this feature. |
|
Automatic scaling of task instances |
Supported. Instances are automatically scaled in and out based on the number of queued tasks and the instance resource utilization. |
You must implement scaling and instance load balancing on your own by using a task queue, which is highly complex. |
|
Task instance scaling speed |
Millisecond level. |
Minute level. |
|
Task instance resource utilization |
You only need to select appropriate instance specifications. Instances scale automatically, and billing is based on the actual duration of task processing, so resource utilization is high. |
You must determine the instance specifications and the number of instances when you submit Jobs. Instances are difficult to scale automatically or balance across loads, so resource utilization is low. |
|
Task submission rate |
A single user can submit tens of thousands of tasks per second. |
The entire cluster can start at most hundreds of Jobs per second. |
|
Scheduled or delayed task submission |
Supported. |
Scheduled task submission is supported, but delayed task submission is not supported. |
|
Task deduplication |
Supported. |
Not supported. |
|
Terminating a specified task |
Supported. |
Limited support. This is indirectly achieved by terminating task instances. |
|
Task throttling |
Supported. Throttling can be applied at different granularities, such as per user or per task processing function. |
Not supported. |
|
Automatic callback of task results |
Supported. |
Not supported. |
|
Development and O&M costs |
You only need to implement the task processing logic. |
You must maintain a Kubernetes cluster. |
Task management
States of asynchronous tasks
For each task invocation, Function Compute records the state changes of the task and provides real-time state queries. View the specific state of a task by using the SDK or in the Function Compute console. A task can be in the following states:
|
Execution state |
Description |
|
Enqueued |
The asynchronous message is enqueued and is waiting to be processed. |
|
Dequeued |
The asynchronous message is dequeued and is waiting to be triggered. |
|
Running |
The invocation is being executed. Your instance has started to run the task code. |
|
Succeeded |
The invocation succeeds. |
|
Failed |
The invocation fails. |
|
Stopped |
You have manually stopped this task invocation. The task is terminated. |
|
Stopping |
You have manually stopped this task, and the task is being stopped. |
|
Expired |
You configured a time-to-live for the asynchronous message, and the message has been discarded because it expired (it was not triggered). |
|
Invalid |
Your execution is in an invalid state for reasons such as the function or service being deleted (it was not triggered). |
|
Retrying |
The asynchronous invocation is being retried because of an execution error. When the system is ready to retry, your task changes back to the Running state. |
Call the GetAsyncTask operation to obtain the details of a specific task execution, or call the ListAsyncTasks operation to filter tasks in a specified state.
Manage tasks
Manage tasks in the console
Enable asynchronous tasks when you create a function
-
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 Create Function.
-
In the dialog box that appears, select Task Function, and then click Create {title}. On the Create {title} page, configure the function name, and then click Create.
For more information about each configuration item, see Create a task function.
After the function is created, the Tasks tab of the function details page shows that task mode is enabled by default.
Enable asynchronous task mode for an existing function
Create a function first. For more information, see Function creation.
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 Tasks tab, and then, to the right of Task Mode, click Modify.
-
In the Task Mode panel, for Task Mode, select Disable, and then click Deploy.
Start or stop a task
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 Tasks tab, and then click Submit Task. In the dialog box that appears, select the task ID generation method and the task execution time, and then click OK.
To simulate a task submission, click the icon to the right of Submit Task
and select Configure Test Parameters from the drop-down list instead. An event function receives its input parameters as an event, and an HTTP function receives them as HTTP parameters.In the task list below, you can view information such as Task Status, Task ID, and Instance ID, or log on to an instance.
Manage tasks by calling API operations (SDK)
Configure task mode
Call the PutAsyncInvokeConfig operation to configure the asynchronous invocation mode as task mode. Configure asyncTask as follows. After this configuration is complete, all asynchronous invocations of the function run in task mode.
{
"asyncTask": true
}
After you configure the asynchronous invocation mode as task mode, you can still invoke the function synchronously. However, asynchronous task mode takes effect only for asynchronous invocations.
Trigger a function by using an asynchronous invocation
Trigger an asynchronous invocation to start task mode by calling the InvokeFunction operation and setting the x-fc-invocation-type parameter to Async. When you make the call, you can add the HTTP request header x-fc-async-task-id to set the task ID for this invocation. For more information, see Prevent duplicate task submission.
View tasks
After you submit a task, you can call the GetAsyncTask operation to query information such as the state or the execution record of a specific execution.
If you need to query the list of task executions that meet specified conditions based on a keyword or conditions, you can call the ListAsyncTasks operation.
Stop a task
After you submit a task, you can stop the task as needed. Call the StopAsyncTask operation to stop a task. When you stop a task, you must provide the TaskID that you set when you submitted the task. It can also be the ID that you obtained when you called the ListAsyncTasks operation to query running tasks.
Event triggering
Trigger an asynchronous task by creating a trigger that supports asynchronous invocations. The following triggers support asynchronous invocations.
-
Triggers implemented based on EventBridge include the following types:
ImportantMake sure that, for the HTTP trigger and the triggers implemented based on EventBridge, the Invocation Method is set to Async Invocation.
Prevent duplicate task submission
To prevent a task from being executed more than once, Function Compute allows you to specify a globally unique ID for each submitted task. If an asynchronous interface fails to submit a task, for example, if the asynchronous invocation times out, retry by submitting a task with the same ID. For more information about how to retry, see Retry policy.
Function Compute provides the task concept of TaskID, which is globally unique. Specify this ID each time you submit a task, and retry when a timeout or similar issue occurs. Function Compute validates tasks that you submit repeatedly. When a task with the same ID enters the system, the request is considered a duplicate submission and is rejected, and the error 409 is returned.
Function Compute also provides the concept of RequestID. If you set RequestID but do not set TaskID, the system automatically sets TaskID to RequestID. When you use asynchronous tasks, set TaskID and do not set RequestID.
Set the TaskID
Submit a task execution in Function Compute console, by using Serverless Devs, or by calling an API operation. If you need to set TaskID, set the x-fc-async-task-id parameter when you trigger the function execution.
The Sample code link shows how to set TaskID when you trigger a task execution.
Task monitoring
Use the task monitoring metrics provided by Function Compute to obtain the states of asynchronous tasks in real time and promptly detect exceptions such as errors and timeouts.
Prerequisites
A function is created. For more information, see Function creation.
Procedure
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 details page of the target function, click the Monitoring tab to view the metrics related to asynchronous invocations and the resource usage at the asynchronous task instance level. For more information about monitoring metrics, see Monitoring metrics.
Click the Function Metrics tab to view the metrics related to asynchronous invocations, such as Asynchronous Invocation Processing (count), Asynchronous Invocation Processing Latency (ms), Asynchronous Invocation Trigger Events (count), and Asynchronous Requests Backlogs (count).
Click the Instance Metrics tab to view the resource usage at the asynchronous task instance level.
NoteBefore you enable instance-level metrics, you must enable the logging feature. For more information, see Configure the logging feature.
Configure alert rules for metrics.
If you want to monitor a metric, such as memory usage or vCPU usage, click
in the upper-right corner of the metric chart. You are redirected to the Create Metric-Based Alert Rule panel. Set the alert conditions and thresholds as prompted by the interface, and then click OK.For information about how to configure an alert rule, see the following figure. The parameter values in the figure indicate that when the number of backlogged asynchronous invocations of the function is greater than or equal to 5, medium-level alerts are reported to contacts around the clock by using DingTalk, email, phone calls, and webhooks.

Task orchestration
Combined with CloudFlow, asynchronous invocations of functions can be applied to task workflows in large-scale, complex scenarios. Use methods such as Pass state, Iteration (Map), and Parallel state to orchestrate Function Compute asynchronous tasks. CloudFlow reliably coordinates task execution based on the steps that you define, tracks the state transitions of each task, and runs the retry logic that you define when necessary to ensure that tasks are completed successfully. For more information, see Integrate CloudFlow with Function Compute.
Prerequisites
Create an asynchronous task. For more information, see Task management.
Grant Function Compute the permissions to access Serverless workflow. For more information, see Use a function role to access other cloud services.
Procedure
Log on to the CloudFlow console. In the top navigation bar, select a region.
In the left-side navigation pane, click Workflows. On the Workflows page, click Create Workflow.
In the Create Workflow dialog box, select the method for creating a workflow, and then select the mode of the workflow that you want to create.
CloudFlow supports creating workflows in two modes: Standard and Express. For more information about the two modes, see Standard mode and express mode. For more operations, see Create a workflow from a blank canvas.
Edit the workflow that you created in the previous step.
Edit the workflow.
Select one of the following two editing methods: CloudFlow Studio or YAML. This topic uses the YAML editing method as an example.
In the upper-right corner of the workflow details page, click YAML, enter the Flow Definition Language code in the code editor on the left, and then click Save.
The following example is provided:
Type: StateMachine Name: MyFlow SpecVersion: v1 StartAt: InvokeFunction States: - Type: Task Name: InvokeFunction Action: FC:InvokeFunction TaskMode: RequestComplete Parameters: invocationType: Async resourceArn: acs:fc:us-west-1:103435468****:functions/func-i1****/LATEST End: trueConfigure the workflow role.
In the upper-right corner of the workflow details page, click Configure Workflow, select Execution Role, and then click Save.
NoteMake sure that the role configured for the workflow is granted the AliyunFCInvocationAccess access policy.
On the workflow details page, you can click Execute in the upper-right corner to trigger the workflow task for testing.