Session isolation configuration

Updated at:

Function Compute's session isolation feature enhances support for complex AI applications. By providing both instance and storage isolation, it lets you build secure, stable, and efficient long-running applications within a serverless architecture, delivering on-demand usage, elastic scaling, and controlled security.

Overview

Function Compute's traditional "short-lived, stateless, and event-driven" design is ideal for short-running tasks. However, with the rise of large language models (LLMs) and generative AI, a growing number of enterprise applications require support for long-running execution, context persistence, and strong data isolation.

Function Compute introduces the session isolation feature to address these demands. Built on the core abstraction of a "session," this feature incorporates session instance isolation and session storage isolation.

  1. Session instance isolation: When enabled, the system allocates a dedicated function instance for each session and enforces a 1:1 binding. This instance serves only that session throughout its lifecycle and is automatically released upon termination.

  2. Session storage isolation: Dynamic mounting technology allocates a separate storage space for each session. It uses kernel-level POSIX user permissions to ensure clear data boundaries and prevent unauthorized access.

This feature is ideal for AI applications that require context persistence, strong data isolation, and long-running execution.

Core capabilities

Capability

Value

Dedicated instance

Each session is bound to a dedicated function instance, ensuring a consistent execution environment and preventing interference from shared resources.

Storage isolation

Each session gets a dynamically mounted, dedicated NAS directory that uses POSIX permissions to prevent unauthorized access.

Automatic release

The system automatically reclaims resources when a session ends, preventing idle instances from incurring costs.

Flexible lifecycle

Supports custom idle timeouts to balance performance and cost.

Scope

Type

Supported

Function type

Supports all function types except Task Functions.

Instance specifications

Supports only instances with 2 or more cores (such as 2c4g and 4c8g).

Runtime

If the function uses a Built-in Runtimes, MCP SSE Affinity cannot be selected for Session affinity.

Session storage isolation (dynamic mounting) feature

This feature is in private preview. To use it, please submit a ticket to request access.

Regions that support session instance isolation

Supported in all regions except for UK (London), Saudi Arabia (Riyadh), South Korea (Seoul), Malaysia (Kuala Lumpur), Thailand (Bangkok), Ulanqab Dedicated Cloud HDG, and Ulanqab General Industry Cloud.

Regions that support the session storage isolation feature

Not supported in compliance clouds, Japan (Tokyo), or China (Hohhot). Dynamic mounting of PolarFS is supported only in China (Beijing), China (Shanghai), China (Ulanqab), China (Hong Kong), and US (Silicon Valley).

Configure session instance isolation

Step 1: Configure session instance isolation

Either create a new function with session isolation enabled or configure this feature for an existing function. If you are configuring an existing function, ensure it meets the requirements for instance specifications, runtime, and function type as described in Scope.

Create a function

The following steps focus on the configurations related to session isolation. For information about other settings, see Create a function.

  1. Log on to the Function Compute console. At the top of the page, select a region, for example, China (Hangzhou).

    Before you proceed, check the Scope to ensure you select a region that supports this feature.
  2. Go to the Functions page, click Create Function, and select any Function Type except for Task Function, which does not support session isolation.

    This topic uses a web function as an example. The configuration process is the same for other supported function types. Task Functions are not supported.
  3. Configure the Basic Configurations and Sample Code as needed.

  4. In the Advanced Settings section, go to Isolation & Affinity:

    1. Isolate instance: Enable Instance Isolation and select Session isolation. When you enable session isolation, the system automatically enables session affinity. You must then configure the session affinity parameters.

      Note
      • After you enable session isolation, the number of concurrent sessions per instance is automatically set to 1 and cannot be changed.

      • When session isolation is enabled, session affinity is also automatically enabled:

        If you enable session isolation, all requests from the same client are routed to the same function instance, and that instance serves requests only from that client. Thus, session isolation inherently provides both session affinity and dedicated instance isolation.

    2. Session Affinity: For information about different affinity types, see Best practices for instance isolation. This topic uses Header field affinity as an example. Configure the Header Name, such as x-affinity-header-v1 . This header passes the client identifier used for affinity. Keep the other settings at their default values or configure them as needed.

      If the affinity identifier you want to pass is mySessionId, you must include the following header and value in your HTTP request: x-affinity-header-v1: mySessionId
      Note
      • If this function will later use session storage isolation, you must select either HeaderField or Cookie affinity.

      • If the function's Sample Code uses a Built-in Runtimes, you cannot select MCP SSE Affinity as the affinity type.

  5. Click Create.

Configure an existing function

  1. Log on to the Function Compute console. At the top of the page, select the region where your target function is located, for example, China (Hangzhou).

    Before you proceed, check the Scope to ensure the function's region supports this feature.
  2. Go to the Functions page, select the function for which you want to configure session isolation, and go to the function details page.

  3. On the Configuration tab, find Advanced Settings and click Modify on the right.

  4. Configure Isolation & Affinity:

    1. Isolate instance: Enable Instance Isolation and select Session isolation. When you enable session isolation, the system automatically enables session affinity. You must then configure the session affinity parameters.

      Note
      • After you enable session isolation, the number of concurrent sessions per instance is automatically set to 1 and cannot be changed.

      • When session isolation is enabled, session affinity is also automatically enabled:

        If you enable session isolation, all requests from the same client are routed to the same function instance, and that instance serves requests only from that client. Thus, session isolation inherently provides both session affinity and dedicated instance isolation.

    2. Session Affinity: For information about different affinity types, see Best practices for instance isolation. This topic uses Header field affinity as an example. Configure the Header Name, such as x-affinity-header-v1. This header passes the client identifier used for affinity. Keep the other settings at their default values or configure them as needed.

      If the affinity identifier you want to pass is mySessionId, you must include the following header and value in your HTTP request: x-affinity-header-v1: mySessionId
      Note
      • If this function will later use session storage isolation, you must select either HeaderField or Cookie affinity.

      • If the function's Sample Code uses a Built-in Runtimes, you cannot select MCP SSE Affinity as the affinity type.

  5. Click Deploy.

Step 2: Verify the result

  1. Using HeaderField affinity as an example, test the function by invoking it with different HTTP request header values.

    Session1:

    curl -H "x-affinity-header-v1:Session1" https://example.{regionID}.fcapp.run

    Session2:

    curl -H "x-affinity-header-v1:Session2" https://example.{regionID}.fcapp.run

    Request description:

    1. x-affinity-header-v1: The Header Name you configured for session affinity. Replace it with your actual configuration.

    2. Session1, Session2: The values corresponding to the request header. After session instance isolation is enabled, requests with the same value are dispatched to the same function instance, while requests with different values are dispatched to different function instances.

    3. https://example.{regionID}.fcapp.run: The function's trigger URL. To view this URL, go to the function details page and click the HTTP trigger.

  2. Verify the result:

    In the Function Compute invocation logs, multiple requests from the same session (Session1) reuse the same instance ID (such as c-687e0412-12f6c06f-df). Requests from a different session (Session2) are dispatched to a different instance (such as c-687e03d5-12f6c06f-b). This verifies that the session isolation configuration is in effect.

Use dynamic storage mounting

This topic uses Apsara File Storage NAS as an example. OSS and PolarFS are also supported, and the procedure is similar.

Prerequisites

  1. You have created an Apsara File Storage NAS file system and planned the directory structure for tenant data isolation.

  2. You have enabled the session instance isolation configuration by following the steps in Configure session instance isolation for a function.

  3. Check the function configuration to ensure that the function can access the same VPC where the Apsara File Storage NAS mount target is located:

    • Go to Configuration > Advanced Settings > Network and enable Access to VPC.

    • For Configuration Mode, select Custom Configuration.

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

Step 1: Create a session with NAS

  1. Install dependencies

    macOS / Linux

    # Install using pip3
    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

    # Install 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 code to create a session

    Create a Python file (for example, createSession.py) and copy the following code into it, replacing the key parameters. The example shows how to create a session for "Tenant A," mount its dedicated NAS directory (<YOUR-NAS-SERVER-ADDR>:/tenant-a-data) to the instance's /mnt/data path, and specify the user ID and group ID as UID=1001 and GID=1001.

    Key methods and parameters:

    Important

    Both dynamic session-based NAS mounting and static function-level NAS mounting can be configured in the Configuration > Advanced Settings > Storage tab. However, note the following:

    • The NASConfig below must define a User ID/Group ID that is consistent with the user (User ID) and user group (Group ID) used in the function's mount configuration.

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

    • config.endpoint:

    • CreateSessionInput:

      • session_ttlin_seconds: The session's total time to live (TTL) in seconds.

      • session_idle_timeout_in_seconds: The session's light-sleep (formerly idle) timeout, in seconds.

    • client.create_session_with_options: Replace <Function-Name> with the name of the function for which you are creating the session.

      • NASMountConfig: NAS mount configuration.

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

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

      • user_id: A unique POSIX user ID for this session.

      • group_id: A unique 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 = 'fcv3.<RegionID>.aliyuncs.com'
    client = FC20230330Client(config)
    
    # 2. Prepare the NAS mount configuration.
    nas_mount_config = fc20230330_models.NASMountConfig(
        mount_dir='/mnt/data',  # The mount path inside the instance.
        server_addr='<YOUR-NAS-SERVER-ADDR>:/<tenant-a-path>'  # The NAS file storage address and tenant-specific subdirectory.
    )
    
    # 3. Configure NAS and user identity (assign a unique UID/GID for Tenant A).
    nas_config = fc20230330_models.NASConfig(
        mount_points=[nas_mount_config],
        user_id=1001,  # A unique POSIX user ID for this session.
        group_id=1001  # A unique POSIX group ID for this session.
    )
    
    # 4. Construct the 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('<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}")
    
  3. Run 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.

  4. Sample response

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

Step 2: Use the mounted NAS

Now, when you invoke the function, include the SessionID obtained in the previous step. The function instance can then access the mounted /mnt/data directory. The following example shows how to modify the code for a web function and redeploy it:

import os
from flask import Flask, request, jsonify

# ... (app setup) ...

# Assume the NAS mount path is /mnt/data
NAS_MOUNT_PATH = '/mnt/data'
app = Flask(__name__)


@app.route('/<path:path>', methods=['GET', 'POST'])
def handle_nas_request(path):
    rid = request.headers.get('x-fc-request-id')
    print(f"FC Invoke Start RequestId: {rid}")

    # Construct the full path on the NAS
    # Note: Protect against path traversal attacks
    safe_path = os.path.normpath(os.path.join(NAS_MOUNT_PATH, path))
    if not safe_path.startswith(NAS_MOUNT_PATH):
        return "Path traversal attempt detected!", 400

    response_data = {}

    if request.method == 'POST':
        # Write to the file
        body = request.data.decode('utf-8')
        try:
            with open(safe_path, 'w') as f:
                f.write(body)
            response_data['message'] = f"Successfully wrote to {safe_path}"
            print(f"Wrote to {safe_path}")
        except Exception as e:
            return str(e), 500

    elif request.method == 'GET':
        # Read from the file
        try:
            if os.path.exists(safe_path) and os.path.isfile(safe_path):
                with open(safe_path, 'r') as f:
                    content = f.read()
                response_data['content'] = content
                print(f"Read from {safe_path}")
            else:
                return f"File not found: {safe_path}", 404
        except Exception as e:
            return str(e), 500

    print(f"FC Invoke End RequestId: {rid}")
    return jsonify(response_data)  # Use jsonify to return a JSON-formatted response

# ... (if __name__ == '__main__': block) ...

Step 3: Invoke the function and verify

Call the InvokeFunction API to invoke the function with the session.

Sample code and description:

  • InvokeFunctionHeaders: Construct the request headers, including the sessionId from the previous step.

  • The value of the Header Key must match the value you set when you configured session instance isolation (for example, x-affinity-header-v1) to ensure 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

session_id = '************'
function_name = 'my-session-nas'
# 1. Create an account client.
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'fcv3.<RegionID>.aliyuncs.com'
client = FC20230330Client(config)

# 2. Construct the request headers. The Header Key (x-affinity-header-v1) must match 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 if needed).
invoke_request = fc20230330_models.InvokeFunctionRequest(
    body='your_request_payload'.encode('utf-8')  # Sample payload
)

runtime = util_models.RuntimeOptions()

try:
    # 4. Send the invocation request.
    invoke_response = client.invoke_function_with_options(
        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)

Delete a session

When the task is complete, call the DeleteSession operation 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 shared storage space, configure directory quotas on the NAS side for each tenant's root directory.

  • Garbage collection (GC): The DeleteSession operation does not automatically delete file data on the NAS. You must implement a separate asynchronous GC process to periodically scan and clean up orphaned file directories to reclaim storage space.

How it works

1. 1:1 instance and session binding

When a new session is created, the scheduling system allocates a brand-new function instance from a resource pool and maps the session ID to the instance at the routing layer. The allocated instance has not processed any previous requests.

  • Behavior: During its lifecycle, this instance responds only to requests from the current session and does not accept any other requests.

  • Concurrency control: The system automatically sets the session concurrency per instance to 1, ensuring that all CPU, memory, and local disk resources are exclusively dedicated to that session.

This mechanism is ideal for applications that require long-term context persistence, such as LLM inference and code debugging workflows.

2. Session lifecycle management

A function instance's lifecycle mirrors the session's lifecycle. When a session ends, the system actively releases the corresponding instance, regardless of its type. A session can end through automatic release upon expiration or user-initiated release.

Automatic session release

Type

Description

Configurable

Idle timeout

The system gracefully terminates a session if it receives no requests within a specified period (default: 30 minutes).

Yes. To control the timeout, configure the Session idle timeout (in seconds). The value can be from 0 to 21600.

Time to live (TTL)

The session is automatically terminated after reaching its maximum lifetime (for example, 6 hours), regardless of activity.

Yes. You can specify sessionTTLInSeconds when you create a session. Unit: seconds.

User-initiated release

To delete a session, call the DeleteSession API:

DELETE /services/{serviceName}/functions/{functionName}/sessions/{sessionId}

Upon success:

  • The corresponding instance is immediately released.

  • The routing rule becomes invalid.

  • Subsequent requests using the old session ID will be rejected or will trigger a new session, depending on the session ID reuse configuration.

    Note

    Session ID reuse configuration: When you call the CreateSession API, use the disableSessionIdReuse parameter to control whether session IDs can be reused.

    • The default value is false, which allows reuse. After a session expires, you can send another request with the same SessionID, and the system will treat it as a new session and bind it to a new instance.

    • If set to true, the SessionID cannot be reused after the session expires.

3. Dynamic mounting for storage isolation

In traditional static NAS mounting, all instances share the same directory, creating security risks. Dynamic mounting resolves this issue and addresses session-persistent storage isolation in multi-tenant AI Agent Sandbox scenarios. When creating a session, you can dynamically specify the NAS subdirectory to mount for that session.

How it works

This feature deeply integrates the NAS mounting operation with the CreateSession API call. Taking HeaderField affinity as an example, the overall process is as follows:

image

Preparation phase: Create and configure a session with storage

This phase creates an isolated session environment bound to specific storage.

  1. Send a creation request: A backend management service calls the CreateSession API and specifies the NAS mount configuration and the user identity (UID/GID) for isolation in the request.

  2. Prepare the instance and mount: The Function Compute (FC) platform receives the request and prepares a function instance. This instance performs the NAS mount operation based on the configuration, mounting the dedicated directory to a specified path within the instance (for example, /mnt/data).

  3. Bind and return ID: After the mount is successful, the platform binds this instance to a newly generated, unique SessionID and returns this ID to the backend service.

Invocation phase: Use the configured session

During this phase, the system executes business logic by using the prepared session environment.

  1. Send an invocation request: When calling the InvokeFunction API, the backend management service passes the previously obtained SessionID through a specific HTTP header (such as x-affinity-header-v1).

  2. Route the request: The Function Compute platform's gateway and scheduler use this SessionID to route the request precisely to the specific, bound function instance.

  3. Execute the code: The function code runs in that instance. At this point, the code can directly read from and write to the mounted NAS directory because the environment and permissions have been pre-configured.

  4. Return the result: After the function executes, it returns the result to the original caller.

Key features

Feature

Description

Automatic directory creation

If the remote directory does not exist, the system automatically creates it. The directory's owner is set to the configured user_id and group_id, and its mode is set to 700(rwx------).

POSIX ID-based permission isolation

If necessary, in the function code, set the user_id and group_id of the function instance's main process to the IDs passed during dynamic mounting. This way, even if Tenant A's code attempts to read a file belonging to Tenant B (UID 10002), the Linux kernel and NAS server deny the operation (Permission Denied) because Tenant A's process has a UID of 10001.

Coexistence mechanism

Function-level static mounting and session-level dynamic mounting can coexist.

Related topics