

# DynamoDB에서 TTL(Time To Live) 사용
<a name="time-to-live-ttl-how-to"></a>

**참고**  
TTL 기능이 제대로 작동하는지 디버깅 및 검증하는 데 도움이 되도록 항목 TTL에 제공된 값이 DynamoDB 진단 로그에 일반 텍스트로 로깅됩니다.

Amazon DynamoDB 콘솔, AWS Command Line Interface(AWS CLI)에서 TTL을 활성화하거나 지원되는 AWS SDK와 함께 [Amazon DynamoDB API 참조](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/)를 사용하여 TTL을 활성화할 수 있습니다. 모든 파티션에서 TTL을 활성화하는 데 약 1시간이 걸립니다.

## AWS 콘솔을 사용하여 DynamoDB TTL 활성화
<a name="time-to-live-ttl-how-to-enable-console"></a>

1. AWS Management Console에 로그인하고 [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)에서 DynamoDB 콘솔을 엽니다.

1. **테이블**을 선택한 후 수정하려는 테이블을 선택합니다.

1. **추가 설정** 탭의 **Time To Live(TTL)** 섹션에서 **켜기**를 선택하여 TTL을 활성화합니다.

1. 테이블에서 TTL을 활성화할 경우, DynamoDB에서는 항목이 만료될 수 있는지 여부를 결정할 때 서비스가 검색할 특정 속성 이름을 식별해야 합니다. 아래 표시된 TTL 속성 이름은 대소문자를 구분하며 읽기 및 쓰기 작업에 정의된 속성과 일치해야 합니다. 일치하지 않을 경우 만료된 항목이 삭제되지 않습니다. TTL 속성의 이름을 바꾸려면 TTL을 비활성화했다가 새 속성으로 다시 활성화해야 합니다. TTL은 비활성화된 후에도 약 30분 동안 삭제를 계속 처리합니다. 복원된 테이블에서 TTL을 재구성해야 합니다.  
![DynamoDB가 항목의 만료 여부를 결정하는 데 사용하는 대소문자 구분 TTL 속성 이름입니다.](http://docs.aws.amazon.com/ko_kr/amazondynamodb/latest/developerguide/images/EnableTTL-Settings.png)

1. (선택 사항) 만료 날짜 및 시간을 시뮬레이션하고 몇 가지 항목을 일치시켜 테스트를 수행할 수 있습니다. 그러면 항목의 샘플 목록이 제공되며 만료 시간과 함께 제공된 TTL 속성 이름을 포함하는 항목이 있는지 확인할 수 있습니다.

TTL이 활성화된 후에 DynamoDB 콘솔에서 항목을 볼 때 TTL 속성이 **TTL**로 표시되어 있습니다. 속성 위에 마우스 포인터를 놓으면 항목이 만료되는 날짜와 시간을 볼 수 있습니다.

## API를 사용하여 DynamoDB TTL 활성화
<a name="time-to-live-ttl-how-to-enable-api"></a>

------
#### [ Python ]

[UpdateTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/update_time_to_live.html) 작업을 사용하여 코드로 TTL을 활성화할 수 있습니다.

```
import boto3


def enable_ttl(table_name, ttl_attribute_name):
    """
    Enables TTL on DynamoDB table for a given attribute name
        on success, returns a status code of 200
        on error, throws an exception

    :param table_name: Name of the DynamoDB table
    :param ttl_attribute_name: The name of the TTL attribute being provided to the table.
    """
    try:
        dynamodb = boto3.client('dynamodb')

        # Enable TTL on an existing DynamoDB table
        response = dynamodb.update_time_to_live(
            TableName=table_name,
            TimeToLiveSpecification={
                'Enabled': True,
                'AttributeName': ttl_attribute_name
            }
        )

        # In the returned response, check for a successful status code.
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print("TTL has been enabled successfully.")
        else:
            print(f"Failed to enable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}")
    except Exception as ex:
        print("Couldn't enable TTL in table %s. Here's why: %s" % (table_name, ex))
        raise


# your values
enable_ttl('your-table-name', 'expirationDate')
```

테이블의 TTL 상태를 설명하는 [DescribeTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/describe_time_to_live.html) 작업을 사용하여 TTL이 활성화되었는지 확인할 수 있습니다. `TimeToLive` 상태는 `ENABLED` 또는 `DISABLED`입니다.

```
# create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# set the table name
table_name = 'YourTable'

# describe TTL
response = dynamodb.describe_time_to_live(TableName=table_name)
```

------
#### [ JavaScript ]

[UpdateTimeToLiveCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-dynamodb/Class/UpdateTimeToLiveCommand/) 작업을 사용하여 코드로 TTL을 활성화할 수 있습니다.

```
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

const enableTTL = async (tableName, ttlAttribute) => {

    const client = new DynamoDBClient({});

    const params = {
        TableName: tableName,
        TimeToLiveSpecification: {
            Enabled: true,
            AttributeName: ttlAttribute
        }
    };

    try {
        const response = await client.send(new UpdateTimeToLiveCommand(params));
        if (response.$metadata.httpStatusCode === 200) {
            console.log(`TTL enabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`);
        } else {
            console.log(`Failed to enable TTL for table ${tableName}, response object: ${response}`);
        }
        return response;
    } catch (e) {
        console.error(`Error enabling TTL: ${e}`);
        throw e;
    }
};

// call with your own values
enableTTL('ExampleTable', 'exampleTtlAttribute');
```

------

## AWS CLI를 사용하여 Time To Live 활성화
<a name="time-to-live-ttl-how-to-enable-cli-sdk"></a>

1. `TTLExample` 테이블에서 TTL을 활성화합니다.

   ```
   aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
   ```

1. `TTLExample` 테이블에서 TTL을 비활성화합니다.

   ```
   aws dynamodb describe-time-to-live --table-name TTLExample
   {
       "TimeToLiveDescription": {
           "AttributeName": "ttl",
           "TimeToLiveStatus": "ENABLED"
       }
   }
   ```

1. BASH 셸 및 AWS CLI를 사용하여 `TTLExample` 테이블에 유지 시간(TTL) 속성 설정을 갖는 항목을 추가합니다.

   ```
   EXP=`date -d '+5 days' +%s`
   aws dynamodb put-item --table-name "TTLExample" --item '{"id": {"N": "1"}, "ttl": {"N": "'$EXP'"}}'
   ```

이 예제에서는 현재 날짜부터 시작하여 여기에 5일을 추가하여 만료 시간을 생성합니다. 그런 다음 만료 시간을 epoch 시간 형식으로 변환하여 `TTLExample` 테이블에 항목을 추가합니다.

**참고**  
 유지 시간(TTL)에 만료 값을 설정하는 한 가지 방법은 초 수를 계산하여 만료 시간을 추가하는 것입니다. 예를 들어, 5일은 432,000초입니다. 하지만 날짜로 시작하여 환산하는 방법이 더 많이 사용됩니다.

다음 예제에서와 같이 현재 시간을 epoch 시간 형식으로 변환하는 방법은 간단합니다.
+ Linux 터미널: `date +%s`
+ Python: `import time; int(time.time())`
+ Java: `System.currentTimeMillis() / 1000L`
+ JavaScript: `Math.floor(Date.now() / 1000)`

## CloudFormation을 사용하여 DynamoDB TTL 활성화
<a name="time-to-live-ttl-how-to-enable-cf"></a>

```
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  TTLExampleTable:
    Type: AWS::DynamoDB::Table
    Description: "A DynamoDB table with TTL Specification enabled"
    Properties:
      AttributeDefinitions:
        - AttributeName: "Album"
          AttributeType: "S"
        - AttributeName: "Artist"
          AttributeType: "S"
      KeySchema:
        - AttributeName: "Album"
          KeyType: "HASH"
        - AttributeName: "Artist"
          KeyType: "RANGE"
      ProvisionedThroughput:
        ReadCapacityUnits: "5"
        WriteCapacityUnits: "5"
      TimeToLiveSpecification:
        AttributeName: "TTLExampleAttribute"
        Enabled: true
```

CloudFormation 템플릿 내에서 TTL을 사용하는 방법에 대한 추가 세부 정보는 [여기](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-timetolivespecification.html)에서 확인할 수 있습니다.