Expire data with Time-to-Live (TTL) in Momento Cache
This document provides an overview of Momento Cache’s time-to-live (TTL) functionality. TTL allows items to expire automatically from the cache after a specified number of seconds.
Momento Cache handles TTL expiry and does not consume any bandwidth for metering in your monthly transfer cost.
Expire items after a specified number of seconds
The TTL value is the number of seconds from when Momento Cache writes the item to storage until the item expires from the cache. For example, if you set an item’s TTL value to 900 seconds (15 minutes), the item will expire 15 minutes after insertion into the cache.
How to set TTL in Momento Cache
For more robust examples of the code below in multiple languages, please see "Developing applications with Momento SDKs"
There are three locations to set a TTL value:
-
When creating a CacheClient object in a Momento SDK, you must set a TTL value for the connection. Any future SET operation using that client object will use that TTL value, unless you override the value.
const MY_DEFAULT_TTL = 60; // This value is in seconds
const momento = await CacheClient.create(authToken, MY_DEFAULT_TTL); -
In a SET operation, you can set a TTL value just for this operation and it will override the TTL value set in the CacheClient object.
await momento.set(CACHE_NAME, 'key', 'my value', 40)
// The number 40 is the TTL value in seconds for this item to expire and overrides the connection object's value.Optionally, you can omit the TTL value from the SET operation entirely and the item is inserted into the cache using the TTL value from the cache client object.
await momento.set(CACHE_NAME, 'key', 'my value')
// If you omit the TTL value, this will use the connection object's value. -
If you’re using the CLI when you run the command
momento configure
, it writes a configuration file (~/.momento/config) and stores a value you specify for a default TTL in that file. If you write an item with the CLI from that same user and don’t specify a TTL in the SET operation, the CLI will use the value from that configuration file.
Unless you copy the configuration file with your application, that file and its contents are unique to the location where you ran the momento configure
command.