Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Implement an Elixir function using ETS (Erlang Term Storage) to implement a read-heavy…

  1. User

    Implement an Elixir function using ETS (Erlang Term Storage) to implement a read-heavy cache with public read and protected write access.

  2. GLM 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).

    1. 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 public read + protected write.
      • ETS Limitation: Standard ETS access modes are global for the table. You can't set read to public and write to protected simultaneously on the same table in a single configuration flag.
      • Solution:
        • Option A: Use protected tables. In protected mode, 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. protected means "Read public, Write protected".
          • Docs: "protected - allows read access for all processes, but only the owner process can write."
        • Conclusion: The standard :protected access mode is exactly what the user is asking for. I just need to implement a wrapper around an ETS table created with :protected.
    2. Architectural Design (The "Cache" Module):

      • Owner Process: Since protected tables 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 (or new/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 :protected rights, or simply rely on the fact that :protected allows 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), and MyCache just wraps :ets.insert, the client process will crash because it doesn't have permission.
        • Refinement: The put function must send a message to the owner process (GenServer), and the owner process performs the :ets.insert. The get function can be a direct :ets.lookup call by the client (since reads are public in :protected mode). This achieves "Read-Heavy" optimization (zero overhead for reads).
    3. Step-by-Step Implementation Plan:

      • GenServer: Use a GenServer to own the ETS table.
      • Init:
        • Create the ETS table with :named_table and :protected (default is protected, but explicit is better).
        • read_concurrency: true (Optimization for read-heavy).
      • Read Function (get):
        • Direct call to :ets.lookup.
        • No GenServer call overhead (crucial for read-heavy).
      • Write Function (put/delete):
        • Use GenServer.cast (or call if confirmation is needed).
        • Inside the handle_cast/handle_call, perform :ets.insert.
      • 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.
    4. 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
      
    5. Refining the Solution:

      • The prompt specifically asks for public read and protected write.
      • Standard ETS :protected mode 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).
    6. 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).
    7. Code Review of the Draft:

      • Error Handling: What if the table doesn't exist? The get function will crash. That's generally acceptable in Elixir (let it crash), but maybe start_link needs to ensure the name is passed correctly.
      • Table Type: :set is standard for a cache (unique keys).
      • Heirarchy: Sometimes people use :public for everything and handle locking manually. That's bad for this prompt. The prompt asks for protected write, implying we rely on the built-in protection.
    8. Final Polish:

      • Create a complete, runnable module.
      • Include comments explaining the specific ETS settings.
      • Provide an usage example in the explanation.
    9. 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 :public table 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, :protected is the only correct answer.
      • Optimization: read_concurrency: true is mandatory for "read-heavy".
    10. Final Code Structure:

      • start_link/1
      • get/2 -> :ets.lookup (Direct)
      • put/3 -> GenServer.call (Sync) or cast (Async). I'll use call to ensure the write happened before returning, which is usually safer for a generic cache, but cast is faster. Given "read-heavy", writes can afford a tiny bit of overhead. I'll stick to cast for performance or provide call for reliability. Let's do call for correctness, as async caches can be tricky to debug. Update: Actually, standard cache patterns often use async writes. I'll use cast to emphasize the "read-heavy, write-occasional" nature where write latency isn't the bottleneck. But call is safer. Let's use call to ensure the write happens, or cast and mention it. Let's go with cast to 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:

      1. GenServer: To hold the ETS table.
      2. Table opts: [:named_table, :set, :protected, read_concurrency: true].
      3. Read: :ets.lookup/2.
      4. Write: GenServer.cast/2 -> handle_cast -> :ets.insert/2.

      Let's write it out. To implement a read-heavy cache with public read access and protected write access in Elixir, we rely on the specific access control semantics of ETS:

    11. 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.

    12. 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
    end
    

    How 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 error
    

    Key Design Decisions

    1. Access Mode (:protected):

      • By default, ets:new creates 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 an ArgumentError.
    2. 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.
    3. 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/2 calls :ets.lookup directly 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.