What is a shared database library in an Nx Prisma monorepo?
A shared database library is a single Nx library that owns everything Prisma needs for one database. It holds one schema.prisma, one migrations directory and the generated shared Prisma client. Services never declare models or run migrations themselves. They import the client from the library, and Nx project boundaries make that import the only route to the database. If a monorepo talks to two databases, it has two such libraries, one per database.
+-----------+ +-----------+ +-----------+
| orders-api| | billing | | worker |
+-----+-----+ +-----+-----+ +-----+-----+
| import | import | import
v v v
+---------------------------------------------+
| libs/data-access-db |
| schema.prisma migrations/ |
| generated shared Prisma client |
+----------------------+----------------------+
|
v
+-------------+
| PostgreSQL |
+-------------+
This pattern fits when services read and write the same tables. With a schema per service, each service keeps its own copy of the shared models. When someone adds a column, they have to update every copy. The copies drift apart over time, and whichever service ran its migrations last decides what the real database looks like. Generated types stop matching the actual tables, and you find out at runtime.
A single schema avoids this. A model change happens in one place and produces one migration. It also regenerates one client, so the type checker immediately flags every consumer the change breaks.
The pattern suits backend and platform teams that run several services, workers or scheduled jobs against one database they deliberately share. In that setup, a single owner for the schema reflects how the system already works.
+--------------+ +--------------+ +--------------+
| orders-api | | billing-api | | worker |
+------+-------+ +------+-------+ +------+-------+
| | |
+------------------+------------------+
| import client only
| (no models, no migrations)
- - - - - - - - - - - - - | - - - - - - - - - - - - - Nx project boundary
v
+---------------------------------------------------+
| libs/data-access-db |
| |
| schema.prisma (one per database) |
| | |
| +-- prisma migrate dev --> migrations/ |
| | |
| +-- prisma generate -----> shared Prisma client |
+--------------------------+------------------------+
|
| migrations applied,
| queries via the client
v
+-------------+
| PostgreSQL |
+-------------+
Every service imports the client from one data-access library across the Nx project boundary. That library owns the single schema.prisma, its migrations and the generated Prisma client for the database.
How should you structure the data-access library?
Keep everything the database owns inside one library, for example libs/data-access/db. Put prisma/schema.prisma and prisma/migrations/ there, next to a src/ folder. The schema and its migration history then travel together in code review, and any change to either one is a change to that project in the Nx graph.
Set the generator's output to a path inside the library, such as libs/data-access/db/src/generated, so the client is not written to root node_modules. When the client lands in node_modules, it sits outside the project graph. Nx cannot see that it depends on the schema, caching cannot account for it, and two services can silently run against whichever client was generated last. A path inside the library makes the generated code a visible output that you can cache and invalidate.
The entry point src/index.ts should stay thin. It should export a createPrismaClient factory, connect and disconnect helpers for startup and graceful shutdown, and the generated types. Services should never import from generated/ directly. That way you can change the output path or wrap the client without touching consumers.
Where custom output locations break
- Stale or wrong client. If generate does not run before build, a service bundles a client from an older schema. It compiles and then fails at runtime.
- Bundlers dropping files. Some bundlers do not follow the generated client's runtime file loading. You may need to mark it external or copy it as an asset.
- Docker and query engines. Multi-stage builds can leave out the generated folder. A client generated on a developer machine may also lack the engine binary for the container's platform. Declare
binaryTargetsexplicitly, and run generate inside the build image.
# Folder layout: schema, migrations and generated client all live in one Nx project
libs/data-access/db/
├── project.json
├── prisma/
│ ├── schema.prisma
│ └── migrations/
│ ├── 20240101000000_init/
│ │ └── migration.sql
│ └── migration_lock.toml
└── src/
├── index.ts # thin public API: createPrismaClient, connect, disconnect, types
├── client.ts # factory and lifecycle helpers wrap the generated client
└── generated/ # prisma generate writes here; do not import directly from services
# libs/data-access/db/prisma/schema.prisma
generator client {
provider = "prisma-client-js"
// Relative to this schema file, so the output lands in src/generated, not root node_modules
output = "../src/generated"
// "native" covers the dev machine. The others cover Debian- and Alpine-based containers.
// Each target must match the OpenSSL version actually installed in the runtime image.
binaryTargets = ["native", "debian-openssl-3.0.x", "linux-musl-openssl-3.0.x"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL") // e.g. postgresql://app:changeme@localhost:5432/app
}
model User {
id Int @id @default(autoincrement())
email String @unique
}
The library layout keeps schema.prisma, the migrations folder and the generated client in one Nx project, and the generator block sets a library-relative output path and lists binaryTargets explicitly so container builds get a matching query engine.
How do you wire Prisma generate and migrations as Nx targets?
…as an Nx target rather than a manual step.
On the data-access library, define five targets, each wrapping one Prisma CLI command through nx:run-commands: generate, migrate-dev, migrate-deploy, validate and format. Pin every command to the library's schema path so no command depends on the working directory.
Next, make every consuming service's build, test and lint targets declare dependsOn: ["^generate"]. The caret tells Nx to run generate on each dependency that defines it before the service's own target runs. Nx reads the dependency from the project graph, so a service cannot be built against a client that does not match the current schema.
generate is deterministic, so it is safe to cache. Use the schema file and the installed prisma and @prisma/client versions as inputs, the latter through an externalDependencies input. Declare the generated client directory as the output. When nothing changed, Nx restores the client from the cache in seconds. When the schema or the Prisma version changes, the cache misses and generate runs again. validate can be cached on the same inputs.
Never cache migrate-dev or migrate-deploy. Their effect is on a live database, so replaying a cached "success" against a different database would be wrong. Set cache: false on both. Leave format uncached as well, because it rewrites the schema file in place.
The dependency matters most in CI. If a pipeline skips generate, the job either fails on missing types or, worse, compiles against an old checked-in client and then fails at runtime when a query references a column the client does not know about.
Wiring generate into the task graph removes two recurring costs. Nobody has to remember to regenerate after pulling. Nobody has to spend an afternoon chasing a stale client that only fails on one machine.
{
"name": "data-access",
"targets": {
"generate": {
"executor": "nx:run-commands",
"cache": true,
"inputs": [
"{projectRoot}/prisma/schema.prisma",
{ "externalDependencies": ["prisma", "@prisma/client"] }
],
"outputs": ["{projectRoot}/src/generated/client"],
"options": { "command": "prisma generate --schema=libs/data-access/prisma/schema.prisma" }
},
"validate": {
"executor": "nx:run-commands",
"cache": true,
"inputs": [
"{projectRoot}/prisma/schema.prisma",
{ "externalDependencies": ["prisma"] }
],
"options": { "command": "prisma validate --schema=libs/data-access/prisma/schema.prisma" }
},
"format": {
"executor": "nx:run-commands",
"cache": false,
"options": { "command": "prisma format --schema=libs/data-access/prisma/schema.prisma" }
},
"migrate-dev": {
"executor": "nx:run-commands",
"cache": false,
"options": { "command": "prisma migrate dev --schema=libs/data-access/prisma/schema.prisma" }
},
"migrate-deploy": {
"executor": "nx:run-commands",
"cache": false,
"options": { "command": "prisma migrate deploy --schema=libs/data-access/prisma/schema.prisma" }
}
}
}
The data-access library's project.json: generate and validate are cached on the schema file and Prisma versions, while format and both migrate targets are never cached. Consuming services add dependsOn: ["^generate"] to build, test and lint.
How does nx affected and module boundary linting keep services honest?
…shows up in production.
Make the graph see the schema
nx affected only works if the project graph reflects how code actually depends on the database. Nx infers edges from TypeScript imports. If every service imports the client through the data-access library's path alias, a change to schema.prisma falls inside that library's project root, marks the library as affected, and every service that imports it gets rebuilt and retested. The usual way this breaks is a service importing @prisma/client directly, or a deep path into the generated output. That import produces no edge to your library, so Nx treats the service as unaffected while its types have changed. Route all access through the library's public entry point. CI then tests what the schema change actually touched.
The cost of honesty
A library imported by many services is a hub in the graph. Any schema edit, even adding a nullable column, fans out to every consumer. That is correct behavior, but CI time grows with the number of importers. Remote caching softens this for services whose compiled output doesn't change. Splitting one large schema into per-domain libraries reduces how far each change spreads.
Enforce ownership with tags
Tag each data-access library with its owner and type, for example scope:billing and type:data-access. Then add depConstraints to the @nx/enforce-module-boundaries lint rule so that projects tagged scope:orders can depend only on scope:orders and scope:shared. If an orders service imports the billing database library, lint fails before review. Each team's tables stay behind its own API.
// eslint.config.mjs (workspace root)
// Tags live in each project.json, e.g. libs/billing/data-access:
// "tags": ["scope:billing", "type:data-access"]
import nx from '@nx/eslint-plugin';
export default [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
{
files: ['**/*.ts'],
rules: {
// Fail lint when a project imports outside its allowed tags
'@nx/enforce-module-boundaries': ['error', {
depConstraints: [
{ sourceTag: 'scope:orders', onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
],
}],
// Services must use the data-access library, not the raw client,
// so the project graph gets an edge to the library and nx affected sees schema changes
'no-restricted-imports': ['error', {
paths: [{ name: '@prisma/client', message: 'Import from your scope\'s data-access library instead.' }],
}],
},
},
{
// Only data-access libraries may touch the generated Prisma client directly
files: ['libs/*/data-access/**/*.ts'],
rules: { 'no-restricted-imports': 'off' },
},
];
A root ESLint flat config that uses scope tags with @nx/enforce-module-boundaries to keep each service inside its own team's data-access library, and blocks direct @prisma/client imports so that every database dependency appears in the Nx project graph.
How do you run Prisma migrations safely across multiple services?
Schema ownership needs the same discipline at deploy time. Make one pipeline, usually the one that builds the data-access library, the only place that runs prisma migrate deploy. It runs once per environment, before any dependent service rolls out. Developers create migrations with prisma migrate dev only against the owning library's schema, so migration history stays in a single linear folder.
When several service pipelines can each apply migrations, two problems appear. First, two deploys that start at the same time can both see the same pending migration and try to apply it. Second, a service built from an older commit can deploy after a newer one and expect a schema that has already moved on. Either way, the database ends up in a state that no single commit describes.
Expand and contract
During a rolling deployment, old and new versions of a service share one database. A migration that renames or drops a column in one step breaks whichever version still uses the old shape. Split the change into phases instead:
| Phase | Migration | Application change | Old version safe? |
|---|---|---|---|
| Expand | Add nullable column or new table | None yet | Yes |
| Dual write | None | Write both fields, read old | Yes |
| Backfill | Data script copies old to new | None | Yes |
| Switch reads | None | Read new field | Yes |
| Contract | Drop old column in a later migration | Remove old code paths | No longer deployed |
Run the contract migration only after every service that touched the old field has been redeployed. Use nx affected against the schema to list those services.
How should connection strings and connection pools be configured?
The library should never know which database it talks to. Keep the datasource block in the shared schema pointing at an environment variable such as DATABASE_URL. Each service then supplies its own value at deploy time. This lets the same compiled client run against local, staging and production databases without rebuilding. Different services can also connect with different credentials, so the orders service's role does not need write access to tables it never touches. Hardcoding a URL in the library would make every consumer share one identity and one target, and the URL would end up in your build artifacts.
Shared schema, separate pools
A shared schema does not mean a shared pool. Every running process that instantiates the client opens its own pool, and the database counts every connection against one global limit. Prisma sizes the pool from the host's CPU count unless you set connection_limit in the URL.
Illustrative estimate. These inputs are assumed:
- 6 services, each running 3 replicas
- A pool size of 9 per replica
- 2 extra connections per service for migrations and admin tooling
That works out to 6 × 3 × 9 = 162 connections from the replicas, plus 12 more, for 174 total. Against a configured limit of 100, the later replicas fail to connect during a rolling deploy, when old and new pods overlap and the count grows further.
Tuning the pool or adding a pooler
Start by setting connection_limit explicitly per service, sized to its real concurrency. Most services need far fewer connections than the CPU-based default. If the replica count still pushes the total near the limit, or you run serverless functions that scale unpredictably, put an external pooler in front of the database. With a pooler in transaction mode, thousands of client connections share a small, fixed set of server connections. Point migrations at the database directly, because migrations rely on session-level behaviour that transaction pooling does not preserve.
When should you avoid a shared schema, and what are the alternatives?
A shared schema works while one team, or a few teams with a shared release rhythm, owns the data model. It stops working when the schema becomes the coupling point between services. If one team renames a column, every service importing the client sees new types and has to rebuild. A migration written for one service can lock a table another service depends on. Once services can't deploy without coordinating schema changes, the main reason for having separate services is gone.
There are three common alternatives.
One library per database. Split the schema into separate data-access libraries. Give each one its own generator output directory and its own path alias in the workspace tsconfig, so the two generated clients never overwrite each other or resolve to the same import. Because Nx tracks each library's dependents separately, nx affected narrows to the services that actually import the changed library.
Schema-per-service copies. Each service keeps its own Prisma schema, even if two of them point at the same tables. Teams get autonomy, but the copies drift unless you check them against the real database.
Service-owned databases behind APIs. Each service owns its data outright. Other services read that data through an API or consume its events, never the tables.
Splitting has costs. Prisma can't express relations or joins across separate clients, so you compose that data in application code. Shared reference data, such as countries or plans, ends up duplicated. CI also has more clients to generate.
| Option | Upfront effort | Ongoing cost | Independent deploys |
|---|---|---|---|
| Single shared schema | Low | Rises with team count | Poor |
| One library per database | Moderate | More generate targets, no cross-client joins | Good per database |
| Schema-per-service copies | Low | Drift detection, duplicated models | Good, until copies diverge |
| Service-owned DB via APIs | High | API versioning, data duplication | Best |
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nx prisma monorepo, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.