Repository navigation
Description
In short: On every API request, even a cached anonymous read, Appwrite loads the project's team and its organization keys straight from Postgres, bypassing the cache, although they are only needed for organization API keys and console admins.
Impact:
- Two unnecessary database queries per request; for a cached read they are the only database traffic at all.
- Fixing it raised throughput by +28 to +36 % for cached reads in our test, with the same hardware.
- Each extra query is also extra waiting time when the database is on another host.
👟 Reproduction steps
-
Run Appwrite 2.3.0 self-hosted with
_APP_DB_ADAPTER=postgresqland enablepg_stat_statements. -
Create a table with one row and
read("any"). Read the row once so it is in the Redis cache. -
Reset statistics:
SELECT pg_stat_statements_reset(); -
Send N anonymous requests:
GET /v1/tablesdb/{db}/tables/{table}/rows/{rowId}(no API key, no session). -
Look at the statements:
SELECT calls, left(query, 120) FROM pg_stat_statements ORDER BY calls DESC LIMIT 5;
For N requests you get:
2N RESET statement_timeout 2N SET statement_timeout = $1 N SELECT "main".* FROM "appwrite"."_console_keys" WHERE (("main"."resourceType" = $1) AND ("main"."resourceInternalId" = $2)) … N SELECT "main".* FROM "appwrite"."_console_teams" WHERE (("main"."_id" = $1)) …The row, the project, the database and the table all come from Redis. These two queries are the only Postgres traffic of the request. Together with the timeout handling they make 6 statements (see 🐛 Bug Report: Postgres adapter sets and resets
statement_timeoutaround every query #14079).
👍 Expected behavior
A request that neither uses an organization API key nor comes from a console admin should not load the team at all. If the team is loaded, it should come from the document cache, like the project does.
👎 Actual Behavior
Cause:
app/controllers/shared/api.phpinjects theteamresource into the init hook of every API route (api.php#L62). It is therefore resolved for every request, anonymous ones included.- For any project other than
console, the resource loads the team withfindOne('teams', [Query::equal('$sequence', [$teamInternalId])])(request.php#L959, #L992).find()results are not cached; onlygetDocument()by$idis. - The team collection has an attribute with the filter
subQueryOrganizationKeys(platform.php#L2597). Decoding the team therefore runs a second query,find('keys', resourceType='teams', resourceInternalId=…)(filters.php#L456). $teamis only needed in two cases:- organization API keys (api.php#L194, #L264)
- console admins (api.php#L291)
Measured. Setup: Postgres and Redis on one 4 vCPU node, two API nodes with 4 vCPU each, _APP_WORKER_PER_CORE=12, load from oha, 10 s per step. The usage queue was empty before each run.
The patch changes only one thing: for non-console projects, findOne() is replaced with getDocument('teams', $project->getAttribute('teamId')), which goes through the cache. With the patch, a cached anonymous read sends no statement to Postgres at all; the organization keys come from the cached team as well.
| Request | Concurrency | req/s before | req/s after | p50 / p99 before (ms) | p50 / p99 after (ms) |
|---|---|---|---|---|---|
| Get row (cached, anonymous) | 20 | 2,073 | 2,820 (+36 %) | 9.5 / 19.3 | 7.3 / 18.7 |
| Get row (cached, anonymous) | 80 | 2,286 | 3,008 (+32 %) | 30.4 / 138.0 | 24.3 / 115.6 |
| Get row (cached, anonymous) | 160 | 2,024 | 2,595 (+28 %) | 74.1 / 244.3 | 61.8 / 217.3 |
| List rows (API key, 25 rows + total) | 20 | 1,337 | 1,584 (+18 %) | 16.2 / 28.1 | 11.9 / 38.2 |
| List rows (API key, 25 rows + total) | 80 | 1,654 | 1,944 (+18 %) | 44.5 / 154.2 | 36.4 / 221.6 |
| List rows (API key, 25 rows + total) | 160 | 1,460 | 1,530 (+5 %) | 81.3 / 353.1 | 64.3 / 375.3 |
| Create row (API key) | 20 | 1,150 | 1,423 (+24 %) | 17.2 / 41.2 | 13.4 / 33.6 |
| Create row (API key) | 80 | 1,602 | 1,785 (+11 %) | 43.7 / 159.0 | 40.1 / 160.8 |
| Create row (API key) | 160 | 1,498 | 1,619 (+8 %) | 107.1 / 265.8 | 96.5 / 374.9 |
Further effects with the patch:
- Postgres statements per second for cached reads dropped from 10,491 to 8 at 20 concurrent and from 12,472 to 255 at 80 concurrent.
- CPU on the Postgres node for cached reads dropped from 58–71 % to 37–42 %.
- The API nodes stayed CPU-bound (88–99 %).
The two queries also add latency whenever the database is on another host. With 2 ms of extra latency on the database node (tc netem), a cached read made about 14 sequential round trips as shipped. Six of them are these two queries with their SET/RESET. At 20 concurrent requests that cut throughput from 1,722 to 482 req/s.
In a CPU profile of the API process (excimer, cached reads at 80 concurrent), the team resource accounted for 26.5 % of the API CPU time: 19.5 % for list requests and 20 % for creates.
Suggested fix: resolve the team only when it is needed.
- In the shared API init hook,
$teamis only used:- for organization API keys (api.php#L194, #L264)
- for console admins (api.php#L291)
- Inject a lazy accessor (e.g. a callable
getTeam) instead of the document, and call it only in those branches. - Requests without an organization key on a non-console project then touch neither
_console_teamsnor_console_keys.
The patch measured above (getDocument('teams', teamId) through the document cache) was only a measurement probe to quantify the cost of the two queries. We do not propose it as the fix; see the risks below.
Since when / regression?
- The
teamresource has loaded the team withfindOne('teams')on every request since at least 1.7.0 (then inapp/init/resources.php). It has been injected into the shared API init hook since 1.6.1. - Since 1.9.0, the team collection carries the
subQueryOrganizationKeysfilter. Since then every request runs two uncached queries instead of one, so this is a partial regression in 1.9.0. - Both queries also run on MariaDB installs. Only the
SET/RESET statement_timeoutoverhead around them is Postgres-specific.
Risks / things to consider for the fix
- Other consumers: besides the shared API hook, the resource is injected in about 15 places: the Organization module (projects and project keys), S3 and
Projects\XList. Lazy resolution has to keep their behaviour, e.g. by keeping the eager resource for those routes and using a lazy accessor only in the shared hook. - Caching the team is a security trade-off: the organization keys are attached to the team by a decode filter and would be cached together with the team. Creating or revoking an organization key then has to purge the cached team. Otherwise a revoked key keeps working for as long as the team stays in the cache.
- In 2.3.0 the cached platform team is purged in only one place: after an organization key's access time is updated (api.php#L242). The purge in the deletes worker is for project teams, not the organization.
- We found no endpoint in 2.3.0 that creates or deletes keys with
resourceType = teams. Wherever that happens (e.g. in Cloud), it would need the purge. - This is why we propose lazy loading.
Related: #14075 (same test setup; there the _uid lookups themselves are the problem).
Related issues from the same analysis (Appwrite 2.3.0 with Postgres, same test setup):
- 🐛 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
- 🐛 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,
_APP_DB_ADAPTER=postgresql, PostgreSQL 18.3 (appwrite/postgres:0.1.0), Redis 7.4. - Test setup: Postgres, Redis and ClickHouse on one node; the API on two separate nodes (
_APP_WORKER_PER_CORE=12). - The two queries do not depend on this layout. On a single node they add less latency (local socket), but the work for Postgres is the same.
- From the code, the same two queries should also run on MariaDB installs (not measured).
👀 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: Every API request runs two uncached Postgres queries for the project's team (`findOne('teams')` + organization keys), even when everything else is served from cache[/-][+]🐛 Bug Report: Two uncached team queries on every API request[/+]fix(api): load the team for routes that still read it