AWS ElastiCache - Add TTL


TTL is also known as Time to live. It is used to take advantage of both the lazy load strategy as well as write through strategy. These two strategies were discussed in the previous chapters. Write through ensures that data is always fresh but may fail with empty nodes and may populate the cache with superfluous data. By adding a time to live (TTL) value to each write, we are able to get the advantages of each strategy and largely avoid cluttering up the cache with superfluous data.

How TTL Works

Time to live (TTL) is an integer value that specifies the number of seconds until the key expires. When an application attempts to read an expired key, it is treated as though the key is not found, meaning that the database is queried for the key and the cache is updated. This does not guarantee that a value is not stale, but it keeps data from getting too stale and requires that values in the cache are occasionally refreshed from the database.

TTL Example

The below code gives an example of how TTL is implemented by using a function. It takes help of the set command used by Memcached.

Code for Write Through Strategy

save_customer(customer_id, values)
   customer_record = db.query(""UPDATE Customers WHERE id = {0}"", customer_id, values)
   cache.set(customer_id, customer_record, 300)

   return success

Code for Lazy Load Strategy

   customer_record = cache.get(customer_id)
   if (customer_record != null)
      if (customer_record.TTL < 300)
         return customer_record        // return the record and exit function
   // do this only if the record did not exist in the cache OR
   // the TTL was >= 300, i.e., the record in the cache had expired.
   customer_record = db.query(""SELECT * FROM Customers WHERE id = {0}"", customer_id)
   cache.set(customer_id, customer_record, 300)  // update the cache
   return customer_record