Repository navigation
Description
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
-
Run Appwrite 2.3.0 with
_APP_DB_ADAPTER=postgresqland enablepg_stat_statements. -
Read one row once so it is cached, then reset the statistics:
SELECT pg_stat_statements_reset(); -
Send N anonymous requests
GET /v1/tablesdb/{db}/tables/{table}/rows/{rowId}. -
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
SETbefore and aRESETafter 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
$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_timeoutsent on each PDO connection. - It sends
SET statement_timeoutonly when the value changes and never sendsRESET. - Inside transactions
SET LOCALstays 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_timeoutonly on change and drop theRESET. - 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
SETand the statement in one round trip: a multi-statement simple query, or a transaction-scopedSET LOCALonly 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_timeoutbefore each statement has been in the adapter since 0.33.0; theRESETafter 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
SETcan leak to other clients or be lost between transactions. Installs behind such a pooler needSET LOCALinside 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):
- π Bug Report: Two uncached team queries on every API requestΒ #14077 β every request runs two uncached queries for the project team
- π Bug Report: Postgres insert reads back
_idwith an extra queryΒ #14078 β_idread back after every insert instead ofINSERT β¦ RETURNING - π Bug Report: Postgres adapter sends
ROLLBACKbefore everyBEGINΒ #14080 βROLLBACKbefore everyBEGIN, Postgres log flood - π Bug Report: Postgres: fulltext search never uses an indexΒ #14081 β fulltext indexes on Postgres are plain B-trees,
searchcannot use them - π Bug Report:
total=falseon list endpoints is ignoredΒ #14082 βtotal=falseon list endpoints is ignored - π Bug Report: Pool adapter checks out a connection for every capability getterΒ #14083 β pool adapter checks out a connection for constant capability getters
- π Bug Report: Usage queue backlog evicts the cache from RedisΒ #14084 β usage queue backlog evicts the cache in the shared Redis
- π Bug Report: PostgreSQL adapter never uses the
_uidindex β every create, get and update by row ID scans the whole tableΒ #14075 β Postgres adapter never uses the_uidindex (collation)
π² 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?
- I have read the Code of Conduct
Activity
[-]π 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[/+]