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

オープン
#329 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
postgres, typescript
領域
backend, databases

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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. pg gives 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/dev server per Database resource with startPrismaDevServer(...).
  • @prisma/dev 0.25.2 opens one PGlite database per server and puts a TCP server in front of it: PGLiteSocketServer from @electric-sql/pglite-socket 0.1.3, created with maxConnections: 10.
  • PGlite is Postgres compiled to WebAssembly. It is one backend with one session. It cannot give two connections separate sessions.
  • PGLiteSocketServer keeps 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 is packages/1-prisma-cloud/0-lowering/dev-emulators/src/postgres-main.ts; it calls startPrismaDevServer at line 598 on main at commit 58e858b3. The newest published @prisma/composer-prisma-cloud is 0.25.0, which depends on @prisma/dev ^0.25.2. Asks runs 0.21.0 with the same @prisma/dev 0.25.2.
  • @prisma/dev 0.25.2 is on npm. Its package.json names no source repository. It pins @electric-sql/pglite 0.4.3 and @electric-sql/pglite-socket 0.1.3.
  • @electric-sql/pglite-socket: git clone https://github.com/electric-sql/pglite.git, file packages/pglite-socket/src/index.ts. The newest published version, 0.2.11, has the same queue code (processQueue is 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

  1. 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.
  2. 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 ErrorResponse whose 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 of PGLiteSocketServer's queue, or a change upstream in @electric-sql/pglite-socket.
  3. 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.mjs against a prisma dev database prints a different backend process id for each connection, B reads repro.owner = null, B: select 1 answered while A is in a transaction and C 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

主要言語
TypeScript
スター
6
フォーク
2
平均マージ
1日 9時間
マージ済み PR(30日)
42

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

prisma/composer のほかの issue

prisma/composer の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。