Setting Time To Live(TTL) and User Metadata on Keys

Badger allows setting an optional Time to Live (TTL) value on keys. Once the TTL has elapsed, the key will no longer be retrievable and will be eligible for garbage collection. A TTL can be set as a time.Duration value using the Entry.WithTTL() and Txn.SetEntry() API methods.

  1. err := db.Update(func(txn *badger.Txn) error {
  2. e := badger.NewEntry([]byte("answer"), []byte("42")).WithTTL(time.Hour)
  3. err := txn.SetEntry(e)
  4. return err
  5. })

An optional user metadata value can be set on each key. A user metadata value is represented by a single byte. It can be used to set certain bits along with the key to aid in interpreting or decoding the key-value pair. User metadata can be set using Entry.WithMeta() and Txn.SetEntry() API methods.

  1. err := db.Update(func(txn *badger.Txn) error {
  2. e := badger.NewEntry([]byte("answer"), []byte("42")).WithMeta(byte(1))
  3. err := txn.SetEntry(e)
  4. return err
  5. })

Entry APIs can be used to add the user metadata and TTL for same key. This Entry then can be set using Txn.SetEntry().

  1. err := db.Update(func(txn *badger.Txn) error {
  2. e := badger.NewEntry([]byte("answer"), []byte("42")).WithMeta(byte(1)).WithTTL(time.Hour)
  3. err := txn.SetEntry(e)
  4. return err
  5. })