The local Postgres emulator runs every client connection in one session, so while one connection has a transaction open, every other connection waits and new connections cannot start
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Error
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- postgres, typescript
Línea de trabajo
Start with packages/1-prisma-cloud/0-lowering/dev-emulators/src/postgres-main.ts and @electric-sql/pglite-socket's packages/pglite-socket/src/index.ts, especially processQueue. Run the provided sessions.mjs reproduction against the PGlite socket and a real Postgres to compare connection behavior. Done requires an agreed emulator direction and verification that separate sessions or an explicit, timely error and documentation address the reported behavior.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
What is wrong
prisma dev gives each Database resource a local Postgres. That Postgres accepts up to 10 client connections, but it runs all of them in one Postgres session: PGlite's only session. A real Postgres, and hosted Prisma Postgres, gives each connection its own session. Measured on 2026-09-30 with plain pg against a running prisma dev stack:
- Every connection reports the same backend process id, 42.
- A setting made on connection A is visible on connection B.
- While A has a transaction open, a query on B gets no answer until A commits.
- While A has a transaction open, a new connection C cannot finish connecting.
pggives up with "timeout expired".
Who it hurts: every application on prisma dev in which one connection holds a transaction while other code in the same process needs the database.
- The Prisma ORM's first transaction on a new client reads the contract marker over a second connection. On the emulator it fails after 20 s with
CONTRACT.MARKER_READ_FAILED, caused by "Connection terminated due to connection timeout". On a real Postgres it answers in under 100 ms. The ORM team is changing its side (prisma/orm#30332), but any library or application code that does the same thing will fail the same way. - A request that holds a transaction stops every other request, cron job and worker on the local stack until it commits. With the ORM's default 20 s connect timeout, the others fail.
- Behaviour differs from production in both directions. Code that is correct on Postgres fails locally, and code that depends on shared session state (a
SET, a prepared statement, a temporary table) works locally and breaks in production.
Asks, an application built on Composer and Prisma 8, hit this when its seed script began to write rows in one transaction as its first query. It works around it by running one ordinary query before the first transaction. Asks has also recorded two earlier symptoms of the same shared session: named prepared statements that collide between connections, and the unnamed prepared statement ("") of one connection replaced by another's under concurrent load (bind message supplies 1 parameters, but prepared statement "" requires 0, SQLSTATE 08P01). Those are not reproduced below, but the root cause is the one this issue describes.
Background: how the local Postgres is built
- Composer's Postgres emulator daemon (
postgres-main, in@prisma/composer-prisma-cloud) starts one@prisma/devserver perDatabaseresource withstartPrismaDevServer(...). @prisma/dev0.25.2 opens one PGlite database per server and puts a TCP server in front of it:PGLiteSocketServerfrom@electric-sql/pglite-socket0.1.3, created withmaxConnections: 10.- PGlite is Postgres compiled to WebAssembly. It is one backend with one session. It cannot give two connections separate sessions.
PGLiteSocketServerkeeps each client socket open and sends every protocol message from every socket, including a new connection's startup message, through one shared queue into that session. When the session is inside a transaction, the queue only takes messages from the connection that sent the last message. All other messages, including startup messages, wait until the transaction ends.
How to get the code
- Composer:
git clone https://github.com/prisma/composer.git. The daemon ispackages/1-prisma-cloud/0-lowering/dev-emulators/src/postgres-main.ts; it callsstartPrismaDevServerat line 598 onmainat commit 58e858b3. The newest published@prisma/composer-prisma-cloudis 0.25.0, which depends on@prisma/dev^0.25.2. Asks runs 0.21.0 with the same@prisma/dev0.25.2. @prisma/dev0.25.2 is on npm. Itspackage.jsonnames no source repository. It pins@electric-sql/pglite0.4.3 and@electric-sql/pglite-socket0.1.3.@electric-sql/pglite-socket:git clone https://github.com/electric-sql/pglite.git, filepackages/pglite-socket/src/index.ts. The newest published version, 0.2.11, has the same queue code (processQueueis unchanged; only SSL and cancel request handling and a default changed).
Reproduction
You need Node 24 and pnpm 10. Part A needs nothing else. Part B needs a running prisma dev stack. Part C runs the same script against a real Postgres for comparison and needs Docker.
package.json:
{
"name": "emulator-session-repro",
"private": true,
"type": "module",
"dependencies": {
"@electric-sql/pglite": "0.4.3",
"@electric-sql/pglite-socket": "0.1.3",
"pg": "8.22.0"
}
}
pglite-server.mjs, the same server @prisma/dev 0.25.2 starts, over an in-memory database:
import { PGlite } from '@electric-sql/pglite';
import { PGLiteSocketServer } from '@electric-sql/pglite-socket';
const db = await PGlite.create();
const server = new PGLiteSocketServer({ db, port: 55433, maxConnections: 10 });
await server.start();
console.log(`PGlite socket server on ${server.getServerConn()}`);
sessions.mjs:
import pg from 'pg';
const url = process.env.DATABASE_URL;
const started = Date.now();
const log = (message) => console.log(`[${String(Date.now() - started).padStart(6)} ms] ${message}`);
const timeout = (ms, label) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(`${label}: no answer after ${ms} ms`)), ms));
async function open(name) {
const client = new pg.Client({ connectionString: url, connectionTimeoutMillis: 5000 });
await client.connect();
const { rows } = await client.query('select pg_backend_pid() as pid');
log(`${name} connected, backend pid ${rows[0].pid}`);
return client;
}
const a = await open('A');
const b = await open('B');
await a.query("set repro.owner = 'A'");
const seen = await b.query("select current_setting('repro.owner', true) as owner");
log(`A: set repro.owner = 'A'; B reads repro.owner = ${JSON.stringify(seen.rows[0].owner)}`);
await a.query('reset repro.owner');
await a.query('begin');
log('A: begin');
try {
await Promise.race([b.query('select 1 as one'), timeout(5000, 'B: select 1')]);
log('B: select 1 answered while A is in a transaction');
} catch (error) {
log(error.message);
}
try {
const c = await open('C');
await c.end();
} catch (error) {
log(`C: connect failed while A is in a transaction: ${error.message}`);
}
await a.query('commit');
log('A: commit');
await b.end().catch(() => undefined);
const d = await open('D');
await d.end();
await a.end();
Install once:
pnpm install --ignore-workspace
A. The socket server on its own
node pglite-server.mjs &
# wait for "PGlite socket server on 127.0.0.1:55433"; it took 13 s here
DATABASE_URL=postgres://postgres:postgres@localhost:55433/postgres node sessions.mjs
kill %1
[ 185 ms] A connected, backend pid 42
[ 209 ms] B connected, backend pid 42
[ 212 ms] A: set repro.owner = 'A'; B reads repro.owner = "A"
[ 215 ms] A: begin
[ 5221 ms] B: select 1: no answer after 5000 ms
[ 10228 ms] C: connect failed while A is in a transaction: timeout expired
[ 10231 ms] A: commit
[ 10247 ms] D connected, backend pid 42
B. A prisma dev stack
Take the URL of a running stack's database from ~/.prisma-composer/emulators/postgres/apps.json, key <app name>.databases.<database id>.url. The script holds a transaction for 10 s, and during that time the whole local database answers no one else.
DATABASE_URL='postgres://postgres:postgres@localhost:51401/template1?sslmode=disable' node sessions.mjs
[ 14 ms] A connected, backend pid 42
[ 18 ms] B connected, backend pid 42
[ 22 ms] A: set repro.owner = 'A'; B reads repro.owner = "A"
[ 33 ms] A: begin
[ 5037 ms] B: select 1: no answer after 5000 ms
[ 10046 ms] C: connect failed while A is in a transaction: timeout expired
[ 10048 ms] A: commit
[ 10075 ms] D connected, backend pid 42
C. A real Postgres, for comparison
docker run --rm -d --name emulator-compare-pg -e POSTGRES_PASSWORD=postgres -p 55499:5432 postgres:15
DATABASE_URL=postgres://postgres:postgres@localhost:55499/postgres node sessions.mjs
docker stop emulator-compare-pg
[ 34 ms] A connected, backend pid 4923
[ 42 ms] B connected, backend pid 4924
[ 43 ms] A: set repro.owner = 'A'; B reads repro.owner = null
[ 43 ms] A: begin
[ 44 ms] B: select 1 answered while A is in a transaction
[ 48 ms] C connected, backend pid 4925
[ 49 ms] A: commit
[ 55 ms] D connected, backend pid 4926
(Part C's output was taken on an existing Postgres 15 container; the process ids will differ.)
Expected behaviour
The local Postgres behaves like the hosted one: each connection has its own session, B reads null, B's query answers while A's transaction is open, and C connects.
If PGlite has to stay, a connection that must wait for another connection's transaction should get a clear error within a few seconds, instead of silence until the client's own connect or query timeout.
Cause
@prisma/dev 0.25.2 creates the server with ten connections over one PGlite instance (minified dist/chunk-MGHBCHO2.js, where connectionLimit is 10):
new u({db:s,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:p.connectionLimit,port:a})
@electric-sql/pglite-socket 0.1.3, src/index.ts. Every complete message from a socket, including the startup message, goes into the shared queue (line 350 recognises the startup message, line 393 enqueues it):
await this.queryQueue.enqueue(
this.id,
new Uint8Array(message),
The queue runs one message at a time in the single session. While the session is in a transaction, it only takes the next message from the connection that sent the last one, and stops when there is none (lines 68 to 126):
private async processQueue(): Promise<void> {
// ...
while (this.queue.length > 0) {
let query
if (this.db.isInTransaction() && this.lastHandlerId) {
const i = this.queue.findIndex(
(q) => q.handlerId === this.lastHandlerId,
)
if (i === -1) {
// we didn't find any other query from the same client!
// ...
query = null
} else {
query = this.queue.splice(i, 1)[0]
}
} else {
query = this.queue.shift()
}
if (!query) break
// ...
await this.db.runExclusive(async () => {
return await this.db.execProtocolRawStream(query.message, {
This is the correct choice inside pglite-socket: with one session, letting another connection's statements run inside A's transaction would be worse. The problem is that the emulator presents one session as ten connections, so clients that rely on separate sessions wait on each other, and nothing tells them why.
Recommendation
- Decide whether the local Postgres should be a real Postgres server. That is the only way to give each connection its own session, as hosted Prisma Postgres does, and it removes this issue and the prepared statement collisions together. It costs install size, start-up time and platform support, so it is a product decision for the Composer team.
- Whatever the decision on (1), make the wait visible now. In the emulator's socket layer, when a message has waited behind another connection's open transaction for more than a few seconds (5 s is enough for local work), answer the waiting connection with a Postgres
ErrorResponsewhose message names the cause, for example "the local Postgres emulator runs all connections in one session, and connection 3 has had a transaction open for 5 s". Write the same line to the emulator's log. This needs a wrapper or fork ofPGLiteSocketServer's queue, or a change upstream in@electric-sql/pglite-socket. - Document the one-session model in Composer's local development guide: session settings, prepared statements and temporary tables are shared between connections, and an open transaction stops all other connections, including new ones.
Acceptance criteria
- If (1) is chosen:
sessions.mjsagainst aprisma devdatabase prints a different backend process id for each connection,B reads repro.owner = null,B: select 1 answered while A is in a transactionandC connected. A test in Composer's emulator suite runs the same steps. - If only (2) and (3) are done: in
sessions.mjs, B's query and C's connection fail within the chosen limit with an error that names the other connection's open transaction; the emulator log shows the same message; the local development guide has a section on the one-session model. A test in Composer's emulator suite checks the error. - Either way, the Prisma ORM case (a client whose first work is a transaction, with prisma/orm#30332 not applied) fails within the chosen limit with that message, or answers, instead of failing after 20 s with a connect timeout.
Out of scope
- The Prisma ORM's marker read over a second connection: prisma/orm#30332 and a separate Prisma ORM issue.
Found while building Asks (prisma/asks). Agent: tyr-16
- Lenguaje dominante
- TypeScript
- Estrellas
- 6
- Forks
- 2
- Merge medio
- 1 d 9 h
- PR fusionados (30 d)
- 42
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de prisma/composer
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 90/100
Los mantenedores suelen responder en 1 día
-
@prisma/composer-prisma-cloud 0.36.0 peer-pins @prisma/orm-postgres 8.0.0-rc.20, so it cannot be installed next to the current ORM rc.22 without --legacy-peer-depsQuizá libre de nuevo Un pull request para esta issue se cerró sin fusionarse. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 45/100
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 4/5 1-2 días Aptitud para principiantes 53/100
Los mantenedores suelen responder en 1 día
-
enhancement
Dificultad 4/5 3-5 días Aptitud para principiantes 42/100
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 3-5 días Aptitud para principiantes 52/100
Los mantenedores suelen responder en 1 día
Todos los issues de prisma/composer
Issues similares
-
dream report: normalizeMutation discards ok/status, consumers can only string-match the summaryAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
thecodacus/understory#61 ·
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Termix-SSH/Plugin-Hosts-Config#14 · 1 comentario ·
Los mantenedores suelen responder en 4 días
-
ai-generated priority: p2 size: s type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
JonathanTSilva/jts-website#92 ·
Los mantenedores suelen responder en 1 día
-
Toast announcer reads a doubled period when a toast's title ends in punctuationPosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 88/100
vercel-labs/ui#999 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
ehmpathy/rhachet-roles-ehmpathy#1443 ·
Los mantenedores suelen responder en 1 día