All Products
Search
Document Center

Function Compute:Asynchronous tasks

更新時間:Aug 28, 2024

If you want to track and save the state 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 information

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

  • Regions

    Asynchronous tasks are 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), Malaysia (Kuala Lumpur), Indonesia (Jakarta), Thailand (Bangkok), Japan (Tokyo), and South Korea (Seoul).

  • 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. The asynchronous task feature of Function Compute provides a ready-to-use asynchronous task execution platform that is more efficient and easier to control and observe. 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 dozens of hours.

Offline tasks with fixed loads and low requirements on task submission speeds and timeliness.

Observability

Supported. Metrics, such as logs and the number of queued tasks, and the observability capabilities, including the query 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.

Not directly supported. You can terminate a task by terminating 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 processing logic of tasks.

You must maintain the 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 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 stopped the invocation, and the task is successfully terminated.

Stopping

You stopped the task, and the task is being terminated.

Expired

You configured a validity period for the asynchronous invocation. The invocation expired and was discarded.

Invalid

The invocation becomes invalid and is 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 console

Enable the asynchronous task feature when you create a function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click Create Function.

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

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Configurations tab. In the left-side navigation tree, click Asynchronous Mode Configurations.

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

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. 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 down icon next to Submit Task and select Configure Test Parameters from the drop-down list. Then, 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.

    image

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
}
Note

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.

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.

Note

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

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

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

      image

    • Click the Instance Metrics tab to view instance-level resource usage of asynchronous tasks. The following figure shows an example:

      Note

      Before you enable instance-level metrics, you must enable the logging feature. For more information, see Configure the logging feature.

      image

  3. Configure metric-based alert rules.

    If you want to monitor a metric, such as memory usage or vCPU usage, click image in the upper-right corner of the metric to go to the Create Metric Alert Rule panel. In the panel, set alert conditions and thresholds as prompted, 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.

    image

Task 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

Procedure

  1. Log on to the CloudFlow console. In the top navigation bar, select a region.

  2. In the left-side navigation pane, click Workflows. On the Workflows page, click Create Workflow.

  3. 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 about the procedure, see Create a flow.

  4. Edit the created flow.

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

      The following sample code shows an example:

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

      Note

      Make sure that the role configured for the flow is attached the AliyunFCInvocationAccess policy.

  5. On the flow details page, click Execute in the upper-right corner to trigger the flow and check whether the flow works as expected.