HeadlinesBriefing favicon HeadlinesBriefing.com

Go Cache with TTL for FreeDevTools

DEV Community •
×

Ganesh Kumar, the creator behind the open‑source FreeDevTools hub, expands the platform by adding a thread‑safe in‑memory cache written in Go. The new module introduces TTL support, letting developers store values that automatically expire, a feature missing from the earlier version that only cached raw data in production.

Internally, the cache maps string keys to a CacheItem struct holding an interface{} value and a time.Time expiry. A sync.RWMutex guards concurrent access. The Set method records the current time plus the supplied TTL, while Get checks the expiry on demand, deleting stale entries without a background sweep.

Running the sample, the program stores a name with a 2‑second TTL and a weight with a 5‑second TTL. After sleeping past the first expiry, a Get call returns false, confirming removal. Subsequent Get calls before the second expiry return the weight, demonstrating correct time‑based eviction in Go.

Adding TTL turns a simple cache into a production‑ready component that prevents stale data from polluting responses and reduces database load. The open‑source code invites contributors to tweak eviction policies or integrate with existing frameworks. Future posts may explore LRU strategies or distributed caching for multi‑node deployments today.