Repository navigation
perf(database-watt): cut the database worker's cost per request - #1
Merged
ShogunPanda merged 9 commits intoNov 24, 2026
Merged
Conversation
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)
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:
|
Author
|
Thanks. Points 1, 3 and 4 are addressed in the last three commits; point 2 needs no change.
|
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
force-pushed
the
watt-db-perf
branch
from
November 22, 2026 15:45
f549687 to
27ddc82
Compare
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
approved these changes
Nov 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This builds on supabase#1230 and goes after the database worker's thread, which was the bottleneck: it saturated with about two storage workers.
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. WithDATABASE_ENABLE_PIPELINING=truea batch is a single socket write.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.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.