

# Use isolated sessions for agents
<a name="runtime-sessions"></a>

Amazon Bedrock AgentCore Runtime lets you isolate each user session and safely reuse context across multiple invocations in a user session. Session isolation is critical for AI agent workloads due to their unique operational characteristics:
+  **Complete execution environment separation** : Each user session in AgentCore Runtime receives its own dedicated microVM with isolated Compute, memory, and filesystem resources. This prevents one user’s agent from accessing another user’s data. After session completion, the entire microVM is terminated and memory is sanitized to remove all session data, eliminating cross-session contamination risks.
+  **Stateful reasoning processes** : Unlike stateless functions, AI agents maintain complex contextual state throughout their execution cycle, beyond simple message history for multi-turn conversations. AgentCore Runtime preserves this state securely within a session while ensuring complete isolation between different users, enabling personalized agent experiences without compromising data boundaries.
+  **Privileged tool operations** : AI agents perform privileged operations on users' behalf through integrated tools accessing various resources. AgentCore Runtime’s isolation model ensures these tool operations maintain proper security contexts and prevents credential sharing or permission escalation between different user sessions.
+  **Deterministic security for non-deterministic processes** : AI agent behavior can be non-deterministic due to the probabilistic nature of foundation models. AgentCore Runtime provides consistent, deterministic isolation boundaries regardless of agent execution patterns, delivering the predictable security properties required for enterprise deployments.

**Note**  
AgentCore does not enforce session-to-user mappings - your client backend should maintain the relationship between users and their session IDs. Additionally, your client backend should implement logic for user to session lifecycle management like maximum number of sessions per user.

**Topics**
+ [Understanding ephemeral context](#ephemeral-context)
+ [Extended conversations and multi-step workflows](#extended-conversations)
+ [AgentCore Runtime session lifecycle](#session-lifecycle)
+ [How to use sessions](#using-sessions)
+ [Session headers by protocol](#session-headers-by-protocol)
+ [Configure Amazon Bedrock AgentCore lifecycle settings](runtime-lifecycle-settings.md)
+ [Stop a running session](runtime-stop-session.md)

## Understanding ephemeral context
<a name="ephemeral-context"></a>

By default, the compute (microVM) associated with a session is ephemeral. Any data stored in memory or written to disk persists only for the compute lifecycle. This includes conversation history, user preferences, intermediate calculation results, and any other state information your agent maintains.

To persist filesystem data across session stop/resume cycles, configure **session storage** — a persistent directory that survives compute termination. See [Persist session state across stop/resume with a filesystem configuration (Preview)](runtime-persistent-filesystems.md).

For structured data that needs to be retained beyond the session lifetime (such as user conversation history, learned preferences, or important insights), use AgentCore Memory. This service provides purpose-built persistent storage designed specifically for agent workloads, with both short-term and long-term memory capabilities.

## Extended conversations and multi-step workflows
<a name="extended-conversations"></a>

Unlike traditional serverless functions that terminate after each request, AgentCore supports isolated sessions backed by ephemeral computes lasting up to 8 hours per lifecycle. This simplifies building multi-step agentic workflows as you can make multiple calls to the same environment, with each invocation building upon the context established by previous interactions. You can use both `InvokeAgentRuntime` for agent reasoning and `InvokeAgentRuntimeCommand` for deterministic shell command execution within the same session.

## AgentCore Runtime session lifecycle
<a name="session-lifecycle"></a>

 **Session creation** 

A new session is created on the first invoke with a unique runtimeSessionId provided by your application. AgentCore Runtime provisions a dedicated execution environment (microVM) for each session. Context is preserved between invocations to the same session. Both `InvokeAgentRuntime` and `InvokeAgentRuntimeCommand` operate on the same session — a command sees the same container, filesystem, and environment as the agent.

 **Session states** 

Session state is determined by the compute lifecycle and can be one of the following:
+  **Active** : Either processing a sync request, executing a command, or doing background tasks. Sync invocation and command execution activity is automatically tracked based on invocations to a runtime session. Background tasks are communicated by the agent code by responding with "HealthyBusy" status in pings.
+  **Idle** : When not processing any requests or background tasks. The session has completed processing but remains available for future invocations.
+  **Stopped** : The compute (microVM) provisioned for the session has been terminated and the session is stopped. This can occur due to inactivity (default 15 minutes), reaching max compute lifetime (default 8 hours), an explicit stop by invoking the [StopRuntimeSession](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_StopRuntimeSession.html) API, or if the compute is deemed unhealthy based on health checks. The session transitions back to Active on the next invocation and a new compute is provisioned, with the same lifecycle configuration (i.e. idleRuntimeSessionTimeout and maxLifetime that can be up to another 8 hours). The session itself remains valid until the AgentCore Runtime ARN is deleted. If the runtime is configured with session storage, filesystem data at the configured mount path persists across stop/resume cycles. See [Persist session state across stop/resume with a filesystem configuration (Preview)](runtime-persistent-filesystems.md).

## How to use sessions
<a name="using-sessions"></a>

To use sessions effectively:
+ Generate a unique session ID for each user or conversation with at least 33 characters
+ Pass the same session ID for all related invocations
+ Use different session IDs for different users or conversations

 **Example Using sessions for a conversation** 

```
# First message in a conversation

response1 = agent_core_client.InvokeAgentRuntime(
   agentRuntimeArn=agent_arn,
   runtimeSessionId="user-123456-conversation-12345678", # or uuid.uuid4()
   payload=json.dumps({"prompt": "Tell me about AWS"}).encode()
)

# Follow-up message in the same conversation reuses the runtimeSessionId.

response2 = agent_core_client.InvokeAgentRuntime(
   agentRuntimeArn=agent_arn,
   runtimeSessionId="user-123456-conversation-12345678", # or uuid.uuid4()
   payload=json.dumps({"prompt": "How does it compare to other cloud providers"}).encode()
)
```

By using the same runtimeSessionId for related invocations, you ensure that context is maintained across the conversation, allowing your agent to provide coherent responses that build on previous interactions.

## Session headers by protocol
<a name="session-headers-by-protocol"></a>

When invoking agents, include the appropriate session header to ensure requests are routed to the same microVM. The header depends on your agent’s configured protocol:


| Protocol | Session Header | 
| --- | --- | 
|  MCP  |   `Mcp-Session-Id`   | 
|  HTTP  |   `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id`   | 
|  A2A  |   `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id`   | 
|  AGUI  |   `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id`   | 

 **MicroVM stickiness** : Amazon Bedrock AgentCore uses the session header to route requests to the same microVM instance. Clients must capture the session ID returned in the response and include it in all subsequent requests to ensure session affinity. Without a consistent session ID, each request may be routed to a new microVM, which may result in additional latency due to cold starts.

For MCP protocol specifics including stateless and stateful modes, see [MCP session management and microVM stickiness](runtime-mcp-protocol-contract.md#mcp-session-management).

# Configure Amazon Bedrock AgentCore lifecycle settings
<a name="runtime-lifecycle-settings"></a>

The `LifecycleConfiguration` input parameter to [CreateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateAgentRuntime.html) lets you manage the lifecycle of runtime sessions and resources in Amazon Bedrock AgentCore Runtime. This configuration helps optimize resource utilization by automatically cleaning up idle sessions and preventing long-running instances from consuming resources indefinitely.

You can also configure lifecycle settings for an existing AgentCore Runtime with the [UpdateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UpdateAgentRuntime.html) operation.

**Topics**
+ [Configuration attributes](#configuration-attributes)
+ [Default behavior](#default-behavior)
+ [Create an AgentCore Runtime with lifecycle configuration](#create-agent-runtime-with-lifecycle)
+ [Update the lifecycle configuration for an AgentCore Runtime](#update-lifecycle-configuration)
+ [Get the lifecycle configuration for an AgentCore Runtime](#update-lifecycle-configuration)
+ [Validation and constraints](#validation-and-constraints)
+ [Lifecycle settings and runtime sessions](#lifecycle-and-session-relationship)
+ [Best practices](#best-practices)

## Configuration attributes
<a name="configuration-attributes"></a>


| Attribute | Type | Range (seconds) | Required | Description | 
| --- | --- | --- | --- | --- | 
|   `idleRuntimeSessionTimeout`   |  Integer  |  60-28800  |  No  |  Timeout in seconds for idle runtime sessions. When a session remains idle for this duration, it will trigger termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 900 seconds (15 minutes)  | 
|   `maxLifetime`   |  Integer  |  60-28800  |  No  |  Maximum lifetime for the instance in seconds. Once reached, instances will initialize termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 28800 seconds (8 hours). The session itself can persist beyond this with a new instance provisioned.  | 

### Constraints
<a name="constraints"></a>
+  `idleRuntimeSessionTimeout` must be less than or equal to `maxLifetime` 
+ Both values are measured in seconds
+ Valid range: 60 to 28800 seconds (up to 8 hours)

## Default behavior
<a name="default-behavior"></a>

When `LifecycleConfiguration` is not provided or contains null values, the platform applies the following logic:


| Customer Input | idleRuntimeSessionTimeout | maxLifetime | Result | 
| --- | --- | --- | --- | 
|   **No configuration**   |  900 sec  |  28800s  |  Uses defaults: 900s and 28800s  | 
|   **Only maxLifetime provided**   |  900 sec  |  Customer value  |  If maxLifetime ≤ 900s: uses maxLifetime for both If maxLifetime > 900s: uses 900s for idle, customer value for max  | 
|   **Only idleTimeout provided**   |  Customer value  |  28800s  |  Uses customer value for idle, 28800s for max  | 
|   **Both values provided**   |  Customer value  |  Customer value  |  Uses customer values as-is  | 

### Default values
<a name="default-values"></a>
+  `idleRuntimeSessionTimeout` : **900 seconds** (15 minutes)
+  `maxLifetime` : **28800 seconds** (8 hours)

## Create an AgentCore Runtime with lifecycle configuration
<a name="create-agent-runtime-with-lifecycle"></a>

You can specify a lifecycle configuration when you create an AgentCore Runtime.

```
import boto3

client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

try:
    response = client.create_agent_runtime(
        agentRuntimeName='my_agent_runtime',
        agentRuntimeArtifact={
            'containerConfiguration': {
                'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest'
            }
        },
        lifecycleConfiguration={
            'idleRuntimeSessionTimeout': 1800,  # 30 minutes, configurable
            'maxLifetime': 14400  # 4 hours
        },
        networkConfiguration={'networkMode': 'PUBLIC'},
        roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole'
    )

    print(f"Agent runtime created: {response['agentRuntimeArn']}")
except client.exceptions.ValidationException as e:
    print(f"Validation error: {e}")
except Exception as e:
    print(f"Error creating agent runtime: {e}")
```

## Update the lifecycle configuration for an AgentCore Runtime
<a name="update-lifecycle-configuration"></a>

You can update lifecycle configuration for an existing AgentCore Runtime.

```
import boto3

client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

agent_runtime_id = 'my_agent_runtime'

try:
    response = client.update_agent_runtime(
        agentRuntimeId=agent_runtime_id,
        agentRuntimeArtifact={
            'containerConfiguration': {
                'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest'
            }
        },
        networkConfiguration={'networkMode': 'PUBLIC'},
        roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole',
        lifecycleConfiguration={
            'idleRuntimeSessionTimeout': 600,   # 10 minutes
            'maxLifetime': 7200                 # 2 hours
        }
    )

    print("Lifecycle configuration updated successfully")
except client.exceptions.ValidationException as e:
    print(f"Validation error: {e}")
except client.exceptions.ResourceNotFoundException:
    print("Agent runtime not found")
except Exception as e:
    print(f"Error updating configuration: {e}")
```

## Get the lifecycle configuration for an AgentCore Runtime
<a name="update-lifecycle-configuration"></a>

You can get lifecycle configuration for an existing AgentCore Runtime.

```
import boto3

client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

def get_lifecycle_config():
    try:
        response = client.get_agent_runtime(agentRuntimeId="my_agent_runtime")

        lifecycle_config = response.get('lifecycleConfiguration', {})
        idle_timeout = lifecycle_config.get('idleRuntimeSessionTimeout', 900)
        max_lifetime = lifecycle_config.get('maxLifetime', 28800)

        print(f"Current configuration:")
        print(f"  Idle timeout: {idle_timeout}s ({idle_timeout//60} minutes)")
        print(f"  Max lifetime: {max_lifetime}s ({max_lifetime//3600} hours)")

        return lifecycle_config

    except Exception as e:
        print(f"Error retrieving configuration: {e}")
        return None

# Usage
config = get_lifecycle_config()
print(config)
```

## Validation and constraints
<a name="validation-and-constraints"></a>

The lifecycle configuration includes validation rules and constraints to prevent invalid configurations.

### Common validation errors
<a name="common-validation-errors"></a>

```
import boto3

client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')

try:
    client.create_agent_runtime(
        agentRuntimeName='invalid_config_agent',
        agentRuntimeArtifact={
            'containerConfiguration': {
                'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest'
            }
        },
        lifecycleConfiguration={
            'idleRuntimeSessionTimeout': 3600,  # 1 hour, configurable
            'maxLifetime': 1800                 # 30 minutes - INVALID!
        },
        networkConfiguration={'networkMode': 'PUBLIC'},
        roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole',
        )
except client.exceptions.ValidationException as e:
    print(f"Validation failed: {e}")
    # Output: idleRuntimeSessionTimeout must be less than or equal to maxLifetime
```

### Validation helper function
<a name="validation-helper-function"></a>

```
def validate_lifecycle_config(idle_timeout, max_lifetime):
    """Validate lifecycle configuration before API call"""
    errors = []

    # Check range constraints
    if not (1 <= idle_timeout <= 28800):
        errors.append(f"idleRuntimeSessionTimeout must be between 1 and 28800 seconds")

    if not (1 <= max_lifetime <= 28800):
        errors.append(f"maxLifetime must be between 1 and 28800 seconds")

    # Check relationship constraint
    if idle_timeout > max_lifetime:
        errors.append(f"idleRuntimeSessionTimeout ({idle_timeout}s) must be ≤ maxLifetime ({max_lifetime}s)")

    return errors

# Usage
errors = validate_lifecycle_config(3600, 1800)
if errors:
    for error in errors:
        print(f"Validation error: {error}")
else:
    print("Configuration is valid")
```

## Lifecycle settings and runtime sessions
<a name="lifecycle-and-session-relationship"></a>

The lifecycle configuration settings you define are applied to each individual runtime session. When you invoke an agent with a specific `runtimeSessionId` , AgentCore Runtime provisions a dedicated microVM for that session. The lifecycle timeouts ( `idleRuntimeSessionTimeout` and `maxLifetime` ) govern the lifecycle of that specific microVM instance.

```
import boto3
import json
import uuid

client = boto3.client('bedrock-agentcore', region_name='us-west-2')

# Each unique runtimeSessionId gets its own microVM with lifecycle settings applied
session_id_user_1 = str(uuid.uuid4())  # User 1's session
session_id_user_2 = str(uuid.uuid4())  # User 2's session

# First invocation for User 1 - creates new microVM with lifecycle timers
response1 = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    runtimeSessionId=session_id_user_1,  # Dedicated microVM for this session
    payload=json.dumps({"prompt": "Hello from User 1"}).encode()
)

# First invocation for User 2 - creates separate microVM with its own lifecycle timers
response2 = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    runtimeSessionId=session_id_user_2,  # Different microVM for this session
    payload=json.dumps({"prompt": "Hello from User 2"}).encode()
)

# Subsequent invocations to same session reuse the existing microVM
# The idle timeout resets with each invocation to the same session
response3 = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
    runtimeSessionId=session_id_user_1,  # Reuses User 1's existing microVM
    payload=json.dumps({"prompt": "Follow-up from User 1"}).encode()
)
```

Key points about lifecycle settings and sessions:
+  **Per-session isolation** : Each `runtimeSessionId` gets its own microVM with independent lifecycle timers
+  **Idle timer reset** : The `idleRuntimeSessionTimeout` resets each time you invoke the same session
+  **Maximum lifetime enforcement** : The `maxLifetime` timer starts when the microVM is first created and cannot be reset
+  **Session termination** : When either timeout is reached, only that specific session’s microVM is terminated. The session can be resumed with a new microVM provisioned.

**Tip**  
Each microVM session uses the code assets ( `agentRuntimeArtifact` ) that were deployed at the time of microVM creation. If you update your agent runtime with new code, existing sessions will continue using the previous version until they terminate and new sessions are created.

## Best practices
<a name="best-practices"></a>

Follow these best practices when configuring lifecycle settings for optimal resource utilization and user experience.

### Recommendations
<a name="recommendations"></a>
+  **Start with defaults** (900s idle, 28800s max) and adjust based on usage patterns
+  **Monitor session duration** to optimize timeout values
+  **Use shorter timeouts** for development environments to save costs
+  **Consider user experience** - too short timeouts may interrupt active users
+  **Test configuration changes** in non-production environments first
+  **Document timeout rationale** for your specific use case

### Common patterns
<a name="common-patterns"></a>


| Use Case | Idle Timeout | Max Lifetime | Rationale | 
| --- | --- | --- | --- | 
|   **Interactive Chat**   |  10-15 minutes  |  2-4 hours  |  Balance responsiveness with resource usage  | 
|   **Batch Processing**   |  30 minutes  |  8 hours  |  Allow for long-running operations  | 
|   **Development**   |  5 minutes  |  30 minutes  |  Quick cleanup for cost optimization  | 
|   **Production API**   |  15 minutes  |  4 hours  |  Standard production workload  | 
|   **Demo/Testing**   |  2 minutes  |  15 minutes  |  Aggressive cleanup for temporary usage  | 

# Stop a running session
<a name="runtime-stop-session"></a>

The `StopRuntimeSession` operation lets you immediately terminate active agent AgentCore Runtime sessions for proper resource cleanup and session lifecycle management.

When called, this operation instantly terminates the specified session and stops any ongoing streaming responses. This lets system resources be properly released and prevents accumulation of orphaned sessions.

Use `StopRuntimeSession` in these scenarios:
+  **User-initiated end** : When users explicitly conclude their conversation
+  **Application shutdown** : Proactive cleanup before application termination
+  **Error handling** : Force termination of unresponsive or stalled sessions
+  **Quota management** : Stay within session limits by closing unused sessions
+  **Timeout handling** : Clean up sessions that exceed expected duration

## Prerequisites
<a name="prerequisites"></a>

To use [StopRuntimeSession](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_StopRuntimeSession.html) , you need:
+  `bedrock-agentcore:StopRuntimeSession` IAM permission
+ A valid agent AgentCore Runtime ARN
+ The ID of an active session to terminate

**Example**  

1. You can use the AWS SDK to stop AgentCore Runtime sessions programmatically.

   Python example using boto3 to stop a AgentCore Runtime session.

   ```
   import boto3
   
   # Initialize the AgentCore client
   client = boto3.client('bedrock-agentcore', region_name='us-west-2')
   
   try:
       # Stop the runtime session
       response = client.stop_runtime_session(
           agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
           runtimeSessionId='your-session-id',
           qualifier='DEFAULT'  # Optional: endpoint name
       )
   
       print(f"Session terminated successfully")
       print(f"Request ID: {response['ResponseMetadata']['RequestId']}")
   
   except client.exceptions.ResourceNotFoundException:
       print("Session not found or already terminated")
   except client.exceptions.AccessDeniedException:
       print("Insufficient permissions to stop session")
   except Exception as e:
       print(f"Error stopping session: {str(e)}")
   ```

1. For applications using OAuth authentication, make direct HTTPS requests:

   ```
   import requests
   import urllib.parse
   
   def stop_session_with_oauth(agent_arn, session_id, bearer_token, qualifier="DEFAULT"):
       # URL encode the agent ARN
       encoded_arn = agent_arn.replace(':', '%3A').replace('/', '%2F')
   
       # Construct the endpoint URL
       url = f"https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/{encoded_arn}/stopruntimesession?qualifier={qualifier}"
   
       headers = {
           "Authorization": f"Bearer {bearer_token}",
           "Content-Type": "application/json",
           "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id": session_id
       }
   
       try:
           response = requests.post(url, headers=headers)
           response.raise_for_status()
   
           print(f"Session {session_id} terminated successfully")
           return response.json()
   
       except requests.exceptions.HTTPError as e:
           if e.response.status_code == 404:
               print("Session not found or already terminated")
           elif e.response.status_code == 403:
               print("Insufficient permissions or invalid token")
           else:
               print(f"HTTP error: {e.response.status_code}")
           raise
       except requests.exceptions.RequestException as e:
           print(f"Request failed: {str(e)}")
           raise
   
   # Usage
   stop_session_with_oauth(
       agent_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent",
       session_id="your-session-id",
       bearer_token="your-oauth-token"
   )
   ```

## Response format
<a name="response-format"></a>

Expected response format for successful `StopRuntimeSession` operations.

```
{
    "ResponseMetadata": {
        "RequestId": "12345678-1234-1234-1234-123456789012",
        "HTTPStatusCode": 200
    }
}
```

## Error handling
<a name="error-handling"></a>

Common error responses:


| Status Code | Error | Description | 
| --- | --- | --- | 
|  404  |  ResourceNotFoundException  |  Session not found or already terminated  | 
|  403  |  AccessDeniedException  |  Insufficient permissions  | 
|  400  |  ValidationException  |  Invalid parameters  | 
|  500  |  InternalServerException  |  Service error  | 

## Best practices
<a name="best-practices"></a>

### Session lifecycle management
<a name="session-lifecycle-management"></a>

```
class SessionManager:
    def __init__(self, client, agent_arn):
        self.client = client
        self.agent_arn = agent_arn
        self.active_sessions = set()

    def invoke_agent(self, session_id, payload):
        """Invoke agent and track session"""
        try:
            response = self.client.invoke_agent_runtime(
                agentRuntimeArn=self.agent_arn,
                runtimeSessionId=session_id,
                payload=payload
            )
            self.active_sessions.add(session_id)
            return response
        except Exception as e:
            print(f"Failed to invoke agent: {e}")
            raise

    def stop_session(self, session_id):
        """Stop session and remove from tracking"""
        try:
            self.client.stop_runtime_session(
                agentRuntimeArn=self.agent_arn,
                runtimeSessionId=session_id,
                qualifier=endpoint_name
            )
            self.active_sessions.discard(session_id)
            print(f"Session {session_id} stopped")
        except Exception as e:
            print(f"Failed to stop session {session_id}: {e}")

    def cleanup_all_sessions(self):
        """Stop all tracked sessions"""
        for session_id in list(self.active_sessions):
            self.stop_session(session_id)
```

### Recommendations
<a name="recommendations"></a>
+  **Always handle exceptions** when stopping sessions
+  **Track active sessions** in your application for cleanup
+  **Set timeouts** for stop requests to avoid hanging
+  **Log session terminations** for debugging and monitoring
+  **Use session managers** for complex applications with multiple sessions