# `ExResilience.Cache.Backend`
[🔗](https://github.com/joshrotenberg/ex_resilience/blob/v0.4.0/lib/ex_resilience/cache/backend.ex#L1)

Behaviour for pluggable cache backends.

Implement this behaviour to use a custom caching library
(Cachex, ConCache, etc.) as a cache layer backend.

## Example

A minimal in-memory backend:

    defmodule MyBackend do
      @behaviour ExResilience.Cache.Backend

      @impl true
      def init(_opts), do: {:ok, %{}}

      @impl true
      def get(key, state) do
        case Map.fetch(state, key) do
          {:ok, value} -> {:hit, value, state}
          :error -> {:miss, state}
        end
      end

      @impl true
      def put(key, value, _ttl, state), do: {:ok, Map.put(state, key, value)}

      @impl true
      def invalidate(key, state), do: {:ok, Map.delete(state, key)}

      @impl true
      def stats(state), do: %{size: map_size(state)}
    end

# `key`

```elixir
@type key() :: term()
```

# `state`

```elixir
@type state() :: term()
```

# `ttl_ms`

```elixir
@type ttl_ms() :: non_neg_integer() | nil
```

# `value`

```elixir
@type value() :: term()
```

# `get`

```elixir
@callback get(key(), state()) :: {:hit, value(), state()} | {:miss, state()}
```

Looks up a key. Returns `{:hit, value, state}` on cache hit,
or `{:miss, state}` on cache miss.

# `init`

```elixir
@callback init(opts :: keyword()) :: {:ok, state()} | {:error, term()}
```

Initializes the backend state from the given options.

# `invalidate`

```elixir
@callback invalidate(key(), state()) :: {:ok, state()}
```

Removes the entry for `key`. If `key` is `nil`, removes all entries.

# `put`

```elixir
@callback put(key(), value(), ttl_ms(), state()) :: {:ok, state()}
```

Stores a value under `key` with an optional TTL in milliseconds.
A `nil` TTL means the entry does not expire.

# `stats`

```elixir
@callback stats(state()) :: map()
```

Returns a map of backend statistics (at minimum `%{size: non_neg_integer()}`).

---

*Consult [api-reference.md](api-reference.md) for complete listing*
