Skip to content

perf(database-watt): cut the database worker's cost per request - #1

Merged
ShogunPanda merged 9 commits into
ShogunPanda:watt-db-applicationfrom
mcollina:watt-db-perf
Nov 24, 2026
Merged

ShogunPanda merged 9 commits into
ShogunPanda:watt-db-applicationfrom
mcollina:watt-db-perf

Conversation

@mcollina

@mcollina mcollina commented Nov 22, 2026 •

Copy link
Copy Markdown

This builds on supabase#1230 and goes after the database worker's thread, which was the bottleneck: it saturated with about two storage workers.

  • c84e76f sends a whole transaction as one message instead of four (database.batch: BEGIN, the settings and the scope ride on the first query), and runs single-query operations as one message that also commits. The database worker returns raw rows, which the storage worker parses with the same pg type parsers a direct pool uses, so the database thread no longer builds row objects, dates or JSON. With DATABASE_ENABLE_PIPELINING=true a batch is a single socket write.
  • 5e619e1 moves to Platformatic 3.80.1, which includes perf(itc,runtime): cut per-message messaging overhead platformatic/platformatic#5339 and lowers the messaging cost of every round trip.
  • ab6e754 reads the bucket and the object for object GET and info in one batch instead of two transactions. Each read keeps its permissions: the bucket as the super user, the object with RLS unless the bucket is public. The old and new builds returned the same status and body for 182 request cases covering those routes, roles, and public, private and missing buckets.
  • 2935cff moves to Platformatic 3.80.2 and marks the database messages as plain data (sanitize: false, from perf(itc,runtime): let plain-data messages skip sanitizing platformatic/platformatic#5354), so neither side walks every request and result before posting it. CPU profiles of both builds under the same load show that the walk cost the database thread 0.8 to 1 µs per GET or info request (1.2 to 1.6% of its time) and 6.3 µs per list of 100 objects (3.4%), plus about 1 µs per request on each storage worker. Now it costs nothing, and no message fell back to being sanitized. The change in req/s is smaller than the noise between runs.

Storage workers and the database application have to be deployed together, because query responses now carry raw rows.

Measured on Linux (Docker on an M4 Max, 16 vCPUs) with 4 storage workers, wrk with 128 connections, and Postgres and the S3 store in Docker. Both builds ran back to back with DATABASE_ENABLE_PIPELINING=true, which makes no difference on supabase#1230 alone. Absolute numbers move by about 10% between runs.

Route req/s, supabase#1230 → this PR DB thread µs per request DB thread busy p99
GET 1 KB 3,871 → 9,241 251 → 68 97% → 63% 216 → 20 ms
object info 3,999 → 13,228 242 → 73 97% → 97% 212 → 16 ms
list 100 2,005 → 4,436 487 → 179 98% → 80% 100 → 50 ms
sign URL 7,262 → 13,751 135 → 58 98% → 79% 80 → 20 ms
upload 1 KB 835 → 908 1,007 → 833 84% → 76% 349 → 185 ms

With 4 workers the database thread now has headroom on GET, list, sign and upload. Object info still saturates it, because info does very little work on the storage side. brianc/node-postgres#3871 (draft) removes two more per-query costs on that thread.

CPU profiles of the dedicated database worker showed most of its time going
to per-message overhead and to row handling that the storage workers redo
anyway. A scoped transaction cost four messages (begin, scope, query,
commit) and four Postgres round trips, and every row was parsed into an
object, walked and cloned before crossing threads.

Fewer messages:
- New `database.batch` message: BEGIN, setup statements and a query in one
  message, either committed in the same message (`commit: true`) or left
  open and returned as a lock. A failed batch is rolled back and reported
  as connectionDiscarded, so the caller sends no rollback of its own. BEGIN
  failures are retried on another connection like beginTransaction.
- Transactions start lazily: transaction() and setScope() send nothing; the
  settings and scope travel with the first query (two messages per
  transaction instead of four). A transaction that never runs a query sends
  nothing at all.
- TenantConnection.singleStatementExecutor() runs one statement as a whole
  scoped transaction in one message. StoragePgDB.runQuery takes
  `{ singleStatement: true }` and uses it when the connection provides it;
  the direct pg path is unchanged. Enabled for FindBucketById, FindObject,
  FindObjects, ListObjects, ListBuckets and SearchObjects.
- With DATABASE_ENABLE_PIPELINING the batch is written to Postgres in one
  corked write.

Less work on the database thread:
- Statements run with rowMode 'array' and pass-through type parsers. The
  storage worker builds the row objects with the same pg type parsers, as
  the direct path does, so dates and JSON are no longer parsed, walked and
  cloned on the database thread.
- Lock IDs are a random prefix per registry plus a counter instead of 32
  random bytes per transaction; a lock is now only usable from the
  messaging channel that created it.
- Request IDs are a random prefix per thread plus a counter instead of a
  randomUUID() per message.
- acquire() skips the timeout timer when an idle client is available.
- Error context is only built on the error path.
- If the caller aborts a batch that still opens a transaction, the late
  lock is rolled back right away instead of waiting for the idle timeout.

Against Postgres in Docker, CPU per operation for both ends in one thread
(median of 3): a 1-row scoped transaction goes from 227 to 178 us (150 us
pipelined), the single-statement path is 127 us (86 us pipelined), and a
100-row transaction goes from 702 to 504 us.

Storage workers and the database application must be deployed together:
query and lockedQuery responses now carry raw rows plus fields.
3.80 includes platformatic/platformatic#5339, which cuts the fixed
messaging cost per round trip that the dedicated database worker pays on
every query: no promise race per send, a timeout handled in ITC instead of
an AbortController and timer per message, counter-based request IDs and a
cheaper sanitize().

- Bump @platformatic/*, platformatic and wattpm to ^3.80.1.
- Declare @opentelemetry/instrumentation, which storage imports directly
  but only resolved through hoisting; the new tree no longer hoists it.
- Stub getWorkers, getWorkerForAffinity and onWorkersChange in the
  MessagingApi test mocks, which 3.80 adds to the type.
Object GET and info read the bucket as the super user, then the object:
as the super user for a public bucket, with RLS otherwise. That is two
transactions, two messages to the database worker and two socket writes
there; under load, writes were about a third of the database thread's
time.

- A `database.batch` statement can ask for its own result
  (`result: true`); the response returns those in `results`.
- `TenantConnection.scopedBatch()` (Database Watt only) runs statements
  in one transaction and one message, each after the scope it asks for:
  the connection's or the super user's. Settings are applied once.
- `StoragePgDB.findBucketAndObject()` sends the statements of
  findBucketById() and findObject() that way. It resolves to undefined
  when the connection cannot batch, inside a transaction, and after a
  failure the regular reads might not hit: a Postgres error other than a
  connection, resource or cancellation error, or a refused scope.
- `Storage.findBucketAndObject()` gives the routes the bucket and a
  findObject() with the regular semantics. The object read's scope is
  picked before the bucket is known, from the bucket's last seen public
  flag (per process, up to 10,000 buckets). A row read with RLS is also
  used for a public bucket, since RLS only hides rows; a missing one is
  read again as the super user. A row read as the super user is never
  used where RLS applies. Invalid names and connections that cannot
  batch take the regular reads.

The old and new builds returned the same status and body for 182 request
cases, twice each: GET, authenticated GET, info, public info and HEAD;
service role, authenticated, anon and no token; private, public and
missing buckets; objects that RLS shows and hides.

4 storage workers, pipelining on, wrk with 128 connections, two
interleaved rounds against the previous commit:

  route      req/s           database thread us/req   database thread busy
  GET 1 KB   8.2k -> 10.2k   92 -> 62                  75% -> 62%
  info       9.5k -> 15.4k   102 -> 64                 97% -> 98%
  sign       16.4k -> 16.5k  48 -> 48 (unchanged route)
@ShogunPanda

Copy link
Copy Markdown
Owner

Thanks Matteo, the design is solid and the batch/rollback/lazy-transaction machinery is carefully written and well tested. A few remarks before this can land:

  1. Object query now runs before auth checks. In src/http/routes/object/getObject.ts and getObjectInfo.ts, findBucketAndObject runs (possibly as superuser, depending on the public-bucket cache or publicRoute) before the unauthenticated / missing-bucket checks. The row is never returned, so it's not a leak, but RLS policies and superuser SELECTs now fire on requests that previously never reached findObject. The 182 request-case parity checks mentioned in the description aren't in the repo: could you commit HTTP-level tests for GET/info covering unauthenticated, missing bucket, private and public buckets?
  2. Wire protocol change has no versioning. query/lockedQuery/batch responses now carry raw rows, so old storage workers + a new database application break. Please document the "deploy together" requirement outside the PR body (changelog/README), or consider a simple protocol version check.
  3. Lock ownership. Lock IDs are now prefix + counter, and getLock skips the owner check when owner is missing (src/applications/database/locks.ts). If ITC always supplies context.channel that's fine, but I'd rather fail closed when the owner is absent.
  4. Minor: publicBuckets.clear() at 10,000 entries (src/storage/storage.ts) is a blunt eviction; an LRU or partial eviction would avoid bursts of wrong-scope reads and retries.

@mcollina

mcollina commented Nov 22, 2026 •

Copy link
Copy Markdown
Author

Thanks. Points 1, 3 and 4 are addressed in the last three commits; point 2 needs no change.

  1. f407909 reads the object in the bucket's batch only for a bucket the worker has seen before and, when the request is not authenticated, only if that bucket was public. The first request for a bucket reads it alone, as before. The object query can now run early only if the bucket was deleted or made private since the worker last saw it, and that row is never returned. In Postgres's statement log, 20 rejected requests (anonymous on a private bucket, and a missing bucket) ran 20 object SELECTs before this change and none after. Throughput is unchanged with 4 workers (GET about 9.2k req/s, info about 14k). 27ddc82 adds acceptance/specs/rest-object-read-access.test.ts, which covers every GET, info and HEAD route without a token and with the anon, authenticated and service role JWTs. It reads existing and missing keys from public, private and missing buckets, then repeats the reads while a bucket turns private, public again, empty and deleted. Every request is sent three times. The spec is in the core profile, so the watt-db entries of the acceptance matrix run it. It passes against feat: Added separate Database application. supabase/storage#1230, and against this branch with 1 and 4 workers.
  2. No versioning: this protocol never shipped, and the storage workers and the database application always change together, so there is no compatibility to keep.
  3. 32fab08 gives every lock an owner channel, and only that channel can use the lock. A request without a channel is rejected before a connection is taken.
  4. Also in f407909: the remembered buckets are now an LRU cache (lru-cache, 10,000 entries) instead of a map that is cleared when full.

A lock belongs to the messaging channel that created it, but the owner check
was skipped when either side had no channel. Locks now always have an owner,
and a request can only use a lock through that same channel. The owner is
resolved before a connection is taken, so a request without a channel gets
no connection and no lock. Remove the unused markTransaction.
…ads it

GET and info read the object in the same batch as the bucket, before the
route checks that the bucket exists and, for an unauthenticated request,
that it is public. A request the route rejects could then run an object
read, with RLS or as the super user, that the regular reads never run.

Batch the two reads only for a bucket seen before, and, when the request is
not authenticated, only if that bucket was public. A bucket seen for the
first time is read alone, as before, and remembered. The object then runs
early only if the bucket was deleted or made private since, and its row is
never returned.

The remembered buckets are now an LRU cache instead of a map that is
cleared when full.
Read an object through every GET, info and HEAD route as a caller without a
token, with the anon and authenticated roles and with the service role, from
public, private and missing buckets, for an existing and a missing key. Then
read again after the bucket turns private, public again, empty and deleted.
Each request is sent three times, because a Storage worker reads a bucket it
has not seen yet differently from one it has.
@mcollina

Copy link
Copy Markdown
Author

About point 2: I dropped the protocol versioning commit and force-pushed the branch, so the commit IDs changed (my previous comment now has the new ones). This protocol never shipped, so there is no backward compatibility to keep. Whenever we change the storage workers' side, we change the database application with it, in the same build. A version check or a "deploy together" note would only guard against a mismatch that we never ship, so the protocol stays unversioned.

hyperid gives the same scheme as before, a random UUID per lock registry
plus a counter, without the hand-rolled prefix and counter. It is now a
direct dependency (it was already installed through Platformatic).
Platformatic 3.80.2 includes platformatic/platformatic#5354, which lets
a sender or a handler declare that its messages are plain data. These
are then posted as they are instead of being walked for functions and
symbols first. If a value can't be cloned after all, Platformatic
sanitizes the message and posts it again, and errors thrown by a
handler are always sanitized.

Database Watt messages are plain data both ways: requests carry SQL and
values, results carry raw rows and fields, and failures come back as
error responses rather than thrown errors.

- Bump @platformatic/*, platformatic and wattpm to ^3.80.2.
- Register the database.* handlers with { sanitize: false }.
- Send requests and cancellations with { sanitize: false }.
@ShogunPanda
ShogunPanda merged commit 3a89a7e into ShogunPanda:watt-db-application Nov 24, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants