24 July, 2026

The PostgreSQL Black-Box Architecture in Autheona

By eliminating ORM network chatter and shifting business logic directly into PostgreSQL via versioned JSONB functions, we engineered a fraud detection architecture that processes complex validation rules with ms latency.

If you're new to tech or are a junior, read the following Jargon Decoder before continuing.

Key Terms
  • Black-Box SQL: A database design pattern where the application code cannot access tables directly and interacts exclusively through a strict API of stored procedures.
  • pgTap: A suite of database functions that makes it easy to write unit tests for PostgreSQL objects directly in the database.
  • JSONB: A binary JSON format in PostgreSQL that allows for highly efficient querying and indexing of document-style data.
  • Schema Isolation: Organizing database objects (tables, functions, views) into logical namespaces based on their business domain or access patterns.
  • Data Entropy: A measure of randomness or unpredictability in data, often used in fraud detection to identify programmatically generated email addresses.

The Napkin Math Formula:

Network Latency Impact of Traditional ORM vs. Black-Box Execution

Traditional Latency = (Q * L) + P
Black-Box Latency = L + (P * O)

Q = Number of sequential queries
L = Network latency per round trip
P = Database processing time per query
O = Optimizer efficiency factor (typically 0.8 inside DB)

Example:

A user signup requires 5 sequential steps: user creation, profile setup, subscription initialization, audit logging, and email verification queueing. Assume a 10ms network round trip and 2ms query processing time.

Traditional: (5 * 10ms) + (5 * 2ms) = 60ms total latency
Black-Box: 10ms + ((5 * 2ms) * 0.8) = 18ms total latency

By eliminating network round trips, the Black-Box approach reduces transaction latency by 70%. At 10,000 requests per second, this translates directly to fewer stalled connections, lower compute overhead, and reduced infrastructure spend.

The Graveyard

A web backend, a mobile API, and an internal reporting tool will inevitably implement the same validation logic differently. This duplication guarantees data corruption over time. Furthermore, giving the application global SELECT, INSERT, and DELETE privileges expands the security surface area. A compromised application server results in a fully compromised database.

Performance also degrades at scale. Complex operations require multiple network requests back and forth between the application and the database. Under heavy load, this network chattiness exhausts connection pools and spikes latency, triggering the exact infrastructure costs Autheona is designed to prevent.

PostgreSQL as a Black Box Architecture

Autheona implements a strict Black-Box SQL strategy. The core PostgreSQL database is entirely opaque to the backend application. The application never executes raw queries. It has zero visibility into tables, columns, or relationships. We revoke all table-level access from the application user account. The application is granted EXECUTE privileges exclusively on specific, version-controlled functions.

When the application needs to create a user or evaluate a fraud signal, it passes a JSON payload to a PostgreSQL function. The database processes the input, executes the necessary internal steps, and returns a structured JSON response.

This provides zero-downtime refactoring. We can restructure tables, split columns, and migrate data without modifying a single line of backend code. As long as the function signature and the output schema remain consistent, the application remains completely unaware of the underlying structural changes.

Database Topology and Schema Isolation

A flat database structure becomes unmaintainable as domain logic increases. We separate our database objects into distinct schemas based on their use case and data lifecycle. The topology follows a strict hierarchy. Core operational data resides in one schema. High-volume analytics and logging sit in another. Temporary data, such as transient fraud evaluations, is held in a separate schema optimized for heavy write and delete cycles.

We do not use backend application migrations to manage this topology. We define schemas, tables, and functions using direct SQL files. This decouples database deployments from application deployments, allowing database administrators to tune indexes and partitions without requiring a backend release cycle.

Versioned JSONB Functions

Communication between the application and the database requires a standardized protocol. We categorize all functions into CRUD operations: create, retrieve, update, and delete.

We prefix every function with a version number (e.g., v1). If business requirements change drastically, we deploy a v2 function. The application can migrate to the new function at its own pace, eliminating breaking changes during deployments. To maintain flexibility, we standardize the input and output variables using JSONB. Here is the core template for a v1 function:

CREATE OR REPLACE FUNCTION schema_name.v1 (p_data JSONB)
  RETURNS JSONB VOLATILE
  AS $$
DECLARE
  k_status CONSTANT TEXT := 'status';
  k_code CONSTANT TEXT := 'code';
  k_message CONSTANT TEXT := 'message';
  k_additional CONSTANT TEXT := 'additional';
  k_data CONSTANT TEXT := 'data';
  v_exception TEXT;
BEGIN

  -- Implementation logic goes here

  RETURN json_build_object(k_status, TRUE, k_code, 'CODE', k_message, NULL, k_additional, NULL, k_data, NULL)::JSONB;
EXCEPTION
  WHEN OTHERS THEN
    GET STACKED DIAGNOSTICS v_exception = PG_EXCEPTION_CONTEXT;
  RETURN json_build_object(k_status, FALSE, k_code, SQLSTATE, k_message, SQLERRM, k_additional, v_exception, k_data, NULL)::JSONB;
END;

$$
LANGUAGE plpgsql;

Lines 5-9 declare constant string keys. This prevents typos when constructing the final JSON return object and minimizes memory overhead by reusing string literals. Line 13 executes the core logic, which is omitted here for brevity. Line 15 builds the standard JSON response, explicitly casting it to JSONB for optimized transfer. Line 16 introduces the global exception block. If any error occurs during the transaction, the database automatically rolls back any changes. Lines 18-19 capture the stack trace and SQL error codes, returning them safely inside the structured JSON payload rather than crashing the application connection.

Composability and Scaling

The Black-Box pattern excels when dealing with dependent operations. When scaling a platform, a simple "create project" action quickly evolves to require subscription initialization, quota allocation, and audit logging.

Instead of writing this sequential logic in the application layer, we compose database functions. A primary function can call secondary functions internally, maintaining transactional integrity and avoiding network round trips.

-- Inside the main project creation function

v_subscription_result := schema_main.v1_subscription_create (json_build_object('account_code', v_account_code)::JSONB);

IF NOT (v_subscription_result ->> k_status)::BOOLEAN THEN
  RAISE EXCEPTION 'SUBSCRIPTION_CREATION_FAILED: %', v_subscription_result ->> k_message;
END IF;

Line 3 calls the v1_subscription_create function, passing a dynamically constructed JSON object. The result is stored in v_subscription_result. Line 5 uses the PostgreSQL ->> operator to extract the status value as text, casting it to a BOOLEAN. If the status is false, Line 6 throws a custom exception, appending the exact error message returned by the nested function. This immediately halts execution, triggers the parent function's exception block, and rolls back the entire transaction.

Traditional stored procedures suffer from parameter bloat. If a user profile adds ten new fields, a standard SQL function requires an updated signature with ten new variables. We bypass this structural rigidity by standardizing on PostgreSQL's JSONB data type.

CREATE OR REPLACE FUNCTION schema_name.v1_create (p_data_to_add JSONB)
CREATE OR REPLACE FUNCTION schema_name.v1_retrieve (p_data JSONB)
CREATE OR REPLACE FUNCTION schema_name.v1_update (p_key_to_update UUID, p_payload_to_update JSONB)
CREATE OR REPLACE FUNCTION schema_name.v1_delete (p_key_t_delete UUID)

By compressing arguments into a single JSON object, the function signature becomes immutable. Whether the frontend passes two configuration flags or two hundred initialization parameters, the database interface remains completely static. This isolates the database layer from application-level data model changes and eliminates the parameter bloat that typically plagues complex backend architectures.

Handling Failure States

No architecture is immune to failure. Database CPU utilization can spike, disk IO limits can be reached, or invalid data types can slip past frontend validation.

Our fallback mechanism relies entirely on the standardized JSON return object. The database never throws a raw exception to the application. It traps its own internal errors and packages them into a predictable, structured payload. The universal response object consists of five immutable fields:

  • status: A boolean representing the absolute success or failure of the transaction.
  • code: A normalized, business-level routing key (e.g., USER_CREATED, USER_ALREADY_EXISTS).
  • message: A string capturing the human-readable context or exact failure reason.
  • additional: A debug payload containing internal telemetry, such as the Postgres stack trace.
  • data: The actual JSONB payload containing the queried data on a successful retrieval.

Here is what the backend receives when a constraint violation occurs:

{
  "status": false,
  "code": "USER_ALREADY_EXISTS",
  "message": "duplicate key value violates unique constraint 'users_email_key'",
  "additional": "PL/pgSQL function v1_user_create(jsonb) line 14 at RAISE...",
  "data": null
}

Standardizing responses introduces a specific operational risk: swallowing exceptions. Because the database function catches its own error and returns a formatted JSON object, the actual PostgreSQL transaction does not automatically abort.

To prevent silent failures, our architecture requires a mandatory, centralized middleware interceptor at the API level. This interceptor evaluates the status boolean of every single database response. If status is false, the interceptor immediately issues a ROLLBACK command to the database connection, logs the additional stack trace to our monitoring cluster, and halts execution. This guarantees strict data integrity while preserving the granular debugging context required for rapid incident resolution.

Shifting Left with pgTap

Testing a traditional database architecture requires booting the application, seeding the database, and running integration tests over HTTP. This process is slow, brittle, and difficult to isolate.

Because our logic lives in PostgreSQL, we test it in PostgreSQL. We use pgTap to write comprehensive unit tests for every schema, table constraint, foreign key, function, etc. When a developer modifies the v1_user_create function to include subscription logic, they write a corresponding pgTap test. If an invalid parameter is passed during the test, the test fails in milliseconds. This rapid feedback loop identifies structural defects and logic errors long before the application layer is even aware the database has changed. It ensures absolute confidence in the Black-Box interface prior to deployment.

Why We Built Autheona This Way

Autheona is a user trust API. It runs in the critical path of signup flows, newsletter subscriptions, lead capture forms, and account creation. These are trust boundaries. If Autheona fails, your users don't blame us. They blame you.

If you're building a signup flow - account creation, newsletter subscriptions, lead generation forms - and you need to verify users before letting them in, Autheona runs the trust checks. You integrate in minutes, and your signup flow gets the compliance and security foundation without rebuilding it yourself.

Secure Your Signup Flow →