Implement an Elixir function using ETS (Erlang Term Storage) to implement a read-heavy…
- User
Implement an Elixir function using
ETS(Erlang Term Storage) to implement a read-heavy cache withpublicread andprotectedwrite access. Assistant
1. Analyze the Request: * Language: Elixir. * Core Mechanism: ETS (Erlang Term Storage). * Goal: Implement a read-heavy cache. * Access Control Requirements: * Read:
public(Any process can read). * Write:protected(Only the owner process can write).-
Deconstruct ETS Access Levels:
public: Any process can read/write.protected: Owner can read/write. Others can read.private: Only owner can read/write.- Constraint Analysis: The user wants
publicread +protectedwrite. - ETS Limitation: Standard ETS access modes are global for the table. You can't set read to
publicand write toprotectedsimultaneously on the same table in a single configuration flag. - Solution:
- Option A: Use
protectedtables. Inprotectedmode, the owner writes, everyone else reads. This matches the "Owner writes, others read" semantics perfectly. However, the user specifically asked for "public read". - Option B: Use two tables (Write-through/Caching strategy). A public table for reading and a protected/private table for writing? No, that's over-engineering and consistency is hard.
- Option C (Correction): Re-read the ETS docs.
protectedmeans "Read public, Write protected".- Docs: "protected - allows read access for all processes, but only the owner process can write."
- Conclusion: The standard
:protectedaccess mode is exactly what the user is asking for. I just need to implement a wrapper around an ETS table created with:protected.
- Option A: Use
-
Architectural Design (The "Cache" Module):
- Owner Process: Since
protectedtables require the owner to write, we need a dedicated process (GenServer or Agent) to "own" the ETS table. If the process that creates the table dies, the table dies. - Interface:
start_link/1(ornew/1): Creates the table.get/1: Reads from the table (can be called from any process).put/2: Writes to the table (must execute within the owner process context to work safely/legally with:protectedrights, or simply rely on the fact that:protectedallows owner writes).
- Wait, how does a client write?
- If I use
:protected, only the owning process can call:ets.insert. - If a client calls
MyCache.put(:key, :value), andMyCachejust wraps:ets.insert, the client process will crash because it doesn't have permission. - Refinement: The
putfunction must send a message to the owner process (GenServer), and the owner process performs the:ets.insert. Thegetfunction can be a direct:ets.lookupcall by the client (since reads are public in:protectedmode). This achieves "Read-Heavy" optimization (zero overhead for reads).
- If I use
- Owner Process: Since
-
Step-by-Step Implementation Plan:
- GenServer: Use a GenServer to own the ETS table.
- Init:
- Create the ETS table with
:named_tableand:protected(default is protected, but explicit is better). read_concurrency: true(Optimization for read-heavy).
- Create the ETS table with
- Read Function (
get):- Direct call to
:ets.lookup. - No GenServer call overhead (crucial for read-heavy).
- Direct call to
- Write Function (
put/delete):- Use
GenServer.cast(orcallif confirmation is needed). - Inside the
handle_cast/handle_call, perform:ets.insert.
- Use
- TTL (Optional but good for a cache):
- The prompt didn't ask for TTL, but a "cache" implies it usually. I'll keep it simple first (Key-Value store), maybe mention TTL as an add-on or just stick to strict requirements to avoid over-complication. Let's stick to basic Put/Get.
-
Drafting the Code (Mental or Scratchpad):
defmodule Cache do use GenServer # Public API # Starts the owner def start_link(name) do GenServer.start_link(__MODULE__, name, name: name) end # READ: Public access (Client process does the lookup directly) def get(table_name, key) do # ETS protected allows others to read case :ets.lookup(table_name, key) do [{^key, value}] -> {:ok, value} [] -> {:error, :not_found} end end # WRITE: Protected access (Client sends msg to Owner) def put(table_name, key, value) do # We use cast for fire-and-forget speed, or call for sync GenServer.cast(table_name, {:put, key, value}) end # GenServer Callbacks def init(table_name) do # Create table. :protected is default. # :named_table allows access via atom name. # read_concurrency: true is vital for read-heavy. :ets.new(table_name, [:set, :protected, :named_table, read_concurrency: true]) {:ok, table_name} end def handle_cast({:put, key, value}, table_name) do :ets.insert(table_name, {key, value}) {:noreply, table_name} end end -
Refining the Solution:
- The prompt specifically asks for public read and protected write.
- Standard ETS
:protectedmode works exactly like this:- Owner: Read + Write.
- Others: Read.
- Others (Write): Fails.
- Therefore, the design above is correct. It separates the read path (direct ETS access) from the write path (GenServer proxy).
-
Adding Explanations:
- Explain why we use
:protected. It's the default, but it matches the requirement perfectly. - Explain
read_concurrency: true. This is a specific optimization for read-heavy workloads. - Explain the split API: Direct function call for read (fast), GenServer message for write (safe).
- Explain why we use
-
Code Review of the Draft:
- Error Handling: What if the table doesn't exist? The
getfunction will crash. That's generally acceptable in Elixir (let it crash), but maybestart_linkneeds to ensure the name is passed correctly. - Table Type:
:setis standard for a cache (unique keys). - Heirarchy: Sometimes people use
:publicfor everything and handle locking manually. That's bad for this prompt. The prompt asks forprotectedwrite, implying we rely on the built-in protection.
- Error Handling: What if the table doesn't exist? The
-
Final Polish:
- Create a complete, runnable module.
- Include comments explaining the specific ETS settings.
- Provide an usage example in the explanation.
-
Constructing the Output: (Proceeding to generate the Elixir code based on the drafted logic).
- Module Name:
ReadHeavyCache - Table Name: Passed as argument.
- Key/Value structure:
{key, value}. - Self-Correction: Should I use
:publictable with the GenServer managing writes?- If table is
:public, anyone can write. The prompt asks for "protected write access". This specifically means unauthorized processes should not be able to write. - So,
:protectedis the only correct answer.
- If table is
- Optimization:
read_concurrency: trueis mandatory for "read-heavy".
- Module Name:
-
Final Code Structure:
start_link/1get/2->:ets.lookup(Direct)put/3->GenServer.call(Sync) orcast(Async). I'll usecallto ensure the write happened before returning, which is usually safer for a generic cache, butcastis faster. Given "read-heavy", writes can afford a tiny bit of overhead. I'll stick tocastfor performance or providecallfor reliability. Let's docallfor correctness, as async caches can be tricky to debug. Update: Actually, standard cache patterns often use async writes. I'll usecastto emphasize the "read-heavy, write-occasional" nature where write latency isn't the bottleneck. Butcallis safer. Let's usecallto ensure the write happens, orcastand mention it. Let's go withcastto reduce GenServer bottlenecking, as the user emphasized "Read-Heavy".
Let's re-read: "public read and protected write". Standard ETS
:protected:- Owner: Read/Write.
- Others: Read.
- Others: Write -> ArgumentError.
This fits perfectly.
Implementation details:
- GenServer: To hold the ETS table.
- Table opts:
[:named_table, :set, :protected, read_concurrency: true]. - Read:
:ets.lookup/2. - Write:
GenServer.cast/2->handle_cast->:ets.insert/2.
Let's write it out. To implement a read-heavy cache with
publicread access andprotectedwrite access in Elixir, we rely on the specific access control semantics of ETS: -
protected(Default): This setting allows any process to read (Public Read), but only the owner process can write (Protected Write). This matches your requirement perfectly. -
read_concurrency: true: This optimization is crucial for read-heavy workloads, allowing concurrent reads without locking overhead.
We will implement this using a
GenServer. The GenServer will act as the "Owner" of the table. This allows external processes to read data directly from the ETS table (bypassing the GenServer entirely for speed), while all write operations (inserts, deletes) are sent as messages to the GenServer to be executed safely.The Implementation
defmodule ReadHeavyCache do use GenServer # ---------------------------------------------------------------------------- # Public API # ---------------------------------------------------------------------------- @doc """ Starts the cache. """ def start_link(opts \\ []) do name = Keyword.get(opts, :name, __MODULE__) GenServer.start_link(__MODULE__, name, name: name) end @doc """ Reads a value from the cache. This function executes in the CALLING process (public read). It does not involve message passing to the GenServer, making it extremely fast. """ def get(table \\ __MODULE__, key) do # We use :ets.lookup directly here. # Because the table is :protected, any process can read it. case :ets.lookup(table, key) do [{^key, value}] -> {:ok, value} [] -> {:error, :not_found} end end @doc """ Writes a value to the cache. This function sends a message to the GenServer (protected write). Only the GenServer (the owner) actually performs the insert. """ def put(table \\ __MODULE__, key, value) do GenServer.cast(table, {:put, key, value}) end @doc """ Deletes a value from the cache. """ def delete(table \\ __MODULE__, key) do GenServer.cast(table, {:delete, key}) end # ---------------------------------------------------------------------------- # GenServer Callbacks # ---------------------------------------------------------------------------- @impl true def init(name) do # We create the table inside the GenServer process. # Options: # :named_table - Allows us to access it by atom name. # :set - Standard key-value store. # :protected - (Default) Public Read, Owner-Only Write. # read_concurrency: true - Optimizes for frequent concurrent reads. table = :ets.new(name, [:named_table, :set, :protected, read_concurrency: true]) {:ok, %{table: table}} end @impl true def handle_cast({:put, key, value}, state) do :ets.insert(state.table, {key, value}) {:noreply, state} end @impl true def handle_cast({:delete, key}, state) do :ets.delete(state.table, key) {:noreply, state} end endHow to use it
# 1. Start the cache {:ok, pid} = ReadHeavyCache.start_link(name: :my_cache) # 2. Write data (This goes through the GenServer) ReadHeavyCache.put(:my_cache, "user:1", "Alice") # 3. Read data (This reads directly from ETS, bypassing the GenServer message queue) # This is safe to do from ANY process, not just the one that started the cache. {:ok, value} = ReadHeavyCache.get(:my_cache, "user:1") IO.puts(value) # => "Alice" # 4. Attempting to write directly from an external process # This will CRASH because the table is :protected. # :ets.insert(:my_cache, {"user:2", "Bob"}) # => ** (ArgumentError) argument errorKey Design Decisions
-
Access Mode (
:protected):- By default,
ets:newcreates a protected table. This creates a security boundary where external code can read data instantly but cannot corrupt the table state by writing to it directly. - If external code tries to run
:ets.insert, the Erlang VM throws anArgumentError.
- By default,
-
read_concurrency: true:- This is a performance hint to the VM. In a read-heavy scenario, this reduces the overhead of reading the table from multiple processes simultaneously, as it avoids obtaining heavy locks for every read operation.
-
Direct Read vs. GenServer Call:
- In many GenServer patterns, you might wrap the read in a
handle_call. We did not do that here. - Since we want a high-performance cache,
get/2calls:ets.lookupdirectly in the caller's process. This avoids the overhead of message passing (send, receive, copy) and context switching, making reads significantly faster—often in the sub-microsecond range.
- In many GenServer patterns, you might wrap the read in a
-