TTL: What It Is, Cache Time to Live and How It Works

Author: IT Sectr Published: 2026-06-13 Reading time: 8 min

TTL (Time To Live) is a parameter that determines the maximum time during which data is considered valid. After the TTL expires, the record is marked as stale and must be deleted or updated. According to Mozilla Developer Network (2026), the TTL mechanism is the foundation of HTTP caching through the Cache-Control: max-age header and is used in all modern browsers and mobile applications to optimize network requests.

Key Takeaways

  • TTL (Time To Live) — the lifespan of a record, after which the data is considered outdated and requires updating
  • Balance — a short TTL provides up-to-date data but reduces caching efficiency; a long one improves performance but risks staleness
  • HTTP Caching — the Cache-Control: max-age header sets TTL in seconds for server responses
  • DNS Records — TTL determines how long a resolver caches a domain’s IP address (from 60 to 86400 seconds)
  • Mobile Apps — TTL is used to cache API responses, images, and session data

What Is TTL?

TTL (Time To Live) is a timestamp or interval after which data is considered invalid. In the context of caching, TTL determines how long a record can be stored in the cache before it needs to be re-fetched from the source. In network protocols, TTL limits the lifespan of a packet, preventing infinite routing.

The TTL value is always expressed in time units: milliseconds, seconds, minutes, or hours. After the set time expires, the record is either deleted from the cache or marked as stale. On the next request to a stale record, the system can either return the stale data with a subsequent update (stale-while-revalidate) or block the request until fresh data is obtained.

Choosing TTL is always a trade-off between data freshness and performance. A TTL that is too short (1–5 seconds) forces the application to make frequent network requests, negating the benefit of caching. A TTL that is too long (hours/days) increases the risk of showing outdated information to the user. The optimal value depends on the data type: exchange rates — seconds, weather — minutes, API version — hours.

TTL and Cache Invalidation

TTL is passive invalidation: data is automatically removed after a period of time. The alternative is active invalidation, where the data source notifies the cache about changes (for example, via WebSocket messages or push notifications). Passive invalidation via TTL is simpler to implement but does not guarantee instant freshness. Active invalidation is more complex but allows data to be kept up to date without the delays inherent in TTL.

How TTL Works

The TTL mechanism can be implemented in two ways: absolute expiration and relative expiration. With absolute expiration, the record stores the specific time when it becomes invalid. With relative expiration, the creation time of the record and the TTL as an interval are recorded, and the check is performed by calculating creationTime + TTL > currentTime.

On each request to the cache, the system checks the TTL of each record. If the TTL has expired, the data is deleted or marked as stale, and the request is forwarded to the source. To optimize TTL checking, scheduled cleanup (periodic deletion of all expired records) or lazy cleanup (deletion only when the record is accessed) can be used. Lazy cleanup is more memory-efficient because it does not require a background thread to scan the entire cache.

In distributed systems, TTL is also used for automatic conflict resolution. For example, if two servers simultaneously write different values for the same key, the record with a later TTL can be considered higher priority. Amazon DynamoDB uses TTL for automatic deletion of outdated records in tables — this is a built-in feature that does not require manual management.

Stale Read Strategies

To improve performance when TTL expires, stale read strategies are used. Stale-while-revalidate — immediately return stale data to the client and simultaneously launch a background update. Stale-if-error — return stale data if the source is temporarily unavailable. Cache-Aside (Lazy Loading) — on a cache miss, load the data from the source, save it in the cache with a new TTL, and only then return it to the client. Each strategy is chosen based on data consistency requirements.

TTL in Data Caching

In mobile applications, TTL is a key mechanism for cache management. Let’s look at the main scenarios where TTL determines application behavior and user experience.

Caching HTTP Responses

The HTTP protocol provides a built-in TTL mechanism through Cache-Control headers. The max-age directive sets TTL in seconds: Cache-Control: public, max-age=3600 means the response can be cached for 1 hour. Additional directives s-maxage (for shared caches, e.g., CDN) and stale-while-revalidate provide finer control. When TTL coincides with the expires header, max-age takes priority as the more modern HTTP/1.1 standard.

Data TypeRecommended TTLRationale
Weather10–30 minutesForecasts update infrequently
Exchange Rates15–60 secondsHigh volatility
News Feed2–5 minutesBalance between freshness and performance
User Profile5–30 minutesRarely changes during a session
Product List10–60 minutesPrices do not change every second
Static Resources1–24 hoursVersioned via URL or ETag

Caching Images

For images, TTL can reach several days since the content rarely changes. However, mobile applications often use a hybrid approach: a short TTL for previews (30 minutes — frame freshness) and a long TTL for full-size images (7 days). Images with the HTTP header Cache-Control: immutable should not be re-requested at all until the TTL expires — this is an optimization for static resources proposed in RFC 8246. Such images are cached at the OS level (URLCache, OkHttp Cache) without application involvement.

TTL in Network Protocols

In networks, TTL is used not for caching but to limit the lifespan of packets. Each IP packet contains a TTL field (8 bits), which is decreased by 1 by each router. When TTL reaches 0, the packet is discarded, and the sender receives an ICMP Time Exceeded message. This prevents infinite routing during network loops.

TTL in DNS

DNS records have a TTL that determines how long a resolver (e.g., ISP DNS cache) can store the record without querying the authoritative server. Typical values: 300 seconds (5 minutes) for records with frequent changes, 86400 seconds (24 hours) for stable domains. CDN services often set a low TTL (60–300 seconds) for fast traffic rerouting during failures, while static domains can have a TTL of up to 7 days. When migrating a server, it is recommended to first lower the TTL to 60 seconds (48 hours before migration) so that changes propagate quickly.

TTL in Sessions and Tokens

In mobile applications, TTL is used to manage sessions and access tokens. JWT tokens (JSON Web Tokens) contain an exp (expiration time) field, which is the absolute Unix expiration time. After expiration, a refresh token is used to obtain a new access token without re-authentication. The access token TTL is usually 1–24 hours, the refresh token TTL is 7–30 days. This is a balance between security (short TTL reduces the risk of leakage) and UX (long TTL reduces the frequency of re-logins).

TTL Selection Strategies

Choosing TTL is an engineering decision that depends on the data type, freshness SLA, and the cost of a re-request. Let’s consider the main strategies.

Fixed TTL

The simplest approach — all records have the same TTL. For example, cache all API responses for 5 minutes. Advantage: simplicity of implementation and predictable behavior. Disadvantage: does not account for different change frequencies of different data types. Fixed TTL is justified for homogeneous data where all records have the same “freshness” — for example, cryptocurrency rates on one exchange.

Adaptive TTL

TTL dynamically changes based on data behavior. For example, if a record is rarely updated on the server, TTL increases; if it is updated frequently — it decreases. The implementation can use HTTP response headers: the Age header (how many seconds the response has already been in the cache) and the Date header allow calculating the remaining lifetime. Adaptive TTL provides a better hit ratio but requires additional logic on the client.

Probabilistic TTL Expiration

Probabilistic Early Expiration (PEE) — a technique where TTL is chosen randomly within a given range. This prevents the “thundering herd” effect, where many requests expire simultaneously and all clients hit the source at the same time. PEE is especially useful for CDNs and high-load caches: instead of a single TTL of 300 seconds, a random value from 240 to 360 seconds is used, distributing the load on the source evenly.

TTL Code Examples

Let’s look at a cache implementation with TTL in Kotlin using absolute expiration. Each record stores its creation time, and when reading, it is checked whether the TTL has expired.

kotlin
class TtlCache<K, V>(
    private val defaultTtlMs: Long = 300000L
) {
    private data class Entry<V>(
        val value: V,
        val createdAt: Long = System.currentTimeMillis()
    )

    private val map = ConcurrentHashMap<K, Entry<V>>()

    fun get(key: K): V? {
        val entry = map[key] ?: return null
        if (isExpired(entry)) {
            map.remove(key)
            return null
        }
        return entry.value
    }

    fun put(key: K, value: V, ttlMs: Long = defaultTtlMs) {
        map[key] = Entry(value, createdAt = System.currentTimeMillis() + ttlMs)
    }

    private fun isExpired(entry: Entry<*>): Boolean {
        return System.currentTimeMillis() > entry.createdAt
    }

    fun cleanup() {
        map.entries.removeIf { isExpired(it.value) }
    }
}

The Entry class stores the value and creation time + TTL (absolute expiration). The get method checks expiration on each access (lazy cleanup) — expired records are only deleted when an attempt is made to access them. The cleanup method can be called periodically from a background thread to batch delete all outdated records. ConcurrentHashMap provides thread safety without locking the entire cache.

Example: TTL for Caching API Responses on iOS

In iOS, it is convenient to use URLCache with memoryCapacity and diskCapacity settings for caching with TTL. However, URLCache does not support individual TTL for different requests. Let’s consider a custom NSCache wrapper with TTL support.

swift
final class ApiResponseCache {
    private var cache = NSCache<NSString, CacheEntry>()

    func getResponse(for url: URL) -> Data? {
        guard let entry = cache.object(forKey: url.absoluteString as NSString)
            else { return nil }
        guard entry.expirationDate > Date() else {
            cache.removeObject(forKey: url.absoluteString as NSString)
            return nil
        }
        return entry.data
    }

    func storeResponse(data: Data, for url: URL, ttl: TimeInterval) {
        let entry = CacheEntry(data: data, expirationDate: Date().addingTimeInterval(ttl))
        cache.setObject(entry, forKey: url.absoluteString as NSString)
    }
}

final class CacheEntry: NSObject {
    let data: Data
    let expirationDate: Date
}

In this implementation, NSCache is used as a thread-safe storage. CacheEntry contains Data and expirationDate. When get is called, it checks whether the time has expired; if so, the record is deleted and nil is returned. TTL is set in seconds via TimeInterval and can be different for each URL: typical values for API responses are 120 seconds for dynamic content and 3600 for static data.

Frequently Asked Questions

What is the difference between TTL and data expiration date?

Technically, TTL and expiration date are the same thing: a time interval after which data is considered invalid. The difference is in context: the term TTL is used in IT (caching, networking, DNS), while “expiration date” is more often applied in business logic (promo codes, subscriptions). In implementation, both mechanisms are identical — comparing the current time with the expiration time.

How to choose the optimal TTL?

The optimal TTL is chosen empirically. Methodology: start with a conservative value (30–60 seconds), gradually increase until complaints about outdated data appear. Monitor the cache hit ratio: if it is below 70%, the TTL is too short. Consider SLA: for financial data, TTL can be 1 second; for news — 5 minutes; for profiles — 30 minutes.

What happens after TTL expires in HTTP?

After max-age expires, the browser or mobile application considers the response stale. On the next request to the same URL, the client sends a request with the If-None-Match (ETag) or If-Modified-Since header. If the data has not changed, the server returns 304 Not Modified without a response body, and the TTL is updated. If it has changed, the server returns 200 with new data and a new Cache-Control.

Can TTL be infinite?

Technically, TTL can be very large (max-age=31536000 — 1 year), but this is rarely justified. Even static resources can change, and the client will not know about it until the TTL expires. It is recommended to use versioned URLs (style.css?v=2) with a long TTL: when the file changes, the URL changes, and the old cache automatically becomes stale.

How is TTL related to LRU and FIFO?

TTL and eviction strategies (LRU, FIFO) solve different problems. TTL determines when data becomes irrelevant — this is a temporal criterion. LRU and FIFO determine which data to remove when the cache is full — this is a spatial criterion. They can be combined: a record is deleted if TTL has expired OR the cache is full (by LRU/FIFO). In production systems, both mechanisms work together.

Summary

  • TTL (Time To Live) — the lifespan of a record, after which the data is considered outdated and requires updating
  • Absolute expiration — the record stores the exact expiration time; relative expiration — creation time + interval
  • Balance — a short TTL reduces caching efficiency; a long one increases the risk of outdated data
  • HTTP Cache-Control — max-age sets the server response TTL in seconds with support for stale modes
  • DNS Resolution — TTL from 60 to 86400 seconds determines how long a domain’s IP address is cached
  • Strategies — fixed, adaptive, and probabilistic TTL are applied depending on the data type
  • Use TTL together with LRU/FIFO for complete cache lifecycle management

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also