Elixir Blog Post: Speed up Multitenant Migrations with Database Schema Snapshots

Who doesn’t want to go faster? Migrations in Elixir with Ecto are already quick. Still, we can go faster, especially when we need to onboard customers repeatedly in multi-tenant architectures.

1 Like

Neat!

We do something very similar. We have a “template” Pg schema that we dump/load on demand when a new tenant is created. The name of the schema is "__schema_$template", which is extremely likely to be to be unique when we run String.replace (or sed, can’t remember) on the dump output.

I’m a little confused how your #{prefix} works. Is that literally the name of your Pg schema?

One thing that I love about Ecto is how easy it is to do multitenancy. Between get_dynamic_repo, and default_options, it’s pretty easy to handle multietenancy (besides migrations, but that’s a story for another day).

Contrast that to Rails where they implemented first class support for multitenancy, but it’s very prescriptive about how it works… and further it makes a connection pool per tenant:man_facepalming:

1 Like

Glad to hear that you have a similar process working well for you. Reusing the connection pool is a big deal. The prefix is just a placeholder like yours. I could have named it anything. The snapshot function returns a function that takes a specific prefix as an argument. This creates the unique schema for each tenant.

Did you run into any SSL invoking psql from System.cmd?

1 Like

Nope, no SSL issues at all. We just use the Amazon managed certs for RDS and everything just works.

1 Like