Skip to content

Commit 95aec5e

Browse files
authoredMar 16, 2025··
docs: Add docs for read replicas (#511)
1 parent b03bc13 commit 95aec5e

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Welcome! `AshPostgres` is the PostgreSQL data layer for [Ash Framework](https://
3434
- [Expressions](documentation/topics/advanced/expressions.md)
3535
- [Manual Relationships](documentation/topics/advanced/manual-relationships.md)
3636
- [Schema Based Multitenancy](documentation/topics/advanced/schema-based-multitenancy.md)
37+
- [Read Replicas](documentation/topics/advanced/using-multiple-repos.md)
3738

3839
## Reference
3940

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Using Multiple Repos
2+
3+
When scaling PostgreSQL you may want to setup _read_ replicas to improve
4+
performance and availability. This can be achieved by configuring multiple
5+
repositories in your application.
6+
7+
## Setup Read Replicas
8+
9+
Following the [ecto docs](https://hexdocs.pm/ecto/replicas-and-dynamic-repositories.html), change your Repo configuration:
10+
11+
```elixir
12+
defmodule MyApp.Repo do
13+
use Ecto.Repo,
14+
otp_app: :my_app,
15+
adapter: Ecto.Adapters.Postgres
16+
17+
@replicas [
18+
MyApp.Repo.Replica1,
19+
MyApp.Repo.Replica2,
20+
MyApp.Repo.Replica3,
21+
MyApp.Repo.Replica4
22+
]
23+
24+
def replica do
25+
Enum.random(@replicas)
26+
end
27+
28+
for repo <- @replicas do
29+
defmodule repo do
30+
use Ecto.Repo,
31+
otp_app: :my_app,
32+
adapter: Ecto.Adapters.Postgres,
33+
read_only: true
34+
end
35+
end
36+
end
37+
```
38+
39+
## Configure AshPostgres
40+
41+
Now change the `repo` argument for your `postgres` block as such:
42+
43+
```elixir
44+
defmodule MyApp.MyDomain.MyResource do
45+
use Ash.Resource,
46+
date_layer: AshPostgres.DataLayer
47+
48+
postgres do
49+
table "my_resources"
50+
repo fn
51+
_resource, :read -> MyApp.Repo.replica()
52+
_resource, :mutate -> MyApp.Repo
53+
end
54+
end
55+
end
56+
```

‎mix.exs

+1
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ defmodule AshPostgres.MixProject do
9797
"documentation/topics/development/upgrading-to-2.0.md",
9898
"documentation/topics/advanced/expressions.md",
9999
"documentation/topics/advanced/schema-based-multitenancy.md",
100+
"documentation/topics/advanced/using-multiple-repos.md",
100101
"documentation/topics/advanced/manual-relationships.md",
101102
{"documentation/dsls/DSL-AshPostgres.DataLayer.md",
102103
search_data: Spark.Docs.search_data_for(AshPostgres.DataLayer)},

0 commit comments

Comments
 (0)
Please sign in to comment.