All Products
Search
Document Center

Function Compute:Lifecycle hooks for function instances

Last Updated:Aug 04, 2024

After you implement and configure lifecycle hooks for function instances, Function Compute calls a lifecycle hook when a corresponding event occurs. The following lifecycle hooks can be configured for a function that runs in a Node.js runtime: Initializer hooks and PreStop hooks.

Usage notes

The billing rules for lifecycle hooks of function instances are the same as the billing rules for common invocation requests. However, the execution logs can be queried only in Function Logs, Real-time Logs, and Advanced Logs. The logs for lifecycle hooks are not displayed in the invocation request list. For more information, see View the logs of instance lifecycle hooks.

Initializer hooks

An Initializer hook is invoked after a function instance is started and before a handler is run. Function Compute ensures that the Initializer hook is successfully invoked at most once in the lifecycle of a function instance. For example, if your Initializer hook fails to be executed, the system retries the Initializer hook until the Initializer hook is successfully executed, and then runs your handler.

The Initializer callback has only one context input parameter. The following sample code shows a simple Initializer callback.

ECMAScript modules

Note

This example supports only Node.js 18 and later.

export const initialize = async (context) => {
  console.log('initializer');
  return "";
}

CommonJS modules

exports.initialize = function(context, callback) {
  console.log('initializer');
  callback(null, "");
};   

initialize is the name of the Initializer hook. The name must be the same as the Initializer hook that you configure in the Function Compute console. For example, if you set the name of the Initializer hook to index.initialize for a function, Function Compute loads the initialize method defined in the index.js file after the Initializer property is configured.

Method signature

  • The input parameter is context only, which provides your Function Compute function with the running context at the time of invocation.

  • No value is returned. You must call return or callback in your code to terminate the function.

PreStop hooks

A PreStop hook is executed before a function instance is destroyed. The method signature of a PreStop hook is the same as the method signature of an Initializer hook.

The following sample code provides an example on a simple PreStop hook:

ECMAScript modules

Note

This example supports only Node.js 18 and later.

export const preStop = async (context) => {
  console.log('preStop');
  return "";
}

CommonJS modules

module.exports.preStop = function(context, callback){
  console.log('preStop');
  callback(null, "");
}

Configure lifecycle hooks

Use the Function Compute console

In the Function Compute console, you can configure the Initializer hook and PreStop hook in function configurations. For more information, see Configure instance lifecycles. The format of a hook is [File name.Method name]. Examples:

  • index.initialize indicates the initialize method in the index.js file.

  • index.preStop indicates the preStop method in the index.js file.

db-node.js-lifecycle

Use Serverless Devs to configure lifecycle hooks

If you use Serverless Devs to configure lifecycle hooks, you must add the Initializer hook or PreStop hook to the s.yaml file.

  • Configure the Initializer hook

    Add instanceLifecycleConfig.initializer, including the handler and timeout fields, to props.

  • Configure the PreStop hook

    Add instanceLifecycleConfig.preStop, including the handler and timeout fields, to props.

Sample code:

edition: 3.0.0
name: hello-world-app
access: default         # The alias of the key.

resources:
  hello_world:
    component: fc3 # The name of the component. Serverless Devs is similar to a game console and does not have specific business capabilities without components. A component is similar to a game card. You can insert different game cards into the game console to play different games. Similarly, you can use different components to implement different business capabilities.
    # actions:       # The custom execution logic. For more information about actions, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E8%A1%8C%E4%B8%BA%E6%8F%8F%E8%BF%B0actions.
    props:
      region: cn-hangzhou # For more information about how to use variables, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC.
      functionName: nodejs-fc-hooks
      description: "Node.js lifecycle hooks by serverless devs"
      runtime: nodejs20
      code: ./code
      handler: index.handler
      memorySize: 128
      timeout: 30
      instanceLifecycleConfig:
        preStop:
          handler: index.preStop
          timeout: 3
        initializer:
          handler: index.initialize
          timeout: 3
      internetAccess: true
      logConfig: auto

For more information about the YAML configuration of Serverless Devs, see Common commands of Serverless Devs.

View the logs of instance lifecycle hooks

You can view the logs for lifecycle hook in Logs.

  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 Test Function tab, click Test Function, and then choose Logs > Function Logs.

    On the Logs tab, you can view function invocation logs and Initializer logs. Example:

    2023-09-06 11:18:10FC Initialize Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10load code for handler:index.initialize
    2023-09-06 11:18:102023-09-06 11:18:10 1-64f7ef72-64caf1ff0046194d9a26bbd7 [verbose] initializer
    2023-09-06 11:18:10FC Initialize End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10FC Invoke Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10load code for handler:index.handler
    2023-09-06 11:18:10FC Invoke End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7

    Each function instance is cached for a period of time and not destroyed immediately, you cannot view the logs for PreStop hooks right away. To quickly trigger the PreStop hook, you can update the function configurations or function code. After the update is complete, you can view the logs for PreStop hooks in Function Logs. The following sample code shows an example:

    2023-09-06 11:08:10FC PreStop Start RequestId: 944bca62-b209-47a1-9e48-2723647bce0a
    2023-09-06 11:08:10load code for handler:index.preStop
    2023-09-06 11:08:102023-09-06 11:08:10 944bca62-b209-47a1-9e48-2723647bce0a [verbose] preStop
    2023-09-06 11:08:10FC PreStop End RequestId: 944bca62-b209-47a1-9e48-2723647bce0a

Sample program

Function Compute provides a sample program on a MySQL database that uses Initializer and PreStop hooks. In this example, an Initializer hook is used to obtain MySQL database configurations from environment variables, create MySQL database connections, and test the connectivity. A PreStop hook is used to terminate MySQL connections.

For more information, see nodejs14-mysql.

More information

For more information about the lifecycle hooks of function instances, see Configure instance lifecycles.