Skip to content

🐛 Bug Report: Postgres insert reads back _id with an extra query #14078

Open

Description

@JoshiJoshiJoshi

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

  1. Run Appwrite 2.3.0 with _APP_DB_ADAPTER=postgresql and a table with ≈ 1 M rows.

  2. Enable statement logging: ALTER SYSTEM SET log_statement = 'all'; SELECT pg_reload_conf();

  3. Create one row: POST /v1/tablesdb/{db}/tables/{table}/rows.

  4. After the COMMIT, the log shows a second statement:

    SELECT _uid, _id FROM "appwrite"."_1_database_1_collection_2" WHERE "_uid" IN ('…')
  5. EXPLAIN ANALYZE of that statement shows a Parallel Seq Scan over the whole table, because of the collation issue in 🐛 Bug Report: PostgreSQL adapter never uses the _uid index – 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 $sequence on 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 in createDocuments() and set $sequence from the result. Keep getSequences() as a fallback for adapters without RETURNING.
  • With skipDuplicates (ON CONFLICT DO NOTHING), RETURNING only returns inserted rows. The existing fallback in getSequences() still covers documents without a sequence.
  • With shared tables the batch belongs to one tenant, so matching on _uid is 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.

Risks / things to consider for the fix

  • RETURNING is not available everywhere: PostgreSQL yes, SQLite from 3.35, MariaDB from 10.5, MySQL no. Keep getSequences() as the fallback and enable RETURNING per adapter capability.
  • With skipDuplicates (ON CONFLICT DO NOTHING), RETURNING only 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, _uid is only unique per tenant. Our patch assumes a batch belongs to one tenant; check that or add _tenant to RETURNING.
  • The upsert path also calls getSequences() (Database.php#L7694). It needs its own treatment (RETURNING on INSERT … ON CONFLICT DO UPDATE returns 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):

🎲 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
    feature / relationships
    product / databases
    product / self-hosted
    product / storage
    on Oct 3, 2026
  2. changed the title [-]🐛 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[/+] on Oct 4, 2026
  3. removed
    product / storage
    product / self-hosted
    feature / relationships
    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