Ex: Try out TTL

Hands on Exercise

TTL Documentation

In this exercise you will see the TTL feature in action. Code here is using the local DynamoDB table but you may very well try it with a table on AWS cloud.

1. Setup a table in Local DynamoDB

  • Make sure that local DynamoDb is up
  • OR remove –endpoint-url and run against AWS
aws dynamodb create-table \
    --table-name TTLTest  \
    --attribute-definitions '[
       {
          "AttributeName": "PK",
          "AttributeType": "S"
       }
    ]' \
    --key-schema '[
        {
            "AttributeName": "PK",
            "KeyType": "HASH"
        }
    ]' \
    --billing-mode PAY_PER_REQUEST \
    --endpoint-url  http://localhost:8000

2. Update table for TTL

  • TTL attribute name is ttl
aws dynamodb update-time-to-live \
    --table-name TTLTest \
    --time-to-live-specification 'Enabled=true,AttributeName=ttl' \
    --endpoint-url  http://localhost:8000

3. Review the Python code

  1. Creates an item with ttl set to 10 seconds from current time
  2. Continuously checks if the item has expired or not
  3. Prints the time taken for expiry
import boto3
import time
from datetime import datetime

TABLE_NAME = "TTLTest"

# Time after which item will expire
EXPIRE_TTL = 10

# Code sleeps and checks existence of item
SLEEP_TIME = 5

# Connect to localhost
client = boto3.client("dynamodb", region_name="localhost", endpoint_url="http://localhost:8000", aws_access_key_id="access_key_id", aws_secret_access_key="secret_access_key")

ttl = int(time.time()) + EXPIRE_TTL

# Add an item 
PK = str(datetime.now()).replace(" ","-")
response = client.put_item(
    TableName=TABLE_NAME,
    Item={
        "PK": {"S": PK},
        "ttl": {"N": str(ttl)},
    },
)
print(f"Added item PK = {PK}")

# Continuously check for the item in table
start_time = int(time.time()) 
while True:
    print('.', end='', flush=True),
    response = client.get_item(
        TableName=TABLE_NAME,
        Key={
            "PK": {"S": PK},
        },
    )
    
    time.sleep(SLEEP_TIME)
    if 'Item' not in response.keys() :
        break

time_taken = int(time.time()) - start_time
print('Item expired in {} seconds'.format(time_taken))

4. Run the code

  • Use the command in project root folder
  • Review the Python code
  • Code does a PutItem with ttl=10 seconds and loops on GetItem till item expires
python ttl/put-and-wait-for-expiry.py

5. Cleanup the table

  • Delete table
aws dynamodb delete-table \
    --table-name TTLTest  \
    --endpoint-url http://localhost:8000