mikej

mikej

Idiomatic setup for Ecto replicas with runtime configuration

Okay, this one may get a bit in the weeds but here goes. First, while my application is a Phoenix app, this is more of an Ecto/Elixir setup question. Please let me know if this should go in the general category.

  • My application is multi-tenant.
  • We achieve multi-tenancy with Postgres schemas.
  • It runs on AWS ECS containers.
  • It uses AWS RDS Aurora Postgres as the database backend.

The requirements:

  • Multiple read-only replicas are required. This is a very high traffic system that’s heavy on the reads.
  • Configuration options must be passed at runtime, we use AWS Secret Manager to pass in sensitive data.
  • Different ECS clusters may connect to different RDS clusters.

So the problem I’m facing is: How do I build a system that can connect to different database clusters with different read replicas depending on the cluster configuration it’s running in?

What I have now is this bunch of bananas - it works but it has one very specific limitation.

First, I’m using a runtime config value to read in a comma separated list of replica endpoints:

config :snw_bowman,
  pod_replicas: String.split(System.get_env("POD_REPLICAS") || "localhost", ",", trim: true)

Then in my Repo file I have:

defmodule SnwBowman.Repo do
  @moduledoc false
  require Logger

  use Ecto.Repo,
    otp_app: :snw_bowman,
    adapter: Ecto.Adapters.Postgres

  @replicas [
    SnwBowman.Repo.ReadOnly1,
    SnwBowman.Repo.ReadOnly2
  ]

  def replica do
    @replicas
    |> Enum.random()
  end

  @doc """
  Starts the read-only replicas. This function is called by the GenServer
  defined below, and should not be called directly. The GenServer is started
  under the main supervision tree.
  """
  def start_replicas(hosts) do
    conf = Keyword.put(config(), :read_only, true)

    for {repo, index} <- Enum.with_index(@replicas) do
      case repo.start_link(
             Keyword.put(conf, :hostname, Enum.at(hosts, index))
             |> Keyword.put(:name, repo)
           ) do
        {:ok, _} -> :ok
        {:error, reason} -> Logger.error("Failed to start replica #{index}: #{inspect(reason)}")
      end
    end
  end

  for repo <- @replicas do
    defmodule repo do
      use Ecto.Repo,
        otp_app: :snw_bowman,
        adapter: Ecto.Adapters.Postgres
    end
  end
end

defmodule SnwBowman.Repo.Replicas do
  @moduledoc false
  @name :snw_bowman_repo_replicas

  use GenServer

  def start_link(args) do
    GenServer.start_link(__MODULE__, args, name: @name)
  end

  def init(hosts: hosts) do
    SnwBowman.Repo.start_replicas(hosts)
    {:ok, %{}}
  end
end

The key here being start_replicas/0 and the GenServer module at the bottom. Those are used in the application.ex file like this:

defmodule SnwBowman.Application do

  use Application

  @impl true
  def start(_type, _args) do

    children =
      [
        ...
        # Start the Ecto repository
        SnwBowman.Repo,
        # Start the replicas
        {SnwBowman.Repo.Replicas, hosts: Application.get_env(:snw_bowman, :pod_replicas)}
        ...
      ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: SnwBowman.Supervisor]
    Supervisor.start_link(children, opts)
  end

end

This allows me to sub in a different :hostname value for each replica, have them configured at run time, and start under the main supervision tree.

The biggest problem is that it requires that ALL clusters have the same number of read replicas.

The second problem is that this just feels… odd. Like there should be some code smells, but I can’t see them. Is this idiomatic Elixir? Is there a better way to handle this?

Would love to hear some feedback and suggestions.

Thanks in advance,
~mike

Most Liked

LostKobrakai

LostKobrakai

You can use two base repos. One for the write repo and one for replicas.

You need to select a repo no matter if you generate modules for them or if you do dynamic repos (e.g. registered to a registry). You can even hide some of that behind a module also adhereing to the repo behaviour (see e.g. fly_postgres_elixir/lib/repo.ex at main · superfly/fly_postgres_elixir · GitHub)

Where Next?

Popular in Questions Top

New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement