Best practices for asynchronous tasks

更新时间:
复制 MD 格式

Asynchronous tasks extend basic asynchronous invocations with real-time observability and operational control — letting you track execution status, stop long-running functions, and retry failed invocations from the Function Compute console.

This guide walks through deploying a sample function with asynchronous tasks enabled, routing failure notifications to a Simple Message Queue (formerly MNS) (SMQ) queue, and verifying the end-to-end flow using Serverless Devs.

How it works

When you invoke a function asynchronously, Function Compute returns 202 immediately and queues the request for backend processing. With asynchronous tasks enabled, each queued invocation becomes a trackable task:

  • Observable: View real-time execution status (including whether a message is removed from the queue, whether function execution is triggered, and whether the result is sent to the destination), execution logs, and historical records filtered by name, time, or status.

  • Operable: Stop a running execution or re-run any completed execution — whether it succeeded or failed.

When an invocation fails or is stopped, Function Compute pushes a structured message to the configured destination queue, so you can inspect the error and act on it programmatically.

For a conceptual overview, see Asynchronous tasks.

Prerequisites

Before you begin, ensure that you have:

Deploy the function

  1. Clone the sample project:

    git clone https://github.com/awesome-fc/Stateful-Async-Invocation.git
  2. Go to the project directory:

    cd Stateful-Async-Invocation
  3. Open s.yaml and replace {accountid} with your Alibaba Cloud account ID and {myqueue} with the name of your SMQ queue. The complete s.yaml is shown below for reference:

    ParameterDescription
    maxAsyncEventAgeInSecondsMaximum time (in seconds) a queued event waits before being discarded. Set to 172800 (48 hours) in this example.
    maxAsyncRetryAttemptsNumber of retries after the initial invocation fails. Set to 1 here — the function is tried twice in total before being routed to the failure destination.
    asyncTaskSet to true to enable asynchronous task tracking in the console.
    destinationConfigConfigures where Function Compute pushes result messages. Both onSuccess and onFailure point to the same SMQ queue in this example.
    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   # Max age of a queued event: 48 hours
            maxAsyncRetryAttempts: 1            # Retry once on failure before routing to destination
            asyncTask: true                     # Enables asynchronous task tracking
            qualifier: LATEST
            destinationConfig:
              onSuccess:
                destination: acs:mns:cn-hangzhou:{accountid}:/queues/{myqueue}/messages
              onFailure:
                destination: acs:mns:cn-hangzhou:{accountid}:/queues/{myqueue}/messages

    Key asyncInvokeConfig parameters:

  4. Deploy the function:

    sudo s deploy

    After deployment, log in to the Function Compute console to confirm that the function my-fc-job is created and the asynchronous task feature is enabled.

Verify the setup

  1. Invoke the function asynchronously using Serverless Devs:

    To view execution logs from the console, configure Simple Log Service for the function first. See Configure the logging feature.
    sudo s invoke --invocation-type Async -e '{"failure":true}'

    Manage and monitor the invocation in the Function Compute console under Task management. See Task management for details.

  2. Check the destination queue for result messages. Open the SMQ console and receive messages from your queue. Because the invocation payload sets "failure": true, the function times out. The message pushed to the failure destination looks like this:

    FieldDescription
    requestIdUnique ID for this invocation. Use it to correlate logs in Simple Log Service.
    functionArnARN-style identifier for the function in Alibaba Cloud.
    conditionReason the destination was triggered. InvocationError indicates the invocation failed.
    approximateInvokeCountTotal number of attempts, including retries. 2 means the function was tried once and retried once (maxAsyncRetryAttempts: 1).
    responsePayloadThe error message returned by the function. Use this to diagnose failures without checking logs manually.
    {
        "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)\"}"
    }

    Key fields in the message:

Best practices

Design functions to be idempotent. Because asynchronous invocations may be retried (controlled by maxAsyncRetryAttempts), your function logic should produce the same outcome regardless of how many times it runs. A common pattern is to use the requestId as an idempotency key when recording results.

Configure a destination to capture failures. Function Compute only pushes result messages to the SMQ queue when destinationConfig is set in asyncInvokeConfig. Without it, failed invocations are silently discarded after the retry limit is reached.

What's next