All Products
Search
Document Center

:Session lifecycle management

Last Updated:Dec 18, 2025

In stateful scenarios such as AI inference, online games, and multi-tenant Software as a Service (SaaS), managing persistent state and multi-tenant data isolation are core challenges. Function Compute treats a session as an explicit resource and provides a comprehensive set of lifecycle management APIs. This enables instance prefetching and fine-grained resource control. For multitenancy scenarios, you can also dynamically mount dedicated persistent storage when you create a session. This ensures 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 create a session and prefetch an instance. This lets you load large model weights during the initialization phase, which significantly improves 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 specify an independent POSIX user identity (UID/GID) for each directory. This ensures that the datasets and model shards of different tenants are logically isolated on physically shared storage and 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, in 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 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.

Applicability

  • Region restrictions: This feature is not supported in the China (Hohhot) region. The dynamic NAS mounting feature is available only in the US (Silicon Valley) region. To request support for other regions, you can specify them when you submit a ticket.

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

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

    • Non-isolation 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.

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 bound storage.

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

image

Step 1: Enable session affinity

When you create a function or update a function configuration, enable the session affinity configuration. For HeaderField affinity, you must 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 choose Function Management > Function List.

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

  3. On the Configuration page, under Advanced Configuration, click image.

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

    Note

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

  5. Click Deploy to apply the configuration.

Step 2: Create a session resource

This section 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, such as createSession.py. Copy the following code into the file and replace the core parameters.

    Core methods and parameters:

    • config.endpoint:

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

      • <Endpoint>: For more information, see the Function Compute 3.0 Service Area List. The format is fcv3.[region_id].aliyuns.com.

    • CreateSessionInput:

      • session_ttlin_seconds: The total time to live (TTL) of the session, in seconds.

      • session_idle_timeout_in_seconds: The idle timeout period 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'<Your 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, you must configure the function as follows:

    1. Instance Fencing: Go to Configuration > Advanced Configuration > Instance Fencing and select Session Fencing.

    2. Allow VPC Access:

      • Enable Allow VPC Access in Configuration > Advanced Configuration > Network.

      • Set Configuration Method to Custom Configuration.

      • VPC: Select the VPC containing the mount target.

  2. Add the nas_config configuration: In the code from Step 2: Create a session resource, refer to the following code to add the nas_config object. 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, but note the following:

    • 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'<Your 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 createSession.py

    Parameters:

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

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

  2. View the results.

    • 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 that is returned from 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 implement 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'<Your 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, you can 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. You can 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, you can call DeleteSession - Delete session resources to release the session resources.

Production environment recommendations

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

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

  • Data garbage collection (GC): 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 a supporting asynchronous garbage collection (GC) mechanism to periodically scan and clean up orphaned file directories to reclaim storage space.

Billing

  • Billing starts after the CreateSession - Create a session resource operation is successful, and 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 session resource API, billing is handled in one of the following two ways:

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

    • In isolation mode, `DeleteSession` terminates running requests, destroys the bound 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 idle elastic instances.

More examples

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

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
}

References and feature descriptions

Feature

Description

CreateSession - Create a session resource

  1. Creates an explicit session resource. The system automatically generates a unique SessionID and pre-allocates and binds a function instance.

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

  3. Allows you to specify the `SessionIdleTimeoutInSeconds` and `SessionTTLInSeconds` parameters. If these parameters are not specified, the function's default configurations are used.

  4. Applies to HeaderField and Cookie affinity types. After this API is called, the session can be used for request routing.

  5. Custom SessionIDs are not supported. The SessionID must be generated by the server.

  6. If you do not call `CreateSession` in advance, you can include a custom SessionID in the first `InvokeFunction` call. The server treats this as a new session.

GetSession - Obtain session configuration information

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

  2. Allows you to precisely locate a session by `functionName` and `qualifier`.

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

ListSessions - List session information

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

  1. Returns up to 100 records at a time. The default is 20.

  2. If `qualifier` is not passed or is set to LATEST, sessions for all versions are returned.

  3. If the status is not passed, sessions in the Active and Expired statuses are returned by default.

UpdateSession - Update session configuration

Updates the `SessionIdleTimeoutInSeconds` and `SessionTTLInSeconds` parameters of a session. The update takes effect immediately, and `lastModifiedTime` is automatically refreshed. You can use this to dynamically extend or shorten the session's validity period.

DeleteSession - Deletes a session resource

  1. Deletes a specified session. The system purges the related data. After deletion, the session cannot be queried using `GetSession` or `ListSessions`.

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

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

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

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