All Products
Search
Document Center

Function Compute:Lifecycle hooks for function instances

Last Updated:Mar 27, 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 Node.js runtime: Initializer hooks and PreStop hooks.

Usage notes

The billing rules for the 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, Instance Logs, and Advanced Logs. The logs for lifecycle hooks are not displayed in Call Request List. For more information, see Query logs related to hooks.

Initializer hooks

An Initializer hook is executed after a function instance is started before a handler runs. Function Compute ensures that the Initializer hook is successfully invoked only 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.

An Initializer hook consists of the context input parameter and can be used in the same manner as a handler.

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

ECMAScript modules

Note

This example supports only Node.js 18 or later.

export const initialize = async (event, 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 configured 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 FC 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 or later.

export const preStop = async (event, 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.FC For more information, see Function instance lifecycle. 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 the initializer and initializationTimeout fields to the function configurations.

  • Configure the PreStop hook

    Add the instanceLifecycleConfig.preStop field, including handler and timeout, to the function configurations.

Sample code:

edition: 1.0.0          # The version of the YAML specification. The version complies with the semantic versioning specification.
name: hello-world       # The name of the project.
access: default         # The alias of the key.

services:
  fc-deploy-test: # The name of the module.
    component: devsapp/fc  # The name of the component.
    props:                 # The property value of the component.
      region: cn-hangzhou   # The ID of the region.
      service:             # The configurations of the service.
        name: fc-deploy-service    # The name of the service.
        description: dem component # A brief description of the service.
      function:                       # The configurations of the function.
        name: fc-base-service         # The name of the function.
        description: 'this is test'   # A brief description of the function.
        codeUri: './code'             # The location of the code.
        handler: 'index.handler'      # The handler of the function. The format varies based on the language.
        memorySize: 128               # The memory size of the function.
        runtime: nodejs14             # The runtime environment.
        timeout: 60                   # The timeout period for the execution of the function.
        initializationTimeout: 20     # The timeout period for the execution of the Initializer method.
        initializer: index.initialize # The Initializer method.
        instanceLifecycleConfig:      # The extension function.
          preStop:                    # The PreStop hook.
            handler: index.preStop    # The handler.
            timeout: 60               # The timeout period.

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 the Initializer and PreStop hooks. In this example, the Initializer hook is used to obtain MySQL database configurations from environment variables, create MySQL database connections, and test the connectivity. The PreStop hook is used to close MySQL connections.

For more information, see nodejs14-mysql.

More information

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