Caching
Ginject's built-in CacheModule provides a sharded LFU in-memory cache with TTL, atomic SetNX, and a pluggable backend interface.
Caching
Ginject ships a production-ready in-memory cache module backed by a sharded LFU (Least Frequently Used) eviction strategy.
Setup
Import CacheModule as a global module so CacheService is available everywhere:
CacheService API
Inject *cache.CacheService into any provider or controller:
Get
Returns ([]byte, bool). The bool is false on a cache miss or if the key has expired.
Set
Pass 0 as TTL for no expiration. Returns an error if the key is empty.
SetNX (atomic conditional set)
Set only if the key does not exist. Returns (bool, error):
SetNX is atomic: if two goroutines call it simultaneously with the same key, exactly one will receive true.
Delete
Keys
List all keys currently in the cache:
Useful for cache inspection and debugging. Not intended for hot paths.
TTL
Check the remaining TTL for a key:
Cache Interface
The Backend field accepts anything implementing cache.Cache. Plug in Redis, Memcached, or a test double:
Memory Cache Internals
The default MemoryCache uses:
- Sharding — the key space is partitioned across N shards (based on a hash of the key) to reduce lock contention under high concurrency.
- LFU eviction — when a shard is full, the least frequently accessed entry is evicted.
- Per-entry TTL — entries are lazily expired on access.
Cache Pattern: Read-Through
Cache Pattern: Idempotency Key
Using Cache in ThrottlerGuard
Provide the cache service as the throttler's store: