

# Expire data with Time to Live (TTL) for Amazon Keyspaces (for Apache Cassandra)
<a name="TTL"></a>

Amazon Keyspaces (for Apache Cassandra) Time to Live (TTL) helps you simplify your application logic and optimize the price of storage by expiring data from tables automatically. Data that you no longer need is automatically deleted from your table based on the Time to Live value that you set. 

This makes it easier to comply with data retention policies based on business, industry, or regulatory requirements that define how long data needs to be retained or specify when data must be deleted. 

For example, you can use TTL in an AdTech application to schedule when data for specific ads expires and is no longer visible to clients. You can also use TTL to retire older data automatically and save on your storage costs. 

You can set a default TTL value for the entire table, and overwrite that value for individual rows and columns. TTL operations don't impact your application's performance. Also, the number of rows and columns marked to expire with TTL doesn't affect your table's availability.

Amazon Keyspaces automatically filters out expired data so that expired data isn't returned in query results or available for use in data manipulation language (DML) statements. Amazon Keyspaces typically deletes expired data from storage within 10 days of the expiration date. 

In rare cases, Amazon Keyspaces may not be able to delete data within 10 days if there is sustained activity on the underlying storage partition to protect availability. In these cases, Amazon Keyspaces continues to attempt to delete the expired data once traffic on the partition decreases. 

After the data is permanently deleted from storage, you stop incurring storage fees. 

You can set, modify, or disable default TTL settings for new and existing tables by using the console, Cassandra Query Language (CQL), or the AWS CLI. 

On tables with default TTL configured, you can use CQL statements to override the default TTL settings of the table and apply custom TTL values to rows and columns. For more information, see [Use the `INSERT` statement to set custom Time to Live (TTL) values for new rows](TTL-how-to-insert-cql.md) and [Use the `UPDATE` statement to edit custom Time to Live (TTL) settings for rows and columns](TTL-how-to-update-cql.md).

TTL pricing is based on the size of the rows being deleted or updated by using Time to Live. TTL operations are metered in units of `TTL deletes`. One TTL delete is consumed per KB of data per row that is deleted or updated. 

For example, to update a row that stores 2.5 KB of data and to delete one or more columns within the row at the same time requires three TTL deletes. Or, to delete an entire row that contains 3.5 KB of data requires four TTL deletes. 

One TTL delete is consumed per KB of deleted data per row. For more information about pricing, see [Amazon Keyspaces (for Apache Cassandra) pricing](https://aws.amazon.com/keyspaces/pricing).

**Topics**
+ [Amazon Keyspaces Time to Live and integration with AWS services](#ttl-howitworks_integration)
+ [Create a new table with default Time to Live (TTL) settings](TTL-how-to-create-table.md)
+ [Update the default Time to Live (TTL) value of a table](TTL-how-to-update-default.md)
+ [Create table with custom Time to Live (TTL) settings enabled](TTL-how-to-enable-custom-new.md)
+ [Update table with custom Time to Live (TTL)](TTL-how-to-enable-custom-alter.md)
+ [Use the `INSERT` statement to set custom Time to Live (TTL) values for new rows](TTL-how-to-insert-cql.md)
+ [Use the `UPDATE` statement to edit custom Time to Live (TTL) settings for rows and columns](TTL-how-to-update-cql.md)

## Amazon Keyspaces Time to Live and integration with AWS services
<a name="ttl-howitworks_integration"></a>

The following TTL metric is available in Amazon CloudWatch to enable continuous monitoring.
+ `TTLDeletes` – The units consumed to delete or update data in a row by using Time to Live (TTL).

For more information about how to monitor CloudWatch metrics, see [Monitoring Amazon Keyspaces with Amazon CloudWatch](monitoring-cloudwatch.md).

When you use CloudFormation, you can turn on TTL when creating an Amazon Keyspaces table. For more information, see the [AWS CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cassandra-table.html). 

# Create a new table with default Time to Live (TTL) settings
<a name="TTL-how-to-create-table"></a>

In Amazon Keyspaces, you can set a default TTL value for all rows in a table when the table is created. 

The default TTL value for a table is zero, which means that data doesn't expire automatically. If the default TTL value for a table is greater than zero, an expiration timestamp is added to each row.

TTL values are set in seconds, and the maximum configurable value is 630,720,000 seconds, which is the equivalent of 20 years. 

After table creation, you can overwrite the table's default TTL setting for specific rows or columns with CQL DML statements. For more information, see [Use the `INSERT` statement to set custom Time to Live (TTL) values for new rows](TTL-how-to-insert-cql.md) and [Use the `UPDATE` statement to edit custom Time to Live (TTL) settings for rows and columns](TTL-how-to-update-cql.md).

When you enable TTL on a table, Amazon Keyspaces begins to store additional TTL-related metadata for each row. In addition, TTL uses expiration timestamps to track when rows or columns expire. The timestamps are stored as row metadata and contribute to the storage cost for the row. 

 After the TTL feature is enabled, you can't disable it for a table. Setting the table’s `default_time_to_live` to 0 disables default expiration times for new data, but it doesn't deactivate the TTL feature or revert the table back to the original Amazon Keyspaces storage metadata or write behavior. 

The following examples show how to create a new table with a default TTL value.

------
#### [ Console ]

**Create a new table with a Time to Live default value using the console.**

1. Sign in to the AWS Management Console, and open the Amazon Keyspaces console at [https://console.aws.amazon.com/keyspaces/home](https://console.aws.amazon.com/keyspaces/home).

1. In the navigation pane, choose **Tables**, and then choose **Create table**.

1. On the **Create table** page in the **Table details** section, select a keyspace and provide a name for the new table.

1. In the **Schema** section, create the schema for your table.

1. In the **Table settings** section, choose **Customize settings**.

1. Continue to **Time to Live (TTL)**.

   In this step, you select the default TTL settings for the table. 

   For the **Default TTL period**, enter the expiration time and choose the unit of time you entered, for example seconds, days, or years. Amazon Keyspaces will store the value in seconds.

1. Choose **Create table**. Your table is created with the specified default TTL value.

------
#### [ Cassandra Query Language (CQL) ]

**Create a new table with a default TTL value using CQL**

1. The following statement creates a new table with the default TTL value set to 3,024,000 seconds, which represents 35 days.

   ```
   CREATE TABLE my_table (
                   userid uuid,
                   time timeuuid,
                   subject text,
                   body text,
                   user inet,
                   PRIMARY KEY (userid, time)
                   ) WITH default_time_to_live = 3024000;
   ```

1. To confirm the TTL settings for the new table, use the `cqlsh` `DESCRIBE` statement as shown in the following example. The output shows the default TTL setting for the table as `default_time_to_live`.

   ```
   DESC TABLE my_table;
   ```

   ```
   CREATE TABLE my_keyspace.my_table (
       userid uuid,
       time timeuuid,
       body text,
       subject text,
       user inet,
       PRIMARY KEY (userid, time)
   ) WITH CLUSTERING ORDER BY (time ASC)
       AND bloom_filter_fp_chance = 0.01
       AND caching = {'class': 'com.amazonaws.cassandra.DefaultCaching'}
       AND comment = ''
       AND compaction = {'class': 'com.amazonaws.cassandra.DefaultCompaction'}
       AND compression = {'class': 'com.amazonaws.cassandra.DefaultCompression'}
       AND crc_check_chance = 1.0
       AND dclocal_read_repair_chance = 0.0
       AND default_time_to_live = 3024000
       AND gc_grace_seconds = 7776000
       AND max_index_interval = 2048
       AND memtable_flush_period_in_ms = 3600000
       AND min_index_interval = 128
       AND read_repair_chance = 0.0
       AND speculative_retry = '99PERCENTILE';
   ```

------
#### [ CLI ]

**Create a new table with a default TTL value using the AWS CLI**

1. You can use the following command to create a new table with the default TTL value set to one year.

   ```
   aws keyspaces create-table --keyspace-name 'myKeyspace' --table-name 'myTable' \
               --schema-definition 'allColumns=[{name=id,type=int},{name=name,type=text},{name=date,type=timestamp}],partitionKeys=[{name=id}]' \
               --default-time-to-live '31536000'
   ```

1. To confirm the TTL status of the table, you can use the following command.

   ```
   aws keyspaces get-table --keyspace-name 'myKeyspace' --table-name 'myTable'
   ```

   The output of the command looks like in the following example

   ```
   {
       "keyspaceName": "myKeyspace",
       "tableName": "myTable",
       "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/myKeyspace/table/myTable",
       "creationTimestamp": "2024-09-02T10:52:22.190000+00:00",
       "status": "ACTIVE",
       "schemaDefinition": {
           "allColumns": [
               {
                   "name": "id",
                   "type": "int"
               },
               {
                   "name": "date",
                   "type": "timestamp"
               },
               {
                   "name": "name",
                   "type": "text"
               }
           ],
           "partitionKeys": [
               {
                   "name": "id"
               }
           ],
           "clusteringKeys": [],
           "staticColumns": []
       },
       "capacitySpecification": {
           "throughputMode": "PAY_PER_REQUEST",
           "lastUpdateToPayPerRequestTimestamp": "2024-09-02T10:52:22.190000+00:00"
       },
       "encryptionSpecification": {
           "type": "AWS_OWNED_KMS_KEY"
       },
       "pointInTimeRecovery": {
           "status": "DISABLED"
       },
       "ttl": {
           "status": "ENABLED"
       },
       "defaultTimeToLive": 31536000,
       "comment": {
           "message": ""
       },
       "replicaSpecifications": []
   }
   ```

------

# Update the default Time to Live (TTL) value of a table
<a name="TTL-how-to-update-default"></a>

You can update an existing table with a new default TTL value. TTL values are set in seconds, and the maximum configurable value is 630,720,000 seconds, which is the equivalent of 20 years.

When you enable TTL on a table, Amazon Keyspaces begins to store additional TTL-related metadata for each row. In addition, TTL uses expiration timestamps to track when rows or columns expire. The timestamps are stored as row metadata and contribute to the storage cost for the row. 

After TTL has been enabled for a table, you can overwrite the table's default TTL setting for specific rows or columns with CQL DML statements. For more information, see [Use the `INSERT` statement to set custom Time to Live (TTL) values for new rows](TTL-how-to-insert-cql.md) and [Use the `UPDATE` statement to edit custom Time to Live (TTL) settings for rows and columns](TTL-how-to-update-cql.md).

 After the TTL feature is enabled, you can't disable it for a table. Setting the table’s `default_time_to_live` to 0 disables default expiration times for new data, but it doesn't deactivate the TTL feature or revert the table back to the original Amazon Keyspaces storage metadata or write behavior. 

Follow these steps to update default Time to Live settings for existing tables using the console, CQL, or the AWS CLI.

------
#### [ Console ]

**Update the default TTL value of a table using the console**

1. Sign in to the AWS Management Console, and open the Amazon Keyspaces console at [https://console.aws.amazon.com/keyspaces/home](https://console.aws.amazon.com/keyspaces/home).

1. Choose the table that you want to update, and then choose the **Additional settings** tab.

1. Continue to **Time to Live (TTL)** and choose **Edit**.

1. For the **Default TTL period**, enter the expiration time and choose the unit of time, for example seconds, days, or years. Amazon Keyspaces will store the value in seconds. This doesn't change the TTL value of existing rows. 

1. When the TTL settings are defined, choose **Save changes**.

------
#### [ Cassandra Query Language (CQL) ]

**Update the default TTL value of a table using CQL**

1. You can use `ALTER TABLE` to edit default Time to Live (TTL) settings of a table. To update the default TTL settings of the table to 2,592,000 seconds, which represents 30 days, you can use the following statement.

   ```
   ALTER TABLE my_table WITH default_time_to_live = 2592000;
   ```

1. To confirm the TTL settings for the updated table, use the `cqlsh` `DESCRIBE` statement as shown in the following example. The output shows the default TTL setting for the table as `default_time_to_live`.

   ```
   DESC TABLE my_table;
   ```

   The output of the statement should look similar to this example.

   ```
   CREATE TABLE my_keyspace.my_table (
       id int PRIMARY KEY,
       date timestamp,
       name text
   ) WITH bloom_filter_fp_chance = 0.01
       AND caching = {'class': 'com.amazonaws.cassandra.DefaultCaching'}
       AND comment = ''
       AND compaction = {'class': 'com.amazonaws.cassandra.DefaultCompaction'}
       AND compression = {'class': 'com.amazonaws.cassandra.DefaultCompression'}
       AND crc_check_chance = 1.0
       AND dclocal_read_repair_chance = 0.0
       AND default_time_to_live = 2592000
       AND gc_grace_seconds = 7776000
       AND max_index_interval = 2048
       AND memtable_flush_period_in_ms = 3600000
       AND min_index_interval = 128
       AND read_repair_chance = 0.0
       AND speculative_retry = '99PERCENTILE';
   ```

------
#### [ CLI ]

**Update the default TTL value of a table using the AWS CLI**

1. You can use `update-table` to edit the default TTL value a table. To update the default TTL settings of the table to 2,592,000 seconds, which represents 30 days, you can use the following statement.

   ```
   aws keyspaces update-table --keyspace-name 'myKeyspace' --table-name 'myTable' --default-time-to-live '2592000'
   ```

1. To confirm the updated default TTL value, you can use the following statement.

   ```
   aws keyspaces get-table --keyspace-name 'myKeyspace' --table-name 'myTable'
   ```

   The output of the statement should look like in the following example.

   ```
   {
       "keyspaceName": "myKeyspace",
       "tableName": "myTable",
       "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/myKeyspace/table/myTable",
       "creationTimestamp": "2024-09-02T10:52:22.190000+00:00",
       "status": "ACTIVE",
       "schemaDefinition": {
           "allColumns": [
               {
                   "name": "id",
                   "type": "int"
               },
               {
                   "name": "date",
                   "type": "timestamp"
               },
               {
                   "name": "name",
                   "type": "text"
               }
           ],
           "partitionKeys": [
               {
                   "name": "id"
               }
           ],
           "clusteringKeys": [],
           "staticColumns": []
       },
       "capacitySpecification": {
           "throughputMode": "PAY_PER_REQUEST",
           "lastUpdateToPayPerRequestTimestamp": "2024-09-02T10:52:22.190000+00:00"
       },
       "encryptionSpecification": {
           "type": "AWS_OWNED_KMS_KEY"
       },
       "pointInTimeRecovery": {
           "status": "DISABLED"
       },
       "ttl": {
           "status": "ENABLED"
       },
       "defaultTimeToLive": 2592000,
       "comment": {
           "message": ""
       },
       "replicaSpecifications": []
   }
   ```

------

# Create table with custom Time to Live (TTL) settings enabled
<a name="TTL-how-to-enable-custom-new"></a>

To create a new table with Time to Live custom settings that can be applied to rows and columns without enabling TTL default settings for the entire table, you can use the following commands.

**Note**  
If a table is created with `ttl` custom settings enabled, you can't disable the setting later.

------
#### [ Cassandra Query Language (CQL) ]

**Create a new table with custom TTL setting using CQL**
+ 

  ```
  CREATE TABLE my_keyspace.my_table (id int primary key) WITH CUSTOM_PROPERTIES={'ttl':{'status': 'enabled'}};
  ```

------
#### [ CLI ]

**Create a new table with custom TTL setting using the AWS CLI**

1. You can use the following command to create a new table with TTL enabled.

   ```
   aws keyspaces create-table --keyspace-name 'myKeyspace' --table-name 'myTable' \
                                   --schema-definition 'allColumns=[{name=id,type=int},{name=name,type=text}, {name=date,type=timestamp}],partitionKeys=[{name=id}]' \
                                   --ttl 'status=ENABLED'
   ```

1. To confirm that TTL is enabled for the table, you can use the following statement.

   ```
   aws keyspaces get-table --keyspace-name 'myKeyspace' --table-name 'myTable'
   ```

   The output of the statement should look like in the following example.

   ```
   {
       "keyspaceName": "myKeyspace",
       "tableName": "myTable",
       "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/myKeyspace/table/myTable",
       "creationTimestamp": "2024-09-02T10:52:22.190000+00:00",
       "status": "ACTIVE",
       "schemaDefinition": {
           "allColumns": [
            {
                   "name": "id",
                   "type": "int"
               },
               {
                   "name": "date",
                   "type": "timestamp"
               },
               {
                   "name": "name",
                   "type": "text"
               }
           ],
           "partitionKeys": [
               {
                   "name": "id"
               }
           ],
           "clusteringKeys": [],
           "staticColumns": []
       },
       "capacitySpecification": {
           "throughputMode": "PAY_PER_REQUEST",
           "lastUpdateToPayPerRequestTimestamp": "2024-09-02T11:18:55.796000+00:00"
       },
       "encryptionSpecification": {
           "type": "AWS_OWNED_KMS_KEY"
       },
       "pointInTimeRecovery": {
           "status": "DISABLED"
       },
       "ttl": {
           "status": "ENABLED"
       },
       "defaultTimeToLive": 0,
       "comment": {
           "message": ""
       },
       "replicaSpecifications": []
   }
   ```

------

# Update table with custom Time to Live (TTL)
<a name="TTL-how-to-enable-custom-alter"></a>

To enable Time to Live custom settings for a table so that TTL values can be applied to individual rows and columns without setting a TTL default value for the entire table, you can use the following commands.

**Note**  
After `ttl` is enabled, you can't disable it for the table.

------
#### [ Cassandra Query Language (CQL) ]

**Enable custom TTL settings for a table using CQL**
+ 

  ```
  ALTER TABLE my_table WITH CUSTOM_PROPERTIES={'ttl':{'status': 'enabled'}};
  ```

------
#### [ CLI ]

**Enable custom TTL settings for a table using the AWS CLI**

1. You can use the following command to update the custom TTL setting of a table.

   ```
   aws keyspaces update-table --keyspace-name 'myKeyspace' --table-name 'myTable' --ttl 'status=ENABLED'
   ```

1. To confirm that TTL is now enabled for the table, you can use the following statement.

   ```
   aws keyspaces get-table --keyspace-name 'myKeyspace' --table-name 'myTable'
   ```

   The output of the statement should look like in the following example.

   ```
   {
       "keyspaceName": "myKeyspace",
       "tableName": "myTable",
       "resourceArn": "arn:aws:cassandra:us-east-1:111122223333:/keyspace/myKeyspace/table/myTable",
       "creationTimestamp": "2024-09-02T11:32:27.349000+00:00",
       "status": "ACTIVE",
       "schemaDefinition": {
           "allColumns": [
               {
                   "name": "id",
                   "type": "int"
               },
               {
                   "name": "date",
                   "type": "timestamp"
               },
               {
                   "name": "name",
                   "type": "text"
               }
           ],
           "partitionKeys": [
               {
                   "name": "id"
               }
           ],
           "clusteringKeys": [],
           "staticColumns": []
       },
       "capacitySpecification": {
           "throughputMode": "PAY_PER_REQUEST",
           "lastUpdateToPayPerRequestTimestamp": "2024-09-02T11:32:27.349000+00:00"
       },
       "encryptionSpecification": {
           "type": "AWS_OWNED_KMS_KEY"
       },
       "pointInTimeRecovery": {
           "status": "DISABLED"
       },
       "ttl": {
           "status": "ENABLED"
       },
       "defaultTimeToLive": 0,
       "comment": {
           "message": ""
       },
       "replicaSpecifications": []
   }
   ```

------

# Use the `INSERT` statement to set custom Time to Live (TTL) values for new rows
<a name="TTL-how-to-insert-cql"></a>

**Note**  
Before you can set custom TTL values for rows using the `INSERT` statement, you must first enable custom TTL on the table. For more information, see [Update table with custom Time to Live (TTL)](TTL-how-to-enable-custom-alter.md).

To overwrite a table's default TTL value by setting expiration dates for individual rows, you can use the `INSERT` statement:
+ `INSERT` – Insert a new row of data with a TTL value set.

Setting TTL values for new rows using the `INSERT` statement takes precedence over the default TTL setting of the table. 

The following CQL statement inserts a row of data into the table and changes the default TTL setting to 259,200 seconds (which is equivalent to 3 days).

```
INSERT INTO my_table (userid, time, subject, body, user)
        VALUES (B79CB3BA-745E-5D9A-8903-4A02327A7E09, 96a29100-5e25-11ec-90d7-b5d91eceda0a, 'Message', 'Hello','205.212.123.123')
        USING TTL 259200;
```

To confirm the TTL settings for the inserted row, use the following statement.

```
SELECT TTL (subject) from my_table;
```

# Use the `UPDATE` statement to edit custom Time to Live (TTL) settings for rows and columns
<a name="TTL-how-to-update-cql"></a>

**Note**  
Before you can set custom TTL values for rows and columns, you must enable TTL on the table first. For more information, see [Update table with custom Time to Live (TTL)](TTL-how-to-enable-custom-alter.md).

You can use the `UPDATE` statement to overwrite a table's default TTL value by setting the expiration date for individual rows and columns:
+ Rows – You can update an existing row of data with a custom TTL value.
+ Columns – You can update a subset of columns within existing rows with a custom TTL value.

Setting TTL values for rows and columns takes precedence over the default TTL setting for the table. 

To change the TTL settings of the 'subject' column inserted earlier from 259,200 seconds (3 days) to 86,400 seconds (one day), use the following statement.

```
UPDATE my_table USING TTL 86400 set subject = 'Updated Message' WHERE userid = B79CB3BA-745E-5D9A-8903-4A02327A7E09 and time = 96a29100-5e25-11ec-90d7-b5d91eceda0a;
```

You can run a simple select query to see the updated record before the expiration time.

```
SELECT * from my_table;
```

The query shows the following output.

```
userid                               | time                                 | body  | subject         | user
--------------------------------------+--------------------------------------+-------+-----------------+-----------------
b79cb3ba-745e-5d9a-8903-4a02327a7e09  | 96a29100-5e25-11ec-90d7-b5d91eceda0a | Hello | Updated Message | 205.212.123.123
50554d6e-29bb-11e5-b345-feff819cdc9f  | cf03fb21-59b5-11ec-b371-dff626ab9620 | Hello |         Message | 205.212.123.123
```

To confirm that the expiration was successful, run the same query again after the configured expiration time.

```
SELECT * from my_table;
```

The query shows the following output after the 'subject' column has expired.

```
userid                               | time                                 | body  | subject | user
--------------------------------------+--------------------------------------+-------+---------+-----------------
b79cb3ba-745e-5d9a-8903-4a02327a7e09  | 96a29100-5e25-11ec-90d7-b5d91eceda0a | Hello |    null | 205.212.123.123
50554d6e-29bb-11e5-b345-feff819cdc9f  | cf03fb21-59b5-11ec-b371-dff626ab9620 | Hello | Message | 205.212.123.123
```