If you want to track and save the status of each phase of an asynchronous invocation of a function, you can enable the task mode to process asynchronous requests. This topic describes the background information, limits, and common features of asynchronous tasks.
Background
After you enable the asynchronous task feature, you can obtain the following capabilities:
State transition information, such as Enqueued, Succeeded, and Failed, is recorded for each function invocation.
The lifecycle management capabilities of function requests are provided. You can terminate running asynchronous tasks.
Latency is increased for function invocations and executions if the asynchronous task feature is enabled because status information needs to be saved. The increased latency does not generate additional fees. For more information about the billing of Function Compute, see Billing overview.
Limits
Scenarios
Although the asynchronous task feature provides more capabilities, more system overheads are incurred. We recommend that you disable the asynchronous task feature in the following scenarios:
Your business applications are sensitive to the latencies of request processing links and require the average latency to be less than 100 milliseconds.
You need to initiate at least thousands of asynchronous invocations per second.
Supported regions
The asynchronous task feature is supported in the following regions: China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Shenzhen), China (Chengdu), China (Hong Kong), Singapore, UK (London), US (Silicon Valley), US (Virginia), Germany (Frankfurt), Australia (Sydney) Closing Down, Malaysia (Kuala Lumpur), Indonesia (Jakarta), Thailand (Bangkok), Japan (Tokyo), and South Korea (Seoul).
Validity period
You can query the task status information only within the last seven days.
Comparison between asynchronous tasks and Kubernetes jobs
Both the asynchronous task feature of Function Compute and Kubernetes jobs can be used to execute asynchronous tasks. Function Compute provides a ready-to-use asynchronous task execution platform that is more efficient and easier to control and observe based on the asynchronous task feature. The following table compares the two methods:
Item | Asynchronous tasks of Function Compute | Kubernetes jobs |
Scenarios | Real-time tasks that last tens of milliseconds and offline tasks that last tens of hours. | Offline tasks with fixed workloads and low requirements on task submission speed and timeliness. |
Observability | Supported. Logs, metrics such the number of queued tasks, and observability capabilities such as querying of task link durations and task status, are provided. | You must integrate open source software to implement the observability capabilities. |
Automatic scaling of task instances | Supported. Automatic scaling based on the number of queued tasks and instance resource usage can be performed. | You must use task queues to manually implement scaling and load balancing of instances, which is more complicated. |
Scaling speed of task instances | In milliseconds. | In minutes. |
Resource utilization of task instances | You need to only select the instance type. The instances are automatically scaled. You are charged based on the actual task-processing durations. The resource utilization is high. | You must determine the specifications and number of instances when Jobs are submitted. It is difficult to implement auto scaling and load balancing of instances. The resource utilization is low. |
Task submission speed | A single user can submit tens of thousands of tasks per second. | Up to hundreds of jobs can be started in a cluster per second. |
Scheduled or deferred task submission | Supported. | Scheduled task submission is supported. Deferred task submission is not supported. |
Task deduplication | Supported. | Not supported. |
Task termination | Supported. | Supported under certain conditions. You can terminate a task by stopping a task instance. |
Task throttling | Supported. Throttling can be performed at different granularities, such as at the user level or at the task-processing function level. | Not supported. |
Automatic result callback for a task | Supported. | Not supported. |
Development and O&M costs | You need to only implement the task processing logic. | You must maintain a Kubernetes cluster. |
Task management
States of an asynchronous task
For each task invocation, Function Compute records the information about the state changes of tasks and allows you to query the states of a task in real time. You can view the states of a task by using the Function Compute SDK or the Function Compute console. A task can be in one of the following states:
State | Description |
Enqueued | The asynchronous invocation is enqueued and to be executed. |
Processed | The asynchronous invocation is dequeued and waiting to be triggered. |
Running | The invocation is being executed and your instance has started to run the task code. |
Succeeded | The invocation succeeds. |
Failed | The invocation fails. |
Stopped | You attempted to stop the invocation, and the task is successfully terminated. |
Stopping | You attempted to stop the task, and the task is being terminated. |
Expired | You have configured a validity period for the asynchronous invocation. The invocation expired and was discarded. |
Invalid | The invocation is invalid and not triggered due to specific reasons. For example, the function is deleted. |
Retrying | The invocation is being retried after an execution error occurred. When the system is ready to retry the task, the state of the task changes to Running. |
You can call the GetAsyncTask operation to query the details of an asynchronous task. You can also call the ListAsyncTasks operation to filter tasks in a specified state.
Manage tasks
Manage tasks in the Function Compute console
Enable the asynchronous task feature 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.
On the Create Function page, select Task Function, configure the parameters based on your business requirements, and then click Create.
For more information about the parameters, see Create a task function.
After the function is created, the task mode is enabled by default in the Asynchronous Mode Configurations tab of the Configurations page.
Enable the asynchronous task mode for an existing function
Before you proceed, make sure that a function is created. For more information about how to create a function, 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 Configurations tab. In the left-side navigation tree, click Asynchronous Mode Configurations.
In the Asynchronous Mode Configurations section, click Modify. In the Asynchronous Mode Configurations panel, set Task Mode to Enable and 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 a task ID generation method and specify the task execution time, and then click OK.
You can also click the icon on the right side of Submit Task and select Configure Test Parameters from the drop-down list. An event function uses event and an HTTP function uses HTTP parameters to pass input parameters to the function to simulate task submission.
In the task list below, you can view the task status, task details, request ID, and instance ID, and connect to an instance.
Call API operations to manage tasks
Configure the task mode
You can call the PutAsyncInvokeConfig operation to enable the asynchronous task mode for asynchronous invocations. Configure asyncTask as shown in the following code snippet. Then, the asynchronous task mode is enabled for all asynchronous invocations of the function.
{
"asyncTask": true
}
After you configure the asynchronous task mode, you can still invoke the function in synchronous mode. The asynchronous task mode takes effect only for asynchronous invocations.
Trigger the function in asynchronous mode
You can call the InvokeFunction operation to trigger an asynchronous invocation to activate the task mode for the function. Set the x-fc-invocation-type request parameter to Async. You can add the HTTP request header x-fc-async-task-id to set a task ID for this call. For more information, see Task deduplication.
View a task
After you submit a task, you can call the GetAsyncTask operation to query the execution status and execution records of the task.
You can call the ListAsyncTasks operation to query a list of asynchronous tasks based on keywords or conditions.
Stop a task
After you submit a task, you can stop the task based on your business requirements. You can call the StopAsyncTask operation to stop an asynchronous task. When you stop a task, you must specify the task ID that you set when you submit the task. You can also call the ListAsyncTasks operation to query the IDs of running tasks.
Trigger tasks by using events
You can create triggers that support asynchronous invocations to trigger asynchronous tasks. The following items list the triggers that support asynchronous invocations.
EventBridge-based triggers:
ImportantMake sure that HTTP triggers and EventBridge-based triggers are triggered in the asynchronous mode.
Task deduplication
To avoid repeated task execution, Function Compute allows you to set a globally unique ID for each submitted task. If an asynchronous operation, such as the asynchronous submission operation, times out, you can retry by submitting a task with the same ID. For more information, see Retry policy.
Function Compute allows you to configure TaskID, which is a globally unique task ID. We recommend that you specify a task ID each time you submit a task. You can use the task ID to retry the task in case of an error such as a timeout error. Function Compute verifies the tasks that you submit. If a task with the same ID enters the system, the request is rejected and error 409
is returned.
Function Compute also provides RequestID. If you set RequestID but do not set TaskID, the system automatically sets TaskID to the value of RequestID. When you use asynchronous tasks, we recommend that you specify the TaskID and do not specify RequestID.
Set TaskID
You can submit a task for execution by using the Function Compute console, using Serverless Devs, or calling an API operation. If you need to configure TaskID, set the x-fc-async-task-id parameter when you trigger your function.
For more information about the sample code for setting TaskID, see Sample code.
Task monitoring
You can use the task monitoring metrics provided by Function Compute to monitor the status of asynchronous tasks in real time and detect exceptions such as errors and timeouts in a timely manner.
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 desired function.
On the details page of the function, click the Monitoring tab to view metrics related to asynchronous invocations and instance-level resource usage of asynchronous tasks. For more information about the metrics, see Monitoring metrics.
Click the Function Metrics tab to view metrics related to asynchronous invocations. The following figure shows an example:
Click the Instance Metrics tab to view instance-level resource usage of asynchronous tasks. The following figure shows an example:
NoteBefore you enable instance-level metrics, you must enable the logging feature. For more information, see Configure the logging feature.
Configure metric-based alert rules.
If you want to monitor a metric, such as memory usage and vCPU usage, click in the upper-right corner of the metric to go to the Create Metric-based Alert Rule panel. Configure alert conditions and thresholds based on your business requirements, and then click OK.
The following figure provides an example on configuring an alert rule, in which an alert with Medium severity is reported to contacts by DingTalk, email, phone, and webhook around the clock if the backlog of asynchronous invocations of a function is greater than or equal to five.
Job orchestration
You can integrate Function Compute with CloudFlow so that asynchronous invocations of functions can be applied to task processes in large-scale and complex scenarios. You can orchestrate Function Compute asynchronous tasks based on the control logic of CloudFlow, such as Sequence, Choice, and Parallel. CloudFlow coordinates the execution of tasks according to the specified steps in a reliable manner, tracks state transitions of each task, and executes the defined retry logic when necessary to ensure smooth and successful task completion. For more information, see Integrate CloudFlow with Function Compute.
Prerequisites
An asynchronous task is created. For more information, see Task management.
Permissions to access CloudFlow are granted to Function Compute. For more information, see Grant Function Compute permissions to access other Alibaba 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 a method to create a workflow, and then select a mode for the workflow.
CloudFlow allows you to create workflows in standard mode or express mode. For more information about the two modes, see Standard mode and express mode. For more information, see Create a workflow based on a blank canvas.
Edit the created flow.
Edit the flow.
You can use CloudFlow Studio or YAML to edit the flow. In this example, YAML is used.
In the upper-right corner of the flow details page, click YAML. In the left-side code editor, enter code to be used by the flow and click Save.
Sample code:
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: true
Configure a flow role.
In the upper-right corner of the flow details page, click Configure Workflow, select a role from the Execution Role drop-down list in the Role Configuration section, and then click Save.
NoteMake sure that the role configured for the flow is attached the AliyunFCInvocationAccess policy.
On the flow details page, click Execute in the upper-right corner to trigger the flow and check whether the flow works as expected.