Repository navigation
Description
In short: Appwrite's Postgres tables have an index on the row ID, but the queries are written in a way that Postgres cannot use it. So every lookup by ID reads the whole table instead of jumping to the row.
Impact:
- Creating, reading (uncached) and updating rows gets slower the bigger the table: on 1 M rows a single create takes β 0.5 s instead of β 25 ms (76 instead of 1,400 creates/s).
- It also hits internal tables (users, sessions, teams, keys, transactions), so busy projects slow down over time without any obvious reason.
- Small tables hide it, which is why it is easy to miss in development.
π Reproduction steps
-
Run Appwrite 2.3.0 self-hosted with
_APP_DB_ADAPTER=postgresql. -
Create a table, e.g.
loadtest/writeswith a few string/integer columns. -
Fill it with 1,000,000 rows (bulk create, 1,000 rows per request).
-
Measure any of these requests:
POST /v1/tablesdb/{db}/tables/{table}/rows(create a single row)GET /v1/tablesdb/{db}/tables/{table}/rows/{rowId}for a row that is not in the cache yetPATCH /v1/tablesdb/{db}/tables/{table}/rows/{rowId}with newpermissionson a table with row security
-
Check the query plan in the
appwrite-postgresqlcontainer, using the query exactly as Appwrite sends it:EXPLAIN ANALYZE SELECT "main".* FROM "appwrite"."_1_database_1_collection_2" AS "main" WHERE "main"."_uid" = '<rowId>';
β
Parallel Seq Scan, all rows filtered. WithSET enable_seqscan = off;the plan stays a (disabled) sequential scan. -
The same query with the collation of the index uses the index:
EXPLAIN ANALYZE SELECT "main".* FROM "appwrite"."_1_database_1_collection_2" AS "main" WHERE "main"."_uid" COLLATE utf8_ci_ai = '<rowId>';
β
Index Scan using _1_database_1_collection_2_uid, 0.03 ms instead of 30β300 ms.
Minimal reproduction in plain SQL (no Appwrite needed, ~1 minute)
Same collation and index definitions as utopia-php/database:
CREATE COLLATION IF NOT EXISTS utf8_ci_ai (provider = icu, locale = 'und-u-ks-level1', deterministic = false);
CREATE TABLE docs (_id bigserial PRIMARY KEY, _uid varchar(255) NOT NULL, name text);
CREATE UNIQUE INDEX docs_uid ON docs (_uid COLLATE utf8_ci_ai);
CREATE TABLE docs_perms (_id bigserial PRIMARY KEY, _type varchar(12) NOT NULL,
_permission varchar(255) NOT NULL, _document varchar(255) NOT NULL);
CREATE UNIQUE INDEX docs_ukey ON docs_perms (_document COLLATE utf8_ci_ai, _type, _permission);
INSERT INTO docs (_uid, name) SELECT md5(i::text), 'row ' || i FROM generate_series(1, 1000000) AS i;
INSERT INTO docs_perms (_document, _type, _permission)
SELECT md5(i::text), 'read', 'user:' || (i % 500) FROM generate_series(1, 1000000) AS i;
ANALYZE docs; ANALYZE docs_perms;
-- as issued by the adapter: sequential scans
EXPLAIN (ANALYZE, COSTS OFF) SELECT * FROM docs AS main WHERE main._uid = md5('123456');
EXPLAIN (ANALYZE, COSTS OFF) SELECT _uid, _id FROM docs WHERE _uid IN (md5('123456'));
BEGIN; EXPLAIN (ANALYZE, COSTS OFF) DELETE FROM docs_perms WHERE _document = md5('123456'); ROLLBACK;
-- index cannot be used even when sequential scans are disabled
SET enable_seqscan = off;
EXPLAIN (COSTS OFF) SELECT * FROM docs AS main WHERE main._uid = md5('123456');
RESET enable_seqscan;
-- with the index collation: index scans
EXPLAIN (ANALYZE, COSTS OFF) SELECT * FROM docs AS main WHERE main._uid COLLATE utf8_ci_ai = md5('123456');
BEGIN; EXPLAIN (ANALYZE, COSTS OFF) DELETE FROM docs_perms WHERE _document COLLATE utf8_ci_ai = md5('123456'); ROLLBACK;Result on PostgreSQL 18.3: _uid = β¦ 26 ms (Parallel Seq Scan), _uid IN (β¦) 24 ms (Parallel Seq Scan), DELETE β¦ _document = β¦ 52 ms (Seq Scan); with COLLATE utf8_ci_ai 0.13 ms and 0.06 ms (Index Scan).
π Expected behavior
Lookups by row ID ($id) use the unique index on _uid, and permission lookups use the index on _perms._document. Create, get and update by ID should cost about the same on a table with 1,000 rows as on a table with 1,000,000 rows.
π Actual Behavior
Every lookup by ID is a full sequential scan, so its cost grows linearly with the table size.
Cause. utopia-php/database (Postgres adapter, introduced in utopia-php/database#739) creates the indexes with the non-deterministic ICU collation utf8_ci_ai:
CREATE UNIQUE INDEX "β¦_uid" ON β¦ ("_uid" COLLATE utf8_ci_ai);
CREATE UNIQUE INDEX "β¦_ukey" ON β¦_perms (_document COLLATE utf8_ci_ai, _type, _permission);The queries compare without COLLATE (column default collation), so PostgreSQL cannot use these indexes at all:
getDocument():WHERE "main"."_uid" = :_uidandβ¦ FOR UPDATE(SQL.php#L392)getSequences(): after every insert the generated_idis read back withWHERE "_uid" IN (β¦)(SQL.php#L897), called fromDatabase::createDocuments()whenever an$onNextcallback is set, which Appwrite does when creating rows (Database.php#L5931)- permission cleanup on update/delete:
WHERE _document = :_uid(Postgres.php#L1121, #L1413, SQL.php#L634) - further
WHERE _uid = :_uidin Postgres.php#L1358 and #L1399 - likely also the permission subquery in
find()(SQL.php#L1981), not measured
Links point to the current main / 7.4.0; Appwrite 2.3.0 ships 7.3.11 with the same code. This affects every table, including the internal ones: in our test instance (one project) all 69 _uid indexes and all 69 _perms._document indexes carry utf8_ci_ai, and lookups on _console_users, _console_keys, _console_teams, _1_users, _1_sessions, _1_teams, _1_memberships and _1_transactions show the same plan.
Measured through the API (Postgres on its own 4 vCPU node, two API nodes with 4 vCPU each, load from oha/k6). "Plain index" is a manually added CREATE INDEX β¦ (_uid) or β¦ _perms (_document) without collation, as a comparison:
| Scenario | As shipped | With plain index |
|---|---|---|
| Create row, table with 1M rows, 40 concurrent | 76 rows/s, p50 550 ms (reading back _id after the insert: 495 ms per call) |
1,406 rows/s, p50 26 ms |
| Get row by ID, not cached, 1M rows, 20 concurrent | 65 req/s, p50 312 ms (lookup 287 ms per call) | 1,330 req/s, p50 11.5 ms (lookup 0.031 ms) |
| Update row with new permissions, 100k rows / 200k permission entries, 40 concurrent | 383 req/s, p50 97 ms (DELETE FROM _perms 54.7 ms per call) |
1,137 req/s, p50 33 ms (0.049 ms per call) |
| Share of Postgres time spent in these lookups on small tables (0β30k rows): create / bulk create (100 rows) / update / transaction commit | 75 % / 91 % / 89 % / 89 % | Postgres time per written row β86 % to β91 % |
Transactions (/v1/tablesdb/transactions) are hit twice: every staged row is read back by _uid on commit, and _1_transactions is locked by _uid (WHERE _uid = $1 FOR UPDATE) β so commits get slower the more transactions have ever been created.
Suggested fix: compare with the index collation wherever _uid or _document is matched ("_uid" COLLATE utf8_ci_ai = :_uid, "_uid" COLLATE utf8_ci_ai IN (β¦), _document COLLATE utf8_ci_ai = :_uid). This keeps the case-insensitive uniqueness from utopia-php/database#739 and makes the existing indexes usable. Alternatively, declare the columns themselves with COLLATE utf8_ci_ai (needs a migration).
Workaround until then: an additional plain index per table (CREATE INDEX CONCURRENTLY β¦ (_uid) and β¦ _perms (_document)). It works, but it is unknown to Appwrite and has to be repeated for every new table.
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 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
π² 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.0from the official compose file),utopia-php/database7.3.11. - Customizations in the test setup: Postgres moved to a separate node,
max_connectionsraised,_APP_WORKER_PER_COREvaried between 6 and 30. None of these affect the result: the plain SQL reproduction above shows the same plans on a stock PostgreSQL 18 with only the adapter's collation and index definitions. - Requests sent with an API key (bulk and transactions require one); reads were anonymous on a table with
read("any").
π 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
JoshiJoshiJoshi commentedon Oct 4, 2026
End-to-end check on the same cluster (2 API nodes Γ 4 vCPU, Postgres/Redis/ClickHouse on a third node, table with 3.3 M rows, 80 concurrent requests), stock 2.3.0 settings, before vs. with this fix plus #14078:
Before, each insert read β 2.5 M rows; afterwards a handful. Same hardware and settings in both runs, only the fixes differ.