Repository navigation
Description
In short: After inserting a row, the Postgres adapter runs a second query just to learn the row's internal ID. Postgres could return that ID from the insert itself. Because of #14075 that second query reads the whole table.
Impact:
- On a table with 1.5 M rows, single-row creates went from 31–55 to 1,100–1,500 per second (×26–36) with the change.
- Write latency dropped from ≈ 0.8 s to ≈ 17 ms (p50).
- Even with the collation fixed, it would still be one unnecessary query per insert.
👟 Reproduction steps
-
Run Appwrite 2.3.0 with
_APP_DB_ADAPTER=postgresqland a table with ≈ 1 M rows. -
Enable statement logging:
ALTER SYSTEM SET log_statement = 'all'; SELECT pg_reload_conf(); -
Create one row:
POST /v1/tablesdb/{db}/tables/{table}/rows. -
After the
COMMIT, the log shows a second statement:SELECT _uid, _id FROM "appwrite"."_1_database_1_collection_2" WHERE "_uid" IN ('…')
-
EXPLAIN ANALYZEof that statement shows aParallel Seq Scanover the whole table, because of the collation issue in 🐛 Bug Report: PostgreSQL adapter never uses the_uidindex – every create, get and update by row ID scans the whole table #14075.
👍 Expected behavior
The generated _id comes back from the insert itself (INSERT … RETURNING "_uid", "_id"), without a second query per write.
👎 Actual Behavior
Summary
Database::createDocuments() calls Adapter::getSequences() after the insert whenever an $onNext callback is set or the collection has relationships (Database.php#L5983). Appwrite sets $onNext even for a single createRow.
getSequences() then runs a second statement to find the auto-generated _id values (SQL.php#L860, L897):
SELECT _uid, _id FROM "<table>" WHERE "_uid" IN (…)PostgreSQL can return these values from the insert itself: INSERT … RETURNING "_uid", "_id". That saves one statement per batch.
Because of #14075 (the _uid index carries collation utf8_ci_ai, the query compares without it), this lookup is currently a sequential scan of the whole table on every insert. On large tables it is the dominant cost of a write.
Impact measured through the Appwrite API
Single-row creates (POST /v1/tablesdb/{db}/tables/{table}/rows, API key) on a table with ≈ 1.5 M rows (it grew from 1.4 M to 1.6 M during the runs), without any manually added index. The usage queue was empty before each run.
The patch (createDocuments() in SQL.php) works as follows for the Postgres adapter:
- It appends
RETURNING "_uid", "_id"to the insert (insert at SQL.php#L2530-L2540). - It sets
$sequenceon each document from the result. getSequences()then skips the lookup by itself, because every document already has a sequence.
| Concurrency | rows/s before | rows/s after | p50 before → after | p99 before → after | CPU Postgres node |
|---|---|---|---|---|---|
| 20 | 31 | 1,111 | 777 ms → 17.1 ms | 1,086 ms → 48.7 ms | 96 → 69 % |
| 80 | 42 | 1,540 | 2,314 ms → 44.7 ms | 3,031 ms → 254 ms | 95 → 80 % |
| 160 | 55 | 1,433 | 2,736 ms → 108.5 ms | 5,912 ms → 331 ms | 95 → 78 % |
Tuples read per write dropped from ≈ 1.4–1.5 M to 5–7. Before the patch the API nodes idled (4–5 % CPU) while Postgres scanned. After the patch they were the limit (93–96 %). Write throughput was then at the level of an install with an extra plain index on _uid (the workaround from #14075).
Suggested fix
- Postgres (and SQLite ≥ 3.35, MariaDB ≥ 10.5): add
RETURNING "_uid", "_id"to the insert increateDocuments()and set$sequencefrom the result. KeepgetSequences()as a fallback for adapters withoutRETURNING. - With
skipDuplicates(ON CONFLICT DO NOTHING),RETURNINGonly returns inserted rows. The existing fallback ingetSequences()still covers documents without a sequence. - With shared tables the batch belongs to one tenant, so matching on
_uidis unambiguous.
This complements the collation fix in #14075 but does not replace it: getDocument() and the permission cleanup still look up by _uid/_document.
Since when / regression?
Version numbers refer to utopia-php/database unless an Appwrite version is named.
getSequences()has existed since 0.71.0 and has been called after every insert with$onNextin all Appwrite releases with the Postgres adapter (2.0.0 onwards).- The extra statement only becomes a full table scan because of the
_uidcollation (since 3.0.0, 🐛 Bug Report: PostgreSQL adapter never uses the_uidindex – every create, get and update by row ID scans the whole table #14075). It is not a regression in itself.
Risks / things to consider for the fix
RETURNINGis not available everywhere: PostgreSQL yes, SQLite from 3.35, MariaDB from 10.5, MySQL no. KeepgetSequences()as the fallback and enableRETURNINGper adapter capability.- With
skipDuplicates(ON CONFLICT DO NOTHING),RETURNINGonly returns the rows actually inserted. Map the result by_uid, never by position. Skipped documents keep their (empty) sequence and go through the fallback. - With shared tables,
_uidis only unique per tenant. Our patch assumes a batch belongs to one tenant; check that or add_tenanttoRETURNING. - The upsert path also calls
getSequences()(Database.php#L7694). It needs its own treatment (RETURNINGonINSERT … ON CONFLICT DO UPDATEreturns both inserted and updated rows).
Related: utopia-php/database#953, #14075.
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 adapter sets and resets
statement_timeoutaround every query #14079 –SET/RESET statement_timeoutaround every query - 🐛 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 reads back `_id` with a separate query after every insert instead of `INSERT … RETURNING` – a full table scan per write[/-][+]🐛 Bug Report: Postgres insert reads back `_id` with an extra query[/+]