All Products
Search
Document Center

Function Compute:Function instance lifecycle hooks

Last Updated:Apr 01, 2026

Function Compute invokes lifecycle hooks at defined points in a function instance's life — once when an instance starts and once before it shuts down. This topic shows how to implement the Initializer and PreStop hooks in a custom runtime.

How it works

A function instance moves through three phases:

  • Initialization: When Function Compute creates or unfreezes an instance, it calls the Initializer hook (if configured) before routing any traffic to the instance. Use this phase to load models, warm up connection pools, or run any setup that must complete before the first request.

  • Invocation: The instance handles function invocations. The main handler routes requests to your business logic.

  • Shutdown: Before Function Compute freezes or destroys an instance, it calls the PreStop hook (if configured). Use this phase to flush buffers, close connections, or clean up resources.

Lifecycle hooks are billed at the same rate as normal invocations. Their logs appear in Function Logs and Advanced Logs, but not in the Invocation Requests list.

For background on instance lifecycle configuration, see Configure instance lifecycle.

Hook interface reference

Your custom runtime HTTP server must expose the following endpoints:

HookPathMethodRequest bodySuccessFailure
Initializer/initializePOSTNone2xxNon-2xx
PreStop/pre-stopGETNone2xxNon-2xx

Both hooks receive the common request headers, including x-fc-request-id.

Important

If the Initializer hook times out or returns a non-2xx status, the server still returns HTTP 200. Check the X-Fc-Error-Type:InitializationError response header or the errorMessage field in the response body to detect initialization failures.

Implement lifecycle hooks

The following Python 3.10 Flask example shows all three endpoints in a single HTTP server: the Initializer hook, the main invocation handler, and the PreStop hook.

import os
from flask import Flask, request

app = Flask(__name__)

# Initializer hook — runs once when the instance starts
@app.route('/initialize', methods=['POST'])
def init_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC Initialize Start RequestId: " + rid)
    # Add setup logic here: load models, open connections, etc.
    print("FC Initialize End RequestId: " + rid)
    return "OK"

# Main invocation handler
@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)
    # Add business logic here
    print("FC invoke End RequestId: " + rid)
    return "Hello, World!", 200, [('Function-Name', os.getenv('FC_FUNCTION_NAME'))]

# PreStop hook — runs before the instance is frozen or destroyed
@app.route('/pre-stop', methods=['GET'])
def prestop_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC PreStop Start RequestId: " + rid)
    # Add cleanup logic here: flush buffers, close connections, etc.
    print("FC PreStop End RequestId: " + rid)
    return "OK"


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

Only implement /initialize if you configure an Initializer for the function. If no Initializer is configured, Function Compute never calls /initialize — even if the endpoint exists in your HTTP server.

The PreStop hook follows the same implementation pattern as the Initializer hook.

Error scenarios for the Initializer hook

If the initialization logic raises an exception or returns a non-2xx status, Function Compute records an initialization error:

# Scenario 1: unhandled exception
@app.route('/initialize', methods=['POST'])
def init():
    raise Exception("initialization failed")
    return "OK", 200, []

# Scenario 2: explicit non-2xx response
@app.route('/initialize', methods=['POST'])
def init():
    return "OK", 404, []

Error handling

Function Compute responds differently to errors depending on which hook fails and what status code it returns.

Initializer errors

Status codePlatform behavior
400, 404Function Compute does not resend the current request. It retries the Initializer hook until the hook succeeds.
500Function Compute restarts the function instance.

PreStop errors

Status codePlatform behavior
400, 404The error does not affect instance freezing or shutdown. Function Compute proceeds normally.

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 you want to configure.

  3. Click the Configuration tab. In the Instance Configuration section, click Modify.

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

  5. Implement the hook logic in your code. Click Deploy above the code editor, then click Test Function.

View lifecycle hook logs

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. Select a region and click the function you want to inspect.

  3. Click the Test tab, click Test Function, then choose Logs > Function Logs.

Function Logs displays both invocation logs and Initializer hook logs in chronological order. The following example shows an Initializer execution followed by a function invocation:

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 the instance for a period before destroying it. To trigger the PreStop hook on demand, update the function's configuration or code, then check Function Logs:

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