---
# System prepended metadata

title: Untitled

---

`# Kache: A golang caching library

This package implements a couple of caches with different eviction policies. 
Both the caches adhere to the following contract:
```golang
type Cache interface {
  // Inserts the provided key/value pair into the cache, making it
  // available for future get() calls.
  Put(key, value string)

  // Returns a value previously provided via put(). An empty Option
  // may be returned if the requested data was never inserted or is
  // no longer available.
  Get(key string) types.Option
}
```

The `Option` struct exposes a `IsPresent()` method to. check for the presence of a value. Use it in conjunction with Get() to get the value returned by the cache. 

The exposed cache types are:

#### LRU Cache
As the name suggests, this is a fixed size cache which uses LRU as its eviction policy.
```golang

import "srm.io/kache"

func main() {
  // size of the cache
  size := 2
  lru := kache.NewLRU(size)

  lru.Put("foo", "bar")
  lru.Put("foo-2", "bar")
  // will evict the least recently used key "foo"
  lru.Put("foo-3", "bar")
}
```

#### Tiered Cache
This is a 2-tier cache implementation with hot and cold caches. The hot cache is used to store repeatedly accessed keys. The hot cache uses a hybrid of LRU and TTL cache eviction policy, while the cold cache just uses the LRU policy.

Workflow:
- A new key value pair gets added to the cold cache.
- On future accesses, the key value pair gets moved to the hot cache with a TTL mentioned while initializing the cache.
- Any further `Get(key)` calls are serviced by the hot cache till the TTL parameter is valid.
- Any further `Put(key, value)` calls in the hot cache re-initialize the TTL parameter.
- Once the TTL is invalidated, the `key` gets evicted from the hot cache.

```golang

import (
  "time"
  
  "srm.io/kache"
)

func main() {
  opts := kache.TieredOptions{
    HotCacheSize: 2,
    TTL: 5 * time.Second
  }
  cache, err := kache.NewTiered(opts)
  if err != nil {
    return err
  }

  cache.Put("foo", "bar")
  cache.Put("foo-2", "bar")
  // will promote it to hot cache with a TTL value of 5 seconds.
  cache.Get("foo")s
}
````