Agent KV: state in a process, no locks
Before the code: what a key-value store actually is
So far the server understands the Redis language but has nothing to remember. Time to give it a brain. The brain is a map held inside a BEAM process, plus a small companion table of timers for keys that should disappear on their own. That is the whole Redis storage model, in plain English. The Elixir twist is that you do not need locks. The process owns the map, and the mailbox naturally serialises every read and write into one orderly queue.
The store, with and without timers
Quiz: Quiz
Loading practice…
Agent wraps a process that holds state. Every call to the agent goes through its mailbox; the agent processes one message at a time. We get atomicity without writing a single lock.
defmodule Store do
use Agent
def start_link(_), do: Agent.start_link(fn -> %{} end, name: __MODULE__)
def get(key), do: Agent.get(__MODULE__, &Map.get(&1, key))
def set(key, value), do: Agent.update(__MODULE__, &Map.put(&1, key, value))
def delete(keys), do:
Agent.get_and_update(__MODULE__, fn m ->
{Enum.count(keys, &Map.has_key?(m, &1)), Map.drop(m, keys)}
end)
def keys, do: Agent.get(__MODULE__, &Map.keys/1)
def size, do: Agent.get(__MODULE__, &map_size/1)
endStore wraps an Agent with a friendly API.
Matching exercise: Pick the right Elixir state primitive
Loading practice…
Where the other siblings reached for Mutex or RWLock, Elixir reaches for a process. The actor model serialises by sending messages, not by acquiring locks. Same correctness; different shape.