All Products
Search
Document Center

Function Compute:Function instance lifecycle hooks

Last Updated:Mar 24, 2026

This topic describes how to implement lifecycle hooks for function instances in a custom runtime.

Background

After you implement and configure lifecycle hooks for a function instance, Function Compute invokes the corresponding hook when a relevant lifecycle event occurs. The function instance lifecycle includes Initializer and PreStop hooks. For more information, see Configure instance lifecycle.

Lifecycle hooks are billed based on the same rules as normal invocation requests. However, you can view their execution logs only in Function Logs or Advanced Logs. The logs for lifecycle hooks do not appear in the Invocation Requests list. For more information, see View the logs of instance lifecycle hooks.

Implement lifecycle hooks

Function Compute invokes the corresponding callbacks when relevant instance lifecycle events occur. The function instance lifecycle involves Initializer and PreStop callbacks.

Path

Request

Expected response

(Optional) POST /initialize

Request body: None.

Request headers: Includes the common request headers. For more information, see Common request headers in Function Compute.

Response body: The return value of the Initializer hook.

StatusCode

  • 2xx: Success.

  • Non-2xx: Failure.

Note

If the Initializer hook times out or fails, the server always returns an HTTP 200 status code. You must check the X-Fc-Error-Type:InitializationError response header or the errorMessage field in the response body to identify an initialization failure.

(Optional) GET /pre-stop

Response body: The return value of the PreStop hook.

StatusCode

  • 2xx: Success.

  • Non-2xx: Failure.

The following example uses a Python 3.10 custom runtime to demonstrate how to implement lifecycle hooks.

import os
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/initialize', methods=['POST'])
def init_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC Initialize Start RequestId: " + rid)
    # do your things
    print("FC Initialize End RequestId: " + rid)
    return "OK"

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def hello_world(path):
    rid = request.headers.get('x-fc-request-id')
    print("FC invoke Start RequestId: " + rid)
    # do your things
    print("FC invoke End RequestId: " + rid)
    return "Hello, World!", 200, [('Function-Name', os.getenv('FC_FUNCTION_NAME'))]


@app.route('/pre-stop', methods=['GET'])
def prestop_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC PreStop Start RequestId: " + rid)
    # do your things
    print("FC PreStop End RequestId: " + rid)
    return "OK"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

In addition to the successful execution path, your function might encounter errors in Python. The following examples show error scenarios for the /initialize endpoint.

@app.route('/initialize', methods=['POST'])
def init():
    raise Exception("hahaha")
    return "OK", 200, []
@app.route('/initialize', methods=['POST'])
def init():
    return "OK", 404, []

To use the Initializer hook in a custom runtime, you must implement logic in your HTTP server for the /initialize path that accepts POST requests. For a code example, see the initialize entry in the table above.

Important

If you create a function without setting an Initializer, you do not need to implement /initialize. In this case, even if the HTTP Server implements /initialize, the /initialize logic in the code will not be called and executed.

The PreStop hook is implemented in the same way as the Initializer hook.

Error codes

Error code

Description

400

  • If an Initializer hook fails and returns a 400 or 404 error, Function Compute does not resend the request. Instead, it continues to retry the hook until it succeeds.

  • If a PreStop hook fails and returns a 400 or 404 error, it does not affect the freezing or stopping of the function instance.

404

500

Function Compute restarts the function instance.

Configure lifecycle hooks

  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 Configuration tab. In the Instance Configuration section of the left-side navigation pane, click Modify.

  4. In the Instance Configuration panel, set the hook and timeout period, and then click Deploy.

  5. After configuring the hooks, implement their logic in your code. Click Deploy above the code editor, and then click Test Function.

View instance lifecycle hook logs

You can view the logs for lifecycle hooks in Function 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 tab, click Test Function, and then choose Logs > Function Logs.

    On the Function Logs tab, you can view the function's invocation logs and Initializer hook logs. The following is an example:

    2024-06-26 10:59:23FC Initialize Start RequestId: 529eab23-9b3a-4ffc-88c8-9a686*******
    2024-06-26 10:59:23FC Initialize End RequestId: 529eab23-9b3a-4ffc-88c8-9a686*******
    2024-06-26 10:59:25FC Invoke Start RequestId: 1-667b840c-15c49df0-b7dc1*******
    2024-06-26 10:59:25FC Invoke End RequestId: 1-667b840c-15c49df0-b7dc1*******

    PreStop hook logs may not appear immediately because Function Compute caches a function instance for a period before destroying it. To trigger the PreStop hook on demand, you can update the function's configuration or code. After the update, check Function Logs to view the logs for the PreStop hook.

    2024-06-26 11:04:33FC PreStop Start RequestId: c4385899-f071-490e-a8b7-e33c5*******
    2024-06-26 11:04:33FC PreStop End RequestId: c4385899-f071-490e-a8b7-e33c5*******