Pangolin: architectural notes
Beyond software, I’m also a contemporary artist. I ran a fundraising event last year; an auction that distributed proceeds between the non-profit organisation, and hundreds of contributing artists. That yielded a considerable number of mutable Word invoices, often featuring minor calculation errors.
I have many friends with an occasional need to request payment, who do not run structured businesses in any traditional sense. This is not a commercially attractive demographic, and conventional bookkeeping tools don’t well suit the use case. Design is, fundamentally, an asymmetry of effort. I therefore resolved to develop an over-engineered core, supporting a deceptively lightweight product surface. This document articulates a couple of interesting decisions made over that course.



Data model
One of the core architectural decisions made was to encode correctness, to the greatest degree possible, in the database layer. No authoritative arithmetic is performed in application code. Rather, a series of Postgres views perform calculations on each line item; joining and conditionally applying relevant taxes, before aggregation at the document-level.1
This involves two many:many junction tables, and a conditional flag on the referenced configuration record—in other words, significant relational complexity lifted from callers. Floating-point precision issues are also neatly sidestepped, without having to introduce a new dependency. Accordingly, the codebase heavily orients around Drizzle.
Referential and historical integrity
Invoices are immutable, but their relational data is not implicitly so. Configuration holds data essential to decode documents, such as currency and taxes, but may be updated over time. Client billing information will similarly change. We use a slowly changing dimension pattern to maintain an immutable historical record. Only SCD entities may be included in the printable payload.
Strict referential integrity is enforced through composite foreign keys. These operate on denormalised references; for instance, a config ID is propagated down the invoice entity graph, such that document, line_item, and the item_tax junction table must all reference the same version. We can then ensure, at the junction level, that the referenced tax record is allowed under the active user configuration. You can see a simplified constraint in the above figure. This same pattern is used to protect ownership, eliminating cross-tenant references which would fail on read.
Tenant isolation
Every database table has an explicit row-level security policy for every operation, inherited by derived views via security invoker. This is a defence-in-depth strategy, enforcing tenant boundaries alongside the data.
We translate application session into PostgreSQL through a withRLS() adapter. This resolves the ambient session, initiates a transaction, and injects claims into that transaction scope. This is near the sole entry point into the database, and appears all throughout the codebase. A branded transaction type allows misuse to fail at compile-time.
/** * Resolves the Better Auth session from request headers, then wraps your * Drizzle calls in a transaction that sets the authenticated user for RLS. */ export async function withRLS<T>( callback: (tx: AuthTransaction, session: Session) => Promise<T>, ): Promise<T>;
withRLS()Drizzle semantics natively convert nested transaction calls into savepoints:2 a subtle pitfall, as deeply nested calls could silently fragment to break atomicity. We instead rely on Node.js AsyncLocalStorage to reuse the outer scope and run a plain query. This also helps mitigate the largest trade-off: that every database call is transactional, and opens a WebSocket connection. Folding into a single context is great for performance, and prevents the connection pool from exhausting.
RLS policy is also used to uphold immutability guarantees. Unlike column-level security, this can live alongside the Drizzle schema and track within generated migrations. An entire row must share policy, which influences database design. For example: mutable status, such as voiding an invoice, is separated from immutable data in a one-to-one relationship, using a deferred foreign key.
A complementary bypassRLS() helper allows circumvention within test environments: used for preconditions, and to assert application-layer protections.
Testing rigour
That architectural decision comes with unique testing constraints. We can’t mock database calls to assert behaviour like taxation and writability. Instead, we spin up a real instance. PGlite offers lightweight, disposable WASM Postgres. An in-memory fixture runs migration history, and isolates Better Auth against that database instance.
/** Vitest fixture to simulate a user connection with: * - a disposable PGlite database * - a logged-in session * - an isolated, per-test transaction */ export const asUser = test .extend('client', { scope: 'worker' }, async ({}, { onCleanup }) => { const client = await warmClient(); onCleanup(() => client.$client.close()); return client; }) .extend<{ db: TestTX }>({ db: [ async ({ client }, use) => { await client.transaction(tx => testConnection.run(tx, async () => { await use(tx); // Rollback skips commit-time checks, so run them here await tx.execute(sql`SET CONSTRAINTS ALL IMMEDIATE`); throw ROLLBACK; // Sentinel error })) .catch(err => { if (err !== ROLLBACK) throw err; }); }, // Forces fixture to run even if not destructured in the test. // Production code may access DB, even if test does not. { auto: true }, ], }) .extend('auth', ({ db }) => createTestAuth(db)) .extend('session', ({ db, auth }) => createTestSession(db, auth)) .extend('seed', ({ db, session }): SeedFixture => { /* … */ });
The connection is warmed during setup, and reused over a test worker. This preserves execution speed by delegating isolation to the fixture transaction. Concurrent testing again leverages AsyncLocalStorage to prevent races, although the underlying database remains single-connection.
Vitest is used to run unit and integration tests, along with type-level assertions. UI testing uses browser mode environments, matrixed through Playwright. Due to the code-first schema, application tests can also assert database invariants, such as mandatory indexes.
There are two other notable testing layers, both addressing the API contract.3
- Spectral linting targets the OpenAPI specification, generated through a Hono pipeline. This enforces style, security practices, and consistency (such as RFC 9457 problem detail responses).
- Adherence to this specification is then verified through adversarial fuzz testing. I built a small bridge between Schemathesis, which is Python based, and Vitest—allowing reuse of the same database isolation machinery used for integration testing.
Data protection
The design scope intentionally minimises processed sensitive data. Payment is not handled, so the only financial details captured are the receiving bank account details. This data is encrypted, as are columns not required for database indexing and filtering. It is necessary to filter clients by region, but the street address—which is more sensitive—can be encrypted.
This is achieved through symmetric envelope encryption, whereby a single KEK is used to protect tenant DEKs, and facilitate key rotation. XChaCha20-Poly1305 was chosen, with a managed nonce via noble cryptography. The consuming crypto utilities form closures, encapsulating key access and minimising the potential for misuse.4
/** Issues a crypto vault to the provided callback. * @remarks Keys are zeroed once the outermost callback settles. */ export async function withVault<T>( callback: (vault: Vault) => Promise<T & NoVault<T>>, ): Promise<T>;
withVault() mirrors the withRLS() pattern from earlierA custom Drizzle type was written to serialise encrypted data to a Postgres bytea column. An Encrypted class is used to discriminate values, both at type and runtime levels. This allows a recursive walker to safely parse objects containing mixed types.
Interface design
This article is not intended as interface analysis, so this section will remain brief. I have a visual background, and believe in the importance of treating design implementation as a serious engineering concern.5 I want to finish with an interesting CSS-only technique to cleanly tile over variable width content.




Pencil scribble effect
Voided invoices are not included in aggregation statistics, so I felt the need for an indication directly targeting excluded figures, not merely at the invoice level.
Edit the text to see the scribble change
Figures are of variable dimensions, so stretching a single stroke over the text would quickly fall apart. I had naively hoped that a sawtooth-style stroke would ease tiling concerns: reducing the protrusion of backstrokes into clipped edges, which form orphaned islands of graphite in the corners of the frame. In practice, these vertical strokes felt unnaturally rigid—and the width of the stroke meant that they would frequently be clipped regardless.

Complete scribble stroke, with consistent frequency
The solution was ultimately very simple. The stroke is drawn to maintain a clear breakpoint at regular intervals. We then apply the CSS round() function, which had just hit baseline, to quantise the scribble width to the stroke frequency. This is a progressive enhancement, and unsupported browsers can just fallback to standard clipping.
.scribble { --size: 6rem; --frequency: 7; width: round(up, 100%, calc(var(--size) / var(--frequency))); /* Center the scribble pattern, snapping to the grid */ /* This ensures the first and last segments vary between instances */ background-position: round(down, 50%, calc(var(--size) / var(--frequency))) 50%; background-size: var(--size); background-repeat: repeat-x; background-image: url("/scribble.svg"); }
Variations are trivial, using stacked nth-child selectors to apply transforms. The pencil effect is an SVG filter, inspired by this fantastic write-up and baked into the tile for improved performance.6
Further reading
-
We support global addresses with metadata adapted from the Google address data service. This drives formatting, validation, and an internationalised field input.
-
I touched down across the globe to find the database unresponsive. The cause transpired to be a DNS resolution bug in Node. The issue thread is an interesting read.
-
CSS custom property based polyfill for
light-dark()adapted from Lightning CSS. It bridges between JavaScript and CSS config files, which otherwise do not agree on the dark variant. -
A brief technique for instant theme transitions.
Footnotes
-
The performance penalty is acceptable at this scale. ↑
-
Note that
SAVEPOINTrequires access to the transaction scope. This issue would arise if attempting to mirror Drizzle semantics when reusing nested context. ↑ -
A conditional
#rpcimport resolves the same pipeline on both internal and external reads, therefore this testing additionally validates application assumptions. ↑ -
Zeroing is merely best-attempt in JavaScript, due to limited explicit resource management. ↑
-
As an example: this site uses area-based image scaling, to preserve a consistent visual weight between images of different orientations. ↑
-
WebKit does not reliably handle complex SVG filters, so this is also a compatibility win. ↑