Skip to Content
Data ArchitectureTransactional Schema

Transactional Schema (PostgreSQL 18)

Overview & Storage Boundaries

OpenTier v1.1.0 cleanly partitions data by workload:

  • PostgreSQL 18 is the ACID system of record for accounts, sessions, conversations, metadata, credit ledgers, and provider catalog configurations.
  • Qdrant is the dedicated vector system of record for dense neural vectors (3072d) and sparse BM25 token indices (knowledge_chunks collection).

All PostgreSQL migrations are centralized in server/api/migrations/ and applied automatically on API gateway startup via SQLx.

Migration ToolLocationPrimary Tables
sqlx-cliserver/api/migrations/users, sessions, accounts, conversations, chat_messages, user_memories, documents, ingestion_jobs, model_providers, models, user_credit_balances, credit_transactions, credit_holds, event_outbox

Entity Relationship Diagram


Core Table Details

1. Identity & Authentication

users

System accounts for standard, contributor, and admin roles.

ColumnTypeConstraintsDescription
idUUIDPK, gen_random_uuid()Unique user identifier.
emailVARCHAR(255)UNIQUE, NOT NULLUser email address.
email_verifiedBOOLEANNOT NULL, DEFAULT falseVerification status (OAuth auto-verifies).
password_hashVARCHAR(255)NULLBcrypt hash (null for OAuth-only users).
nameVARCHAR(255)NULLDisplay name.
usernameVARCHAR(50)UNIQUE, NULLProfile username.
roleuser_roleNOT NULL, DEFAULT ‘user’Enum: user, contributor, admin.
deleted_atTIMESTAMPTZNULLSoft-deletion timestamp.

sessions

Opaque session tokens for stateless REST & SSE authentication.

ColumnTypeConstraintsDescription
idUUIDPKSession ID.
user_idUUIDFK users(id) ON DELETE CASCADETarget user.
session_tokenVARCHAR(255)UNIQUE, NOT NULL64-character random cryptographically secure token.
expires_atTIMESTAMPTZNOT NULLExpiration timestamp (default: 30 days).
roleuser_roleNOT NULLCached user role snapshot for O(1) single-lookup auth.
ip_addressINETNULLClient IP address.
user_agentTEXTNULLClient user agent string.

accounts

External OAuth 2.0 identity bindings (Google, GitHub, Microsoft, Discord).


AI Model Catalog & Routing Tables

v1.1.0 replaces hardcoded model environment variables with dynamic, database-backed catalog configurations.

model_providers

Configured LLM and embedding providers. API keys are sealed at rest using AES-256-GCM.

ColumnTypeDescription
idUUID PKProvider identifier.
nameVARCHAR(100)Display name (e.g. Google Gemini, OpenAI).
slugVARCHAR(50) UNIQUEProvider slug (google, openai, ollama, custom).
api_baseVARCHAR(255)Base URL endpoint override (e.g. for Ollama or vLLM).
encrypted_api_keyTEXTAES-256-GCM sealed ciphertext blob (decrypted via ENCRYPTION_MASTER_KEY).
enabledBOOLEANGlobal enable/disable toggle.
configJSONBProvider-specific tunings and headers.

models

Specific models attached to providers with pricing and fallback chains.

ColumnTypeDescription
idUUID PKModel identifier.
provider_idUUID FKReferences model_providers(id).
slugVARCHAR(100) UNIQUEModel slug (e.g. gemini-2.5-flash, gpt-4o, text-embedding-3-large).
model_typeVARCHAR(20)chat, embedding, or rerank.
context_windowINTEGERToken limit for prompt context.
pricingJSONBCost structure: {"input_cost_per_million": 0.15, "output_cost_per_million": 0.60}.
is_defaultBOOLEANDefault model for the given model_type.
fallback_slugVARCHAR(100)Slug of secondary model to try if this model is exhausted or errors.

Credit Ledger & Billing Tables

v1.1.0 introduces an immutable, append-only credit ledger for real-time token metering and usage quotas. Credits are denominated such that **1 credit = 0.001USD∗∗(1,000credits=0.001 USD** (1,000 credits = 1.00). New users receive an automatic 10.00 credit signup bonus ($0.01 equivalent).

user_credit_balances

Atomic user balance and optimistic lock version tracking.

ColumnTypeConstraintsDescription
user_idUUIDPK, FK users(id)User owning the credit balance.
balanceNUMERIC(14,4)NOT NULL, DEFAULT 0, CHECK >= 0Spendable credit balance.
heldNUMERIC(14,4)NOT NULL, DEFAULT 0Currently reserved credits for active streaming calls.
versionBIGINTNOT NULL, DEFAULT 0Version counter for optimistic concurrency checks.

credit_transactions (Append-Only Ledger)

Comprehensive audit trail recording every balance adjustment, token consumption, and grant.

ColumnTypeConstraintsDescription
idUUIDPK, gen_random_uuid()Unique transaction ID.
user_idUUIDFK users(id)Debited or credited user.
deltaNUMERIC(14,4)NOT NULLChange in balance (positive for grants, negative for usage).
balance_afterNUMERIC(14,4)NOT NULLSnapshot of balance immediately following transaction.
reasonVARCHAR(30)NOT NULLgrant, usage, refund, admin_adjustment, signup_bonus.
model_idUUIDFK models(id)Model consumed during the transaction (if usage).
tokens_inINTEGERDEFAULT 0Input prompt tokens billed.
tokens_outINTEGERDEFAULT 0Generated completion tokens billed.
cost_inputNUMERIC(14,6)DEFAULT 0Computed credit cost of input tokens.
cost_outputNUMERIC(14,6)DEFAULT 0Computed credit cost of output tokens.
conversation_idUUIDNULLContext conversation ID.
idempotency_keyTEXTNOT NULL, UNIQUEDeduplication key preventing double-billing on retries.
correlation_idVARCHAR(64)NULLDistributed tracing correlation ID.

credit_holds

Temporary reservations placed prior to streaming responses to guarantee sufficient funds before tokens are generated.


Transactional Outbox (event_outbox)

Guarantees reliable message publishing between PostgreSQL transactions and Redis Streams without dual-write race conditions.

ColumnTypeDescription
idUUID PKEvent ID.
streamTEXTTarget Redis stream (e.g. opentier:intel:chat_events).
event_typeTEXTEvent type descriptor (e.g. billing.charge.v1).
correlation_idTEXTTracing correlation ID.
payloadJSONBSerialized event payload.
attemptsINTEGERDelivery attempt count.
published_atTIMESTAMPTZTimestamp when successfully acknowledged by Redis.

Chat & Ingestion Tables

  • conversations: Chat thread metadata, titles, and ownership.
  • chat_messages: Chat messages with sources (JSONB) citations and tree branching via parent_id.
  • user_memories: Persistent per-user context updated asynchronously by workers.
  • documents: Ingested content catalogs (titles, URLs, status).
  • ingestion_jobs: Status tracking (queued, processing, completed, failed) for the background worker ingestion pipeline.
Last updated on