Architecture & State
Architecture & State Ownership
HTTP PostgreSQL Gateway is designed as a persistent, high-throughput bridge between short-lived HTTP-only environments and a private PostgreSQL cluster. It maintains long-lived TCP connections, enforces fine-grained authorization, and coordinates state across background workers.
Component Topology
flowchart TD
Client["Serverless / Edge Client"]
subgraph Fastify["Fastify Web Server"]
Hooks["Authentication & Rate Limiting"]
AdminPool["PostgreSQL Admin Pool"]
QueryPools["Per-Key Query Pools"]
JsonDB[("data/data.json + Lock")]
Worker[("SQLite Analytics Worker")]
end
Postgres[("PostgreSQL Server")]
Client -->|"HTTPS JSON"| Hooks
Hooks --> AdminPool
Hooks --> QueryPools
Hooks --> JsonDB
Hooks -.-> Worker
AdminPool --> Postgres
QueryPools --> Postgres
Core Subsystems
1. HTTP Layer (Fastify)
Fastify manages request routing, JSON parsing, payload size enforcement, compression, and error responses. Authentication and rate limiting execute as early lifecycle hooks. Public access is strictly limited to GET /health and HEAD /health.
2. Administrative PostgreSQL Pool
A dedicated connection pool configured by database.url serves internal gateway operations:
- Verifying database identities and validating schemas.
- Managing persistent execution state in the
http_postgres_gatewayschema. - Performing administrative actions (creating/renaming databases, listing tables).
- Provisioning restricted PostgreSQL roles for scoped API keys.
3. Per-Key Query Pools
Client SQL runs through isolated pools segregated by database name and API key identity.
- Verification: Before checkout, each session is verified against PostgreSQL's
pg_stat_activityto guarantee it is idle and healthy. - Session Reset: After every request, the gateway issues
DISCARD ALLand rolls back uncommitted transactions before returning the connection to the pool. - Global Budgeting: A process-wide connection cap (
database.pool.maxGlobalQueries) bounds total query connections across all pools.
4. API-Key Metadata Store (data/data.json)
Stores the administrator password hash, API key records, database identity bindings, and HMAC seed material used to derive credentials for scoped PostgreSQL roles. Writers are serialized using a SQLite lock file (data/data.json.lock).
5. Rate-Limit Store
- Redis Mode (Production): Distributed atomic counters shared across multiple gateway replicas using Redis
EVALscripts. - In-Memory Mode (Local Dev): Process-local rate-limiting windows when Redis is disabled.
6. SQLite Analytics Worker
Query counts and failed-query diagnostics are buffered in memory and flushed asynchronously to SQLite via a dedicated worker thread. Analytics writes never block SQL execution.
Request Lifecycle
The lifecycle of an authenticated client query through the three core phases:
flowchart LR
subgraph P1["1. Ingress & Auth"]
direction TB
S1["POST /query"] --> S2["IP Rate Limiter"]
S2 --> S3["API Key & DB Auth"]
S3 --> S4["Key Rate Limiter"]
end
subgraph P2["2. Pool & Execution"]
direction TB
S5["Role Resolution"] --> S6["Pool Checkout"]
S6 --> S7["Timeout Limits (30s)"]
S7 --> S8["PostgreSQL Execution"]
end
subgraph P3["3. Result & Return"]
direction TB
S9["Serialization"] --> S10["Async Analytics"]
S10 --> S11["DISCARD ALL Cleanup"]
S11 --> S12["Client Response"]
end
P1 ==> P2
P2 ==> P3
Execution Modes & Durability Matrix
| Work Type | Input / Queue Location | Outcome Storage | Restart Behavior |
|---|---|---|---|
| Immediate Query | Request memory | HTTP response body | No replay; outcome unknown if interrupted |
| Async Query | Process scheduler | http_postgres_gateway.async_queries | Record survives; interrupted work not replayed |
| Atomic Batch | Process scheduler | http_postgres_gateway.transactions | Record survives; idempotent retry supported |
| Queued Transaction | Process heap memory | Process heap until committed | Lost on restart; must be recreated |
Transaction Lifecycle & Commit Staging
For atomic batches (POST /transaction/execute):
- Idempotency Check: If an
Idempotency-Keyheader is present, the gateway verifies the normalized fingerprint against previous submissions. - Persistence: The batch is recorded in PostgreSQL in the
http_postgres_gateway.transactionstable with statuspending. - Execution: Statements are executed in order inside a transaction block.
- Result Staging: Results are staged before issuing
COMMIT. - Commit Confirmation: The gateway commits the transaction and immediately updates status to
committed. Results are exposed only after commit confirmation is written. - Failure & Unknown States: If connection to PostgreSQL is lost during
COMMIT, the transaction status becomesunknown. The client must inspect application state before retrying.
Scaling Boundaries & Multi-Process Clusters
When scaling to multiple gateway instances behind a load balancer:
- Durable Records: Async query and atomic batch records in
http_postgres_gatewaycan be read or polled by any replica connected to the same administrative database. - Shared Metadata: Replicas must share
data/data.jsonover a filesystem that provides reliable POSIX SQLite locking and atomic file renaming. - Distributed Rate Limiting: Redis is required for unified rate limits across replicas.
- Queued Transactions: Interactive queued transactions are held in process memory. Workflows using queued transactions require sticky sessions (session affinity).
