- AWS ElastiCache Tutorial
- Home
- Overview
- Environment
- Interfaces
- Launching Cluster
- Viewing Cluster Details
- Cluster Endpoints
- Accessing Cluster
- Modifying Cluster
- Rebooting Cluster
- Adding Nodes
- Removing Nodes
- Scaling the Clusters
- Delete Cluster
- Redis Shards
- Parameter Group
- Listing Parameters
- Deleting Parameters
- Engine Parameters
- Backup and Restore
- Monitoring Node - Metrics
- Memcached & Redis
- Accessing Memcached Cluster
- Lazy Loading
- Write Through
- Add TTL
- Memcached VPC
- Creating Memcached Cluster
- Connecting to Cluster in VPC
- Delete Memcached Cluster
- IAM policies
- SNS Notifications
- Events
- Managing Tags
- Managing Costs
- AWS ElastiCache - Resources
- Quick Guide
- Useful Resources
- Discussion
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
get_customer(customer_id) 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
To Continue Learning Please Login
Login with Google