To track the status of asynchronous function invocations, you can enable task mode. This mode provides greater control and observability over your asynchronous requests. This topic describes the background information, limits, and features of asynchronous tasks.
Background information
When you enable asynchronous tasks, you can:
Record detailed status transition information for each function invocation, such as Enqueued, Succeeded, and Failed.
Manage the lifecycle of function requests and stop running asynchronous tasks.
Asynchronous tasks save status information, which adds a small amount of extra latency to the function invocation and execution. This latency does not incur extra charges. For more information about Function Compute billing, see Billing overview.
Limits
Scenario limits
Asynchronous tasks offer more features but create more system overhead. You should disable task mode in the following scenarios:
You are highly sensitive to request processing latency and require an average latency of less than 100 ms.
You require thousands or more asynchronous invocations per second.
Region limits
Asynchronous tasks are supported in the following regions: 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).
Time limits
You can query task status information only for the last 7 days.
Comparison between asynchronous tasks and Kubernetes Jobs
To run asynchronous tasks, you can use the asynchronous task feature of Function Compute or the Jobs feature of Kubernetes. Function Compute asynchronous tasks provide an out-of-the-box platform for running asynchronous tasks that is more efficient, controllable, and observable. The following table compares the two features.
Comparison item | Function Compute asynchronous tasks | Kubernetes Jobs |
Scenarios | Suitable for real-time tasks that run for tens of milliseconds and offline tasks that run for up to tens of hours. | Suitable for offline tasks where submission speed is not high, the payload is relatively fixed, and real-time performance is not critical. |
Task observability | Supported. Provides rich observability features, such as logs, metrics for the number of queued tasks, task link latency, and task status queries. | Requires you to integrate open source software. |
Automatic scaling of task instances | Supported. Automatically scales instances based on the number of queued tasks and instance resource utilization. | Requires you to implement scaling and instance load balancing through a task queue, which is complex. |
Task instance scaling speed | Milliseconds. | Minutes. |
Task instance resource utilization | You only need to select a suitable instance type. Instances scale automatically, and you are billed for the actual running time of tasks, which results in high resource utilization. | You must determine the instance type and number when you submit a Job. Instances are difficult to scale automatically and load balance, which results in low resource utilization. |
Task submission speed | A single user can submit tens of thousands of tasks per second. | An entire cluster can start a maximum of several hundred Jobs per second. |
Scheduled or delayed task submission | Supported. | Supports scheduled task submission but not delayed task submission. |
Task deduplication | Supported. | Not supported. |
Stop a specific task | Supported. | Limited support. This is achieved indirectly by stopping task instances. |
Task throttling | Supported. You can throttle traffic at different granularities, such as by user or task execution function. | Not supported. |
Automatic task result callback | Supported. | Not supported. |
Development and operations costs | You only need to implement the task processing logic. | Requires you to maintain a Kubernetes cluster. |
Task management
Asynchronous task statuses
For each task invocation, Function Compute records the status change process and provides a real-time status query feature. You can view the specific status of a task using the SDK or in the Function Compute console. The following task statuses are available:
Execution status | Description |
Enqueued | The asynchronous message is enqueued and waiting to be processed. |
Processed | The asynchronous message is dequeued and waiting to be triggered. |
Running | The invocation is in progress. Your instance has started to run the task code. |
Succeeded | The invocation succeeded. |
Failed | The invocation failed. |
Stopped | You have manually stopped the task invocation. The task is successfully stopped. |
Stopping | You manually stopped the task. The system is trying to stop the task. |
Expired | You configured a time-to-live (TTL) for the asynchronous message. The message expired and was discarded without being triggered. |
Invalid | Your execution is in an invalid state and was not triggered because the function or service was deleted. |
Retrying | The asynchronous invocation is being retried due to an execution error. When the system is ready to retry, the task status changes back to Running. |
You can call the GetAsyncTask - Get an asynchronous task API operation to retrieve the details of a task execution. You can also call the ListAsyncTasks - Get a list of asynchronous tasks API operation to filter tasks by a specific status.
Manage tasks
Manage tasks in the console
Enable the asynchronous task feature when you create a function
Log on to the Function Compute console. In the navigation pane on the left, 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 click Create Task Function. On the Create Task Function page, set a function name and click Create.
For more information about the configuration items, see Create a task function.
After the function is created, navigate to the Task tab on the function details page. The task mode is enabled by default.
Enable the asynchronous task pattern for an existing function
You must first create a function. For more information, see 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 the function that you want to manage.
On the function details page, choose the Task tab and click Edit to the right of Task Mode.
In the Task Mode 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, choose the Task tab and click Submit Task. In the dialog box that appears, select a method to generate the task ID and specify the task execution time. Then, click OK.
You can also click the
icon to the right of Submit Task and select Configure Test Parameters from the drop-down list to simulate a task submission. In this case, input parameters are passed to the function as an event for an event function or as HTTP parameters for an HTTP function.
In the task list at the bottom, you can view the Task Status, Task ID, and Instance ID, or log on to the instance.
Call API operations to manage tasks
Configure the task mode
Call the PutAsyncInvokeConfig - Configure asynchronous invocation for a function API operation to set the asynchronous invocation mode to task mode. Set asyncTask to the following content. After you apply this configuration, all asynchronous invocations for the function are in task mode.
{
"asyncTask": true
}
After you set the asynchronous invocation mode to task mode, you can still invoke the function synchronously. However, the asynchronous task mode takes effect only for asynchronous invocations.
Trigger the function in asynchronous mode
You can call the InvokeFunction - Invoke a function API operation and set the x-fc-invocation-type parameter to Async to trigger an asynchronous invocation and start the task mode. You can add the x-fc-async-task-id HTTP request header to the invocation to set a task ID. For more information, see Prevent duplicate task submissions.
View jobs
After you submit a task, you can call the GetAsyncTask - Get an asynchronous task API operation to query the status or execution records of the task.
To query a list of task executions based on keywords or conditions, you can call the ListAsyncTasks - Get a list of asynchronous tasks API operation.
Stop a job
After you submit a task, you can stop it as needed by calling the StopAsyncTask - Stop an asynchronous task API operation. When you stop a task, you must provide the TaskID. This is the ID that you set when you submitted the task or the ID that you obtained when you called the ListAsyncTasks - Get a list of asynchronous tasks API operation to query running tasks.
Event triggers
You can trigger asynchronous tasks by creating triggers that support asynchronous invocation. The following triggers support asynchronous invocation:
Triggers implemented through EventBridge, including the following:
ImportantMake sure that the Invocation Method for HTTP triggers and triggers implemented through EventBridge is set to Asynchronous Invocation.
Prevent duplicate task submissions
To prevent duplicate task executions, Function Compute lets you set a globally unique ID for each submitted task. If an asynchronous API call to submit a task fails, for example, due to a timeout, you can retry the submission with the same ID. For more information about retry methods, see Retry policy.
Function Compute provides the TaskID concept, which is a globally unique ID. We recommend that you specify this ID every time you submit a task and retry in case of a timeout. Function Compute validates duplicate task submissions. If a task with the same ID is submitted again, the request is considered a duplicate and is rejected with a 409
error.
Function Compute also provides the RequestID concept. If you set a RequestID but not a TaskID, the system automatically sets the TaskID to the RequestID. When you use asynchronous tasks, we recommend that you set the TaskID and do not set the RequestID.
Set a TaskID
You can submit a task execution in the Function Compute console, using Serverless Devs, or by calling an API operation. To set a TaskID, set the x-fc-async-task-id parameter when you trigger the function execution.
For sample code on how to set a TaskID when triggering a task execution, see Sample code.
Task monitoring
You can use the task monitoring metrics provided by Function Compute to retrieve the real-time status of asynchronous tasks and promptly detect issues such as errors or timeouts.
Prerequisites
A function is created. For more information, see Create a function.
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 target function.
On the details page of the target function, choose the Monitoring tab to view metrics related to asynchronous invocations and the resource usage of asynchronous task instances. For more information about monitoring metrics, see Monitoring metrics.
Click the Function Metrics tab to view metrics related to asynchronous invocations, such as Async Invocation Status, Async Latency, Async Event Triggered, and Async Queue Size.
Click the Instance Metrics tab to view the resource usage of asynchronous task instances.
NoteBefore you can enable instance-level metrics, you must first enable the logging feature. For more information, see Configure logging.
Set an alert rule for a metric.
If you want to monitor a metric, such as memory usage or vCPU usage, click the
icon in the upper-right corner of the metric. You are redirected to the Create Metric Alert Rule panel. Set the alert conditions and threshold as prompted, and then click OK.
The following figure shows how to set an alert rule. The parameter settings in the figure indicate that if the number of backlogged asynchronous function invocations is greater than or equal to 5, a medium-level alert is reported to the contact around the clock using DingTalk, email, phone, and webhook.
Task orchestration
When integrated with CloudFlow, asynchronous function invocations can be used for task flows in large-scale and complex scenarios. You can use states such as Pass, Map, and Parallel to orchestrate Function Compute asynchronous tasks. CloudFlow reliably coordinates task execution according to the predefined steps, tracks the status transitions of each task, and executes the retry logic that you define when necessary to ensure that the tasks are successfully completed. For more information, see Integrate Function Compute.
Prerequisites
An asynchronous task is created. For more information, see Task management.
Function Compute is granted the permissions to access CloudFlow. For more information, see Grant Function Compute permissions to access other Alibaba Cloud services using function roles.
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 and a mode to create the workflow.
CloudFlow supports standard and express workflows. For more information about the two modes, see Standard workflows and express workflows. For more information about the operations, see Create a workflow based on a blank canvas.
Edit the workflow that you created in the previous step.
Edit the flow.
You can edit the flow in CloudFlow Studio or using YAML. This topic uses YAML as an example.
On the flow details page, click YAML in the upper-right corner. Enter the Flow Definition Language in the code editor on the left and click Save.
The following example shows the 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.
On the flow details page, click Workflow Configuration in the upper-right corner. Select an Execution Role and click Save.
NoteMake sure that the role configured for the flow is granted the AliyunFCInvocationAccess access policy.
On the flow details page, you can click Execute in the upper-right corner to trigger the workflow for testing.