<?xml version='1.0' encoding='utf-8'?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><title>Shujie Zhang — PostgreSQL engineering</title><link>https://postgamma.com/blog/</link><description>PostgreSQL engineering notes by Shujie Zhang.</description><language>en</language><atom:link href="https://postgamma.com/blog/postgresql.xml" rel="self" type="application/rss+xml" /><lastBuildDate>Wed, 04 Nov 2026 00:00:00 +0000</lastBuildDate><item><title>How PostGamma Runs PostgreSQL in WebAssembly</title><link>https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/</link><description>Moving PostgreSQL into a browser means dealing with session state, blocking work, storage, and cancellation—not just compiling C.</description><pubDate>Wed, 04 Nov 2026 00:00:00 +0000</pubDate><dc:creator>Shujie Zhang</dc:creator><guid isPermaLink="true">https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/</guid><category>Engineering</category><content:encoded>&lt;h1 id="how-postgamma-runs-postgresql-in-webassembly"&gt;How PostGamma Runs PostgreSQL in WebAssembly&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#how-postgamma-runs-postgresql-in-webassembly" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;A PostgreSQL backend can spend its whole life waiting for commands, executing
queries, and waiting again. A browser page cannot do that on its main thread
without losing the ability to respond to the user.&lt;/p&gt;
&lt;p&gt;That difference shapes the browser build of PostGamma. Compiling the C code
is one part of the work. The more interesting questions are where the work
runs, who owns its state, and how a blocked operation can be interrupted.&lt;/p&gt;
&lt;p&gt;The &lt;a href="https://postgamma.com/blog/postgresql-in-your-browser-with-postgamma/"&gt;browser preview&lt;/a&gt; runs
PostgreSQL 19 and upstream psql locally. This article describes the boundaries
behind that terminal, rather than treating a successful compilation as the
whole port.&lt;/p&gt;
&lt;h2 id="threads-make-state-ownership-explicit"&gt;Threads make state ownership explicit&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#threads-make-state-ownership-explicit" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;PostgreSQL normally gives each connection a backend process. A variable with
process lifetime can therefore belong to one backend without the C declaration
saying so explicitly. Put several backends in one address space, and that
assumption needs attention.&lt;/p&gt;
&lt;p&gt;Consider session configuration. If one connection changes its time zone,
another connection must not silently inherit that setting. At the same time,
connections to the same database need to share the database's buffer and lock
management. Making every global variable thread-local would not express both
requirements.&lt;/p&gt;
&lt;p&gt;PostGamma handles this through reviewed ownership rules and source
transformation. Clang identifies declarations and accesses; rules determine
which state belongs to a session, an instance, a tool invocation, or a
synchronized shared owner. A runtime supplies the corresponding storage and
lifecycle operations. I described the general approach in
&lt;a href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/"&gt;Threading PostgreSQL Without Editing Upstream Source Code&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The browser build reuses that foundation. It does not maintain an independently
rewritten SQL parser or executor. It also does not assume that browser threads
behave exactly like processes on a Linux host.&lt;/p&gt;
&lt;h2 id="follow-one-setting-across-two-sessions"&gt;Follow one setting across two sessions&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#follow-one-setting-across-two-sessions" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Here is the ownership invariant in observable terms. &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are two
connections opened on the same SDK database instance:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-0-1" name="__codelineno-0-1" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-1"&gt;&lt;/a&gt;&lt;span class="kd"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'session-a'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a id="__codelineno-0-2" name="__codelineno-0-2" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-2"&gt;&lt;/a&gt;&lt;span class="kd"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'session-b'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a id="__codelineno-0-3" name="__codelineno-0-3" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-3"&gt;&lt;/a&gt;&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;a id="__codelineno-0-4" name="__codelineno-0-4" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-4"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SET TIME ZONE 'Asia/Tokyo'"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a id="__codelineno-0-5" name="__codelineno-0-5" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-5"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SET TIME ZONE 'America/New_York'"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a id="__codelineno-0-6" name="__codelineno-0-6" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-6"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'SHOW TIME ZONE'&lt;/span&gt;&lt;span class="p"&gt;))[&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;a id="__codelineno-0-7" name="__codelineno-0-7" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-7"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'SHOW TIME ZONE'&lt;/span&gt;&lt;span class="p"&gt;))[&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mf"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;a id="__codelineno-0-8" name="__codelineno-0-8" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-8"&gt;&lt;/a&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;finally&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;a id="__codelineno-0-9" name="__codelineno-0-9" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-9"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;close&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;a id="__codelineno-0-10" name="__codelineno-0-10" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-10"&gt;&lt;/a&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;close&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;a id="__codelineno-0-11" name="__codelineno-0-11" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-0-11"&gt;&lt;/a&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The expected values are &lt;code&gt;Asia/Tokyo&lt;/code&gt; and &lt;code&gt;America/New_York&lt;/code&gt;. Both connections
can see the same committed tables; they must not overwrite each other's
session configuration. The example isolates one property of session state,
not every property of transaction isolation.&lt;/p&gt;
&lt;figure class="pg-article-figure"&gt;
  &lt;img src="https://postgamma.com/assets/images/blog/figures/state-ownership.svg" alt="Two session-owned settings lead into distinct active contexts, while database files and shared memory have instance lifetime." width="1000" height="540" loading="lazy"&gt;
  &lt;figcaption&gt;State owner and execution carrier are different concepts. This is an ownership diagram, not a fixed Worker allocation.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;&lt;a href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#ownership-model-title"&gt;Open the interactive illustration on the website&lt;/a&gt; (no database or test runs in this model).&lt;/p&gt;

&lt;p&gt;Why not just use C thread-local storage? A physical carrier thread is an
execution resource. A logical session's state has to survive the intervals
when that session is not running, and the runtime may schedule work through a
pool. If the only owner were the physical thread, the next session using that
carrier could observe the previous session's values. A thread-local pointer
can identify the active context; it does not, by itself, define the lifetime
of all state reachable through that context.&lt;/p&gt;
&lt;p&gt;The reviewed GUC pipeline is relevant here. The ownership policy classifies
built-in GUC storage as managed state; the generator combines catalog and AST
facts rather than treating every variable whose name resembles a setting as
an independent global. Inspect
&lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/buildsys/project_guc_storage.py"&gt;&lt;code&gt;project_guc_storage.py&lt;/code&gt;&lt;/a&gt;
and the &lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/manifests/ownership/backend-guc-transitions.json"&gt;GUC transition policy&lt;/a&gt;
for the actual decisions. The diagram simplifies this pipeline into its
observable ownership contract.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Object&lt;/th&gt;
&lt;th&gt;Required lifetime or identity&lt;/th&gt;
&lt;th&gt;Failure to look for&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Connection's settings&lt;/td&gt;
&lt;td&gt;The logical session&lt;/td&gt;
&lt;td&gt;A setting leaks into another connection&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Database files and shared database structures&lt;/td&gt;
&lt;td&gt;The database instance&lt;/td&gt;
&lt;td&gt;Sessions see unrelated databases, or shared structures are duplicated incorrectly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Active context on a carrier&lt;/td&gt;
&lt;td&gt;The current unit of execution&lt;/td&gt;
&lt;td&gt;A resumed operation uses another session's state&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A tool such as psql&lt;/td&gt;
&lt;td&gt;Its tool invocation&lt;/td&gt;
&lt;td&gt;Reset starts with stale terminal or client state&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id="keep-the-page-out-of-the-blocking-path"&gt;Keep the page out of the blocking path&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#keep-the-page-out-of-the-blocking-path" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The page renders controls and results. PostgreSQL executes in Workers, using
Emscripten's pthread support and shared WebAssembly memory.&lt;/p&gt;
&lt;p&gt;A simplified view looks like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-1-1" name="__codelineno-1-1" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-1"&gt;&lt;/a&gt;Browser page
&lt;a id="__codelineno-1-2" name="__codelineno-1-2" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-2"&gt;&lt;/a&gt;    | requests, results, cancellation
&lt;a id="__codelineno-1-3" name="__codelineno-1-3" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-3"&gt;&lt;/a&gt;    v
&lt;a id="__codelineno-1-4" name="__codelineno-1-4" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-4"&gt;&lt;/a&gt;Control Worker
&lt;a id="__codelineno-1-5" name="__codelineno-1-5" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-5"&gt;&lt;/a&gt;    |
&lt;a id="__codelineno-1-6" name="__codelineno-1-6" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-6"&gt;&lt;/a&gt;    +-- PostgreSQL session work in pthread Workers
&lt;a id="__codelineno-1-7" name="__codelineno-1-7" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-7"&gt;&lt;/a&gt;    +-- Shared database and runtime state
&lt;a id="__codelineno-1-8" name="__codelineno-1-8" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-1-8"&gt;&lt;/a&gt;    +-- Filesystem and browser storage adapters
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This is a responsibility diagram, not a promise of one browser Worker per SQL
statement. The configured pool includes infrastructure and other runtime work.
The preview supports four SQL connections and a bounded pool of parallel query
workers; those are different limits.&lt;/p&gt;
&lt;p&gt;The distinction matters for a query that waits. The page must remain able to
request cancellation even while PostgreSQL is busy. Connection startup and
teardown also need to yield at the right boundaries, so that one lifecycle
operation does not prevent another connection from making progress.&lt;/p&gt;
&lt;p&gt;The browser SDK has a
&lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/wasm/src/api/database.ts"&gt;dedicated lifecycle implementation&lt;/a&gt;,
and the runtime has
&lt;a href="https://github.com/postgamma/postgamma/tree/c752f8ca5bdb5b801b26de586defc630cf6f5839/runtime/platform/emscripten"&gt;target-specific thread and wait support&lt;/a&gt;.
These are parts of the database integration, not UI timing tricks.&lt;/p&gt;
&lt;h2 id="cancellation-is-also-an-ownership-problem"&gt;Cancellation is also an ownership problem&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#cancellation-is-also-an-ownership-problem" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Imagine a request that starts, times out at the page, and finishes later in a
Worker. Rejecting its JavaScript promise does not prove that the native
operation released its payload, request slot, or connection state. Reusing
those owners too early can deliver an old result to a new operation.&lt;/p&gt;
&lt;p&gt;The transport gives admitted operations a monotonically increasing sequence
number and keeps a pending entry for each outstanding call. Incoming replies
look up that sequence; a reply for an already retired sequence is ignored.
The actual handler contains this guard:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-2-1" name="__codelineno-2-1" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-2-1"&gt;&lt;/a&gt;&lt;span class="kd"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nx"&gt;waiter&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;pending&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;sequence&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a id="__codelineno-2-2" name="__codelineno-2-2" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#__codelineno-2-2"&gt;&lt;/a&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;waiter&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Retired sequence: never deliver it to a later request.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Connection handles also carry generations. The sequence identifies an
operation; the handle generation identifies the lifetime of the object it
uses. They prevent different kinds of accidental reuse.&lt;/p&gt;
&lt;p&gt;On instance failure, the transport stops admitting work and asks the control
Worker to discard the instance. It normally waits for cleanup acknowledgement
before rejecting the pending callers. If cleanup cannot acknowledge within its
own bound, it retires the Workers. That is why “cancel the UI spinner” is not
the resource contract.&lt;/p&gt;
&lt;div class="pg-technical-note"&gt;
&lt;p&gt;&lt;strong&gt;Two deadlines, two questions.&lt;/strong&gt; An operation deadline asks whether the
caller is still willing to wait. Retirement asks whether the runtime can
safely release or replace its owners. A timeout message alone answers only
the first question.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;The relevant source is the &lt;code&gt;Transport&lt;/code&gt; implementation in
&lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/wasm/src/api/database.ts"&gt;&lt;code&gt;database.ts&lt;/code&gt;&lt;/a&gt;
and the listener/deadline ownership in
&lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/wasm/src/api/control.ts"&gt;&lt;code&gt;OperationControl&lt;/code&gt;&lt;/a&gt;.
The excerpt is an implementation detail of this revision, not an SDK API to
call from an application.&lt;/p&gt;
&lt;h2 id="the-upstream-checkout-remains-an-input"&gt;The upstream checkout remains an input&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#the-upstream-checkout-remains-an-input" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;A portable build still needs changes to assumptions about the operating
system. The browser target has no native socket server to launch and no
ordinary operating-system process boundary for each backend.&lt;/p&gt;
&lt;p&gt;PostGamma exports the pinned PostgreSQL revision into a generated source tree.
The Wasm build applies reviewed target adaptations there. For example, the
shared-memory configuration must select the provider implemented by the
browser runtime.&lt;/p&gt;
&lt;p&gt;Those adaptations check the source shape and record input and output hashes.
If an expected source pattern changes, generation stops for review. It does
not silently accept an unmatched replacement. The
&lt;a href="https://github.com/postgamma/postgamma/blob/c752f8ca5bdb5b801b26de586defc630cf6f5839/buildsys/wasm_source.py"&gt;source adaptation rules&lt;/a&gt;
show the checks and the reasons for each change.&lt;/p&gt;
&lt;p&gt;Keeping the upstream checkout unchanged does not mean the resulting PostgreSQL
binary is unmodified. The transformations and runtime are exactly what make
this execution model possible. Keeping the input separate makes that work
inspectable and repeatable.&lt;/p&gt;
&lt;h2 id="persistence-needs-a-storage-contract"&gt;Persistence needs a storage contract&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#persistence-needs-a-storage-contract" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Memory storage is useful for an interactive demonstration. Once the instance
is discarded, its database is gone. That is the mode used by the homepage's
psql terminal.&lt;/p&gt;
&lt;p&gt;OPFS is a separate option. It lets the engine keep database files in storage
owned by the browser origin. PostgreSQL still manages pages, transactions, and
WAL; an adapter maps the required file operations and storage barriers to the
browser environment.&lt;/p&gt;
&lt;p&gt;A successful synchronous COMMIT waits for the browser storage barriers used
by this implementation. That statement has a limit: closing a tab to test
recovery does not prove hardware power-loss durability. Likewise, a correct
WAL recovery path does not prevent the user from clearing the site's data or
the browser from evicting best-effort storage.&lt;/p&gt;
&lt;p&gt;There is also an ownership question across tabs. The preview allows one live
owner of a named OPFS database at a time. Opening the same name in another tab
must wait or return a lock error. It must not create two independent buffer
managers writing to the same files.&lt;/p&gt;
&lt;p&gt;These constraints belong in application design. A local database still needs
an export path and a clear explanation of what deleting browser data means.&lt;/p&gt;
&lt;h2 id="a-terminal-and-an-sdk-share-the-engine-not-every-lifecycle"&gt;A terminal and an SDK share the engine, not every lifecycle&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#a-terminal-and-an-sdk-share-the-engine-not-every-lifecycle" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The Live terminal uses real psql and its matching private libpq. Their protocol
traffic stays inside the browser through an in-memory transport. There is no
remote SQL server behind the prompt.&lt;/p&gt;
&lt;p&gt;That preserves familiar behavior: continuation prompts, backslash commands,
COPY input, result formatting, and transaction state. The page provides
terminal rendering and keyboard handling.&lt;/p&gt;
&lt;p&gt;It does not make shell commands available. Nor does it make network connection
strings work. The terminal currently owns its database instance; applications
should not mix its lifetime with SDK connections to that same instance. The
SDK is the interface for an application that wants to manage its own queries,
results, storage choice, and close sequence.&lt;/p&gt;
&lt;h2 id="test-the-boundaries-not-just-the-demonstration"&gt;Test the boundaries, not just the demonstration&lt;a class="headerlink" href="https://postgamma.com/blog/how-postgamma-runs-postgresql-in-webassembly/#test-the-boundaries-not-just-the-demonstration" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;A useful browser test has to get past the first query. Can another connection
continue while one connection waits? Can a query be cancelled and the session
reused? Does a committed record survive reopening an OPFS database? What happens
if a tab disappears before a COMMIT reply arrives?&lt;/p&gt;
&lt;p&gt;PostGamma has separate gates for these behaviors, plus tests of the packaged
SDK in Chromium, Firefox, and Linux WebKit. A pass in Linux WebKit does not
establish physical Safari or mobile-device support.&lt;/p&gt;
&lt;p&gt;A later article will describe how the weekly suite keeps those results
attributable: which source revision ran, which package was installed, and which
checks really finished. The &lt;a href="https://postgamma.com/getting-started/browser/"&gt;browser guide&lt;/a&gt;
documents the current API and deployment requirements.&lt;/p&gt;</content:encoded></item><item><title>A Repeated Check in PostGamma</title><link>https://postgamma.com/blog/a-repeated-check-in-postgamma/</link><description>Why threads can help with many short queries, and how I removed a repeated check from state access.</description><pubDate>Sat, 31 Oct 2026 13:19:02 +0000</pubDate><dc:creator>Shujie Zhang</dc:creator><guid isPermaLink="true">https://postgamma.com/blog/a-repeated-check-in-postgamma/</guid><category>Engineering</category><content:encoded>&lt;h1 id="a-repeated-check-in-postgamma"&gt;A Repeated Check in PostGamma&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#a-repeated-check-in-postgamma" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;One useful case for threads is a busy server handling many short queries.
The SQL itself may be cheap, but switching between sessions still costs time.&lt;/p&gt;
&lt;p&gt;During a performance investigation, I found extra CPU work in PostGamma's
state access code. The database could run the queries correctly, but the
runtime was doing some of the same work again and again.&lt;/p&gt;
&lt;p&gt;This post follows one small part of that problem: checking the same table
pointer every time PostgreSQL reads a state variable. At the end, I also
show a separate test with many active sessions.&lt;/p&gt;
&lt;p&gt;The state-access experiment is from October 10, 2026. It compares two
versions of the threaded server. Both experiments in this post use the
server, rather than the embedded C or Python library.&lt;/p&gt;
&lt;h2 id="why-a-variable-read-needs-runtime-code"&gt;Why a variable read needs runtime code&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#why-a-variable-read-needs-runtime-code" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;PostGamma runs PostgreSQL with threads. State that used to belong to a
backend process now has an explicit owner. That owner may be an instance,
a PostgreSQL execution role, or a session. Here, a role means a runtime task
such as a backend or checkpointer, not a SQL user role.&lt;/p&gt;
&lt;p&gt;Generated code needs a way to find the right value. In this version, it
uses a table of state addresses. Each variable has a slot in the table.&lt;/p&gt;
&lt;p&gt;By this point, I had already added address caching. The runtime resolves
and initializes a slot on its first use. Later accesses can use the saved
address.&lt;/p&gt;
&lt;p&gt;But even a cached access still had several steps. It loaded the current
table pointer, checked that pointer, read the slot, and checked whether
the slot was ready.&lt;/p&gt;
&lt;p&gt;The repeated work was in ordinary paths, including transaction setup and
memory management. A small cost there can occur many times during a query.&lt;/p&gt;
&lt;h2 id="the-check-i-focused-on"&gt;The check I focused on&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#the-check-i-focused-on" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This is a shortened example of the old access path:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-0-1" name="__codelineno-0-1" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-1"&gt;&lt;/a&gt;&lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_state_addresses&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a id="__codelineno-0-2" name="__codelineno-0-2" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-2"&gt;&lt;/a&gt;
&lt;a id="__codelineno-0-3" name="__codelineno-0-3" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-3"&gt;&lt;/a&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;a id="__codelineno-0-4" name="__codelineno-0-4" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-4"&gt;&lt;/a&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;fail&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;a id="__codelineno-0-5" name="__codelineno-0-5" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-5"&gt;&lt;/a&gt;
&lt;a id="__codelineno-0-6" name="__codelineno-0-6" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-6"&gt;&lt;/a&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;slot&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;a id="__codelineno-0-7" name="__codelineno-0-7" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-7"&gt;&lt;/a&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;a id="__codelineno-0-8" name="__codelineno-0-8" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-0-8"&gt;&lt;/a&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resolve_and_initialize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;slot&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The real code also checks the slot number and its initialization template.
I left those checks out here to keep the example small.&lt;/p&gt;
&lt;p&gt;The table-pointer check had a useful job: rejecting access to state
without an active execution context. I needed to keep that error visible.&lt;/p&gt;
&lt;p&gt;But during normal execution, the same table pointer was checked over and
over. The runtime already controlled when that pointer could change. It
changed when a worker entered a context or restored the previous one.&lt;/p&gt;
&lt;p&gt;That gave me a way to avoid repeating this check on every access.&lt;/p&gt;
&lt;h2 id="always-give-the-worker-a-readable-table"&gt;Always give the worker a readable table&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#always-give-the-worker-a-readable-table" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;I changed the runtime so the table pointer always points to a readable
table.&lt;/p&gt;
&lt;p&gt;When a worker has an active context, it points to that context's table.
When there is no active context, it points to a shared empty table. Every
entry in the empty table is &lt;code&gt;NULL&lt;/code&gt;, and the runtime never changes it.&lt;/p&gt;
&lt;p&gt;The normal access path can then do this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-1-1" name="__codelineno-1-1" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-1-1"&gt;&lt;/a&gt;&lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_state_addresses&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a id="__codelineno-1-2" name="__codelineno-1-2" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-1-2"&gt;&lt;/a&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;slot&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;a id="__codelineno-1-3" name="__codelineno-1-3" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-1-3"&gt;&lt;/a&gt;
&lt;a id="__codelineno-1-4" name="__codelineno-1-4" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-1-4"&gt;&lt;/a&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;a id="__codelineno-1-5" name="__codelineno-1-5" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#__codelineno-1-5"&gt;&lt;/a&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resolve_and_initialize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;slot&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The runtime checks the context and table when binding or restoring them.
The slot still has its own first-access check.&lt;/p&gt;
&lt;p&gt;An access without an active context is still an error. It reads a &lt;code&gt;NULL&lt;/code&gt;
entry from the empty table and enters the existing resolver. The resolver
rejects the missing context before it can initialize anything.&lt;/p&gt;
&lt;p&gt;The address cache belongs to the logical execution context. A worker
holds a pointer to that cache while running the context. This matters
when a session later runs on a different worker.&lt;/p&gt;
&lt;p&gt;You can see the
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/runtime/include/postgamma/backend_state_runtime.h"&gt;state access code&lt;/a&gt;
and the
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/runtime/src/execution_context.c"&gt;binding and restore code&lt;/a&gt;
in the repository.&lt;/p&gt;
&lt;h2 id="checking-that-the-change-was-safe"&gt;Checking that the change was safe&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#checking-that-the-change-was-safe" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;I checked warm accesses, first accesses, and accesses without a context.
Warm accesses must keep using the cache. An invalid access must still
fail.&lt;/p&gt;
&lt;p&gt;The tests also covered separate role and session state, nested contexts,
and moving an execution context between worker threads. After a nested
call, the caller must get its original table back.&lt;/p&gt;
&lt;p&gt;The tested version passed PostgreSQL regression and isolation tests.
Runtime tests also passed with memory and thread sanitizers.&lt;/p&gt;
&lt;p&gt;There was a separate pointer initialization fix in that version too.
It fixed how some generated state containing pointers was initialized. The
timings below compare the complete builds, so they do not isolate the
effect of one removed check.&lt;/p&gt;
&lt;h2 id="measuring-the-state-access-change"&gt;Measuring the state-access change&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#measuring-the-state-access-change" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;I used the same compiler and linker options, SQL, data, and CPU placement
for both versions. The client and server used separate CPUs. Each test
ran after warmup, with six alternating pairs of runs. Each run performed
100,000 operations and checked their results.&lt;/p&gt;
&lt;p&gt;These were read-only tests on a memory-backed filesystem. The timing runs
did not use a profiler. The results below are median wall-clock time per
operation. Lower is better.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Workload&lt;/th&gt;
&lt;th style="text-align: right;"&gt;Before&lt;/th&gt;
&lt;th style="text-align: right;"&gt;After&lt;/th&gt;
&lt;th style="text-align: right;"&gt;Time change&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;SELECT 1&lt;/code&gt; over a connection&lt;/td&gt;
&lt;td style="text-align: right;"&gt;61.808 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;61.774 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;-0.05%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One prepared point query over a connection&lt;/td&gt;
&lt;td style="text-align: right;"&gt;78.925 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;80.018 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;+1.38%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A point-query loop inside PL/pgSQL&lt;/td&gt;
&lt;td style="text-align: right;"&gt;10.087 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;9.205 us&lt;/td&gt;
&lt;td style="text-align: right;"&gt;-8.74%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The PL/pgSQL test runs many lookups inside one function call. Its time is
per lookup inside that loop. The network tests send a separate request
for each operation, so their absolute times measure different work.&lt;/p&gt;
&lt;p&gt;The internal loop was faster in five of the six pairs. One pair was about
22% slower. The network point query was faster in only two pairs. I kept all
of the &lt;a href="https://postgamma.com/blog/evidence/state-access-check-2026-10-10.json"&gt;timing samples&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;SELECT 1&lt;/code&gt; stayed about the same. The network point query did not show a
stable improvement. The internal loop showed a lower median time, but
the results also show why I would not promise the same gain for every
workload.&lt;/p&gt;
&lt;p&gt;This was an October development experiment. It measures a small change
between two threaded builds. It does not measure the current release
candidate against PostgreSQL.&lt;/p&gt;
&lt;h2 id="why-short-queries-make-switching-matter"&gt;Why short queries make switching matter&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#why-short-queries-make-switching-matter" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The next test looks at a different question: how the threaded server
compares with PostgreSQL's normal process-based server under load.&lt;/p&gt;
&lt;p&gt;Think of 16 open connections, each repeatedly asking for one row. With
four server CPUs, those CPUs keep moving between active backends.&lt;/p&gt;
&lt;p&gt;A &lt;a href="https://www.postgresql.org/docs/19/tutorial-arch.html"&gt;normal PostgreSQL server&lt;/a&gt;
uses a separate process for each connection. PostGamma's threaded server
runs its backends as threads in one process. They share an address space.&lt;/p&gt;
&lt;p&gt;When a CPU switches directly between two of those threads, it can keep
the same address space. On Linux x86, the
&lt;a href="https://github.com/torvalds/linux/blob/v6.8/arch/x86/mm/tlb.c#L527-L550"&gt;switching code&lt;/a&gt;
has a fast path for this case. That can reduce the cost of serving many
short queries as the CPU moves between sessions.&lt;/p&gt;
&lt;p&gt;Threads still need scheduling, locks, and wakeups. The network server
still uses sockets. The benefit depends on how much time goes to
switching and networking compared with running the SQL.&lt;/p&gt;
&lt;h2 id="a-separate-test-with-many-active-sessions"&gt;A separate test with many active sessions&lt;a class="headerlink" href="https://postgamma.com/blog/a-repeated-check-in-postgamma/#a-separate-test-with-many-active-sessions" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;On October 14, I compared a later threaded candidate with PostgreSQL's
normal process-based server. Both used the same PostgreSQL 19 beta source,
compiler policy, SQL, and data. This candidate included several runtime
changes beyond the one described above.&lt;/p&gt;
&lt;p&gt;The clients kept their connections open and sent queries through ordinary
TCP and libpq. Each query read one row by its primary key. This measured
repeated work across active sessions, without opening a new connection
for every query.&lt;/p&gt;
&lt;p&gt;The server had four assigned CPUs. The clients used two other CPUs. Each
case had three paired rounds, alternating which server ran first. A round
had three seconds of warmup and twelve seconds of measurement. The host
was a shared virtual machine.&lt;/p&gt;
&lt;p&gt;Here is the prepared point query at different session counts. The numbers
are mean queries per second across the three rounds. Higher is better.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: right;"&gt;Clients&lt;/th&gt;
&lt;th style="text-align: right;"&gt;PostgreSQL&lt;/th&gt;
&lt;th style="text-align: right;"&gt;PostGamma&lt;/th&gt;
&lt;th style="text-align: right;"&gt;Change&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: right;"&gt;1&lt;/td&gt;
&lt;td style="text-align: right;"&gt;9,883&lt;/td&gt;
&lt;td style="text-align: right;"&gt;9,375&lt;/td&gt;
&lt;td style="text-align: right;"&gt;-5.1%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: right;"&gt;4&lt;/td&gt;
&lt;td style="text-align: right;"&gt;37,693&lt;/td&gt;
&lt;td style="text-align: right;"&gt;36,889&lt;/td&gt;
&lt;td style="text-align: right;"&gt;-2.1%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: right;"&gt;16&lt;/td&gt;
&lt;td style="text-align: right;"&gt;39,982&lt;/td&gt;
&lt;td style="text-align: right;"&gt;50,033&lt;/td&gt;
&lt;td style="text-align: right;"&gt;+25.1%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;At 16 sessions, the same point query using the simple protocol also had
higher throughput: &lt;strong&gt;14.4% more queries per second&lt;/strong&gt;. Both point-query
tests were faster in all three paired rounds at that concurrency.&lt;/p&gt;
&lt;p&gt;That is a useful case for the threaded design: many short queries, with
more active sessions than server CPUs. In the prepared point-query test at
16 sessions, PostGamma also used less measured server CPU time per query:
about 79 microseconds versus 99 for PostgreSQL.&lt;/p&gt;
&lt;p&gt;This fits the reason to expect a benefit from threads. It does not isolate
the cost of switching address spaces from all the other runtime changes.
With 1 or 4 sessions, PostGamma's measured throughput was lower in this test.
It also used more CPU time per query at those session counts.
Other workloads differed too: at 16 sessions, a range aggregation was
9.1% slower in the threaded build.&lt;/p&gt;
&lt;p&gt;The &lt;a href="https://postgamma.com/blog/evidence/short-query-concurrency-2026-10-14.json"&gt;full results and build identities&lt;/a&gt;
include all 21 workload and concurrency combinations, including slower
results. These are historical development results. They are separate from
the earlier state-access comparison and from current release performance.&lt;/p&gt;
&lt;p&gt;I kept the simpler access path and its checks at context boundaries.
The useful part of this investigation was finding repeated work in
code that runs very often. The result also reminded me to check both
that inner path and the time a client actually sees.&lt;/p&gt;
&lt;p&gt;For the state model behind this code, see
&lt;a href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/"&gt;Threading PostgreSQL Without Editing Upstream Source Code&lt;/a&gt;.&lt;/p&gt;</content:encoded></item><item><title>Threading PostgreSQL Without Editing Upstream Source Code</title><link>https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/</link><description>PostGamma reads an unmodified PostgreSQL checkout and generates a separate threaded build.</description><pubDate>Sat, 31 Oct 2026 13:19:01 +0000</pubDate><dc:creator>Shujie Zhang</dc:creator><guid isPermaLink="true">https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/</guid><category>Engineering</category><content:encoded>&lt;h1 id="threading-postgresql-without-editing-upstream-source-code"&gt;Threading PostgreSQL Without Editing Upstream Source Code&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#threading-postgresql-without-editing-upstream-source-code" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;PostGamma starts with an unmodified PostgreSQL checkout. It reads that
source and creates a separate tree with the changes needed for threads.&lt;/p&gt;
&lt;p&gt;The upstream checkout stays untouched. PostGamma's rules and build tools
change only the generated copy. The runtime library supports the threaded code.&lt;/p&gt;
&lt;p&gt;This approach produces a threaded PostgreSQL server. It also lets me build
an embedded library for C and Python applications.&lt;/p&gt;
&lt;h2 id="why-i-stopped-editing-postgresql-directly"&gt;Why I stopped editing PostgreSQL directly&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#why-i-stopped-editing-postgresql-directly" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;My first prototype used direct edits to PostgreSQL. With AI coding tools,
I had a version that compiled and passed regression tests after about
48 hours.&lt;/p&gt;
&lt;p&gt;That was a useful start. But I would have to keep those edits working as
PostgreSQL changed. The prototype did not solve that maintenance problem.&lt;/p&gt;
&lt;p&gt;So I changed the approach. I moved the work into a source transformation
and a runtime library. PostgreSQL's source became an input to the build.&lt;/p&gt;
&lt;h2 id="keep-the-input-and-output-separate"&gt;Keep the input and output separate&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#keep-the-input-and-output-separate" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The build has a simple shape:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;a id="__codelineno-0-1" name="__codelineno-0-1" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-1"&gt;&lt;/a&gt;Upstream PostgreSQL checkout
&lt;a id="__codelineno-0-2" name="__codelineno-0-2" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-2"&gt;&lt;/a&gt;        (kept unchanged)
&lt;a id="__codelineno-0-3" name="__codelineno-0-3" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-3"&gt;&lt;/a&gt;               |
&lt;a id="__codelineno-0-4" name="__codelineno-0-4" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-4"&gt;&lt;/a&gt;               v
&lt;a id="__codelineno-0-5" name="__codelineno-0-5" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-5"&gt;&lt;/a&gt;    Clang + PostGamma rules
&lt;a id="__codelineno-0-6" name="__codelineno-0-6" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-6"&gt;&lt;/a&gt;               |
&lt;a id="__codelineno-0-7" name="__codelineno-0-7" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-7"&gt;&lt;/a&gt;               v
&lt;a id="__codelineno-0-8" name="__codelineno-0-8" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-8"&gt;&lt;/a&gt;      Generated source tree
&lt;a id="__codelineno-0-9" name="__codelineno-0-9" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-9"&gt;&lt;/a&gt;               |
&lt;a id="__codelineno-0-10" name="__codelineno-0-10" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-10"&gt;&lt;/a&gt;       + PostGamma runtime
&lt;a id="__codelineno-0-11" name="__codelineno-0-11" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-11"&gt;&lt;/a&gt;               |
&lt;a id="__codelineno-0-12" name="__codelineno-0-12" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-12"&gt;&lt;/a&gt;               v
&lt;a id="__codelineno-0-13" name="__codelineno-0-13" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#__codelineno-0-13"&gt;&lt;/a&gt;Threaded server or embedded library
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;First, the build checks that the checkout is at the expected upstream
commit and has no local changes. The
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/buildsys/materialize.py"&gt;source-copy step&lt;/a&gt;
then exports that commit into the build directory.&lt;/p&gt;
&lt;p&gt;The transformation changes this copy. For example, accesses to backend
state can become calls into PostGamma's runtime.&lt;/p&gt;
&lt;p&gt;For the threaded server build, that tree is in
&lt;code&gt;build/generated/postgres/&lt;/code&gt;. I can open the generated C files, compare
them with upstream, and debug the result.&lt;/p&gt;
&lt;p&gt;When I need to fix a transformation, I change its rules or build tools.
The next build generates the source again. I don't maintain edits inside
the generated directory.&lt;/p&gt;
&lt;p&gt;This is what I mean by keeping the upstream source untouched. The output
is a modified PostgreSQL build, with PostGamma's runtime linked into it.&lt;/p&gt;
&lt;h2 id="why-use-clang"&gt;Why use Clang&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#why-use-clang" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Clang parses the C code. It can find a variable's declaration and the
places that refer to it. This matters when different variables share the
same name.&lt;/p&gt;
&lt;p&gt;PostGamma uses that information to prepare source replacements. The rules
say which state needs a new owner and which operations need runtime
support.&lt;/p&gt;
&lt;p&gt;Clang does not decide the ownership model for me. I still have to write
and review those rules.&lt;/p&gt;
&lt;h2 id="one-example-is-the-session-time-zone"&gt;One example is the session time zone&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#one-example-is-the-session-time-zone" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;A PostgreSQL backend normally has its own process. Many writable global
variables are private to that process. Threads share an address space,
so those values need explicit owners.&lt;/p&gt;
&lt;p&gt;Take &lt;code&gt;session_timezone&lt;/code&gt;. One connection can use &lt;code&gt;UTC&lt;/code&gt;. Another can use
&lt;code&gt;Asia/Shanghai&lt;/code&gt;. Changing one connection's setting must leave the other
connection's setting alone.&lt;/p&gt;
&lt;p&gt;The
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/manifests/ownership/backend-state-rules.json"&gt;ownership rules&lt;/a&gt;
mark this variable as session state. The transformation redirects its
accesses to the active session's storage. The runtime binds a worker thread to
that state before it runs PostgreSQL code.&lt;/p&gt;
&lt;p&gt;This lets me describe the ownership rule and generate the affected
accesses. I don't have to edit each use by hand.&lt;/p&gt;
&lt;p&gt;Other values belong to a database instance or a PostgreSQL execution
role, such as a backend or checkpointer. Here, a role means a runtime task,
not a SQL user role. Some values can stay shared because they are read-only.
Those choices also live in the ownership rules.&lt;/p&gt;
&lt;h2 id="check-each-generated-change"&gt;Check each generated change&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#check-each-generated-change" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The transformation produces a replacement plan: a list of exact text edits
for each file. Before applying it, the build checks each file's source hash.
It also checks the original text at each replacement location. A mismatch
stops the build.&lt;/p&gt;
&lt;p&gt;These checks are in the
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/buildsys/apply_replacements.py"&gt;replacement tool&lt;/a&gt;.
They help catch a plan being applied to source it was not built for.
The tool also rejects replacements that overlap or fall outside a file.&lt;/p&gt;
&lt;p&gt;The generated code is available for review. I can compare the original
source, the planned replacements, and the resulting C code when something
goes wrong.&lt;/p&gt;
&lt;h2 id="what-the-runtime-still-has-to-do"&gt;What the runtime still has to do&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#what-the-runtime-still-has-to-do" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Generating the source is one part of making threads work. The runtime
still has to initialize state, route cancellation, manage waits, and
clean up a connection when it closes.&lt;/p&gt;
&lt;p&gt;A new thread also needs explicit initialization rules. It does not get a
private copy of its parent's memory through &lt;code&gt;fork()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;PostGamma keeps PostgreSQL's SQL parser, planner, executor, transactions,
WAL, and recovery code. The transformation changes how that code finds
state and works with the runtime.&lt;/p&gt;
&lt;p&gt;Threads also share failures. In an embedded application, a native memory
fault can affect the host process. Keeping the upstream checkout clean
helps with maintenance; runtime behavior still needs careful testing.&lt;/p&gt;
&lt;h2 id="following-upstream-changes"&gt;Following upstream changes&lt;a class="headerlink" href="https://postgamma.com/blog/threading-postgresql-without-editing-upstream-source-code/#following-upstream-changes" title="Permanent link"&gt;&amp;para;&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;An upstream update can change assumptions in the rules. It may need new
rules or runtime work. I still need to generate the new tree and test it.&lt;/p&gt;
&lt;p&gt;A
&lt;a href="https://github.com/postgamma/postgamma/blob/cc19919ef8aa1c6ccf4ddb87e9a555f6cac884cb/.github/workflows/upstream-canary.yml"&gt;weekly compatibility workflow&lt;/a&gt;
tests PostgreSQL's &lt;code&gt;REL_19_STABLE&lt;/code&gt; and &lt;code&gt;master&lt;/code&gt; branches. The
current product target is PostgreSQL 19. Testing a development branch
helps find adaptation work early.&lt;/p&gt;
&lt;p&gt;I also use PostgreSQL regression and isolation tests, runtime tests,
and C and Python package checks. They cover behavior that source checks
alone cannot prove.&lt;/p&gt;
&lt;p&gt;This is the approach I want to keep: start from upstream PostgreSQL,
generate the changes, and test the result. The upstream code stays easy
to compare with the threaded build. The rules and runtime are the parts
I maintain in PostGamma.&lt;/p&gt;</content:encoded></item></channel></rss>