dgraph-io/badger · warning

invalid cache type

Error message

invalid cache type

What it means

Returned by db.MaxCost (the query variant of SetMaxCost) when the cache argument is neither BlockCache nor IndexCache. Only those two cache kinds are recognized; passing any other badger.CacheType value yields this error.

Source

Thrown at db.go:2146

)

// CacheMaxCost updates the max cost of the given cache (either block or index cache).
// The call will have an effect only if the DB was created with the cache. Otherwise it is
// a no-op. If you pass a negative value, the function will return the current value
// without updating it.
func (db *DB) CacheMaxCost(cache CacheType, maxCost int64) (int64, error) {
	if db == nil {
		return 0, nil
	}

	if maxCost < 0 {
		switch cache {
		case BlockCache:
			return db.blockCache.MaxCost(), nil
		case IndexCache:
			return db.indexCache.MaxCost(), nil
		default:
			return 0, errors.New("invalid cache type")
		}
	}

	switch cache {
	case BlockCache:
		db.blockCache.UpdateMaxCost(maxCost)
		return maxCost, nil
	case IndexCache:
		db.indexCache.UpdateMaxCost(maxCost)
		return maxCost, nil
	default:
		return 0, errors.New("invalid cache type")
	}
}

func (db *DB) LevelsToString() string {
	levels := db.Levels()
	h := func(sz int64) string {

View on GitHub (pinned to 2a001d466f)

Solutions

  1. Only pass the exported constants badger.BlockCache or badger.IndexCache
  2. Validate/cache-normalize the value from config before calling MaxCost
  3. Check the badger API docs for the exact CacheType constants in your version

Example fix

// before
cost, err := db.MaxCost(badger.CacheType(cfg.CacheKind))

// after
var ct badger.CacheType
switch cfg.CacheKind {
case "block": ct = badger.BlockCache
case "index": ct = badger.IndexCache
default: return fmt.Errorf("unknown cache kind %q", cfg.CacheKind)
}
cost, err := db.MaxCost(ct)
Defensive patterns

Strategy: type-guard

Validate before calling

if ct != badger.BlockCache && ct != badger.IndexCache { return errors.New("unsupported cache type") }

Type guard

func validCacheType(ct badger.CacheType) bool {
    return ct == badger.BlockCache || ct == badger.IndexCache
}

Prevention

When it happens

Trigger: Calling db.MaxCost(cache) with a cache type value outside the defined BlockCache/IndexCache set — e.g. a zero-value CacheType, a cast integer, or a type from a different badger version.

Common situations: Storing cache kinds in config files and reading them unvalidated; a refactor renaming/adding cache constants; code shared across badger versions where the CacheType enum differs.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of dgraph-io/badger@2a001d466f (2026-09-05). Data as JSON: /api/errors/e9b95689128884ef. Report an issue: GitHub.