The BEAM Edge · For Elixir developers

A per-customer LLM token budget in Elixir with ETS

One ETS table, a token bucket per customer and a compare-and-swap write: 70 lines that stop one account spending your month's model budget. Tested.

Short answer Keep a token bucket per customer in one ETS table, reserve an estimate before each model call, refund the unused part after, and write with :ets.select_replace as compare-and-swap so concurrent requests cannot overspend. Our module and five tests pass on Elixir 1.20.4.

A SaaS that calls a model API has a cost per customer that the customer controls. One account that pastes a 300-page PDF into a chat, or one script stuck in a loop, can spend more in an afternoon than the account pays in a month. A rate limit on requests does not catch it, because the cost is in tokens, not requests.

The fix is a token budget per customer, checked before each call. On the BEAM that needs no Redis and no extra process per customer: one ETS table, a token bucket per customer, and a compare-and-swap write so concurrent requests cannot overspend. The module below is seventy lines; its five tests pass on Elixir 1.20.4, run three times.

§1

The module

Illustrative

Elixir

defmodule LLMBudget do
  @moduledoc "Per-customer token budgets for LLM calls: a token bucket per customer in ETS, refilled continuously."
  use GenServer

  @table __MODULE__

  # The GenServer only owns the table; reads and writes go straight to ETS.
  def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)

  @impl true
  def init(_opts) do
    :ets.new(@table, [:named_table, :public, :set, write_concurrency: true, read_concurrency: true])
    {:ok, nil}
  end

  @doc """
  Reserve `cost` tokens for `customer` before calling the model.
  Returns :ok, {:error, :over_budget, retry_after_ms}, or {:error, :too_large} if `cost` exceeds `capacity`. `capacity` is the largest burst, `per_second` the refill rate.
  """
  def reserve(customer, cost, capacity, per_second, now_ms \\ System.monotonic_time(:millisecond))
      when cost > 0 and per_second > 0 do
    {tokens, last} = current(customer, capacity, now_ms)
    available = min(capacity * 1.0, tokens + max(now_ms - last, 0) * per_second / 1000)

    {new_tokens, reply} =
      cond do
        available >= cost -> {available - cost, :ok}
        cost > capacity -> {available, {:error, :too_large}}
        true -> {available, {:error, :over_budget, ceil((cost - available) * 1000 / per_second)}}
      end

    # Compare-and-swap: write only if the row is still what we read; otherwise another process won, so retry.
    if swap(customer, {tokens, last}, {new_tokens, max(now_ms, last)}),
      do: reply,
      else: reserve(customer, cost, capacity, per_second, now_ms)
  end

  @doc "Give back what a call did not use, once the real token count is known."
  def refund(customer, unused, capacity) when unused > 0 do
    case :ets.lookup(@table, customer) do
      [{^customer, tokens, last}] ->
        if swap(customer, {tokens, last}, {min(capacity * 1.0, tokens + unused), last}),
          do: :ok,
          else: refund(customer, unused, capacity)

      [] ->
        :ok
    end
  end

  def refund(_customer, _unused, _capacity), do: :ok

  defp current(customer, capacity, now_ms) do
    case :ets.lookup(@table, customer) do
      [{^customer, tokens, last}] ->
        {tokens, last}

      [] ->
        # First call for this customer: start with a full bucket (insert_new loses quietly to a concurrent insert).
        :ets.insert_new(@table, {customer, capacity * 1.0, now_ms})
        [{^customer, tokens, last}] = :ets.lookup(@table, customer)
        {tokens, last}
    end
  end

  defp swap(customer, {tokens, last}, {new_tokens, new_last}) do
    match = [{{customer, tokens, last}, [], [{:const, {customer, new_tokens, new_last}}]}]
    :ets.select_replace(@table, match) == 1
  end
end
Fig. 1 — Elixir 1.20.4. Time is passed in, so tests run without sleeping. It shows the idea; it isn't production code.
§2

How it works

A bucket per customer. Each row holds the customer, the tokens left, and when it was last updated. Tokens refill continuously at per_second, up to capacity, so a customer can burst to the full budget and then settles at the refill rate.

Reserve before the call, refund after. You do not know the exact token count until the model answers, so reserve an estimate, such as the prompt tokens plus your max_tokens, and call refund/3 with what was not used. Over budget, reserve/5 returns how many milliseconds until the cost would fit; round up to whole seconds for a Retry-After header. A cost above capacity can never fit, so it returns {:error, :too_large}, and the guard rejects a cost or refill rate that is not positive.

Compare-and-swap, not a lock. Two requests from the same customer can arrive at the same moment. Instead of serializing them through a GenServer, each one reads the row, computes the new value and writes it with :ets.select_replace/2 only if the row is unchanged; the loser retries. The Erlang documentation gives this pattern as a generic single-object compare-and-swapSource 1, and because the key in the pattern is fully bound, the write is a single key lookup, not a table scanSource 1. The GenServer only owns the table. One caveat: the customer key goes into a match pattern, so it must not contain atoms such as :_ or :"$1"; strings, integers and ordinary tuples are fine.

Start full, once. :ets.insert_new/2 returns false instead of overwriting when the key already existsSource 1, so two first requests cannot both create a full bucket.

§3

What the tests check

Five ExUnit tests, Elixir 1.20.4, each run passed three times in a row (our test, October 2026)
ScenarioResult
Spend 6,000 then 4,000 of a 10,000 budget, then ask for 500 more:ok, :ok, then {:error, :over_budget, 5000}
Spend everything, wait 5 s at 100 tokens/s, ask for 500:ok; a request above capacity gets {:error, :too_large}
Two customers (a string and a tuple key) each spend their full budgetBoth :ok; budgets are separate
Reserve 8,000, refund 5,000, reserve 7,000All :ok
20,000 concurrent reservations of 1 token against 10,000Exactly 10,000 succeed

The last test is the one that matters. With the swap replaced by a plain :ets.insert/2, it failed every run, letting more than 10,000 requests through each time (between 10,001 and 10,078 in our runs and a reviewer's); with the compare-and-swap, exactly 10,000 succeed, every run.

§4

Putting it in an app

  1. Start `LLMBudget` in your supervision tree, so the table exists before the first request.
  2. Size buckets per plan. Capacity and refill rate are arguments, so a free plan and a paid plan can share the code.
  3. Count the real tokens. Model APIs return token usage in their responses; refund the difference between your estimate and the actual count.
  4. It is per node. ETS lives in one node's memory; on a cluster, either route each customer to one node or accept a budget per node. A restart refills every bucket.

Sources

  1. ets (Erlang/OTP documentation). Retrieved . ↩ ↩ ↩

Published · Updated Report an error (support@agentum.cloud)