

# Amazon Bedrock AgentCore 수명 주기 설정 구성
<a name="runtime-lifecycle-settings"></a>

[CreateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateAgentRuntime.html)에 대한 `LifecycleConfiguration` 입력 파라미터를 사용하면 Amazon Bedrock AgentCore 런타임에서 런타임 세션 및 리소스의 수명 주기를 관리할 수 있습니다. 이 구성은 유휴 세션을 자동으로 정리하고 장기 실행 인스턴스가 리소스를 무기한 사용하지 못하도록 하여 리소스 사용률을 최적화하는 데 도움이 됩니다.

[UpdateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UpdateAgentRuntime.html) 작업을 사용하여 기존 AgentCore 런타임에 대한 수명 주기 설정을 구성할 수도 있습니다.

**Topics**
+ [구성 속성](#configuration-attributes)
+ [기본 동작](#default-behavior)
+ [수명 주기 구성을 사용하여 AgentCore 런타임 생성](#create-agent-runtime-with-lifecycle)
+ [AgentCore 런타임의 수명 주기 구성 업데이트](#update-lifecycle-configuration)
+ [AgentCore 런타임의 수명 주기 구성 가져오기](#update-lifecycle-configuration)
+ [검증 및 제약 조건](#validation-and-constraints)
+ [수명 주기 설정 및 런타임 세션](#lifecycle-and-session-relationship)
+ [모범 사례](#best-practices)

## 구성 속성
<a name="configuration-attributes"></a>


| 속성 | 유형 | 범위(초) | 필수 | 설명 | 
| --- | --- | --- | --- | --- | 
|  `idleRuntimeSessionTimeout`  | Integer | 60-28800 | 아니요 | 유휴 런타임 세션의 초 단위 제한 시간입니다. 세션이이 기간 동안 유휴 상태로 유지되면 종료가 트리거됩니다. 로깅 및 기타 프로세스 완료로 인해 종료는 최대 15초 동안 지속될 수 있습니다. 기본값: 900초(15분) | 
|  `maxLifetime`  | Integer | 60-28800 | 아니요 | 인스턴스의 최대 수명은 초입니다. 도달하면 인스턴스가 종료를 초기화합니다. 로깅 및 기타 프로세스 완료로 인해 종료는 최대 15초 동안 지속될 수 있습니다. 기본값: 28,800초(8시간). 새 인스턴스가 프로비저닝되면 세션 자체가이 이상으로 유지될 수 있습니다. | 

### 제약 조건
<a name="constraints"></a>
+  `idleRuntimeSessionTimeout`는 보다 작거나 같아야 합니다. `maxLifetime` 
+ 두 값 모두 초 단위로 측정됩니다.
+ 유효한 범위: 60\~28800초(최대 8시간)

## 기본 동작
<a name="default-behavior"></a>

`LifecycleConfiguration`이 제공되지 않거나 null 값을 포함하는 경우 플랫폼은 다음 로직을 적용합니다.


| 고객 입력 | idleRuntimeSessionTimeout | maxLifetime | 결과 | 
| --- | --- | --- | --- | 
|  **구성 없음**  | 900초 | 28800s | 기본값 사용: 900초 및 28800초 | 
|  **maxLifetime만 제공됨**  | 900초 | 고객 값 | maxLifetime이 ≤ 900s인 경우: maxLifetime이 > maxLifetime 900s인 경우: 유휴에는 900s를 사용하고 최대에는 고객 값을 사용합니다. | 
|  **idleTimeout만 제공됨**  | 고객 값 | 28800s | 유휴의 경우 고객 값을 사용하고 최대의 경우 28,800초를 사용합니다. | 
|  **두 값이 모두 제공됨**  | 고객 값 | 고객 값 | 고객 값을 있는 그대로 사용합니다. | 

### 기본값
<a name="default-values"></a>
+  `idleRuntimeSessionTimeout` : **900초**(15분)
+  `maxLifetime` : **28800초**(8시간)

## 수명 주기 구성을 사용하여 AgentCore 런타임 생성
<a name="create-agent-runtime-with-lifecycle"></a>

AgentCore 런타임을 생성할 때 수명 주기 구성을 지정할 수 있습니다.

```
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}")
```

## AgentCore 런타임의 수명 주기 구성 업데이트
<a name="update-lifecycle-configuration"></a>

기존 AgentCore 런타임의 수명 주기 구성을 업데이트할 수 있습니다.

```
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}")
```

## AgentCore 런타임의 수명 주기 구성 가져오기
<a name="update-lifecycle-configuration"></a>

기존 AgentCore 런타임에 대한 수명 주기 구성을 가져올 수 있습니다.

```
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)
```

## 검증 및 제약 조건
<a name="validation-and-constraints"></a>

수명 주기 구성에는 잘못된 구성을 방지하기 위한 검증 규칙 및 제약 조건이 포함됩니다.

### 일반적인 검증 오류
<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
```

### 검증 도우미 함수
<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")
```

## 수명 주기 설정 및 런타임 세션
<a name="lifecycle-and-session-relationship"></a>

정의한 수명 주기 구성 설정은 각 개별 런타임 세션에 적용됩니다. 특정 `runtimeSessionId`를 사용하여 에이전트를 호출하면 AgentCore 런타임은 해당 세션에 대한 전용 microVM을 프로비저닝합니다. 수명 주기 제한 시간( `idleRuntimeSessionTimeout` 및 `maxLifetime` )은 해당 특정 microVM 인스턴스의 수명 주기를 제어합니다.

```
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()
)
```

수명 주기 설정 및 세션에 대한 요점:
+  **세션별 격리**: 각는 독립적인 수명 주기 타이머가 있는 자체 microVM`runtimeSessionId`을 가져옵니다.
+  **유휴 타이머 재설정**:는 동일한 세션을 호출할 때마다 `idleRuntimeSessionTimeout` 재설정됩니다.
+  **최대 수명 적용**: `maxLifetime` 타이머는 microVM이 처음 생성될 때 시작되며 재설정할 수 없습니다.
+  **세션 종료** : 제한 시간에 도달하면 특정 세션의 microVM만 종료됩니다. 새 microVM이 프로비저닝된 상태에서 세션을 재개할 수 있습니다.

**작은 정보**  
각 microVM 세션은 microVM 생성 시 배포된 코드 자산(`agentRuntimeArtifact`)을 사용합니다. 에이전트 런타임을 새 코드로 업데이트하면 기존 세션은 종료되고 새 세션이 생성될 때까지 이전 버전을 계속 사용합니다.

## 모범 사례
<a name="best-practices"></a>

최적의 리소스 사용률 및 사용자 경험을 위해 수명 주기 설정을 구성할 때 다음 모범 사례를 따르세요.

### 권장 사항
<a name="recommendations"></a>
+  **기본값(900초 유휴, 최대 28,800초)으로 시작하고** 사용 패턴에 따라 조정
+  **세션 기간을 모니터링**하여 제한 시간 값 최적화
+  개발 환경에 더 **짧은 제한 시간을 사용하여** 비용 절감
+  **사용자 경험 고려** - 제한 시간이 너무 짧으면 활성 사용자가 중단될 수 있음
+  먼저 비프로덕션 환경에서 **구성 변경 사항 테스트** 
+  특정 사용 사례에 대한 **시간 초과 근거 문서화** 

### 일반적인 패턴
<a name="common-patterns"></a>


| 사용 사례 | 유휴 제한 시간 | 최대 수명 | 이론적 근거 | 
| --- | --- | --- | --- | 
|  **대화형 채팅**  | 10\~15분 | 2\~4시간 | 응답성과 리소스 사용량의 균형 | 
|  **배치 처리**  | 30 분 |  8 시간 | 장기 실행 작업 허용 | 
|  **개발**  | 5분 | 30 분 | 비용 최적화를 위한 빠른 정리 | 
|  **프로덕션 API**  | 15분 | 4시간 | 표준 프로덕션 워크로드 | 
|  **데모/테스트**  | 2 minutes | 15분 | 임시 사용에 대한 적극적인 정리 | 