TTL (Time to Live)
Overview
TTL (Time to Live) is an expiration set on data or network packets. Data past its TTL is treated as "expired" and is either deleted automatically or has to be fetched again. The concept of TTL is used in several layers of web technology, including DNS records, CDN caches, database records, and network packets.
TTL in DNS
The TTL of a DNS record specifies the number of seconds a resolver (a DNS cache server) caches that record. A record with a TTL of 3600 (1 hour) is cached by the resolver for 1 hour, and during that time the resolver doesn't query the authoritative DNS server.
Setting a TTL is a trade-off. A long TTL reduces the number of queries to DNS servers and speeds up name resolution. A short TTL makes changes take effect faster, but it increases the load on DNS servers. One practice is to set a TTL of around 1 to 24 hours for records that rarely change, and to temporarily shorten the TTL ahead of time when you plan to change a DNS record.
TTL in databases
In DynamoDB, if you enable TTL on a table and set a TTL attribute (a Unix timestamp) on a record, the record is automatically deleted after it expires. This suits managing data that's no longer needed after a certain period, such as session information, temporary tokens, and cached data.
In a web service like a question box, TTL can be used to manage how long login sessions last by setting a TTL on session IDs, or to prevent reuse by setting a short TTL on one-time tokens. Compared with cleaning up old records regularly through batch processing, automatic deletion by TTL takes less operational work and is less likely to miss records that should be deleted.
TTL in CDN caching
In a CDN (Content Delivery Network), TTL controls how long content fetched from the origin server is cached on edge servers. One possible approach is to set a long TTL for static assets (images, CSS, JavaScript) and either not cache dynamic content (API responses) or set an extremely short TTL for it.
When you set a long TTL for static assets, including a hash value in the file name (for example, main.a1b2c3.js) means the file automatically gets a new URL when its content is updated, which avoids the problem of an old cache being served. This technique is called cache busting, and in Next.js, the names of static files whose content never changes once served include a hash value.