All Products
Search
Document Center

Function Compute:Instance lifecycle hooks

Last Updated:Apr 16, 2026

After you implement and configure instance lifecycle hooks, Function Compute invokes the corresponding hook for specific instance lifecycle events. This topic describes how to implement these hooks in a custom image.

Background

The instance lifecycle involves the Initializer hook and the PreStop hook. The Initializer hook has two types: invoke code and execute instruction. Currently, only GPU-accelerated functions support the execute instruction type. For more information, see Configure instance lifecycle.

Instance lifecycle hooks follow the same billing rules as normal invocation requests. However, their execution logs are available only in Real-time Log, Function Logs, or Advanced Logs, and do not appear on the Invocation Request List. For more information, see View instance lifecycle hook logs.

Note

Currently, logs from execute instruction hooks cannot be written to Function Log.

Implement callback methods

Function Compute invokes the corresponding hook for specific instance lifecycle events. The instance lifecycle involves the Initializer hook and the PreStop hook. The Initializer hook supports two types: invoke code and execute instruction. You cannot configure both types simultaneously; only one can be active at a time.

Invoke code

After you configure an invoke code hook, the system sends an HTTP request to your function, such as POST /initialize or GET /pre-stop, when an instance starts or is about to stop. You must handle the request in your application code.

Path

Request

Expected response

(Optional) POST /initialize

Response body: The return value of the function's Initializer hook.

StatusCode

  • 2xx: Success.

  • Non-2xx: Failure.

Note

If an Initializer hook fails or times out, the server always returns an HTTP 200 status code. To confirm a failure, you must check for the X-Fc-Error-Type:InitializationError response header or an errorMessage field in the response body.

(Optional) GET /pre-stop

Response body: The return value of the function's PreStop hook.

StatusCode

  • 2xx: Success.

  • Non-2xx: Failure.

To use the Initializer hook in a custom image, your HTTP server must implement logic for the /initialize path and POST method. The same applies to the PreStop hook, which requires logic for the /pre-stop path and GET method. The following sample code shows an implementation for a custom Python 3.10 runtime.

Note

You only need to implement the /initialize logic if you configure an Initializer hook. If the hook is not configured, any corresponding code in your HTTP server is never invoked. The same applies to the PreStop hook and the /pre-stop path.

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)

The previous example shows a successful initialization. The following examples show how a /initialize hook can fail in Python.

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

Execute instruction

An execute instruction hook runs a command to initialize the instance after it starts. You can use any shell supported by the function's runtime environment, such as /bin/bash, /bin/sh, /bin/csh, or /bin/zsh.

The Function Compute console provides two preset options: /bin/bash and /bin/sh. This topic uses /bin/sh as an example.

#!/bin/sh

URL="http://localhost:7860"
REQUEST_PATH="sdapi/v1/txt2img"
JSON_DATA='{
	"prompt": "",
	"steps": 1,
	"height": 8,
	"width": 8
}'
temp_file=$(mktemp)
trap 'rm -f "$temp_file"' EXIT

if ! http_code=$(curl -s -w "%{http_code}" \
	-H "Content-Type: application/json" \
	-d "$JSON_DATA" \
	-o "$temp_file" \
	-X POST "$URL"/"$REQUEST_PATH"); then
	echo "{\"status\": \"curl_error\", \"code\": $curl_exit_code}" \
	| jq . >&2
	exit 1
fi

response=$(<"$temp_file")
echo "http code $http_code"

if [ "$http_code" -eq 200 ]; then
	echo "$response" | jq -r '.' || printf "%s\n" "$response"
	exit 0
else
	echo "$response_body" \
	| jq -c 'if type == "object" then . else {raw: .} end' 2>/dev/null \
	| jq -s '{status: "http_error", code: $code, response: .[0]}' \
		--arg code "$http_code" \
		>&2
	exit 1
fi

An exit code of 0 indicates success. Any other exit code indicates failure. To aid troubleshooting, you can write error details to standard error (stderr) in the script. For example, the following snippet shows how to output error details and set the exit code to 1 when a curl request fails.

if ! http_code=$(curl -s -w "%{http_code}" \
	-H "Content-Type: application/json" \
	-d "$JSON_DATA" \
	-o "$temp_file" \
	-X POST "$URL"/"$REQUEST_PATH"); then
	echo "{\"status\": \"curl_error\", \"code\": $curl_exit_code}" \
	| jq . >&2
	exit 1
fi

Callback error codes

Invoke code

Error code

Description

400

  • If an Initializer hook fails with a 400 or 404 error, that specific request is not retried. However, the system attempts to initialize the instance again until it succeeds.

  • A 400 or 404 failure in a PreStop hook does not affect the freezing or stopping of the function instance.

404

500

Function Compute restarts the instance.

Execute instruction

If the exit code is not 0, the instruction fails and is not re-executed. The system then returns an error.

Configure instance 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, click Modify.

  4. In the Instance Configuration panel, configure the Initializer hook and set the Initializer Timeout.

    • Invoke code

      image

    • Execute instruction

      The console provides two preset shells: /bin/bash and /bin/sh.

      image

  5. In the Instance Configuration panel, configure the PreStop hook and set its timeout. Then click Deploy.

    image

View instance lifecycle hook logs

Note

Currently, logs from execute instruction hooks cannot be written to Function Log.

You can view hook logs 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*******

    Function instances are cached for a period and not destroyed immediately, so PreStop hook logs may not appear right away. To trigger the PreStop hook sooner, update the function's configuration or code. After the update completes, view Function Logs again to see the PreStop hook logs. The following is an example:

    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*******