TTLDB
A lightweight, generic, thread-safe in-memory cache for Go with TTL-based expiration.
TTLDB is designed to be simple, fast, and safe for concurrent use. It supports automatic expiration of cached items and optional sliding expiration, making it suitable for web services, APIs, background workers, and other high-throughput applications.
Features
- ✅ Generic API
- ✅ Thread-safe
- ✅ Per-item TTL
- ✅ Automatic expiration
- ✅ Optional sliding expiration
- ✅ Simple and lightweight
- ✅ Suitable for high-concurrency workloads
Installation
go get github.com/erfanshekari/ttldb
Quick Start
Create a cache:
package main
import (
"time"
"github.com/erfanshekari/ttldb"
)
func main() {
cache := ttldb.New[string, string]()
cache.Start()
defer cache.Stop()
cache.Set("user:1", "Alice", 5*time.Minute)
value, ok := cache.Get("user:1")
if ok {
println(value)
}
}
Expiration
Each item has its own TTL.
cache.Set("token", "foobar", 30*time.Second)
After the TTL expires, the item becomes unavailable and is automatically removed by the cache.
Important
Automatic expiration is disabled until Start() is called.
cache := ttldb.New[string, string]()
cache.Start()
defer cache.Stop()
Sliding Expiration
Sliding expiration extends an item's lifetime every time it is successfully accessed.
Enable it when creating the cache:
cache := ttldb.New[string, string](
ttldb.SlidingExpiration,
)
This is useful for sessions, authentication tokens, and frequently accessed data.
API
type Cache[K comparable, V any] interface {
Start()
Stop()
Clear()
Set(key K, value V, ttl time.Duration)
Get(key K) (V, bool)
Delete(key K)
Has(key K) bool
}
Methods
| Method |
Description |
Start() |
Starts the background expiration process. |
Stop() |
Stops the background expiration process. |
Set() |
Stores a value with the specified TTL. |
Get() |
Retrieves a value. Returns (value, true) if found. |
Has() |
Reports whether a key exists and has not expired. |
Delete() |
Removes a key from the cache. |
Clear() |
Removes all items from the cache. |
Concurrency
TTLDB is safe for concurrent use by multiple goroutines.
Use Cases
- API response caching
- Session storage
- Authentication tokens
- Rate limiting
- Temporary application state
- Database query caching
Contributing
Contributions, bug reports, and feature requests are welcome. Feel free to open an issue or submit a pull request.
If you find this project useful, consider giving it a ⭐ on GitHub!