Best practices for asynchronous tasks

Updated at: 2024-11-22 05:24

Asynchronous tasks allow you to obtain information about the status of your business in real time and manage the execution of functions so that you can better handle abnormal situations. For example, you can configure alert notifications and perform automated retries. The following example shows how to use Serverless Devs and the Function Compute console to implement an asynchronous task.

Background

Function as a service (FaaS) was originally used for stateless, short-term, and lightweight computing, such as API backend services, image processing, and stream processing. FaaS functions can be invoked in various scenarios, either in asynchronous or synchronous mode. When a function is synchronously invoked, the function is immediately executed. When a function is asynchronously invoked, the 202 HTTP code is immediately returned, and the asynchronously invoked message is queued for processing by the backend service.

Scenarios

As business grows, some live streaming businesses are gradually migrating to FaaS. In such scenarios, the execution duration is long, the execution of functions is sensitive to latency, and high availability is required. Developers need to obtain information about the status of their business in real time and manage function executions. Neither synchronous nor regular asynchronous invocations are suitable for such scenarios. This is because regular asynchronous invocations are insensitive to latency, while in synchronous invocations, persistent connections are unstable and client resources are occupied. Asynchronous invocations can help balance workloads during peak hours of offline business to smoothly buffer traffic for downstream systems when traffic spikes occur. Based on these benefits of asynchronous invocations, Function Compute introduces asynchronous tasks. Asynchronous tasks are suitable for the following business scenarios:

  • Observable executions

    • You want to view information about an execution in real time, such as whether a message is removed from the queue, whether the execution of a function is triggered, and whether the execution result is sent to the destination.

    • Your business needs to be operated in the same way that task executions are operated.

      • You want to view the event that triggers a specific execution and real-time execution logs.

      • You want to query historical records based on the name, time, or status of an execution.

  • Operable executions

    Your business needs to be operated in the same way as task executions are operated.

    • In some cases, you may need to stop a function execution if the execution duration is long.

    • You want to re-perform failed or successful executions.

For more information about asynchronous tasks, see Asynchronous tasks.

Preparations

Procedure

You can use asynchronous tasks for the following purposes:

  • View the execution status in the Function Compute console or by calling a Function Compute API operation or SDK after an asynchronous function execution starts.

  • Function Compute pushes asynchronous messages to the specified Simple Message Queue (formerly MNS) queue if a function execution fails or is stopped. This helps you obtain information about failed asynchronous invocations and perform operations accordingly.

  1. Run the following command to clone the project:

    git clone https://github.com/awesome-fc/Stateful-Async-Invocation.git
  2. Run the following command to go to the project directory:

    cd Stateful-Async-Invocation
  3. Modify the s.yaml file.

    The following code snippet provides a complete example of the s.yaml file. Change the value of {accountid} to the ID of your Alibaba Cloud account, and the value of {myqueue} to the destination Simple Message Queue (formerly MNS) queue that you configured for asynchronous invocations.

    edition: 3.0.0
    name: stateful-async-inovcation-demo
    access: default
    resources:
      fc-job:
        component: fc3
        props:
          region: cn-hangzhou
          description: this is test
          handler: index.handler
          memorySize: 128
          runtime: python3
          instanceConcurrency: 1
          timeout: 60
          internetAccess: true
          role: acs:ram::{accountid}:role/aliyunfcdefaultrole
          functionName: my-fc-job
          code: ./code
          asyncInvokeConfig:
            maxAsyncEventAgeInSeconds: 172800
            maxAsyncRetryAttempts: 1
            asyncTask: true
            qualifier: LATEST
            destinationConfig:
              onSuccess:
                destination: acs:mns:cn-hangzhou:{accountid}:/queues/{myqueue}/messages
              onFailure:
                destination: acs:mns:cn-hangzhou:{accountid}:/queues/{myqueue}/messages
  4. Run the following command in the project directory to deploy the function:

    sudo s deploy

    After the function is deployed, you can log on to the Function Compute console to check whether the function is created and whether the asynchronous task feature is enabled for the function.

Verify configurations

  1. You can use Serverless Devs to invoke the function that is deployed in the previous step. The following sample code provides an example:

    sudo s invoke --invocation-type Async -e '{"failure":true}'

    You can view and manage asynchronous invocations in the Function Compute console. For more information, see Task management.

    Note

    To view the detailed information such as the execution logs of a function, you must configure Simple Log Service for the function. For more information, see Configure the logging feature.

  2. After a function is invoked, you can go to the specified destination, if configured, to view the push records.

    In this example, an Simple Message Queue (formerly MNS) queue is specified as the destination. You can receive the messages that are pushed to the destination in the SMQ console. The following code snippet shows an example:

    {
        "timestamp": 1728465119433,
        "requestContext": {
            "requestId": "1-670648a1-15197d0b-d07710222f9d",
            "functionArn": "acs:fc:cn-hangzhou:1034354682****:functions/my-fc-job",
            "condition": "InvocationError",
            "approximateInvokeCount": 2
        },
        "requestPayload": "{\"failure\":true}",
        "responseContext": {
            "statusCode": 200,
            "functionError": "InvocationError"
        },
        "responsePayload": "{\"errorMessage\":\"Function timed out after 60 seconds (maxMemoryUsage: 8MB)\"}"
    }
    Note

    If an asynchronous invocation fails or is stopped, you can obtain information about the error in SMQ.

  • On this page (1, T)
  • Background
  • Scenarios
  • Preparations
  • Procedure
  • Verify configurations
Feedback
phone Contact Us

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

alicare alicarealicarealicare