Sobes.tech
Junior — Middle

How is the mechanism of updating or resetting outdated data in the cache implemented?

sobes.tech AI

Answer from AI

The mechanism for updating or resetting outdated data in the cache is usually implemented using the following approaches:

  1. Time To Live (TTL) — data in the cache is stored for a limited time, after which it is automatically considered outdated and removed or updated upon the next request.

  2. Lazy updating — data is updated when accessed if it is outdated.

  3. Active updating (cache warming) — a process is periodically run to update the cache in advance.

  4. Invalidation on event — when the source data changes, the corresponding cache entries are reset or updated.

In Python, libraries such as cachetools with TTL can be used for implementation:

from cachetools import TTLCache

cache = TTLCache(maxsize=100, ttl=300)  # Cache with TTL of 300 seconds

@cached(cache)
def get_data(key):
    # Fetch data from source
    pass

Thus, outdated data is automatically removed from the cache after TTL expires, and the next request triggers an update.