I was reading a mailing-list post from Holly Cummins about getting PGlite into Quarkus with Endive. She wanted to get the combination running, and I was intrigued enough to try it. PostgreSQL compiled to WebAssembly, a WebAssembly runtime written in Java, and Quarkus around the whole thing. Could I vibe-code the glue for that? And, well, what would I actually have once it could execute a query?
I wanted to package the engine with the application and create a database inside the JVM. For a local tool or a test that needs PostgreSQL behavior, removing the separate database process could make the setup simpler. But I also wanted to follow that idea past the first successful SELECT, into who owns the session, what happens after a bad query, and where a committed row lives when I stop the JVM.
I used a coding agent to build the prototype and exercise those questions. It can initialize PostgreSQL, execute SQL, handle transactions, recover from SQL errors, and restore saved data in another JVM. Reading the adapter makes the qualifications quite concrete, though. In this version, a successful commit can still leave all my changes in JVM memory. Java only copies them to the host filesystem during a clean close. That decision is in my adapter, and it changes what I can ask an application to trust.
I needed a different PGlite build
PGlite normally arrives as PostgreSQL compiled to WebAssembly with a TypeScript/JavaScript client around it. That client gives JavaScript developers their query API and coordinates the engine with its environment, including browser or Node persistence. I needed to account for those host responsibilities when moving the engine into Java.
A .wasm file contains imports as well as executable instructions. The usual PGlite package expects JavaScript host support generated by Emscripten, the toolchain used to compile the C engine. Endive can execute WebAssembly on the JVM, but it doesn't supply PGlite's JavaScript client or a Node environment. So, being able to load WebAssembly was only part of the connection I needed to make.
I used an experimental WASI build from the PGlite PostgreSQL sources instead. WASI, the WebAssembly System Interface, defines host functions for files, clocks, arguments, random data, and similar capabilities. Endive supplies a Java implementation of WASI Preview 1. That gave the prototype a defined way to connect the database engine to an environment prepared by Java.
The artifact also includes patches from wasipg, which embeds this PostgreSQL build in Go. Those patches restore SQL error recovery and correct parts of the guest's message processing. I reused that build and patch series with an Endive host. The recovery mechanism came from the wasipg authors; the integration I wanted to explore was the Java side. There is no Go runtime in this application.
For this experiment I used PostgreSQL 17.5, Endive 1.1.0, and Quarkus 3.37.3, with the Quarkus Endive extension built from a pinned source commit. The Java sources target release 21, and I ran the JVM checks on Temurin 25 on macOS arm64. I've kept the exact sources and hashes in the provenance file. I'm staying with the JVM here; I haven't verified a native image.
What I share between databases
The Quarkus Endive extension gives me a named WasmQuarkusContext through CDI. In the dynamic-loading path I used, it supplies the execution mode and leaves application code to provide the module. I still need to create the database environment, start PostgreSQL, exchange messages, and close everything in the right order.
I kept compilation separate from a database's lifetime. PGliteFactory checks the bundled archive, parses the module, and caches the compiled machine factory. Opening another PGliteDatabase can reuse that compiled code while receiving fresh WASM memory, its own WASI environment, and a separate virtual filesystem. The small HTTP demonstration owns one such database through PGliteService, which closes it in a CDI destruction callback.
This is quite easy to misread as a connection pool. Each instance has its own database state. Sharing compiled code saves recompilation; it doesn't let those instances query the same tables. I need to keep that distinction in mind before adding more instances and calling the result a pool.
Endive's runtime compiler translates WASM functions into JVM bytecode. In this build, the large PostgreSQL parser function, base_yyparse, falls back to the interpreter. The runtime compiler enables that fallback for functions that exceed JVM method limits by default and logs a warning identifying the function. So my PostgreSQL execution path contains both compiled and interpreted functions. I have no query-load measurements yet that tell me how much that affects performance.
Starting an instance is also the adapter's responsibility. Java prepares the environment, disables automatic startup, calls _start, checks pgl_initdb, starts the backend, and enables its wire interface. Those exported functions form the application binary interface, or ABI, that my host expects. The first database request currently does this lazily, including compilation. Before putting the service behind real traffic, I'd need to decide when the database becomes ready and what a caller sees if initialization fails. Quarkus listening on an HTTP port doesn't answer that for me.
My Java code speaks PostgreSQL through files
My Java adapter exchanges PostgreSQL wire messages through files in the guest's data directory: .s.PGSQL.5432.in and .s.PGSQL.5432.out, with companion lock files. These files are part of the guest ABI. Java writes request bytes, calls the backend to consume them, and reads the replies. The pinned module uses this file interface without exporting the optional use_socketfile entry point.
Endive's WASI Preview 1 support table lists sock_accept, sock_recv, and sock_send as unsupported, so the guest can't own a TCP listener through this WASI host. A protocol bridge with a Java listener would be a separate design. The HTTP API here is just how I drive the existing adapter from outside the application.
I can retain PostgreSQL's existing vocabulary across this boundary. PostgresWire sends a simple-query message containing SQL text and decodes columns, rows, command tags, errors, and ReadyForQuery. That last message tells the adapter that the exchange has ended and carries the transaction state. A duplicate key arrives with SQLSTATE 23505, so the Java caller can recognize the database error without parsing an English message. PostgreSQL describes the exchange in its protocol documentation.
The files don't remove the need for careful message handling, of course. The pinned patches provide wasipg_flush to expose buffered replies without advancing through another input-processing step. My host drains pending output and stops decoding at the first ReadyForQuery, because this experimental backend can re-emit stale replies. During startup, it must also recognize a password challenge and answer it before waiting for the backend to become ready.
I can't swap the guest build without considering those transport details. The adapter uses a specific sequence of processing calls and flushes, and replacing the WASM artifact means checking that replies still belong to the correct requests, especially after an error. The current tests cover the exchanges the prototype uses; they don't cover the whole PostgreSQL protocol.
The result API shows how far I am from a general Java driver. It returns column names, command tags, and text values, with SQL NULL becoming Java null. A numeric result such as 42 arrives as a string. The decoder skips type and format metadata, so binary results would be misread as text. Proper type conversion needs that metadata and a deliberate mapping to Java values.
Parameter binding is missing too. Right now I can submit SQL strings, but I can't send a statement and its values separately through this API. I would add that before using it with application input. Streaming results, COPY handling, notices, and notifications need their own protocol support as well. For now, the entire reply and its decoded rows sit in memory. Limiting the SQL input to one megabyte does nothing to limit how many rows a query can return.
I need a bad query to leave PostgreSQL alive
A syntax error is an ordinary thing to send a database, particularly in a prototype where I'm trying queries. I need PostgreSQL to report the error and accept the next request. Recreating the database after each failed statement would give me a very different session contract.
PostgreSQL uses C's setjmp and longjmp machinery to return from an error to a recovery point. The experimental WASI source configuration used as the starting point disabled that path and could abort the instance on an ordinary SQL error. The wasipg patches restore recovery using WASI SDK 33 and standardized WebAssembly exception handling. The author explains the changes in PGlite issue 1071.
That gives me a dependency all the way through the system. The C build has to emit the recovery operations, Endive has to execute them, and my Java host has to consume the error reply correctly. Putting a try/catch around the Java call can't repair a guest that has already trapped.
I exercised that path with invalid SQL, duplicate keys, and division by zero, repeated one hundred times each. Successful queries between the failures continued to use the same instance. Those three hundred errors gave me a way to check that the session kept serving queries without silently replacing the engine. A WASM trap still ends the session in my adapter: it marks the database unusable, and I haven't implemented automatic replacement.
Inside a transaction, recovery has another meaning. After a duplicate key, PostgreSQL reports transaction state E; a subsequent query gets 25P02, indicating the failed transaction. I have to issue ROLLBACK before queries can succeed again. I checked that sequence on the same instance too. Preserving the transaction status lets the Java API distinguish an aborted transaction from a dead engine. Memory exhaustion, deep recursion, and interrupted queries still need separate investigation; ordinary SQL errors don't tell me how those failures end.
Then I have to decide who owns the transaction
The current adapter serializes access to one PostgreSQL session. Its Java methods are synchronized, and the transaction callback holds the lock from BEGIN through COMMIT or ROLLBACK. Another caller waits until that callback finishes. I checked this with twenty transaction calls from four Java threads, which all contributed to the final counter value by taking turns through the session.
Well, that still leaves a fairly large difference between serializing method calls and owning a transaction. The raw SQL endpoint allows one request to send BEGIN and return while the transaction remains open. Reading that path makes the gap clear: caller A can begin a transaction, caller B can insert a row, and caller A can roll it back. The monitor protects each call, but nothing associates that open transaction with caller A. Session settings and temporary objects are shared in the same way.
The batch endpoint keeps the lock across its statements, so another caller can't enter halfway through. It accepts arbitrary SQL, including transaction-control statements. Inside the synchronized transaction() method, after BEGIN, this is the callback's success path:
T value = work.apply(this);
if (!"T".equals(transactionStatus)) {
throw new IllegalStateException("Transaction callback must leave its transaction open and valid");
}
execute("COMMIT");
return value;T tells me that a transaction is open and valid; it doesn't identify the transaction I began. Following that code, a callback can insert a row, send COMMIT, then send BEGIN. The state is T again, the wrapper commits the new transaction, and the method returns success. The earlier insert has already been committed inside the guest. Nothing in this check reports that the callback split my transaction in two. So I need the API to enforce transaction ownership before I let unrelated callers share it.
Adding more instances would give each one separate database state, and the persistence-directory lock deliberately rejects a second owner of the same directory. Concurrent PostgreSQL sessions against shared data would need a different storage and coordination design. My four Java callers are still taking turns through a single session.
There is also the Quarkus meaning of a transaction. My callback sends SQL commands directly; it doesn't enlist a resource with Narayana, Quarkus's transaction manager. Adding @Transactional to a service won't bring these operations into a managed transaction. The companion has no JDBC driver, Agroal datasource, or Hibernate integration. Connecting it to Quarkus's datasource facilities is another layer to design.
I need to choose the Java API before adding more features. I can keep a small explicit interface for embedded SQL, or build a driver or protocol bridge for existing clients. Both need connection ownership, reset behavior, cancellation, and type conversion. JDBC would bring a broader contract than the few messages I currently decode, and I don't want the familiar PostgreSQL protocol to hide that from me.
My committed data is still in JVM memory
The guest reads and writes a Jimfs filesystem in memory. Java pre-opens Jimfs paths under the guest names /tmp and /dev through WASI. The host snapshot directory stays on the Java side: the adapter copies database files to and from it explicitly. I followed Endive's virtual filesystem guidance here: passing the host filesystem directly doesn't enforce path sandboxing by default. Keeping guest files in Jimfs narrows what the engine can reach, while leaving persistence to the Java host.
On a clean close, I roll back any unfinished transaction and shut down the guest before saving its files. This is the relevant branch in close():
if (!dead) {
if (!"I".equals(transactionStatus)) {
execute("ROLLBACK");
}
execute("CHECKPOINT");
call("pgl_shutdown");
storage.persist();
}storage.persist() copies the database files into a new host snapshot. Once the copy finishes, it atomically replaces the CURRENT pointer and removes the older snapshots. Opening the database reverses the copy into fresh guest memory. The previous snapshot stays selected while the new one is being assembled.
But the word commit deserves some care here. PostgreSQL's live files, including its write-ahead log, are still in Jimfs until that shutdown copy. My application can return success for a transaction and lose it if the JVM crashes afterwards. A trapped guest also skips the save path. For a disposable database I can accept that contract. For data I need to retain, I would have to change when those bytes reach persistent storage.
Even the atomic pointer replacement needs a precise claim. It changes which snapshot the adapter selects; it doesn't establish power-loss durability. I haven't defined explicit file and directory synchronization or tested what happens if copying fails, the disk fills, or pointer replacement is interrupted. Taking copies more frequently would still require a consistent snapshot protocol. I'd have to change the storage design to make commits durable.
I used two separate JVM processes to check the restart path. The first committed one row, left another in an aborted transaction, and shut down gracefully. The second saw only the committed row and could still recover from a bad query. Starting a new process forced Java to restore the data from the host directory, with none of the first JVM's memory available.
The restore also exposed a detail I had to fix in session initialization. The application table was present in the saved database, yet an unqualified query couldn't find it because the resumed backend had search_path=pg_catalog. The adapter now sets PostgreSQL's normal "$user", public search path after startup. So I had to restore both the files and the session behavior an application expects. Copying the files alone left me with a database that appeared to have lost its table.
There's still no snapshot integrity manifest, enforced version compatibility, database upgrade path, or backup tooling. The restore code only checks that PG_VERSION exists, and I haven't established compatibility with a normal PostgreSQL server's data directory. The demo's default location is under target, too. If I want to retain data beyond build cleanup, I have to put it somewhere separately managed.
The engine now shares my application's limits
Removing the database process puts its resource demands inside my JVM. WASM memory, Jimfs files, compiled code, and buffered query results all contribute. Saving and restoring also copy the database between memory and host storage. I've only exercised small datasets, so I can't say yet how this behaves with a large database or sustained traffic. The interpreter fallback is one part of that performance question; data copying and result buffering belong in the same measurement.
I also need a way to stop a query. The adapter bounds how many times it calls the guest's processing function, but a single call can take a long time. While it holds the session lock, everyone else waits. The REST methods are blocking, which keeps this path off the event loop, but doesn't give me query deadlines, cancellation, or a recovery policy after interruption.
The HTTP interface is a local experiment. It binds to loopback and accepts raw SQL without application authentication or authorization. The internal password exchange is no substitute: the upstream WASI backend doesn't actually verify the password. Jimfs limits file exposure, with CPU and memory still shared with the host application. Even the /dev/urandom compatibility file is a finite buffer populated at startup. Before using this more broadly, I need to examine the host services the database depends on, alongside the calls that return rows.
And, of course, bundling the engine makes updating it my responsibility. I have a checked artifact hash, pinned sources, C patches, and license notices, plus a local build of the Endive extension. They identify what I'm running. A maintained rebuild and release process still needs to handle PostgreSQL updates and check that the adapter's expected exports, message behavior, and saved data remain compatible.
That applies to extensions as well. PGlite's JavaScript ecosystem advertises capabilities such as pgvector, but I haven't integrated extension loading in this Java host. The same goes for its JavaScript live-query and synchronization facilities. I can't inherit those capabilities just by using the underlying database engine.
What I take from the experiment
I've kept the adapter and reproduction steps in the companion, with the JVM checks and source notes alongside it. Those include the packaged application and distinguish the behavior I exercised from gaps I found by reading the code.
For a local tool or a test using disposable data, I can see a reason to continue with this design. I'd first settle parameter binding and transaction ownership, then measure it with the queries and data size the application needs. If I need commits to survive a crash, persistence becomes an earlier decision because it changes the promise I can make to callers.
Holly's post started with a combination I wanted to try. Vibe-coding got me to an adapter that runs PostgreSQL inside Quarkus, and I can now follow a query from Java into the engine and back. What stays with me is how much of the database contract ended up in that Java code: who shares a session, how an error leaves it, and when a successful commit reaches disk. Is this production ready? Probably not. But a very neat experiment to test how far we can push things.




