All Products
Search
Document Center

Function Compute:Session lifecycle management

Last Updated:Mar 20, 2026

In stateful scenarios such as AI inference, online games, and multi-tenant Software as a Service (SaaS), managing persistent state and ensuring multi-tenant data isolation are core challenges. To address these challenges, Function Compute (FC) treats a session as an explicit resource and provides a comprehensive set of lifecycle management APIs that enable instance prefetching and fine-grained resource control. For multi-tenant scenarios, you can also dynamically mount dedicated persistent storage when creating a session to ensure strict data isolation at the file system level.

Scenarios

Scenario 1: AI Sandbox intelligent computing power service

  • Model and data preloading: You can use the CreateSession API to pre-create a session and prefetch an instance. During initialization, you can load large model weights to significantly improve the response speed of the first inference.

  • Secure data isolation and mounting: When creating a session, you can dynamically mount a dedicated NAS directory for each tenant and assign an independent POSIX user identity (UID/GID) to each directory. This ensures that the datasets and model shards of different tenants are logically isolated on physically shared storage and can be securely loaded on demand.

  • Autonomous lifecycle control: You can use an API to destroy idle sessions and release computing power resources. You can also extend the session time-to-live (TTL) for high-priority tasks to balance cost and performance.

Scenario 2: Online game service

  • Session state persistence: You can use session affinity to cache a player's real-time state, such as location and equipment, on a specific instance. This ensures low latency for high-frequency interactions. You can use session-specific persistent storage to reliably save critical game archives.

  • Precise TTL management: You can set independent light hibernation (formerly idle) timeout (TTL) policies for player sessions in different scenarios, such as matchmaking queues and battle rooms. This prevents zombie sessions from continuously occupying resources.

Feature description

Features

Behavior description

CreateSession - Create a session resource

  1. This operation creates an explicit session resource and pre-allocates a bound function instance. Session IDs can be generated in two ways:

    1. The client provides a custom session ID in the request. This method applies only to HeaderField affinity.

      1. Length limit: 1 to 64 characters.

      2. ID format: The ID must start with a letter (uppercase or lowercase), a digit, or an underscore (_). Subsequent characters can be letters (uppercase or lowercase), digits, underscores (_), or hyphens (-).

    2. The client does not provide a custom ID. In this case, the server generates a globally unique session ID and returns it in the response. This method applies to both HeaderField and Cookie affinity.

  2. You can dynamically mount a dedicated persistent storage directory for the session using the nas_config parameter during creation. You can also specify the user and group ID (UID/GID) for the file system directory.

  3. You can specify the light hibernation timeout `SessionIdleTimeoutInSeconds` and the session lifecycle parameter `SessionTTLInSeconds`. If you do not specify these parameters, the function's default configurations are used.

  4. This operation applies to HeaderField and Cookie affinity types.

  5. If you do not call `CreateSession` in advance, you can still implement affinity by including a session ID in an `InvokeFunction` call.

  6. You can specify whether to reuse a session ID after the session expires using the DisableSessionIDReuse parameter:

    1. If DisableSessionIDReuse is set to `false` (default), the session ID can be reused. After a session expires, if a request is sent with the same session ID, the system treats it as a new session and continues to provide the service. The session lifecycle is recalculated, but the new session is not guaranteed to be bound to the same instance as the original session.

    2. If DisableSessionIDReuse is set to `true`, the session ID cannot be reused. After a session expires, if a request is sent with the same session ID, the system rejects the request and returns an error message. This behavior is enforced for three days after the session expires. If a request is sent with the session ID more than three days after expiration, the system treats the request as a new session.

    3. If a user explicitly deletes a session using the DeleteSession API, the session becomes invalid and cannot be reused.

GetSession - Get session configuration information

  1. This operation retrieves the details of a specified session. The details include the SessionID, associated function, affinity type, lifecycle configuration, status, and instance information.

  2. You can precisely locate a session by `functionName` and `qualifier`.

  3. This operation returns the complete configuration of a specified active session. You cannot retrieve information about sessions that have expired or been explicitly deleted using `DeleteSession`.

ListSessions - Query a list of session information

This operation lists the sessions for a specified function. You can filter by `qualifier`, status, or `sessionID`, and use paged queries.

  1. This operation returns up to 100 records at a time. The default value is 20.

  2. If you do not pass a `qualifier` or set it to LATEST, sessions for all versions are returned.

  3. If you do not pass a status, sessions in the Active and Expired statuses are returned by default.

UpdateSession - Update session configuration

This operation updates the light hibernation (formerly idle) timeout `SessionIdleTimeoutInSeconds` and the session lifecycle parameter `SessionTTLInSeconds`. The update takes effect immediately, and the `lastModifiedTime` is automatically refreshed. You can use this to dynamically extend or shorten the session's validity period.

Note: After you update the TTL, the timer continues from the session's creation time and does not reset.

DeleteSession - Delete a session resource

  1. This operation deletes a specified session. The system purges the associated data. After deletion, the session cannot be queried using `GetSession` or `ListSessions`.

  2. After deletion, requests that carry the same SessionID are treated as requests for new sessions.

  3. If there are running requests at the time of deletion:

    • In a session fencing scenario, the associated resources are immediately released, and the running requests are terminated.

    • In a non-session fencing scenario, the requests continue to run until completion to ensure a graceful exit.

How it works: Session state transitions and lifecycle

image

Create a session

  • Manual creation: You can invoke the CreateSession - Create a session resource API. A successful invocation changes the session status to Active.

  • Passive creation: A session is automatically created with the Active status when you successfully invoke a function for the first time by calling the InvokeFunction operation with a custom SessionID.

Destroy a session

  • Passive destruction: If a session's TTL or light hibernation (formerly idle) timeout is reached, the system automatically changes its status to Expired.

  • Active deletion: If you call the DeleteSession - Delete a session resource API and the call is successful, the session status becomes Deleted.

    • Fencing mode: The session is deleted, requests are terminated, and the associated resources are automatically released.

    • Non-fencing mode: The session is deleted, and running requests are gracefully terminated. This process includes the following cases:

      1. The resources are released.

      2. The resources continue to process other sessions that have not expired or been deleted.

      3. The resources are bound to and reused by new sessions.

Note

Status transitions are unidirectional and irreversible: Active → Expired / Deleted. The Expired and Deleted statuses cannot be converted to each other.

Differences and working principles of TTL and IdleTimeout

In session management, the system typically uses two time parameters to control a session's validity period:

Parameter

Meaning

sessionTTLInSeconds

The maximum time to live for a session from its creation, regardless of whether it is active.

sessionIdleTimeoutInSeconds

The maximum waiting time for a session when there are no requests. The timer resets when a new request arrives.

The key differences are:

  • sessionTTLInSeconds is a "hard limit". The session is forcibly destroyed when its TTL is reached, even if it is active.

  • sessionIdleTimeoutInSeconds is a "soft limit". The session's lifetime can be extended by activity, but it cannot exceed the TTL.

Procedure

Core flow overview

  1. Create a function and enable the session affinity feature.

  2. Call the CreateSession API to create a session. To mount persistent storage for the session, add the nas_config parameter to the request.

  3. When you call InvokeFunction, include the sessionId to route the request to the session instance with the associated storage.

  4. As needed, call UpdateSession or DeleteSession to manage the session lifecycle.

image

Step 1: Enable session affinity

If you are creating or updating a function configuration, specify a Header Key, such as x-affinity-header-v1, to pass the SessionID. The following example describes how to update an existing function configuration:

  1. Log on to the Function Compute console, and then click Function Management > Function List.

  2. On the Function List page, click the name of the function that you want to configure to go to the function details page.

  3. On the Configuration page, find Advanced Configuration, and click image.

  4. Turn on the Session Affinity switch, select HeaderField Affinity, and configure the Header Name, such as x-affinity-header-v1.

    Note

    The header name cannot start with the x-fc- prefix. It must start with a letter. Subsequent characters can be digits, hyphens (-), underscores (_), or letters. The name must be 5 to 40 characters long.

  5. Click Deploy to complete the configuration update.

Step 2: Create a session resource

This topic uses the Python SDK as an example to show you how to create a session by calling the CreateSession - Create a session resource API.

  1. Install SDK dependencies.

    macOS / Linux

    # Use pip3 to install
    pip3 install alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util
    
    # If you encounter permission issues, use the --user parameter
    pip3 install --user alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util
    
    # For macOS Homebrew Python environments, use --break-system-packages
    pip3 install --break-system-packages alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util

    Windows

    # Use pip to install
    pip install alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util
    
    # Or specify Python 3
    py -3 -m pip install alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util
  2. Write the core code to create a session.

    Create a Python code file (for example, createSession.py). Copy the following code into the file and replace the core parameters.

    Core methods and parameters:

    • config.endpoint:

      • <Alibaba Cloud account ID>: Replace this with your Alibaba Cloud account ID.

      • <Endpoint>: For more information, see Function Compute 3.0 service area list. The format is fcv3.[region_id].aliyuns.com.

    • CreateSessionInput:

      • session_ttl_in_seconds: The total TTL of the session, in seconds.

      • session_idle_timeout_in_seconds: The light hibernation (formerly idle) timeout of the session, in seconds.

    • client.create_session_with_options: Replace <Your function name> with the name of the function for which you want to create the session.

    # -*- coding: utf-8 -*-
    from alibabacloud_fc20230330.client import Client as FC20230330Client
    from alibabacloud_credentials.client import Client as CredentialClient
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_fc20230330 import models as fc20230330_models
    from alibabacloud_tea_util import models as util_models
    
    # 1. Create an account client.
    credential = CredentialClient()
    config = open_api_models.Config(credential=credential)
    config.endpoint = f'<Alibaba Cloud account ID>.<Endpoint>'
    client = FC20230330Client(config)
    
    # 2. Construct a CreateSession request.
    create_session_input = fc20230330_models.CreateSessionInput(
        session_ttlin_seconds=3600,
        session_idle_timeout_in_seconds=600
    )
    create_session_request = fc20230330_models.CreateSessionRequest(
        body=create_session_input
    )
    
    # 3. Send the request.
    runtime = util_models.RuntimeOptions()
    response = client.create_session_with_options('<Your function name>', create_session_request, {}, runtime)
    
    # 4. Get the sessionId from the response.
    print(response.body.to_map())
    session_id = response.body.session_id
    print(f"Session created successfully. Session ID: {session_id}")
    

Step 3: (Optional) Configure dynamic storage

  1. Configure the function: To configure dynamic storage for a session, configure the function as follows:

    1. Instance Fencing: Go to the Configuration tab, navigate to Advanced Configuration > Instance Fencing, and select Session Fencing.

    2. Allow VPC Access:

      • Enable Allow VPC Access on the Configuration tab under Advanced Configuration > Network.

      • Set Configuration Method to Custom Configuration.

      • For VPC, select the VPC where the mount target is located.

  2. Add the nas_config configuration: In the code from Step 2: Create a session resource, add the nas_config object using the following code. This object specifies the mount information and user identity.

    Core methods and parameters:

    Important

    You can configure dynamic NAS mounting for a session and NAS mounting for the function in the Configuration > Advanced Configuration > Storage settings at the same time. Note:

    • The User ID/Group ID defined in the following NASConfig must match the user (User ID) and user group (Group ID) used in the function mount configuration.

    • The same mount path (mount_dir) cannot be used for both dynamic session mounting and function mounting.

    • NASConfig: Configures the NAS file system and user identity. For example, you can assign an independent UID/GID to Tenant A.

      • NASMountConfig: The NAS mount configuration.

        • mount_dir: The mount path within the instance, such as /home/test.

        • server_addr: The address of the NAS file system and the tenant-specific subdirectory.

      • user_id: Specifies an independent POSIX User ID for this session.

      • group_id: Specifies an independent POSIX Group ID for this session.

# -*- coding: utf-8 -*-
from alibabacloud_fc20230330.client import Client as FC20230330Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_fc20230330 import models as fc20230330_models
from alibabacloud_tea_util import models as util_models

# 1. Create an account client.
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = f'<Alibaba Cloud account ID>.<Endpoint>'
client = FC20230330Client(config)

# 2. Prepare the NAS mount configuration.
nas_mount_config = fc20230330_models.NASMountConfig(
    mount_dir='/mnt/data',  # The mount path within the instance
    server_addr='<YOUR-NAS-SERVER-ADDR>:/<tenant-a-path>'  # The address of the NAS file system and the tenant-specific subdirectory
)

# 3. Configure the NAS file system and user identity. For example, assign an independent UID/GID to Tenant A.
nas_config = fc20230330_models.NASConfig(
    mount_points=[nas_mount_config],
    user_id=1001,  # Specify an independent POSIX User ID for this session.
    group_id=1001  # Specify an independent POSIX Group ID for this session.
)

# 4. Construct a CreateSession request.
create_session_input = fc20230330_models.CreateSessionInput(
    nas_config=nas_config,
    session_ttlin_seconds=3600,
    session_idle_timeout_in_seconds=600
)
create_session_request = fc20230330_models.CreateSessionRequest(
    body=create_session_input
)

# 5. Send the request.
runtime = util_models.RuntimeOptions()
response = client.create_session_with_options('<Your function name>', create_session_request, {}, runtime)

# 6. Get the sessionId from the response.
print(response.body.to_map())
session_id = response.body.session_id
print(f"Session created successfully. Session ID: {session_id}")

Step 4: Run the code to create a session

  1. Run the following commands to execute the code:

    export ALIBABA_CLOUD_ACCESS_KEY_ID=LTAI****************
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<yourAccessKeySecret>
    python3 creatSession.py

    Parameters:

    • ALIBABA_CLOUD_ACCESS_KEY_ID: Specifies the AccessKey ID of your Alibaba Cloud account or RAM user.

    • ALIBABA_CLOUD_ACCESS_KEY_SECRET: Specifies the AccessKey secret of your Alibaba Cloud account or RAM user.

  2. View the result.

    • Console output:

      {
        'containerId': 'c-********-********-************', 
        'createdTime': '2025-10-30T06:38:10Z', 
        'functionName': '****', 
        'lastModifiedTime': '2025-10-30T06:38:10Z', 
        'nasConfig': 
          {
            'groupId': 0, 
            'mountPoints': [
              {
                'enableTLS': False, 
                'mountDir': '/home/test', 
                'serverAddr': '*-*.*.nas.aliyuncs.com:/test'
                 }
                   ], 
                   'userId': 0
                   }, 
         'qualifier': 'LATEST', 
         'sessionAffinityType': 'HEADER_FIELD', 
         'sessionId': '******************', 
         'sessionIdleTimeoutInSeconds': 600, 
         'sessionStatus': 'Active', 
         'sessionTTLInSeconds': 3600
         }
      Session created successfully. Session ID: ************

Step 5: Use a session to invoke a function

Call the InvokeFunction - Invoke a function API to invoke the function using a session.

Core code and description:

InvokeFunctionHeaders: Construct the request header to include the sessionId returned in the previous step. The value of the Header Key must match the value that you set in Step 1: Enable session affinity, such as x-affinity-header-v1, to enable session-bound routing.

# -*- coding: utf-8 -*-
from alibabacloud_fc20230330.client import Client as FC20230330Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_fc20230330 import models as fc20230330_models
from alibabacloud_tea_util import models as util_models


# 1. Create an account client.
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = f'<Alibaba Cloud account ID>.<Endpoint>'
client = FC20230330Client(config)

# 2. Construct the request header. The Header Key ("x-affinity-header-v1") must be the same as the session affinity key configured for the function.
headers = fc20230330_models.InvokeFunctionHeaders(
    common_headers={
        "x-affinity-header-v1": 'session_id'
    }
)

# 3. Construct the invocation request. You can pass a body as needed.
invoke_request = fc20230330_models.InvokeFunctionRequest(
    body='your_request_payload'.encode('utf-8')  # Example payload
)

runtime = util_models.RuntimeOptions()

try:
    # 4. Send the invocation request.
    invoke_response = client.invoke_function_with_options(
        'your_function_name',
        invoke_request,
        headers,
        runtime
    )
    # 5. Process the response.
    print(f"Status Code: {invoke_response.status_code}")
    print(f"Response Body: {invoke_response.body.decode('utf-8')}")
except Exception as error:
    print(error.message)

What to do next: Update and delete a session

  1. As needed, call UpdateSession - Update session configuration to extend the session validity period or perform other updates.

    Note

    After you pass `nas_config` in a `CreateSession` call, you cannot update the configuration using the `UpdateSession` API.

  2. Call GetSession - Get session configuration information to retrieve the latest configuration information for the current session and confirm the update.

  3. After the task is complete, call DeleteSession - Delete a session resource to release the session resources.

Production environment recommendations

  • UID/GID planning: To ensure isolation, assign a unique POSIX UID to each tenant.

  • Directory Quotas: To prevent a single tenant from exhausting the shared storage space, configure directory quotas for the root directory of each tenant on the NAS side.

  • Data garbage collection (GC): Because the <a baseurl="t3144757_v2_0_0.xdita" data-node="6117158" data-root="85749" data-tag="xref" href="t3144017.xdita#" id="3a76f76305rbs">DeleteSession - Delete session resources</a> operation does not automatically delete file data on NAS, you must set up an asynchronous garbage collection (GC) mechanism to periodically scan and clean up orphaned directories to reclaim storage space.

Billing

  • Billing starts after the CreateSession - Create a session resource operation is successful. You are charged based on the runtime of the instance.

  • You are charged for a session even if it is idle, as long as it has not expired or been deleted.

  • After you call the DeleteSession - Delete a session resource API, billing is handled in one of the following two ways:

    • In non-fencing mode, `DeleteSession` does not terminate ongoing calls. You are charged for the instance resources associated with the session until the execution is complete.

    • In fencing mode, `DeleteSession` terminates running requests, destroys the associated instance resources, and stops billing.

During an active session, if there are requests, you are charged based on the unit price for active elastic instances. If there are no requests, you are charged based on the unit price for elastic instances in light hibernation (formerly idle).

More examples

This topic provides an example that uses the Go SDK. For more examples, see OpenAPI Explorer.

package main

import (
	"fmt"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	fc20230330 "github.com/alibabacloud-go/fc-20230330/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
	config := &openapi.Config{
		AccessKeyId:     tea.String("xxx"), // Configure the AccessKey ID.
		AccessKeySecret: tea.String("xxx"), // Configure the AccessKey secret.
		Protocol:        tea.String("http"),
		Endpoint:        tea.String("xxx"), // Configure the endpoint.
	}
	fcClient, err := fc20230330.NewClient(config)
	if err != nil {
		panic(err)
	}

	funcName := "test-session-function1"
	qualifier := "LATEST"
	sessionID, err := createSession(fcClient, funcName, qualifier)
	if err != nil {
		panic(err)
	}

	err = invokeFunctionWithSession(fcClient, funcName, qualifier, sessionID)
	if err != nil {
		panic(err)
	}

	err = updateSession(fcClient, funcName, sessionID, qualifier)
	if err != nil {
		panic(err)
	}

	err = getSession(fcClient, funcName, sessionID, qualifier)
	if err != nil {
		panic(err)
	}

	err = deleteSession(fcClient, funcName, sessionID, qualifier)
	if err != nil {
		panic(err)
	}
	return
}

// Create a session resource.
func createSession(fcClient *fc20230330.Client, functionName string, qualifier string) (string, error) {
	body := fc20230330.CreateSessionInput{
		SessionTTLInSeconds:         tea.Int64(21500), // The time can be customized.
		SessionIdleTimeoutInSeconds: tea.Int64(2000),  // The time can be customized.
	}
	req := fc20230330.CreateSessionRequest{
		Body:      &body,
		Qualifier: tea.String(qualifier),
	}

	resp, err := fcClient.CreateSession(&functionName, &req)
	if err != nil {
		return "", err
	}
	fmt.Printf("create session success %+v \n", resp.Body.String())
	return *resp.Body.SessionId, nil
}

// Request a session.
func invokeFunctionWithSession(fcClient *fc20230330.Client, functionName string, qualifier string, sessionId string) error {
	commonHeaders := map[string]*string{
		"x-affinity-header-v1": tea.String(sessionId), // The key must be the same as the Header Field specified when the function was created.
	}
	header := &fc20230330.InvokeFunctionHeaders{
		CommonHeaders: commonHeaders,
	}
	invokeReq := &fc20230330.InvokeFunctionRequest{
		Qualifier: tea.String(qualifier),
	}
	_, err := fcClient.InvokeFunctionWithOptions(tea.String(functionName), invokeReq, header, &util.RuntimeOptions{})
	return err
}

// Update the session resource.
func updateSession(fcClient *fc20230330.Client, functionName string, sessionId string, qualifier string) error {
	body := fc20230330.UpdateSessionInput{
		SessionTTLInSeconds:         tea.Int64(21501), // The time can be updated.
		SessionIdleTimeoutInSeconds: tea.Int64(2001),  // The time can be updated.
	}

	req := fc20230330.UpdateSessionRequest{
		Body:      &body,
		Qualifier: tea.String(qualifier),
	}

	resp, err := fcClient.UpdateSession(&functionName, &sessionId, &req)
	if err != nil {
		return err
	}
	fmt.Printf("update session success %+v\n ", resp.Body.String())
	return nil
}

// Get the session resource.
func getSession(fcClient *fc20230330.Client, functionName string, sessionId string, qualifier string) error {
	req := &fc20230330.GetSessionRequest{}
	if qualifier != "" {
		req.Qualifier = tea.String(qualifier)
	}
	getSession, err := fcClient.GetSession(tea.String(functionName), tea.String(sessionId), req)
	if err != nil {
		return err
	}
	fmt.Printf("get session success %+v ", getSession.Body.String())
	return nil
}

// Delete the session resource.
func deleteSession(fcClient *fc20230330.Client, functionName string, sessionId string, qualifier string) error {
	req := fc20230330.DeleteSessionRequest{
		Qualifier: tea.String(qualifier),
	}
	resp, err := fcClient.DeleteSession(&functionName, &sessionId, &req)
	if err != nil {
		return err
	}
	fmt.Printf("delete session success %+v\n ", *resp.StatusCode)
	return nil
}

Error codes

API

Error code

Error message

Cause

Suggestion

Common error codes

400

function has no session affinity config

The function has no affinity type configured.

Set the function's affinity type to HeaderField or Cookie.

400

the sessionAffinity of function is invalid, only supports GENERATED_COOKIE and HEADER_FIELD

The function's session affinity type is not supported by the Session API.

Change the function's affinity type to HeaderField or Cookie.

400

session storage mounts are only supported for session exclusive function

Dynamic mounting is supported only for session fencing.

Set the function's fencing type to session fencing.

500

an internal error has occurred. Please retry

A server-side system error occurred.

Retry the operation.

CreateSession

400

sessionId {xxx} already exists

The session ID already exists. This error can occur if you provide a custom session ID that is already in the Active state.

Verify whether the session ID already exists. If you want to reuse it, first delete it using the DeleteSession API, and then create it again.

400

SessionID exceeds the maximum allowed length (max: 64, actual: 'xx')

The custom session ID is too long. The maximum length is 64 characters.

Shorten the custom session ID to 64 characters or less.

400

The provided sessionID is invalid (allowed:'^[a-zA-Z0-9_][a-zA-ZO-9_-]*$')

The custom session ID does not adhere to the specified format.

Ensure the SessionID adheres to the specified format.

GetSession/DeleteSession/UpdateSession

400

session %s does not exist, deleted by the user or expired and removed by the system

The session is invalid, has expired, or has been deleted. Information cannot be retrieved.

Confirm that the session ID is valid.