Skip to content

πŸ› Bug Report: Postgres adapter sets and resets statement_timeout around every queryΒ #14079

Open

Description

@JoshiJoshiJoshi

In short: Before each database query the Postgres adapter sets a timeout and afterwards resets it, so one query becomes three round trips to the database, even though the timeout value never changes.

Impact:

  • Postgres receives 2–3Γ— as many statements as needed (βˆ’49 to βˆ’66 % with the change).
  • Each round trip adds latency; with the database on another host this adds up quickly (a cached read makes β‰ˆ 14 sequential round trips today).
  • Throughput gain in our setup was small (the API CPU was the limit), the main win is less database load and latency.

πŸ‘Ÿ Reproduction steps

  1. Run Appwrite 2.3.0 with _APP_DB_ADAPTER=postgresql and enable pg_stat_statements.

  2. Read one row once so it is cached, then reset the statistics: SELECT pg_stat_statements_reset();

  3. Send N anonymous requests GET /v1/tablesdb/{db}/tables/{table}/rows/{rowId}.

  4. SELECT calls, left(query, 100) FROM pg_stat_statements ORDER BY calls DESC LIMIT 5;

    2N  RESET statement_timeout
    2N  SET statement_timeout = $1
     N  SELECT … _console_keys …
     N  SELECT … _console_teams …
    

    Every real query is wrapped in a SET before and a RESET after it.

πŸ‘ Expected behavior

The statement timeout is applied once per connection, or only when its value changes. A query costs one round trip, not three.

πŸ‘Ž Actual Behavior

Summary

Postgres::execute() wraps every prepared statement that runs outside a transaction like this:

  • before it: SET statement_timeout = '<n>ms'
  • after it: RESET statement_timeout

Inside a transaction it adds SET LOCAL statement_timeout before every statement.

The effect: every query outside a transaction costs three round trips instead of one, and every query inside a transaction costs two. This happens even when the timeout is 0 and even though the value never changes between statements.

Cause

Postgres.php#L65-L85:

$sql = $this->inTransaction === 0
    ? "SET statement_timeout = '{$this->timeout}ms'"
    : "SET LOCAL statement_timeout = '{$this->timeout}ms'";
$pdo->exec($sql);
try {
    return $stmt->execute();
} finally {
    if ($this->inTransaction === 0) {
        $pdo->exec("RESET statement_timeout");
    }
}

Impact measured through the Appwrite API

Setup: Postgres on its own 4 vCPU node, two API nodes with 4 vCPU each, oha, 10 s per step. The usage queue was empty before each run.

The patch keeps the timeout semantics:

  • It remembers the last statement_timeout sent on each PDO connection.
  • It sends SET statement_timeout only when the value changes and never sends RESET.
  • Inside transactions SET LOCAL stays as is.
Request Concurrency req/s before β†’ after p50 / p99 before β†’ after (ms) Postgres statements/s before β†’ after CPU Postgres node before β†’ after
Get row (cached, anonymous) 20 2,073 β†’ 2,102 9.5 / 19.3 β†’ 9.1 / 24.6 10,491 β†’ 3,552 58 β†’ 54 %
Get row (cached, anonymous) 80 2,286 β†’ 2,427 30.4 / 138.0 β†’ 30.3 / 148.9 12,472 β†’ 4,552 65 β†’ 57 %
List rows (25 rows + total) 20 1,337 β†’ 1,515 (+13 %) 16.2 / 28.1 β†’ 13.0 / 31.8 14,524 β†’ 5,427 70 β†’ 63 %
List rows (25 rows + total) 80 1,654 β†’ 1,680 44.5 / 154.2 β†’ 46.2 / 123.8 18,087 β†’ 6,119 83 β†’ 75 %
Create row 20 1,150 β†’ 1,208 17.2 / 41.2 β†’ 15.5 / 36.2 9,116 β†’ 4,613 72 β†’ 69 %
Create row 80 1,602 β†’ 1,531 43.7 / 159.0 β†’ 49.2 / 146.7 11,920 β†’ 5,770 85 β†’ 81 %

Statements per second dropped by 49–66 %, and CPU on the Postgres node by 3–8 points. Throughput changed by βˆ’4 % to +13 %, because in our setup the API nodes were the CPU limit (85–100 %). The change mainly frees database capacity and saves one round trip per statement (β‰ˆ 0.3–0.5 ms on a remote database host). That matters most where a request runs several queries.

Combined with the Appwrite-side fix for the team lookup (#14077), cached reads gained +33 to +36 %.

Sensitivity to network latency. The round trips matter most when the database is not on the same host. We added artificial latency to the replies from the database/Redis node to the API nodes (tc netem) and measured at 20 concurrent requests. The "fewer round trips" column has this fix, the team fix, INSERT … RETURNING and the pool-getter fix applied together, so it is not this fix alone:

Request Added latency req/s as shipped p50 as shipped req/s fewer round trips p50 fewer round trips
Get row (cached) 0 ms 1,722 11.2 ms 2,884 6.0 ms
Get row (cached) +2 ms 482 39.8 ms 784 24.2 ms
Create row 0 ms 1,142 17.3 ms 1,410 12.5 ms
Create row +2 ms 308 63.3 ms 416 46.0 ms

As shipped, the p50 of a cached read grows by β‰ˆ 14 ms per added millisecond of latency, so the request makes about 14 sequential round trips. A single-row create makes about 23. With fewer round trips it is about 9 and 17.

Suggested fix

Apply the session timeout once per connection, or only when it changes:

  • Track the value last set on the connection (or in the pool wrapper, close to fix: hold pooled timeouts on the pool, not on a connectionΒ utopia-php/database#945). Send SET statement_timeout only on change and drop the RESET.
  • When a connection goes back to the pool with a non-default value, reset it once at that point instead of after every statement.
  • Alternatively, send SET and the statement in one round trip: a multi-statement simple query, or a transaction-scoped SET LOCAL only for statements that really have a timeout.

The MariaDB adapter avoids the extra round trip with SET STATEMENT max_statement_time=… FOR ….

Since when / regression?

Version numbers refer to utopia-php/database unless an Appwrite version is named.

  • SET statement_timeout before each statement has been in the adapter since 0.33.0; the RESET after each statement since 0.69.3.
  • All Appwrite releases with the Postgres adapter (2.0.0 with 7.3.4 onwards) are affected. It is not a regression.

Risks / things to consider for the fix

  • Remember the value per physical connection, not per adapter handle. One pooled connection serves handles with different timeouts (e.g. platform database without timeout, project database with 15 s). A compare-before-set on the connection covers that.
  • After a reconnect the server-side value is unknown again. The remembered value has to be dropped together with the old connection.
  • PgBouncer in transaction pooling mode: a session-level SET can leak to other clients or be lost between transactions. Installs behind such a pooler need SET LOCAL inside a transaction, or the timeout set on the role or database instead. This could be a configuration switch.
  • A statement that times out must not leave a changed timeout behind for the next user of the connection.

Related: utopia-php/database#945 (timeouts held on the pool), #14075 (same test setup).

Related issues from the same analysis (Appwrite 2.3.0 with Postgres, same test setup):

🎲 Appwrite version

Version 2.3.0 (self-hosted)

πŸ’» Operating system

Linux (Debian 12, Docker 29.8)

🧱 Your Environment

Self-hosted Appwrite 2.3.0 with _APP_DB_ADAPTER=postgresql, PostgreSQL 18.3 (appwrite/postgres:0.1.0), utopia-php/database 7.3.11. Test setup: Postgres, Redis and ClickHouse on one 4 vCPU node, the API on two separate 4 vCPU nodes, load from oha. The code in question lives in utopia-php/database; filed here because it ships with Appwrite and affects every Appwrite install that uses Postgres. Related test setup: #14075.

πŸ‘€ Have you spent some time to check if this issue has been raised before?

  • I checked and didn't find similar issue

🏒 Have you read the Code of Conduct?

Activity

  1. added
    product / auth
    product / console
    product / databases
    product / self-hosted
    product / storage
    sdk / cli
    on Oct 3, 2026
  2. changed the title [-]πŸ› Bug Report: Postgres adapter sends `SET statement_timeout` + `RESET statement_timeout` around every query – three round trips per query[/-] [+]πŸ› Bug Report: Postgres adapter sets and resets `statement_timeout` around every query[/+] on Oct 4, 2026
  3. removed
    product / storage
    product / auth
    product / console
    product / self-hosted
    sdk / cli
    on Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    product / databases

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions