Most Elixir teams never consciously choose a data layer. They inherit mix phx.new, get Ecto, and move on. That default is usually right — until the schema count passes fifty, half the team is arguing about where authorization belongs, and someone proposes a rewrite to “just use SQL.”

The problem is that Ecto, Ash and Postgrex are not three competitors at the same altitude. They are three different answers to the question how much of your database should live in Elixir code? Picking the wrong altitude is expensive: too much abstraction and you fight the framework for every report query, too little and you rebuild an ORM badly, one module at a time.

This guide compares all three with real code, current repository activity, and the migration traps that only show up in production.

TL;DR: Quick Verdict

  • Choose Ecto for 80% of applications. It is the safest default: mature, boring, excellent Postgres support, and every Elixir developer already knows it.
  • Choose Ash if your product is CRUD-shaped, multi-tenant, and needs policy-based authorization plus a GraphQL/JSON:API surface without writing three parallel layers by hand.
  • Choose Postgrex when your workload is analytical, bulk, or SQL-first — COPY pipelines, window functions, materialized views, time-series rollups. Not as an application-wide ORM replacement.

Combining them is normal and healthy: Ash runs on top of Ecto, and Ecto runs on top of Postgrex. Only the top of that stack is a choice.

Ecto vs Ash vs Postgrex at a Glance

DimensionEctoAshPostgrex
GitHub stars6,5082,5751,214
Last commit2026-11-302026-11-302026-11-30
Abstraction levelQuery DSL + schema mappingFull resource frameworkWire protocol driver only
MigrationsEcto.MigrationAshPostgres migrations (Ecto-compatible)Hand-written SQL
AuthorizationManual (contexts, plugs)Declarative policies per actionNone
Multi-tenancyManual (prefix option)First-class (schema or attribute)Manual
Learning curve1–2 weeks3–6 weeksHours, but you write SQL forever
Escape hatch to raw SQLEcto.Adapters.SQL.query/4Same (it delegates to Ecto)It is raw SQL
Best fitGeneral Phoenix appsLarge CRUD domains, SaaS platformsETL, reporting, bulk ingest

The star counts tell a story on their own: Ecto is the ecosystem’s center of gravity, Ash is a serious framework with a real following, and Postgrex is plumbing that most people use without ever naming it.

Which One Fits Your Project?

Use caseRecommendationWhy
Standard Phoenix SaaS, <30 tablesEctoFastest path, best docs, easiest hiring
Multi-tenant B2B product with role-based accessAshPolicies and tenant scoping are built in, not bolted on
Nightly aggregation job reading 200M rowsPostgrex (or Ecto.Adapters.SQL)Cursor-based streaming, no schema hydration cost
Public API over an existing legacy databaseAshDeclarative interfaces can wrap tables you cannot migrate
Team of Elixir newcomersEctoAsh’s DSL is powerful precisely because it is opinionated
Hybrid: product on Ecto, analytics on raw SQLEcto + PostgrexSame pool, two access styles, zero duplication of config

Ecto: The Default That Earned It

Ecto separates three concerns most ORMs blur together: schemas (data shape), changesets (validation and casting), and queries (composable SQL). That separation is why it survives large codebases — a changeset is a plain data structure you can pipe, test, and reuse outside of persistence.

1
2
3
4
5
6
7
# mix.exs
defp deps do
  [
    {:ecto_sql, "~> 3.13"},
    {:postgrex, "~> 0.21"}
  ]
end

A typical schema and changeset:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
defmodule Billing.Invoice do
  use Ecto.Schema
  import Ecto.Changeset

  schema "invoices" do
    field :number, :string
    field :amount_cents, :integer
    field :status, Ecto.Enum, values: [:draft, :open, :paid, :void]
    belongs_to :customer, Billing.Customer
    has_many :line_items, Billing.LineItem
    timestamps(type: :utc_datetime_usec)
  end

  def changeset(invoice, attrs) do
    invoice
    |> cast(attrs, [:number, :amount_cents, :status, :customer_id])
    |> validate_required([:number, :amount_cents, :customer_id])
    |> validate_number(:amount_cents, greater_than_or_equal_to: 0)
    |> unique_constraint(:number)
  end
end

Migrations are versioned files, not diffs against live state — which is exactly what you want when three branches deploy in the same week:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
defmodule Repo.Migrations.CreateInvoices do
  use Ecto.Migration

  def change do
    create table(:invoices) do
      add :number, :string, null: false
      add :amount_cents, :integer, null: false
      add :status, :string, null: false, default: "draft"
      add :customer_id, references(:customers, on_delete: :delete_all), null: false
      timestamps(type: :utc_datetime_usec)
    end

    create unique_index(:invoices, [:number])
    create index(:invoices, [:customer_id, :status])
  end
end

Where Ecto pays off is composition. Ecto.Multi gives you an explicit, testable transaction script instead of nested Repo.transaction calls buried in contexts:

1
2
3
4
5
6
Ecto.Multi.new()
|> Ecto.Multi.insert(:invoice, Invoice.changeset(%Invoice{}, attrs))
|> Ecto.Multi.run(:ledger, fn _repo, %{invoice: inv} ->
  Ledger.post_invoice(inv)
end)
|> Repo.transaction()

Where Ecto costs you is anything set-shaped: bulk upserts across 500k rows, recursive CTEs, window functions. You can write them, but you will be reaching for fragment/1 and Ecto.Adapters.SQL.query/4 more often than the docs admit.

If you are still deciding how background jobs and caching fit around your persistence layer, our guides on Elixir background processing with Oban, Broadway and Quantum and Elixir caching with Nebulex, Cachex and ConCache cover the layers directly above and beside the database.

Ash: Declarative Resources and Built-In Policies

Ash framework — official wordmark

Ash asks a different question than Ecto: not “how do I map this table?” but “what is this resource, what can be done to it, and who is allowed to do it?” A resource declares attributes, actions, relationships, and policies in one file, and Ash derives the API, the authorization checks, and the query layer from it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
defmodule Billing.Invoice do
  use Ash.Resource,
    domain: Billing,
    data_layer: AshPostgres.DataLayer,
    authorizers: [Ash.Policy.Authorizer]

  postgres do
    table "invoices"
    repo Billing.Repo
  end

  attributes do
    uuid_primary_key :id
    attribute :number, :string, allow_nil?: false
    attribute :amount_cents, :integer, allow_nil?: false
    attribute :status, :atom, constraints: [one_of: [:draft, :open, :paid, :void]], default: :draft
    timestamps()
  end

  actions do
    defaults [:read, :destroy]
    create :create, accept: [:number, :amount_cents, :status]
    update :mark_paid, accept: [], change: set_attribute(:status, :paid)
  end

  relationships do
    belongs_to :customer, Billing.Customer, allow_nil?: false
    has_many :line_items, Billing.LineItem
  end

  policies do
    policy action_type(:read) do
      authorize_if expr(customer.owner_id == ^actor(:id))
    end
    policy action(:mark_paid) do
      forbid_unless actor_attribute_equals(:role, :billing_admin)
    end
  end
end

Reading is action-based rather than query-based, which is the philosophical divide:

1
2
3
Billing.Invoice
|> Ash.Query.filter(status == :open and amount_cents > 10_000)
|> Ash.read!(actor: current_user)

The cost is real. Ash’s DSL is large, error messages during development are less beginner-friendly than Ecto’s, and debugging a policy that silently filters every row takes real practice. Teams that adopt Ash without buying into its model end up with two abstractions fighting each other.

The payoff is equally real: the same resource definition powers your JSON API, your admin interface, and your authorization tests. For a multi-tenant SaaS where “who can see which rows” is the hardest part of the product, that is hundreds of lines of hand-written authorization you never write.

Postgrex: When SQL Is the Point

Postgrex is the driver Ecto sits on. Used directly, it gives you the protocol with no mapping layer: you send SQL and get rows back. For bulk and analytical work this is not a downgrade — it is the correct tool.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{:ok, pid} = Postgrex.start_link(
  hostname: "localhost",
  username: "billing",
  password: System.fetch_env!("PGPASSWORD"),
  database: "billing_prod",
  pool_size: 10
)

# Parameterised query — never interpolate strings into SQL
{:ok, %Postgrex.Result{rows: rows, num_rows: n}} =
  Postgrex.query(pid, "SELECT id, amount_cents FROM invoices WHERE status = $1", ["open"])

# Explicit transaction with rollback semantics
{:ok, _} =
  Postgrex.transaction(pid, fn conn ->
    Postgrex.query!(conn, "UPDATE invoices SET status = $1 WHERE id = $2", ["paid", id])
    Postgrex.query!(conn, "INSERT INTO ledger_entries (invoice_id, amount_cents) VALUES ($1, $2)", [id, amount])
  end)

# Streaming a large result without loading it all into memory
{:ok, stream} = Postgrex.stream(pid, "SELECT id, amount_cents FROM invoices WHERE created_at < $1", [cutoff])
Enum.reduce(stream, 0, fn %Postgrex.Result{rows: rows}, acc ->
  acc + Enum.reduce(rows, 0, fn [_id, cents], s -> s + cents end)
end)

Two things to know before you consider this the “fast path” everywhere:

  1. You lose changesets, so you lose the validation boundary. Every caller must be trusted to send valid data, or you rebuild casting by hand.
  2. Streaming inside a transaction holds a snapshot. Long streams block vacuum on busy tables — chunk by primary key range instead of relying on one giant cursor.

The pragmatic middle ground most mature Elixir codebases land on: Ecto for writes and business rules, Ecto.Adapters.SQL.query/4 (same pool, same telemetry) for the handful of queries where the DSL is noise.

Performance and Operational Reality

Real numbers depend far more on your queries than your abstraction. What matters operationally:

  • Pooling is shared. Ecto and Postgrex both use DBConnection; a raw query through Ecto’s adapter reuses the same pool, so mixing access styles does not double your connection count.
  • Prepared statements are cached per connection by Postgrex. Long-lived pools amortise parsing; short-lived connections (serverless, cron containers) do not.
  • Schema hydration costs something. Loading 50k structs through Ecto allocates 50k maps with atom keys. For report generation, Repo.query/2 returning tuples is measurably cheaper — often 2–4× less allocation, not 2–4× less wall time.
  • N+1 is a design problem, not a library problem. Ecto’s preload/3 and Ash’s load both solve it; neither will save you if the code path was written one row at a time.
  • Migrations are the real risk. Ash generates Ecto-compatible migrations, so you can adopt it incrementally — but only if you commit the generated files, never mix ash.codegen in CI.

A docker-compose.yml that matches what these libraries expect in development:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: billing
      POSTGRES_PASSWORD: billing
      POSTGRES_DB: billing_dev
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    command:
      - "postgres"
      - "-c"
      - "max_connections=200"
      - "-c"
      - "shared_buffers=512MB"
volumes:
  pgdata:

Migration Paths and Common Traps

Trap 1 — Adopting Ash on a mature Ecto schema. Ash can map existing tables, but its action model assumes writes go through actions. If half your code still calls Repo.update/2, policies silently do not apply. Either migrate write paths fully or not at all.

Trap 2 — Using Repo.query everywhere to “avoid overhead.” You lose telemetry events, so your latency dashboards go blind exactly where the hot path is. If you drop to raw SQL, wrap it in a function that emits your own telemetry.

Trap 3 — Multi-tenancy by accident. Ecto’s prefix option is per-query; forget it once and you read another tenant’s rows. Ash’s tenant is part of the action context, which is why teams with strict isolation requirements migrate toward it.

Trap 4 — Migrations that lock. ALTER TABLE ... ADD COLUMN ... DEFAULT is safe on modern Postgres, but CREATE INDEX without CONCURRENTLY on a 50M-row table will take your API down. Use @disable_ddl_transaction true and @disable_migration_lock true for those.

Trap 5 — Testing against a different database. SQLite in tests and Postgres in production hides exactly the bugs you care about (concurrent index creation, JSONB operators, ON CONFLICT semantics). Run the real thing in CI.

If you are wiring authentication on top of these layers, the Elixir authentication comparison of Guardian, Ueberauth and Pow covers how each interacts with your user schema and session model — a decision that is much harder to reverse than the ORM choice.

FAQ

Is Ash worth it over Ecto for a small project? Usually no. Ash’s value scales with the number of resources and the complexity of authorization. Below roughly 15–20 tables with simple roles, the DSL overhead exceeds the code it saves.

Can I use Ash and Ecto together? Yes — AshPostgres is built on Ecto. You can keep Ecto schemas for legacy tables and expose Ash resources over new ones, provided writes to the legacy tables stay in Ecto and you do not expect Ash policies to govern them.

Is raw Postgrex faster than Ecto? For large result sets, yes — mostly because you skip struct hydration and changeset casting. For typical single-row CRUD, the difference is noise compared to network round-trip and index behaviour.

How do I handle multi-tenancy with Ecto? Use Postgres schemas with the prefix option, or a tenant_id column enforced by a repository wrapper. Whichever you choose, enforce it in one place and add a test that fails if the filter is missing.

Does Ash lock me into its migration format? No. mix ash.codegen produces standard Ecto migrations you own and can edit. The commitment is to keeping generated files in version control rather than regenerating them in CI.

Which one should a Phoenix team start with in 2026? Ecto. Add Ash only when policy complexity becomes the dominant cost, and add raw SQL only for queries where the DSL actively obscures intent.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com