liveBook · Manning

Expiration date

As explained in Learn Go with Pocket-Sized Projects

A time to live is a duration after which stored data is considered expired and should no longer be used.

An expiration date is the timestamp after which a cached value is too outdated to trust. A time to live (TTL) determines that timestamp for each stored entry. section 7.0 section 7.4.1

A TTL-based cache applies expiration through a small set of operations:

  • Store each value with an expires timestamp calculated from the current time plus the configured TTL. section 7.4.1
  • Require the TTL when constructing the cache, allowing different caches to suit rapidly changing or stable values. section 7.4.1
  • Check expiration during Read; delete an expired entry and report it as absent, without exposing the reason to the caller. section 7.4.1
  • Leave Delete behavior unchanged and replace both the value and expiration timestamp when Upsert updates an entry. section 7.4.1

Testing expiration

Create a string cache with a 100-millisecond TTL, insert "Norwegian" → "Blue", verify an immediate read succeeds, wait 200 milliseconds, then verify the read returns an empty value and found=false.

Listing 7.14 cache.go: Read with a TTL
func (c *Cache[K, V]) Read(key K) (V, bool) {
    c.mu.Lock()
    defer c.mu.Unlock()

    var zeroV V #1

    e, ok := c.data[key]

    switch {
    case !ok:
        return zeroV, false
    case e.expires.Before(time.Now()):
        // The value has expired.
        delete(c.data, key)
        return zeroV, false
    default:
        return e.value, true
    }
}

Inspect the complete Read implementation that distinguishes missing entries, expired entries, and valid entries. section 7.4.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines TTL storage, construction, updates, reads, deletion, cleanup, and a timing-based test.
Examples
Uses a generic Go cache, timestamped entries, time.Duration values, and a 100-millisecond test.
What you can do after
Build it from scratch by adding configurable expiration and expired-entry cleanup to a generic cache.
How it connects
Connects caching with generics, concurrency safety, cache invalidation, and memory footprint management.

Also explained in

Compare how 4 books explain expiration date →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.