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
| Dimension | Ecto | Ash | Postgrex |
|---|---|---|---|
| GitHub stars | 6,508 | 2,575 | 1,214 |
| Last commit | 2026-11-30 | 2026-11-30 | 2026-11-30 |
| Abstraction level | Query DSL + schema mapping | Full resource framework | Wire protocol driver only |
| Migrations | Ecto.Migration | AshPostgres migrations (Ecto-compatible) | Hand-written SQL |
| Authorization | Manual (contexts, plugs) | Declarative policies per action | None |
| Multi-tenancy | Manual (prefix option) | First-class (schema or attribute) | Manual |
| Learning curve | 1–2 weeks | 3–6 weeks | Hours, but you write SQL forever |
| Escape hatch to raw SQL | Ecto.Adapters.SQL.query/4 | Same (it delegates to Ecto) | It is raw SQL |
| Best fit | General Phoenix apps | Large CRUD domains, SaaS platforms | ETL, 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 case | Recommendation | Why |
|---|---|---|
| Standard Phoenix SaaS, <30 tables | Ecto | Fastest path, best docs, easiest hiring |
| Multi-tenant B2B product with role-based access | Ash | Policies and tenant scoping are built in, not bolted on |
| Nightly aggregation job reading 200M rows | Postgrex (or Ecto.Adapters.SQL) | Cursor-based streaming, no schema hydration cost |
| Public API over an existing legacy database | Ash | Declarative interfaces can wrap tables you cannot migrate |
| Team of Elixir newcomers | Ecto | Ash’s DSL is powerful precisely because it is opinionated |
| Hybrid: product on Ecto, analytics on raw SQL | Ecto + Postgrex | Same 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.
| |
A typical schema and changeset:
| |
Migrations are versioned files, not diffs against live state — which is exactly what you want when three branches deploy in the same week:
| |
Where Ecto pays off is composition. Ecto.Multi gives you an explicit, testable transaction script instead of nested Repo.transaction calls buried in contexts:
| |
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 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.
| |
Reading is action-based rather than query-based, which is the philosophical divide:
| |
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.
| |
Two things to know before you consider this the “fast path” everywhere:
- You lose changesets, so you lose the validation boundary. Every caller must be trusted to send valid data, or you rebuild casting by hand.
- 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/2returning 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/3and Ash’sloadboth 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.codegenin CI.
A docker-compose.yml that matches what these libraries expect in development:
| |
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