Session lifecycle management

更新时间:
复制 MD 格式

In stateful scenarios like AI inference, online gaming, and multi-tenant Software as a Service (SaaS), managing persistent state and ensuring data isolation are core challenges. Function Compute (FC) treats a session as a distinct resource, providing comprehensive lifecycle management APIs for instance pre-warming and fine-grained resource control. For multi-tenant scenarios, you can also dynamically mount dedicated persistent storage when you create a session to ensure strict data isolation at the file system level.

Use cases

Use case 1: AI sandbox for intelligent computing

  • Model and data preloading: Call theCreateSession API to create a session and pre-warm an instance. This allows you to load large model weights during initialization, significantly reducing the first-inference response time.

  • Secure data isolation and mounting: When you create a session, dynamically mount a dedicated NAS directory for each tenant and specify an independent POSIX user identity (UID/GID). 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: Use APIs to destroy idle sessions to release computing power or extend a session's time to live for high-priority tasks. This helps you balance cost and performance.

Use case 2: Online game services

  • Session state persistence: 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. Session-specific persistent storage reliably saves critical game archives.

  • Precise TTL management: Set independent light hibernation timeout and TTL policies for player sessions in various scenarios, such as matchmaking queues and battle rooms. This prevents "zombie sessions" from continuously consuming resources.

Features

Feature

Description

Create a session

  1. Creates an explicit session resource and pre-allocates a bound function instance. A session ID can be generated in one of two ways:

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

      1. Length: 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. If the client does not provide a custom ID, 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 by using the nas_config parameter during creation, and specify its user ID and group ID (UID/GID) in the file system.

  3. You can specify the light hibernation timeout SessionIdleTimeoutInSeconds and the session lifecycle parameter SessionTTLInSeconds. If these parameters are not specified, the default function configuration is used.

  4. This feature applies to the HeaderField and Cookie affinity types.

  5. You can still achieve affinity by including a session ID in an InvokeFunction call, even without calling CreateSession first.

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

    1. DisableSessionIDReuse is false (default): The session ID can be reused. After a session expires, a new request with the same session ID creates a new session. The lifecycle is recalculated, but the new session is not guaranteed to be bound to the original instance.

    2. DisableSessionIDReuse is true: The session ID is not reused. For three days after a session expires, any request with the same session ID is rejected with an error. After this period, such a request creates a new session.

    3. If a user explicitly deletes a session by calling the DeleteSession API, the non-reuse restriction is lifted.

Get session configuration

  1. Gets the details of a specified session, including the session ID, associated function, affinity type, lifecycle configuration, status, and instance information.

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

  3. Information cannot be retrieved for sessions that have expired or been explicitly deleted via DeleteSession.

Query a list of sessions

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

  1. Returns up to 100 records per request. The default is 20.

  2. If you do not pass a qualifier or if you set it to LATEST, the API returns sessions for all versions.

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

Update session configuration

Updates the light hibernation timeout SessionIdleTimeoutInSeconds and the session lifecycle parameter SessionTTLInSeconds for a session. The update takes effect immediately, and lastModifiedTime is automatically refreshed. You can use this feature to dynamically extend or shorten the session validity period.

Note: After you update the TTL, the timer continues from the session's creation time instead of restarting.

Delete a session

  1. Deletes a specified session and purges its related data. After deletion, the session can no longer be queried with GetSession or ListSessions.

  2. After a session is deleted, requests carrying the same session ID create new sessions.

  3. If a request is running when the session is deleted:

    • In a session fencing scenario, the related resources are immediately released, and the running request is terminated.

    • In non-fencing mode, the request continues to run until completion, ensuring a graceful exit.

How it works: Session state and lifecycle

image

Create a session

  • Active creation: Call the Create a session API. Upon successful creation, the session's status becomes Active.

  • Passive creation: A session is automatically created the first time you call a function using InvokeFunction with a custom session ID. After the call succeeds, the session status becomes Active.

Destroy a session

  • Passive destruction: If the session's TTL or light hibernation timeout is reached, the system automatically sets the session's status to Expired.

  • Active destruction: Call the Delete a session API. After the session is successfully deleted, its 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 perform a graceful exit. This includes the following cases:

      1. Resources are released.

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

      3. Resources are bound to and reused by a new session.

Note

State transitions are unidirectional and irreversible: ActiveExpired / Deleted. Transitions between Expired and Deleted are not possible.

TTL vs. idle timeout

In session management, the system typically uses two time-based parameters to control the validity period of a session:

Parameter

Description

sessionTTLInSeconds

The maximum time to live for a session, measured from its creation, regardless of activity.

sessionIdleTimeoutInSeconds

The maximum idle time for a session without any requests. The timer resets with each new request.

The key differences are:

  • sessionTTLInSeconds is a "hard limit": A session is destroyed when its TTL expires, even if it is active.

  • sessionIdleTimeoutInSeconds is a "soft limit": Activity extends a session's lifetime, but not beyond its TTL.

Procedure

Workflow overview

  1. Create a function and enable session affinity.

  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 calling InvokeFunction, include the sessionId to route the request to the instance bound to that session.

  4. As needed, 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 session affinity. For HeaderField affinity, you need to specify a header key, such as x-affinity-header-v1, to pass the session ID. The following example shows how to update an existing function configuration:

  1. Log on to the Function Compute console and click Function Management > Functions.

  2. On the Functions page, click the name of the function you want to configure to open its details page.

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

  4. Turn on the Session Affinity switch, select HeaderField affinity, and configure the Header Name, for example, 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 apply the configuration update.

Step 2: Create a session

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

  1. Install the SDK dependencies.

    macOS / Linux

    # Install by using pip3
    pip3 install alibabacloud_fc20230330 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util
    
    # If you encounter a permission issue, 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

    # Install by using pip
    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 file, such as createSession.py. Copy the following code into the file and replace the core parameters with your actual values.

    Core methods and parameters:

    • config.endpoint:

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

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

    • CreateSessionInput:

      • session_ttl_in_seconds: The total time-to-live of the session, in seconds.

      • session_idle_timeout_in_seconds: The light hibernation timeout of the session, in seconds.

    • client.create_session_with_options: Replace <Function_Name> with the name of the function for which you want to create a 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'<Account_ID>.<Endpoint>'
    client = FC20230330Client(config)
    
    # 2. Construct a CreateSession request.
    create_session_input = fc20230330_models.CreateSessionInput(
        session_ttl_in_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('<Function_Name>', create_session_request, {}, runtime)
    
    # 4. Get the session ID 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

Note

Before you configure dynamic mounting for session fencing, take note of the regional availability of different storage protocols:

  • OSS mounting: Available in the China (Shenzhen), China (Hong Kong), Singapore, and US West (Silicon Valley) regions.

  • NAS mounting: Available in all regions. To use this feature, contact the FC team to add your account to the whitelist.

  • PolarFS mounting: Currently available in the China (Hong Kong) and US West (Silicon Valley) regions. Before you use this feature, your account must be added to the whitelist by both the FC and PolarFS teams.

    Note: PolarFS is available in the US West (Silicon Valley), Beijing, Shanghai, China (Ulanqab), and China (Hong Kong) regions.

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

    1. Instance isolation: On the Configuration tab, navigate to Advanced Settings > Instance isolation, and select Session Isolation.

    2. Access to VPC:

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

      • Set Configuration Mode 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, add the nas_config object to specify the mount information and user identity by referring to the following code.

    Core methods and parameters:

    Important

    You can dynamically mount a NAS file system for a session and mount a NAS file system in the Configuration > Advanced Settings > Storage settings of the function at the same time. Note the following points:

    • The user ID/group ID defined in the NASConfig object below must be the same as the user ID and group ID used in the function's mount configuration.

    • The same mount path (mount_dir) cannot be shared between dynamic session mounting and the function's static mount configuration.

    • NASConfig: Configures the NAS file system and user identity. For example, assign a unique 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'<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 a unique 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_ttl_in_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('<Function_Name>', create_session_request, {}, runtime)

# 6. Get the session ID 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 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: Invoke a function with a session

Call the InvokeFunction API to invoke the function by using a session.

Core code example and description:

InvokeFunctionHeaders: Constructs the request header to include the sessionId returned in the previous step. The header key, such as x-affinity-header-v1, must match the Header Name that you configured in Step 1: Enable session affinity. This implements 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'<Account_ID>.<Endpoint>'
client = FC20230330Client(config)

# 2. Construct the request header. The Header Name ("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')  # An 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)

Next steps: Update and delete a session

  1. As needed, call 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 by using UpdateSession.

  2. Call Get session configuration to get the latest configuration of the current session and confirm the update.

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

Production recommendations

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

  • Directory quota: To prevent a single tenant from exhausting the shared storage space, we recommend configuring a directory quota for each tenant's root directory on the NAS volume.

  • Garbage collection (GC): The Delete a session operation does not automatically delete file data on the NAS file system. You must establish an asynchronous garbage collection (GC) mechanism to periodically scan for and clear orphaned directories to reclaim storage space.

Billing

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

  • A session incurs charges even while idle, as long as it has not expired or been deleted.

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

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

    • In fencing 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 elastic instances in light hibernation.

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

Session affinity is not enabled for the function.

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

400

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

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

Change the function's affinity type to a supported session affinity type.

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 provided custom session ID is already in use by an Active session.

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

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 follow the regular expression matching rule.

Use a valid session ID. It must start with a letter, digit, or underscore, and can be followed by letters, digits, underscores, or hyphens.

GetSession/DeleteSession/UpdateSession

400

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

The specified session does not exist. It may have expired or been deleted.

Confirm that the session ID is valid.