The Trinity BeastAurora Data Dictionary

Complete schema reference for CPMP_Backend_AuroraAurora PostgreSQL Serverless v2. All 42 tables, 491 columns, indexes, and foreign keys.

Database: CPMP_Backend_Aurora Engine: Aurora PostgreSQL Serverless v2 Updated: May 30, 2026 Version: v20

Table of Contents

  1. Group 1 — Core: Users & Authentication
    1. 1.1 api_keys — API key management for subscribers
    2. 1.2 api_key_groups — API key capability group templates
    3. 1.3 rate_limit_template — Rate limit presets by subscription tier
    4. 1.3 users — Subscriber and donor accounts
  2. Group 2 — Configuration
    1. 2.1 application_parameter_profiles — System-mode parameter profiles
    2. 2.2 application_parameters — Runtime configuration parameters
    3. 2.3 report_parameters — LRS-specific configuration
  3. Group 3 — Billing & Payments
    1. 3.1 payment_links — Stripe Payment Link management for checkout
    2. 3.2 transactions — Payment records
    3. 3.3 tier_catalog — Product pricing catalog (single source of truth)
  4. Group 4 — Usage Logging
    1. 4.1 monthly_report_counts — Monthly report usage aggregation
    2. 4.2 report_count — Per-API-key report limit tracking
    3. 4.3 report_usage_logs — LRS report request log
    4. 4.4 usage_logs — LPO API call log
    5. 4.5 mv_usage_daily — Daily-rollup materialized view (Phase 6)
  5. Group 5 — Exchange & Pricing
    1. 5.1 asset_categories — Crypto asset category groupings
    2. 5.2 exchange_asset_map — Exchange-to-asset symbol translations
    3. 5.3 exchange_feeds — Exchange WebSocket feed configurations
  6. Group 6 — Email & Newsletters
    1. 6.1 email_drafts — Email composition drafts
    2. 6.2 email_senders — Verified SES sender identities
    3. 6.3 email_templates — SES email templates
    4. 6.4 email_translations — Multi-language email template fields
    5. 6.5 newsletter_subscribers — Newsletter mailing list
    6. 6.6 newsletter_templates — Newsletter email templates
    7. 6.7 newsletter_translations — Multi-language newsletter content
    8. 6.8 newsletters — Sent newsletter campaigns
  7. Group 7 — Support & Engagement
    1. 7.1 demo_leads — Demo registration captures
    2. 7.2 error_messages — Multi-language API error messages
    3. 7.3 map_pins — CPMP mission impact map markers
    4. 7.4 partner_applications — AWS Partner application submissions
    5. 7.5 support_replies — Support ticket replies
    6. 7.6 support_tickets — Customer support system
  8. Group 8 — Operations & Maintenance
    1. 8.1 cron_execution_logs — Cron job execution tracking
    2. 8.2 cron_reset_logs — Cron job execution log (same schema as cron_execution_logs)
    3. 8.3 cron_reset_summary — Reset summary statistics
  9. Group 9 — Website Analytics
    1. 9.1 page_events — Website interaction event tracking
    2. 9.2 page_views — Website page view analytics
  10. Group 10 — Webhook Push
    1. 10.1 webhook_subscriptions — Webhook subscriber configurations and delivery state
    2. 10.2 webhook_delivery_log — Webhook delivery attempt log
  11. Group 11 — Translation Engine
    1. 11.1 translation_jobs — Translation job orchestration
    2. 11.2 translation_job_events — Translation job audit log
    3. 11.3 translation_quotes — Customer-facing translation quotes with Stripe payment
  12. Group 12 — Agent Profiles
    1. 12.1 agent_profiles — UME agent identity registry
    2. 12.2 agent_profile_events — Agent profile audit log

Logical Data Model — Full Database Diagram

Complete entity-relationship view of all 38 Aurora tables, organized into 11 domain groups. Each diagram shows related tables with their columns and foreign key relationships.

Identity & Access

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    users {
        uuid id PK
        text email UK
        text tier
        text name
        varchar preferred_lang
    }
    api_keys {
        uuid id PK
        uuid user_id FK
        text api_key UK
        text tier
        int query_limit
        int current_usage
        varchar api_lang
    }
    rate_limit_template {
        text tier PK
        int rate_limit_qps
        int burst_limit
        int query_limit
    }
    users ||--o{ api_keys : "owns"
        

Configuration

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    application_parameters {
        varchar key PK
        text value
        text description
    }
    application_parameter_profiles {
        uuid id PK
        text profile_name UK
        int qps
        int burst
        text log_level
    }
    report_parameters {
        varchar key PK
        text value
        text description
    }
        

Billing & Usage Tracking

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    transactions {
        uuid id PK
        text type
        text donor_email
        numeric amount_usd
        text stripe_charge_id UK
    }
    payment_links {
        int id PK
        text link_type
        text tier
        text stripe_url
    }
    usage_logs {
        uuid id PK
        text api_key_id
        text asset
        text source
        float8 price
    }
    report_count {
        uuid api_key PK
        int monthly_count
        int daily_count
    }
    report_usage_logs {
        uuid id PK
        text api_key_id
        text report_type
        int report_duration_ms
    }
    monthly_report_counts {
        text api_key PK
        bigint monthly_reports_counter
    }
    api_keys ||--o{ report_count : "tracks"
    api_keys ||--o{ usage_logs : "generates"
    api_keys {
        uuid id PK
        text tier
    }
        

Exchange & Pricing

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    exchange_feeds {
        int id PK
        text exchange_name UK
        text ws_endpoint
        boolean enabled
        text source_tag
    }
    exchange_asset_map {
        int id PK
        text exchange_name
        text asset
        text exchange_symbol
        boolean enabled
    }
    asset_categories {
        int id PK
        text category_name UK
        int display_order
        boolean enabled
    }
        

Email & Newsletters

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    newsletters {
        uuid id PK
        text title
        text type
        text status
    }
    newsletter_subscribers {
        uuid id PK
        text email
        text source
        varchar preferred_lang
    }
    newsletter_templates {
        uuid id PK
        text name
        text type
    }
    newsletter_translations {
        uuid id PK
        uuid newsletter_id FK
        varchar lang
    }
    email_templates {
        uuid id PK
        text name
        text topic
    }
    email_translations {
        uuid id PK
        text template_name
        varchar lang
        text field_name
    }
    email_drafts {
        uuid id PK
        text subject
        text status
    }
    email_senders {
        uuid id PK
        text display_name
        text email UK
    }
    newsletters ||--o{ newsletter_translations : "translated"
        

Support & Engagement

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    support_tickets {
        uuid id PK
        varchar ticket_number UK
        text email
        varchar status
        varchar preferred_lang
    }
    support_replies {
        uuid id PK
        uuid ticket_id FK
        text author
        varchar author_type
    }
    error_messages {
        int id PK
        varchar message_key
        varchar lang
        text message
    }
    demo_leads {
        uuid id PK
        text email
        text platform
    }
    map_pins {
        uuid id PK
        text type
        float8 lat
        float8 lng
    }
    partner_applications {
        uuid id PK
        text company_name
        text status
    }
    support_tickets ||--o{ support_replies : "has"
        

Operations & Maintenance

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    cron_execution_logs {
        uuid id PK
        text job_name
        text status
        int rows_affected
    }
    cron_reset_logs {
        uuid id PK
        text job_name
        text status
        int rows_affected
    }
    cron_reset_summary {
        uuid id PK
        text job_name
        text status
        int rows_affected
    }
        

Website Analytics

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    page_views {
        uuid id PK
        varchar page_path
        varchar country
        varchar device_type
        varchar visitor_id
    }
    page_events {
        uuid id PK
        varchar page_path
        varchar event_type
        varchar visitor_id
    }
        

Webhook Push Delivery

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    webhook_subscriptions {
        uuid id PK
        uuid api_key_id FK
        text tier
        text delivery_method
        int interval_seconds
        text status
    }
    webhook_delivery_log {
        bigint id PK
        uuid subscription_id FK
        text asset
        numeric price
        text status
        float8 latency_ms
    }
    webhook_subscriptions ||--o{ webhook_delivery_log : "logs"
    api_keys ||--o{ webhook_subscriptions : "subscribes"
    api_keys {
        uuid id PK
        text tier
    }
        

Translation Engine

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#334155', 'primaryTextColor': '#e2e8f0', 'primaryBorderColor': '#475569', 'lineColor': '#64748b', 'secondaryColor': '#1e293b', 'tertiaryColor': '#253347', 'background': 'transparent', 'mainBkg': '#334155', 'nodeBorder': '#475569'}}}%%
erDiagram
    translation_jobs {
        uuid id PK
        varchar job_id UK
        varchar state
        jsonb docs
        jsonb langs
        int total_pairs
        int succeeded_pairs
        int failed_pairs
        numeric bedrock_cost_usd
        varchar model
    }
    translation_job_events {
        bigint id PK
        varchar job_id
        varchar event_type
        varchar doc
        varchar lang
        jsonb detail
    }
    translation_jobs ||--o{ translation_job_events : "emits"
        

38 tables across 11 domain groups. Lines between entities represent foreign key relationships.

Group 1 — Core: Users & Authentication3 tables

1.1 api_keys

Purpose: API key management for all system actors. Stores every issued API key along with its capability flags, tier, rate limits, usage counters, Stripe billing references, and subscription state. Central table for authentication and authorization of all LPO/LRS API requests. The boolean capability flags are the authoritative source for behavioral routing — rate limiting, billing checks, product access, and translation service eligibility.

32 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique identifier for the API key record
user_id FK → users.iduuidYESOwner of the key; references the users table. NULL for system/internal keys.
key_hashtextYESLegacy hash field (unused in current implementation)
nametextYESSubscriber name associated with this key
tiertextfreeYESSubscription tier: free, pro, enterprise, unlimited, lifetime, partner, stress, standard, or translation tier variants. The tier drives rate limit values; the boolean flags drive behavioral routing.
query_limitinteger1000YESMaximum number of API queries allowed per month
current_usageinteger0YESCurrent month's query count; reset monthly by cron job
last_usedtimestamptzYESTimestamp of the most recent API call using this key
created_attimestamptznow()YESWhen this API key was created
revokedbooleanfalseYESWhether this key has been disabled/revoked
rate_limit_qpsinteger5YESMaximum queries per second allowed for this key
burst_limitinteger20YESToken bucket burst capacity for rate limiting
burst_tokensfloat820YESCurrent token balance in the rate-limit token bucket
api_keytextencode(extensions.gen_random_bytes(32), 'hex')NOThe actual API key string (plaintext); used for authentication
last_successtimestamptzYESTimestamp of the last successful (non-error) API call
minimum_wait_secondsfloat8'1'::double precisionYESMinimum time between requests when the key is being throttled
lrs_enabledbooleanfalseYESWhether unlimited LRS (Listener Report Service) reports are enabled
response_formattexttbcNOPreferred response format: tbc (The Trinity Beast Canonical) or plain
stripe_customer_idtextYESStripe customer ID used for billing portal and webhook event lookups
stripe_subscription_idtextYESMain LPO subscription ID in Stripe
stripe_lrs_subscription_idtextYESSeparate LRS add-on subscription ID in Stripe
subscription_statustextactiveNOCurrent subscription state: active, past_due, or canceled
tier_effective_datetimestamptzYESWhen the current tier took effect (for proration tracking)
payment_failed_attimestamptzYESTimestamp of the first payment failure (triggers grace period logic)
api_langvarchar(5)enNOPreferred language for API response messages (UME Phase 2). Default: en
is_systembooleanfalseNOCapability flag. Internal/tooling key — admin, demo, stress. No billing. No rate limits. No user account required.
is_subscriberbooleanfalseNOCapability flag. REST API subscriber — any paying or free tier (free, pro, enterprise, unlimited, lifetime). Has a user account and Stripe record.
is_partnerbooleanfalseNOCapability flag. AWS PrivateLink / VPC peering partner. No rate limits. No billing. 60-minute API key cache.
is_webhookbooleanfalseNOCapability flag. Webhook push product subscriber. Outbound price delivery at tier-configured intervals. Separate tier catalog from REST subscriptions.
is_translationbooleanfalseNOCapability flag. Translation service customer. Files stored in trinity-beast-translations S3 bucket under {api_key_id}/{lang}/{file}. Has a customer registry in Valkey.
is_rate_limitedbooleanfalseNOBehavioral flag. Subject to QPS limits and monthly query caps. Hot path checks this single boolean — no tier string comparison needed. True for: free, pro, enterprise, webhook tiers.
is_billing_exemptbooleanfalseNOBehavioral flag. Skip monthly cap checks entirely. True for: system keys, partner, unlimited, lifetime (paid upfront — no monthly caps). The billing check path is bypassed completely.

API Key Groups — Capability Flag Reference

Every API key belongs to one or more groups defined by its boolean capability flags. The flags are set at key creation and updated when a key's purpose changes. They are the authoritative source for behavioral routing — no tier string comparisons in application code.

Group is_systemis_subscriberis_partner is_webhookis_translation is_rate_limitedis_billing_exempt Purpose
System Internal tooling — admin console, demo key, stress testing. No user account required. No billing. No rate limits.
Subscriber (rate-limited) Paying REST API subscribers on metered tiers (free, pro, enterprise). Subject to QPS limits and monthly query caps.
Subscriber (exempt) Subscribers who paid upfront (unlimited, lifetime). No monthly caps. No rate limits. Billing check path bypassed entirely.
Partner AWS PrivateLink / VPC peering partners. No rate limits. No billing. 60-minute API key cache. We receive freely, we give freely.
Webhook Webhook push product subscribers. Outbound price delivery at tier-configured intervals (3s–60s). Separate tier catalog. Rate-limited by push interval, not QPS.
Translation Translation service customers. Files stored in trinity-beast-translations/{api_key_id}/{lang}/{file}. Customer registry in Valkey. Optional delivery webhook URL.

Behavioral Rules

CheckFlagLogic
Apply rate limiting?is_rate_limitedIf true → enforce QPS + monthly cap. If false → skip entirely.
Check monthly billing cap?is_billing_exemptIf true → skip cap check. If false → check current_usage vs query_limit.
Allow translation service?is_translationIf true → customer has a registry entry and S3 storage path.
Allow partner endpoints?is_partnerIf true → PrivateLink / VPC peering access, 60-min cache.
Allow webhook delivery?is_webhookIf true → outbound push delivery active for this key.

Live Key Inventory (as of 2026-05-31)

Key (truncated)TierGroupOwner
tbcc-admin-fab798…adminSystemInternal — KCC admin console
demo-public-2026-03-01-abc123demoSystemInternal — public demo key
stress-test-unlimited-…stressSystemInternal — stress testing
stress-lifetime-2026-05-01-run17lifetimeSystemInternal — Run 17 stress test
lpo-admin-5194ac1e…lifetimeSubscriber (exempt)corydeankalani@cpmp-site.org
lpo-pro-e3b2cd3b…proSubscriber (rate-limited)Test account
lpo-partner-07be921e…partnerPartnerInternal — partner test key
lpo-webhook-289d463d…standardWebhookTest account

A key can hold multiple capability flags simultaneously. For example, a translation customer who also subscribes to the REST API would have both is_subscriber = true and is_translation = true.

Indexes

  • api_keys_api_key_key — UNIQUE on api_key
  • api_keys_pkey — UNIQUE on id
  • idx_api_keys_hash — on key_hash
  • idx_api_keys_stripe_customer_id — on stripe_customer_id WHERE stripe_customer_id IS NOT NULL
  • idx_api_keys_stripe_subscription_id — on stripe_subscription_id WHERE stripe_subscription_id IS NOT NULL
  • idx_api_keys_user — on user_id

Foreign Keys

  • user_idusers.id

1.2 api_key_groups

Purpose: API key capability group templates. Each row defines a named group with a preset combination of boolean capability flags. When a new API key is created, it is assigned a group_id and the flags are stamped onto the key from the group template in a single JOIN-based UPDATE. Adding a new capability to an entire group requires updating one row here — no per-key migrations. The group is the default; per-key flag overrides are still possible for exceptions.

12 columns

ColumnData TypeDefaultNullableDescription
id PKserialautoNOAuto-increment group identifier. Referenced by api_keys.group_id.
nametextNOUnique machine-readable group name: system, subscriber_metered, subscriber_unlimited, partner, webhook, translation.
display_nametextNOHuman-readable group name for UI and reports.
descriptiontextYESPlain-English description of the group's purpose and behavioral rules.
is_systembooleanfalseNOTemplate flag — internal/tooling keys. No billing. No rate limits.
is_subscriberbooleanfalseNOTemplate flag — REST API subscriber with a user account and Stripe record.
is_partnerbooleanfalseNOTemplate flag — AWS PrivateLink / VPC peering partner.
is_webhookbooleanfalseNOTemplate flag — webhook push product subscriber.
is_translationbooleanfalseNOTemplate flag — translation service customer with S3 storage and Valkey registry.
is_rate_limitedbooleanfalseNOTemplate flag — subject to QPS limits and monthly query caps.
is_billing_exemptbooleanfalseNOTemplate flag — skip monthly cap checks entirely (paid upfront or internal).
enabledbooleantrueNOWhether this group is available for assignment to new keys.
created_attimestamptznow()NOWhen this group was created.

Indexes

  • api_key_groups_name_key — UNIQUE on name
  • idx_api_key_groups_name — on name
  • idx_api_key_groups_enabled — on enabled

Seeded Groups (6 rows)

idnamedisplay_namesyssubprtwebtxrlbe
1systemSystem / Internal
2subscriber_meteredMetered Subscriber
3subscriber_unlimitedUnlimited Subscriber
4partnerAWS Partner
5webhookWebhook Push
6translationTranslation Customer

rl = is_rate_limited · be = is_billing_exempt · sys/sub/prt/web/tx = product capability flags

The JOIN Pattern

To read a key with its full capability profile in one query:

SELECT k.api_key, k.tier, g.name AS group_name,
       g.is_rate_limited, g.is_billing_exempt, g.is_translation
FROM api_keys k
JOIN api_key_groups g ON k.group_id = g.id
WHERE k.api_key = $1

To apply a new capability to an entire group (e.g. give all partners access to a new feature):

-- 1. Add the column to api_key_groups (and api_keys for the cached copy)
ALTER TABLE api_key_groups ADD COLUMN is_new_feature BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE api_keys ADD COLUMN is_new_feature BOOLEAN NOT NULL DEFAULT false;

-- 2. Set the flag on the group
UPDATE api_key_groups SET is_new_feature = true WHERE name = 'partner';

-- 3. Stamp onto all existing keys in that group
UPDATE api_keys k SET is_new_feature = g.is_new_feature
FROM api_key_groups g WHERE k.group_id = g.id AND g.name = 'partner';

New keys automatically get the correct flags at creation time — the receipt Lambda does a JOIN-based UPDATE immediately after INSERT.

1.3 rate_limit_template

Purpose: Rate limit presets by subscription tier. Defines QPS, burst, query limits, and minimum wait configurations for each tier. Used by the Lambda receipt handler when creating new API keys and by the LPO server for runtime rate limiting. Single source of truth for all tier configurations.

7 columns

ColumnData TypeDefaultNullableDescription
tier PKtextNOTier name (PK): free, pro, enterprise, unlimited, lifetime, partner, stress, or webhook_* variants
rate_limit_qpsinteger1NOQueries per second limit (0 = no limit for partner/unlimited/lifetime)
burst_limitinteger5NOToken bucket burst capacity
burst_tokensfloat85.0NOInitial token balance
query_limitinteger1000NOMonthly query limit (999999999 = unlimited)
min_wait_secondsfloat81.0NOMinimum wait between requests in seconds (0 = no wait)
descriptiontextYESHuman-readable description of the tier

Indexes

  • rate_limit_template_pkey — UNIQUE on tier

Current Tier Data (6 LPO + 5 Webhook = 11 rows)

TierQuery LimitQPSBurstMin Wait
LPO Subscription Tiers (6)
free1,000151.0s
pro50,0005100.2s
enterprise500,00010200.1s
unlimitedUnlimited0 (none)0 (none)0 (none)
lifetimeUnlimited0 (none)0 (none)0 (none)
partnerUnlimited0 (none)0 (none)0 (none)
Webhook Associate Tiers (5)
webhook_starter
webhook_standard
webhook_professional
webhook_enterprise
webhook_partner

Webhook tiers control push intervals and max assets, not QPS/burst (those fields are unused for webhook tiers).

1.3 users

Purpose: Subscriber and donor accounts. Minimal profile — email, name, tier, and language preference. The api_keys table holds the detailed subscription state.

6 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique user identifier
emailtextNOUser email address (unique)
tiertextfreeYESAccount tier: free, pro, enterprise, unlimited, lifetime, partner
created_attimestamptznow()YESAccount creation timestamp
nametextFriendYESDisplay name (default: 'Friend')
preferred_langvarchar(5)NULLYESPreferred language for communications (emails, newsletters, support). ISO 639-1 code.

Indexes

  • users_email_key — UNIQUE on email
  • users_pkey — UNIQUE on id
Group 2 — Configuration3 tables

2.1 application_parameter_profiles

Purpose: System-mode parameter profiles. Each profile defines a complete set of runtime tuning parameters (QPS, burst, cache, DB pool, SQS, UDP) that can be activated as a unit. Allows switching between performance modes without editing individual parameters.

34 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOUnique profile identifier
profile_nametextNOProfile name (unique): production, high-traffic, maintenance, etc.
descriptiontextYESHuman-readable description of when to use this profile
qpsinteger1000NOQueries per second setting for this profile
burstinteger1000NOBurst limit setting
log_leveltextinfoNOLogging verbosity: debug, info, warn, error
batch_sizeinteger300NOSQS message batch size for usage logging
batch_secondsinteger1NOSQS batch flush interval in seconds
micro_batch_capinteger500NOMaximum messages in micro-batch buffer
flush_interval_msinteger100NOMicro-batch flush interval in milliseconds
db_max_openinteger150NOMaximum open database connections
db_max_idleinteger75NOMaximum idle database connections
db_conn_lifetime_mininteger10NOMaximum connection lifetime in minutes
db_conn_idle_mininteger5NOMaximum idle connection time in minutes
cache_ttlinteger9NODefault cache TTL setting
config_pollinteger300NOConfiguration poll interval
cache_pool_sizeinteger600NOValkey connection pool size
cache_min_idleinteger120NOMinimum idle Valkey connections
cache_max_retriesinteger1NOMaximum Valkey operation retries
cache_dial_msinteger500NOValkey connection dial timeout in ms
cache_read_msinteger500NOValkey read timeout in ms
cache_write_msinteger500NOValkey write timeout in ms
created_attimestamptznow()NOProfile creation timestamp
updated_attimestamptznow()NOLast modification timestamp
udp_reader_goroutinesinteger8YESNumber of UDP reader goroutines per socket
udp_read_buffer_mbinteger32YESUDP socket read buffer size in MB
udp_write_buffer_mbinteger32YESUDP socket write buffer size in MB
udp_workers_per_socketinteger128YESWorker goroutines per UDP socket
udp_batch_sizeinteger32YESUDP response batch size
udp_pre_serializebooleantrueYESWhether to pre-serialize UDP responses
sqs_batch_sizeinteger10NOSQS send batch size
sqs_flush_msinteger100NOSQS flush interval in milliseconds
sqs_buffer_sizeinteger50000NOSQS in-memory buffer capacity
sqs_timeout_msinteger3000NOSQS operation timeout in milliseconds

Indexes

  • application_parameter_profiles_pkey — UNIQUE on id
  • application_parameter_profiles_profile_name_key — UNIQUE on profile_name

2.2 application_parameters

Purpose: Runtime configuration parameters. Key-value store for all application settings that can be changed without redeployment. Polled every 5 minutes by ECS containers.

4 columns

ColumnData TypeDefaultNullableDescription
key PKvarchar(100)NOParameter name (PK): e.g., admin_api_key, rate_limit_qps, cache_ttl_seconds
valuetextNOParameter value (stored as text, interpreted by application)
descriptiontextYESHuman-readable description of what this parameter controls
updated_attimestampCURRENT_TIMESTAMPYESLast modification timestamp

Indexes

  • application_parameters_pkey — UNIQUE on key

2.3 report_parameters

Purpose: LRS-specific configuration. Key-value pairs for report generation settings (date ranges, limits, formatting).

4 columns

ColumnData TypeDefaultNullableDescription
keyvarchar(100)YESParameter name (PK): LRS-specific settings
valuetextYESParameter value
descriptiontextYESHuman-readable description
updated_attimestampYESLast modification timestamp
Group 3 — Billing & Payments3 tables

3.2 transactions

Purpose: Payment records. Every donation, subscription, and LRS addon purchase is logged here with Stripe references, amounts, and donor information.

15 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique transaction identifier
user_iduuidYESAssociated user (nullable for anonymous donations)
timestamptimestamptznow()YESWhen the transaction occurred
typetextYESTransaction type: donation, subscription, lrs-addon, subscription-lrs-addon
amount_usdnumericYESAmount in USD
stripe_charge_idtextYESStripe charge/payment intent ID (unique)
statustextYESPayment status: succeeded, pending, failed
donor_nametextYESName provided at checkout
donor_emailtextYESEmail provided at checkout
impact_typetextgeneralYESDonation impact category: general, medical, provisions, etc.
recurringbooleanfalseYESWhether this is a recurring payment
stripe_session_idtextYESStripe Checkout session ID
tiertextFreeYESSubscription tier (for subscription transactions)
api_keytextYESAPI key issued or associated with this transaction
preferred_langvarchar(5)NULLYESLanguage preference captured at checkout

Indexes

  • idx_transactions_email — on donor_email
  • idx_transactions_session — on stripe_session_id
  • idx_transactions_tier — on tier
  • transactions_pkey — UNIQUE on id
  • unique_stripe_charge_id — UNIQUE on stripe_charge_id

3.3 tier_catalog

Purpose: Single source of truth for all product pricing and limits — REST subscriptions, webhook push tiers, and donation/impact products. Read live by Raima's /raima/catalog endpoint (no redeploy needed to change prices). The customer-facing checkout pages and this table must agree.

15 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOAuto-incrementing identifier
producttextNOProduct line: rest, webhook, donation, lrs-addon
tiertextNOTier name within the product (e.g., pro, enterprise, unlimited, starter, standard)
display_nametext''NOHuman-readable tier name for display
price_centsbigint0NOPrice in cents (e.g., 9000 = $90.00)
currencytextUSDNOISO currency code
billing_periodtextmonthNOBilling cycle: month, year, one-time
lpo_limitbigint0NOMonthly LPO query limit (0 = unlimited)
lrs_limitbigint0NOMonthly LRS report limit (0 = unlimited)
rate_limitedbooleantrueNOWhether rate limiting applies to this tier
featuresjsonb[]NOFeature list as JSON array (displayed on checkout pages)
summarytext''NOShort description for Raima and internal tooling
sort_orderinteger0NODisplay order within the product group
publishedbooleanfalseNOWhether this tier is visible to customers
created_attimestamptznow()NOCreation timestamp
updated_attimestamptznow()NOLast modification timestamp

Indexes

  • tier_catalog_pkey — UNIQUE on id
  • tier_catalog_product_tier_key — UNIQUE on (product, tier)
  • idx_tier_catalog_product — on product
  • idx_tier_catalog_published — on published
Group 4 — Usage Logging4 tables

4.1 monthly_report_counts

Purpose: Monthly report usage aggregation. Tracks per-key report generation counts and limits for the LRS report system.

4 columns

ColumnData TypeDefaultNullableDescription
api_keytextNOAPI key string (PK) — the actual key value
last_report_generateddateYESDate of the most recent report generation
monthly_reports_allowedbigintNOMaximum reports allowed per month for this key
monthly_reports_counterbigintYESCurrent month report generation count

Indexes

  • pk_monthly_report_counts_api_key — UNIQUE on api_key

4.2 report_count

Purpose: Per-API-key report limit tracking. Enforces daily and monthly report generation caps with automatic monthly reset via cron.

7 columns

ColumnData TypeDefaultNullableDescription
api_key PK FK → api_keys.iduuidNOAPI key UUID (PK, FK → api_keys.id)
last_report_datetimestampnow()NODate of the most recent report generation
monthly_limitinteger10NOMaximum reports per month
monthly_countinteger0NOReports generated this month
daily_countinteger0NOReports generated today
daily_limitinteger50NOMaximum reports per day
reset_monthintegerEXTRACT(month FROM now())NOMonth number when counters were last reset

Indexes

  • idx_report_count_reset_month — on reset_month
  • report_count_pkey — UNIQUE on api_key

Foreign Keys

  • api_keyapi_keys.id

4.3 report_usage_logs

Purpose: LRS report request log. Every report generation is logged with filters, duration, and output format for analytics and debugging.

14 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique log entry identifier
api_key_idtextNOAPI key that generated this report
report_typetextNOReport type: summary, usage, detailed
report_run_datetimestampnow()NOWhen the report was generated
asset_filtertextYESAsset filter applied (if any)
start_date_filterdateYESStart date filter applied
end_date_filterdateYESEnd date filter applied
max_rows_returnedintegerYESNumber of rows in the report output
report_duration_msintegerYESReport generation time in milliseconds
output_formattextNOOutput format: json, csv
additional_filtersjsonbYESAny additional filters as JSON
regiontextYESAWS region that served this request
cluster_nodetextYESECS node that generated this report
created_attimestampnow()NOLog entry creation timestamp

Indexes

  • idx_report_usage_logs_api_key — on api_key_id
  • idx_report_usage_logs_created_at — on created_at
  • report_usage_logs_pkey — UNIQUE on id

4.4 usage_logs

Purpose: LPO API call log. Every API request is logged with timing, status, asset, price, and source information. Written via SQS queue for decoupled performance.

20 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique log entry identifier
user_iduuidYESUser who made the request (nullable)
api_key_idtextYESAPI key used for this request
timestamptimestamptznow()YESWhen the request was made
ip_addresstextYESClient IP address
query_typetextYESRequest type: price, multi-price, historical, etc.
duration_msintegerYESTotal request processing time in milliseconds
token_countintegerYESRate limit tokens consumed
metadatajsonbYESAdditional request metadata as JSON
latency_msinteger0YESBackend latency in milliseconds
statusintegerYESHTTP status code returned
errortextYESError message if request failed
cachedbooleanfalseYESWhether the response was served from cache
assettextYESAsset queried (e.g., BTC, ETH)
cache_age_secondsnumeric0.0YESAge of cached price data in seconds
cluster_nodevarchar(50)BeastMainYESECS node that served this request
aws_regionvarchar(20)us-east-2YESAWS region
sourcetextYESPrice source exchange (e.g., coinbase-ws)
pricefloat80YESPrice value returned
api_langvarchar(5)enNOLanguage of API response messages

Indexes

  • idx_usage_logs_asset — on asset (standalone — asset-only queries with no time filter)
  • idx_usage_logs_ip — on ip_address (trace-ip forensics)
  • idx_usage_logs_timestamp — on timestamp (pure time-range queries)
  • idx_usage_logs_timestamp_asset — composite on (timestamp, asset) — time-range + asset analytics
  • idx_usage_logs_timestamp_api_key_id — composite on (timestamp, api_key_id) — per-key analytics
  • idx_usage_logs_timestamp_source — composite on (timestamp, source) — per-exchange analytics
  • idx_usage_logs_timestamp_cluster_node — composite on (timestamp, cluster_node) — per-node analytics
  • usage_logs_pkey — UNIQUE on id

Composite indexes (Phase 6 optimization): The four (timestamp, dimension) composite indexes were added to match the report/analytics access patterns — every analytics query filters on a time range plus one dimension (asset, key, source, or node). Database self-observability (the /admin/db-insights endpoint) had shown usage_logs doing sequential scans on these filtered queries; the composites let the planner use index scans instead (6–8 ms execution). The three standalone indexes are retained because they still serve queries that filter on a single dimension without a time range.

4.5 mv_usage_daily Materialized View

Purpose: Pre-aggregated daily rollup of usage_logs (Phase 6 optimization). Precomputes per-day totals, latency percentiles, cache-hit rate, and cardinality so the analytics dashboard and the weekly-newsletter pipeline read a small, indexed view instead of scanning the full usage_logs table on every request. Serves the /dashboard/api/admin/daily-rollup endpoint.

13 columns ~48 day rows

ColumnData TypeDescription
daydateDate bucket (America/New_York timezone). Unique — one row per day.
total_requestsbigintCount of all requests that day
avg_latency_msnumericAverage backend latency for the day
p50_latency_msdouble precisionMedian latency (percentile_cont(0.5))
p95_latency_msdouble precision95th-percentile latency
p99_latency_msdouble precision99th-percentile latency
cached_requestsbigintCount of requests served from cache
cache_hit_rate_pctnumericCache hit rate as a percentage
distinct_assetsbigintNumber of distinct assets queried that day
distinct_api_keysbigintNumber of distinct API keys active that day
distinct_sourcesbigintNumber of distinct price sources used
distinct_nodesbigintNumber of distinct cluster nodes that served traffic
last_refreshedtimestamp with time zoneWhen the view was last refreshed — exposed to consumers so they know data freshness

Indexes

  • idx_mv_usage_daily_day — UNIQUE on day. Required to enable REFRESH MATERIALIZED VIEW CONCURRENTLY (concurrent refresh never blocks readers).
Refresh mechanism — pg_cron (native Aurora scheduling): The view is refreshed every 5 minutes by a pg_cron job running inside Aurora. Job name: tbi-mv-usage-daily-refresh (job_id 2), schedule */5 * * * *, command REFRESH MATERIALIZED VIEW CONCURRENTLY mv_usage_daily. Execution history is available in cron.job_run_details. Typical refresh time is under 100ms. The previous external pipeline (EventBridge rule tbi-refresh-mv-schedule → Lambda tbi-ops-refresh-mv) was retired 2026-05-31 when pg_cron v1.6 was installed.
Group 5 — Exchange & Pricing3 tables

5.1 asset_categories

Purpose: Crypto asset category groupings. Organizes the 150 prewarmed assets into display categories (Major Currencies, DeFi, Layer 2, etc.) for the API response grouping.

6 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOAuto-incrementing identifier
category_nametextNOCategory display name: Major Currencies, DeFi, Layer 2, etc.
descriptiontextNOHuman-readable category description
display_orderinteger100NOSort order for API response grouping
enabledbooleantrueNOWhether this category is active
created_attimestamptznow()NOCreation timestamp

Indexes

  • asset_categories_category_name_key — UNIQUE on category_name
  • asset_categories_pkey — UNIQUE on id

5.2 exchange_asset_map

Purpose: Exchange-to-asset symbol translations. Maps generic asset names (BTC, ETH) to exchange-specific trading pair symbols for each of the 6 WebSocket feeds.

6 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOAuto-incrementing identifier
exchange_nametextNOExchange identifier (e.g., coinbase, gemini, kraken)
assettextNOGeneric asset symbol (e.g., BTC, ETH, SOL)
exchange_symboltextNOExchange-specific trading pair symbol
enabledbooleantrueNOWhether this mapping is active for WebSocket subscription
categorytextInfrastructureNOAsset category for grouping (e.g., Infrastructure)

Indexes

  • exchange_asset_map_exchange_name_asset_key — UNIQUE on exchange_name, asset
  • exchange_asset_map_pkey — UNIQUE on id
  • idx_exchange_asset_map_asset — on asset
  • idx_exchange_asset_map_exchange — on exchange_name

5.3 exchange_feeds

Purpose: Exchange WebSocket feed configurations. Complete connection parameters for each exchange — endpoints, subscription formats, message parsing, heartbeat handling, and symbol conventions.

27 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOAuto-incrementing identifier
exchange_nametextNOExchange identifier (unique)
display_nametextNOHuman-readable exchange name
ws_endpointtextNOWebSocket connection URL
subscribe_formattextjsonNOMessage format for subscriptions: json
pair_suffixtextUSDNOTrading pair quote currency suffix (e.g., USD)
symbol_templatetextNOTemplate for constructing subscription symbols
symbol_separatortext-NOCharacter separating base/quote in symbols
parse_regextextYESRegex for parsing price messages (legacy)
enabledbooleantrueNOWhether this feed is active
source_tagtextNOTag used in price cache keys (e.g., coinbase-ws)
notestextYESAdmin notes about this feed
created_attimestamptznow()NOCreation timestamp
updated_attimestamptznow()NOLast modification timestamp
subscribe_templatetextYESFull subscription message template with placeholders
trade_channel_matchtextYESString to match for identifying trade messages
price_pathtextYESJSON path to price value in trade messages
symbol_pathtextYESJSON path to symbol in trade messages
timestamp_pathtextYESJSON path to timestamp in trade messages
timestamp_formattextrfc3339YESTimestamp format: rfc3339, unix, unix_ms
ping_interval_secinteger0YESInterval for sending ping/keepalive messages
ping_messagetextYESPing message content
symbol_styletextstandardYESSymbol formatting style: standard, lowercase, etc.
msg_is_arraybooleanfalseYESWhether trade messages arrive as JSON arrays
array_pathtextYESJSON path when message is nested in array
heartbeat_methodtextYESHow to send heartbeats: ping, message, none
heartbeat_response_methodtextYESHow to respond to server heartbeats

Indexes

  • exchange_feeds_exchange_name_key — UNIQUE on exchange_name
  • exchange_feeds_pkey — UNIQUE on id
  • idx_exchange_feeds_enabled — on enabled
Group 6 — Email & Newsletters8 tables

6.1 email_drafts

Purpose: Email composition drafts. Stores in-progress and sent emails with template references, recipients, and scheduling information.

12 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique draft identifier
template_iduuidYESReference to email_templates (nullable for freeform)
sender_iduuidYESReference to email_senders
subjectvarchar(500)NOEmail subject line
contenttextNOEmail body content (HTML)
recipientstextNORecipient list as JSON array
cctextNOCC recipients
bcctextNOBCC recipients
statusvarchar(20)draftNODraft status: draft, scheduled, sent, failed
created_attimestamptznow()NOCreation timestamp
updated_attimestamptznow()NOLast modification timestamp
sent_attimestamptzYESWhen the email was actually sent

Indexes

  • email_drafts_pkey — UNIQUE on id

6.2 email_senders

Purpose: Verified SES sender identities. Defines the From addresses available for sending (e.g., CPMP Mission, The Trinity Beast).

5 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique sender identifier
display_namevarchar(255)NOSender display name (e.g., CPMP Mission, The Trinity Beast)
emailvarchar(255)NOSender email address (unique, SES verified)
reply_tovarchar(255)NOReply-to address
created_attimestamptznow()NOCreation timestamp

Indexes

  • email_senders_email_key — UNIQUE on email
  • email_senders_pkey — UNIQUE on id

6.3 email_templates

Purpose: SES email templates. Reusable email content templates organized by topic (receipts, welcome, notifications).

6 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique template identifier
topicvarchar(100)NOTemplate category: receipt, welcome, notification, etc.
namevarchar(255)NOTemplate name for lookup
subjectvarchar(500)NODefault subject line
contenttextNOTemplate body content with placeholders
created_attimestamptznow()NOCreation timestamp

Indexes

  • email_templates_pkey — UNIQUE on id

6.4 email_translations

Purpose: Multi-language email template fields. Stores translated versions of template fields (subject, body) for each supported language.

6 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique translation identifier
template_namevarchar(100)NOReference to email template name
langvarchar(5)NOISO 639-1 language code
field_namevarchar(50)NOWhich field is translated: subject, body, cta_text, etc.
field_valuetextNOTranslated content for this field
created_attimestamptznow()YESCreation timestamp

Indexes

  • email_translations_pkey — UNIQUE on id
  • email_translations_template_name_lang_field_name_key — UNIQUE on template_name, lang, field_name

6.5 newsletter_subscribers

Purpose: Newsletter mailing list. Subscribers with email, name, source (cpmp or tbi), opt-out status, and language preference.

7 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique subscriber identifier
emailtextNOSubscriber email address
nametextYESSubscriber display name
sourcetextcpmpYESSubscription source: cpmp or tbi
subscribed_attimestamptznow()YESWhen the subscription was created
opt_outbooleanfalseYESWhether the subscriber has opted out
preferred_langvarchar(5)enYESPreferred newsletter language (ISO 639-1)

Indexes

  • idx_subscribers_source — on source
  • newsletter_subscribers_email_source_key — UNIQUE on email, source
  • newsletter_subscribers_pkey — UNIQUE on id

6.6 newsletter_templates

Purpose: Newsletter email templates. Reusable newsletter content templates organized by type and topic.

6 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique template identifier
typevarchar(20)cpmpNOTemplate type: cpmp or tbi
topicvarchar(100)generalNOTemplate topic/category
namevarchar(255)NOTemplate name for lookup
contenttextNOTemplate body content
created_attimestamptznow()NOCreation timestamp

Indexes

  • newsletter_templates_pkey — UNIQUE on id

6.7 newsletter_translations

Purpose: Multi-language newsletter content. Translated subject and body for each newsletter in each supported language.

9 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique translation identifier
newsletter_id FK → newsletters.iduuidNOReference to newsletters table (FK)
langvarchar(5)NOISO 639-1 language code
subjecttextNOTranslated newsletter subject
body_htmltextNOTranslated newsletter body (HTML)
auto_translatedbooleantrueYESWhether this was machine-translated
reviewedbooleanfalseYESWhether a human has reviewed the translation
created_attimestamptznow()YESCreation timestamp
updated_attimestamptznow()YESLast modification timestamp

Indexes

  • newsletter_translations_newsletter_id_lang_key — UNIQUE on newsletter_id, lang
  • newsletter_translations_pkey — UNIQUE on id

Foreign Keys

  • newsletter_idnewsletters.id

6.8 newsletters

Purpose: Sent newsletter campaigns. Records of each newsletter sent with subscriber count, open rate, and metadata.

9 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique newsletter identifier
titletextNONewsletter title/headline
contenttextNONewsletter body content (English source)
sent_attimestamptznow()YESWhen the newsletter was sent
subscriber_countinteger0YESNumber of recipients at send time
open_ratefloat80.0YESPercentage of recipients who opened
metadatajsonbYESAdditional metadata as JSON
statustextactiveYESNewsletter status: active, archived
typetextcpmpYESNewsletter type: cpmp or tbi

Indexes

  • idx_newsletters_sent_at — on sent_at DESC
  • idx_newsletters_status — on status
  • newsletters_pkey — UNIQUE on id
Group 7 — Support & Engagement6 tables

7.1 demo_leads

Purpose: Demo registration captures. Stores interest submissions from the demo page with email, platform, and IP for rate limiting.

6 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique lead identifier
emailtextNOSubmitted email address
interesttextgeneralNOWhat the lead is interested in
platformtextunknownNOPlatform/source of the submission
client_iptextYESClient IP address (for rate limiting)
created_attimestamptznow()NOSubmission timestamp

Indexes

  • demo_leads_pkey — UNIQUE on id
  • idx_demo_leads_email — on email
  • idx_demo_leads_ip — on client_ip

7.2 error_messages

Purpose: Multi-language API error messages. Lookup table for translating error message keys into the user's preferred language (UME Phase 2).

5 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOAuto-incrementing identifier
message_keyvarchar(100)NOError message key (e.g., invalid_api_key, rate_limited)
langvarchar(5)enNOISO 639-1 language code (default: en)
messagetextNOTranslated error message text
created_attimestamptznow()NOCreation timestamp

Indexes

  • error_messages_message_key_lang_key — UNIQUE on message_key, lang
  • error_messages_pkey — UNIQUE on id

7.3 map_pins

Purpose: CPMP mission impact map markers. Geographic pins for medical camps, provisions, training events, and other ministry activities.

10 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique pin identifier
typetextNOPin type: medical, provisions, training, freedom, wheelchairs, word-of-life
latfloat8YESLatitude coordinate
lngfloat8YESLongitude coordinate
regiontextYESGeographic region name
captiontextYESPin description/caption text
media_urltextYESPrimary media URL (legacy single image)
datetimestamptzYESEvent date
statustextactiveYESPin status: active, archived
media_urlsjsonb[]YESArray of media URLs as JSONB (multiple images)

Indexes

  • map_pins_pkey — UNIQUE on id

7.4 partner_applications

Purpose: AWS Partner application submissions. Tracks companies applying for PrivateLink partner access with their AWS details and review status.

16 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique application identifier
company_nametextNOApplying company name
contact_nametextNOPrimary contact person
contact_emailtextNOContact email address
aws_account_idtextNOApplicant AWS account ID
aws_regiontextNOPreferred AWS region for PrivateLink
vpc_cidrtextYESApplicant VPC CIDR block
connection_typetextNORequested connection type: privatelink, vpn
data_providedtextYESDescription of data/services needed
estimated_volumetextYESEstimated monthly API call volume
notestextYESAdditional notes from applicant
statustextpendingNOApplication status: pending, approved, rejected
reviewed_attimestamptzYESWhen the application was reviewed
reviewer_notestextYESInternal review notes
api_key_iduuidYESIssued API key (after approval)
created_attimestamptznow()NOSubmission timestamp

Indexes

  • idx_partner_apps_email — on contact_email
  • idx_partner_apps_status — on status
  • partner_applications_pkey — UNIQUE on id

7.5 support_replies

Purpose: Support ticket replies. Individual messages within a support ticket thread, from both admin and customer, with optional translation.

8 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique reply identifier
ticket_id FK → support_tickets.iduuidNOParent ticket (FK → support_tickets.id)
authorvarchar(255)NOReply author name or identifier
author_typevarchar(20)adminNOAuthor role: admin or customer
messagetextNOReply message content
is_internalbooleanfalseNOWhether this is an internal note (not visible to customer)
created_attimestamptznow()NOReply timestamp
message_translatedtextYESAuto-translated version of the message (for cross-language support)

Indexes

  • idx_support_replies_created_at — on created_at
  • idx_support_replies_ticket_id — on ticket_id
  • support_replies_pkey — UNIQUE on id

Foreign Keys

  • ticket_idsupport_tickets.id

7.6 support_tickets

Purpose: Customer support system. Tickets submitted via the support form with auto-categorization, status tracking, and language support.

13 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique ticket identifier
ticket_numbervarchar(20)NOHuman-readable ticket number (unique, e.g., TKT-001234)
namevarchar(255)NOSubmitter name
emailvarchar(255)NOSubmitter email address
categoryvarchar(100)generalNOAuto-categorized: billing, technical, api-access, rate-limit, feature-request, bug-report, account, general
subjectvarchar(500)NOTicket subject line
messagetextNOTicket body (original language)
statusvarchar(30)newNOTicket status: new, open, pending, resolved, closed
created_attimestamptznow()NOSubmission timestamp
updated_attimestamptznow()NOLast activity timestamp
client_ipvarchar(100)NOSubmitter IP address
preferred_langvarchar(5)enYESSubmitter preferred language for responses
message_entextYESEnglish translation of message (if submitted in another language)

Indexes

  • idx_support_tickets_category — on category
  • idx_support_tickets_created_at — on created_at DESC
  • idx_support_tickets_email — on email
  • idx_support_tickets_status — on status
  • idx_support_tickets_ticket_number — on ticket_number
  • support_tickets_pkey — UNIQUE on id
  • support_tickets_ticket_number_key — UNIQUE on ticket_number
Group 8 — Operations & Maintenance3 tables

8.1 cron_execution_logs

Purpose: Cron job execution tracking. Logs every scheduled job run (monthly reset, sync, cleanup) with status and row counts.

7 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOUnique log entry identifier
job_nametextNOCron job name: monthly_reset, sync, cleanup, etc.
executed_attimestamptznow()YESWhen the job ran
statustextNOExecution status: success, failed, partial
rows_affectedbigintYESNumber of rows processed
messagetextYESExecution details or error message
created_attimestamptznow()YESLog entry creation timestamp

Indexes

  • cron_execution_logs_pkey — UNIQUE on id

8.2 cron_reset_logs

Purpose: Cron job execution log (same schema as cron_execution_logs). Additional logging for reset operations.

7 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOUnique log entry identifier
job_nametextNOJob name that produced this log
executed_attimestamptznow()YESWhen the job ran
statustextNOExecution status: success, failed
rows_affectedbigintYESNumber of keys/rows reset
messagetextYESDetails or error message
created_attimestamptznow()YESLog entry creation timestamp

Indexes

  • cron_reset_logs_executed_at_idx — on executed_at
  • cron_reset_logs_job_name_idx — on job_name
  • cron_reset_logs_pkey — UNIQUE on id

8.3 cron_reset_summary

Purpose: Reset summary statistics. Aggregated results of monthly usage reset operations.

6 columns

ColumnData TypeDefaultNullableDescription
id PKintegerauto-incrementNOUnique summary identifier
job_nametextYESJob that produced this summary
executed_attimestamptzYESWhen the reset ran
statustextYESOverall status: success, partial, failed
rows_affectedbigintYESTotal rows affected
messagetextYESSummary details

Indexes

  • cron_reset_summary_pkey — UNIQUE on id
  • idx_cron_reset_summary_executed_at — on executed_at
  • idx_cron_reset_summary_job_name — on job_name
  • idx_cron_reset_summary_job_name_executed_at — on job_name, executed_at
  • idx_cron_reset_summary_status — on status
Group 9 — Website Analytics2 tables

9.1 page_events

Purpose: Website interaction event tracking. Click events, form submissions, and other user interactions captured by the analytics script.

8 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique event identifier
page_pathvarchar(500)NOPage URL path where event occurred
event_typevarchar(100)NOEvent type: click, scroll, form_submit, etc.
event_targetvarchar(500)NODOM element that triggered the event
event_datajsonb{}NOAdditional event data as JSON
visitor_idvarchar(64)NOAnonymous visitor fingerprint
session_idvarchar(64)NOBrowser session identifier
created_attimestamptznow()NOEvent timestamp

Indexes

  • idx_page_events_created_at — on created_at DESC
  • idx_page_events_event_type — on event_type
  • idx_page_events_page_path — on page_path
  • page_events_pkey — UNIQUE on id

9.2 page_views

Purpose: Website page view analytics. Every page load with full geo-location data, device info, and session tracking.

19 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique page view identifier
page_pathvarchar(500)NOPage URL path
page_titlevarchar(500)NOHTML page title
referrervarchar(1000)NOReferring URL
user_agentvarchar(1000)NOBrowser user agent string
visitor_idvarchar(64)NOAnonymous visitor fingerprint
session_idvarchar(64)NOBrowser session identifier
screen_widthinteger0NOViewport width in pixels
screen_heightinteger0NOViewport height in pixels
countryvarchar(10)NOISO country code (2-letter)
created_attimestamptznow()NOPage view timestamp
country_namevarchar(100)NOFull country name
regionvarchar(10)NORegion/state code
region_namevarchar(100)NOFull region/state name
cityvarchar(100)NOCity name
latitudevarchar(20)NOApproximate latitude
longitudevarchar(20)NOApproximate longitude
timezonevarchar(50)NOVisitor timezone
device_typevarchar(20)NODevice category: desktop, mobile, tablet

Indexes

  • idx_page_views_created_at — on created_at DESC
  • idx_page_views_page_path — on page_path
  • idx_page_views_visitor_id — on visitor_id
  • page_views_pkey — UNIQUE on id
Group 10 — Webhook Push2 tables

10.1 webhook_subscriptions

Purpose: Webhook subscriber configurations and delivery state. Defines each subscriber's endpoints, assets, intervals, tier, and billing references.

19 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOUnique subscription identifier
api_key_id FK → api_keys.iduuidNOAssociated API key (FK → api_keys.id)
tiertextwebhook_starterNOWebhook tier: webhook_starter, webhook_standard, webhook_professional, webhook_enterprise, webhook_partner
udp_endpoint_iptextYESSubscriber UDP endpoint IP address
udp_endpoint_portintegerYESSubscriber UDP endpoint port
https_endpoint_urltextYESSubscriber HTTPS webhook URL
delivery_methodtextudpNODelivery protocol: udp or https
interval_secondsinteger60NOPrice push interval in seconds
assetstext[]ARRAY[][]NOArray of subscribed asset symbols
max_assetsinteger9NOMaximum assets allowed for this tier
statustextpending_verificationNOSubscription status: pending_verification, active, paused, canceled
verification_tokentextYESToken for endpoint ownership verification
verified_attimestamptzYESWhen endpoint was verified
monthly_push_countinteger0NOPush deliveries this month
stripe_customer_idtextYESStripe customer ID for billing
stripe_subscription_idtextYESStripe subscription ID
subscription_statustextactiveNOBilling status: active, past_due, canceled
created_attimestamptznow()NOCreation timestamp
updated_attimestamptznow()NOLast modification timestamp

Indexes

  • idx_webhook_subs_api_key — on api_key_id
  • idx_webhook_subs_status — on status
  • idx_webhook_subs_tier — on tier
  • webhook_subscriptions_pkey — UNIQUE on id

Foreign Keys

  • api_key_idapi_keys.id

10.2 webhook_delivery_log

Purpose: Webhook delivery attempt log. Every price push delivery is logged with asset, price, method, latency, and status.

12 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOAuto-incrementing delivery log identifier
subscription_id FK → webhook_subscriptions.iduuidNOWhich subscription this delivery belongs to (FK)
assettextNOAsset symbol delivered (e.g., BTC)
pricenumericNOPrice value delivered
sourcetextNOPrice source exchange (e.g., coinbase-ws)
delivery_methodtextNOProtocol used: udp or https
statustextdeliveredNODelivery status: delivered, failed, timeout
latency_msfloat8YESDelivery round-trip time in milliseconds
attemptinteger1NOAttempt number (1 = first try)
errortextYESError message if delivery failed
sequence_numberbigint0NOMonotonically increasing sequence for ordering
created_attimestamptznow()NODelivery timestamp

Indexes

  • idx_webhook_delivery_created — on created_at
  • idx_webhook_delivery_status — on status WHERE status <> 'delivered'
  • idx_webhook_delivery_sub — on subscription_id
  • webhook_delivery_log_pkey — UNIQUE on id

Foreign Keys

  • subscription_idwebhook_subscriptions.id
Group 11 — Translation Engine2 tables

11.1 translation_jobs

Purpose: Translation job orchestration. Tracks every translation batch submitted via the admin API — documents, languages, progress, costs, and Step Function state.

29 columns

ColumnData TypeDefaultNullableDescription
id PKuuidgen_random_uuid()NOInternal UUID (auto-generated)
job_idvarchar(64)NOPublic job identifier (unique, used in API responses)
statevarchar(20)queuedNOJob state: queued, running, completed, failed, cancelled
submitted_attimestamptznow()NOWhen the job was submitted
started_attimestamptzYESWhen processing began
completed_attimestamptzYESWhen processing finished
submitted_byvarchar(50)admin-apiYESWho submitted: admin-api, retry, cli
docsjsonbNOArray of document filenames to translate (JSONB)
langsjsonbNOArray of target language codes (JSONB)
optionsjsonb{}YESJob options as JSON (chunk size overrides, etc.)
progressjsonb{}YESPer-pair progress tracking as JSON
errorsjsonb[]YESArray of error details for failed pairs (JSONB)
bedrock_cost_usdnumeric0YESTotal Bedrock API cost for this job in USD
bedrock_invocationsinteger0YESTotal Bedrock API calls made
total_chunksinteger0YESTotal document chunks processed
total_pairsinteger0YESTotal doc-language pairs in this job
succeeded_pairsinteger0YESNumber of pairs that completed successfully
failed_pairsinteger0YESNumber of pairs that failed
elapsed_secondsintegerYESTotal job duration in seconds
step_function_arntextYESARN of the Step Function execution
retry_ofvarchar(64)YESJob ID this is a retry of (nullable)
idempotency_keyvarchar(128)YESClient-provided idempotency key
cloudfront_invalidation_idsjsonb[]YESArray of CloudFront invalidation IDs (JSONB)
search_index_rebuiltbooleanfalseYESWhether the search index was rebuilt after this job
notification_sentbooleanfalseYESWhether completion notification was sent
created_attimestamptznow()NORecord creation timestamp
updated_attimestamptznow()NOLast state change timestamp
reasontextYESCancellation or failure reason
modelvarcharclaude-sonnet-4.6YESBedrock model used for translation (e.g., claude-sonnet-4.6, claude-haiku-3.5, claude-opus-4)

Indexes

  • idx_translation_jobs_state — on state
  • idx_translation_jobs_submitted_at — on submitted_at DESC
  • translation_jobs_job_id_key — UNIQUE on job_id
  • translation_jobs_pkey — UNIQUE on id

11.2 translation_job_events

Purpose: Translation job audit log. Granular event stream for each job — per-pair start, success, failure, retry, and completion events.

7 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOAuto-incrementing event identifier
job_idvarchar(64)NOParent job identifier (matches translation_jobs.job_id)
event_typevarchar(30)NOEvent type: pair_start, pair_success, pair_failed, job_start, job_complete, etc.
docvarchar(200)YESDocument filename (for pair-level events)
langvarchar(5)YESTarget language code (for pair-level events)
detailjsonb{}YESEvent details as JSON (error messages, timing, chunk counts)
created_attimestamptznow()NOEvent timestamp

Indexes

  • idx_translation_job_events_created_at — on created_at DESC
  • idx_translation_job_events_job_id — on job_id
  • translation_job_events_pkey — UNIQUE on id

11.3 translation_quotes

Purpose: Customer-facing translation quotes with Stripe payment integration. When a customer requests a document translation via the public API, a quote is generated with cost breakdown (per-chunk, per-pair, infrastructure, markup). The customer accepts and pays via Stripe; on payment confirmation the quote transitions to accepted and triggers the translation job.

32 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOAuto-incrementing identifier
quote_idvarchar(64)NOPublic-facing quote identifier (ULID)
api_key_idvarchar(128)NOAPI key that requested the quote
doc_urltextNOURL of the document to translate
doc_namevarchar(255)NODocument filename
doc_size_bytesintegerNODocument size in bytes
estimated_chunksintegerNOEstimated number of translation chunks
difficultyvarchar(21)standardNODocument difficulty: standard, technical, complex
code_blocksinteger0NONumber of code blocks detected in the document
diagramsinteger0NONumber of Mermaid diagrams detected
langsjsonbNOTarget languages as JSON array
lang_countintegerNONumber of target languages
cost_per_chunknumeric(8,4)NOBedrock cost per chunk (USD)
cost_per_pairnumeric(8,4)NOTotal cost per doc-language pair (USD)
infra_per_pairnumeric(8,4)NOInfrastructure cost per pair (S3, CloudFront, compute)
subtotalnumeric(10,4)NOSubtotal before markup (USD)
markup_pctintegerNOMarkup percentage applied
total_pricenumeric(10,4)NOFinal price charged to customer (USD)
modelvarchar(50)claude-sonnet-4.6YESAI model used for translation
statevarchar(21)pendingNOQuote lifecycle: pending, accepted, declined, expired, refunded
expires_attimestamptzNOQuote expiration (24 hours from creation)
accepted_attimestamptzYESWhen the customer accepted and paid
declined_attimestamptzYESWhen the customer declined
stripe_payment_intent_idvarchar(128)YESStripe PaymentIntent ID for this quote
stripe_charge_idvarchar(128)YESStripe Charge ID after successful payment
job_idvarchar(64)YESTranslation job ID created after acceptance
refunded_attimestamptzYESWhen a refund was issued
refund_amountnumeric(10,2)NULLYESRefund amount (USD)
refund_idvarchar(255)NULLYESStripe Refund ID
protected_termsjsonb[]YESCustomer-supplied brand terms to protect during translation
created_attimestamptznow()NOQuote creation timestamp
updated_attimestamptznow()NOLast modification timestamp

Indexes

  • translation_quotes_pkey — UNIQUE on id
  • translation_quotes_quote_id_key — UNIQUE on quote_id
  • idx_quotes_api_key — on api_key_id
  • idx_quotes_expires — on expires_at
  • idx_quotes_state — on state
Group 12 — Agent Profiles2 tables

12.1 agent_profiles

Purpose: Registry of all agent identities in the UME (Unified Messaging Envelope) system. Every API response carries an agent_profile_arn field identifying which agent produced it. This table is the Phase 2 backing store for those identities — versioned, with model bindings, task contracts, and policies. Phase 1 uses constants in code; Phase 2 reads from this table via an admin endpoint.

15 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOAuto-incrementing identifier
namevarchar(64)NOAgent short name (e.g., tbi, raima, webhook-engine)
versionvarchar(16)NOSemantic version (e.g., v1, v2)
arntextNOFull ARN: arn:tbi:{region}:{account}:agent-profile/{name}/{version}
display_namevarchar(128)NOHuman-readable agent name
roletextNOAgent role description (what it does)
model_idvarchar(128)''NOBedrock model ID bound to this agent (empty if no AI backing)
system_prompttext''NOSystem prompt for AI-backed agents
tasksjsonb[]NOTask contract — what this agent can do (JSON array)
policiesjsonb{}NOAccess policies and guardrails (JSON object)
metadatajsonb{}NOArbitrary metadata (tags, labels, deployment info)
activebooleantrueNOWhether this agent profile is currently active
created_attimestampCURRENT_TIMESTAMPNOCreation timestamp
updated_attimestampCURRENT_TIMESTAMPNOLast modification timestamp
bumped_attimestampCURRENT_TIMESTAMPNOLast version bump timestamp

Indexes

  • agent_profiles_pkey — UNIQUE on id
  • agent_profiles_name_version_key — UNIQUE on (name, version)
  • idx_agent_profiles_arn — on arn
  • idx_agent_profiles_name_active — on (name, active)

12.2 agent_profile_events

Purpose: Audit log for agent profile changes. Every create, update, version bump, activate, or deactivate action is recorded with the actor and payload diff.

8 columns

ColumnData TypeDefaultNullableDescription
id PKbigintauto-incrementNOAuto-incrementing event identifier
agent_profile_id FK → agent_profiles.idbigintNOParent agent profile
namevarchar(64)NOAgent name at time of event (denormalized for history)
versionvarchar(16)NOAgent version at time of event
actionvarchar(32)NOAction: created, updated, bumped, activated, deactivated
actorvarchar(128)''NOWho performed the action (admin email or system)
payloadjsonb{}NOEvent payload — diff of changes or full snapshot
created_attimestampCURRENT_TIMESTAMPNOEvent timestamp

Indexes

  • agent_profile_events_pkey — UNIQUE on id
  • idx_agent_profile_events_profile_ts — on (agent_profile_id, created_at DESC)
  • idx_agent_profile_events_name_ts — on (name, created_at DESC)
  • idx_agent_profile_events_action_ts — on (action, created_at DESC)

Schema Summary

42 tables across 12 logical groups, 491 columns total, plus 1 materialized view (mv_usage_daily) backing the analytics dashboard.

GroupTablesColumns
Group 1 — Core: Users & Authentication338
Group 2 — Configuration342
Group 3 — Billing & Payments341
Group 4 — Usage Logging445
Group 5 — Exchange & Pricing339
Group 6 — Email & Newsletters860
Group 7 — Support & Engagement658
Group 8 — Operations & Maintenance320
Group 9 — Website Analytics227
Group 10 — Webhook Push231
Group 11 — Translation Engine368
Group 12 — Agent Profiles223

Foreign Key Relationships

  • api_keys.user_idusers.id
  • newsletter_translations.newsletter_idnewsletters.id
  • report_count.api_keyapi_keys.id
  • support_replies.ticket_idsupport_tickets.id
  • webhook_delivery_log.subscription_idwebhook_subscriptions.id
  • webhook_subscriptions.api_key_idapi_keys.id
  • agent_profile_events.agent_profile_idagent_profiles.id

Database Engine Optimization

A round of PostgreSQL optimization pushed work down into the database engine and removed query-level overhead on the hot paths. The schema-visible results are documented above (the four composite indexes on usage_logs and the mv_usage_daily materialized view). The application-side and engine-side pieces are summarized here.

OptimizationWhat it does
Prepared-statement registry (dbx)Five fixed-shape hot-path queries are registered as named prepared statements at server startup: API-key lookup, API-key last-used touch, application-parameters load, report-count check, and report-count upsert. The registry is nil-safe and fail-soft — if a statement fails to prepare it transparently falls back to an ad-hoc query, so it never blocks startup.
Report-counter upsertThe LRS report counter collapsed a read-then-insert two-step into a single INSERT … ON CONFLICT DO UPDATE with month/day rollover logic, removing a round-trip on every report request.
Set-based usage updatesThe queued-writer Lambda replaced its per-key UPDATE loop with one set-based UPDATE … FROM (unnest(...)), turning N round-trips into 1 per SQS batch.
GROUPING SETS analyticsThe admin analytics summary replaced six separate aggregation queries with a single GROUPING SETS pass that also computes latency percentiles (percentile_cont p50/p95/p99) server-side — measured 2.1× faster (87 ms → 41 ms).
Parameterized admin SQLThe /admin/sql endpoint gained an optional args array for parameterized queries, and the translate-finalize Lambda's interpolated SQL was converted to placeholders — eliminating value-interpolated SQL from the active codebase.
Self-observabilityThe /admin/db-insights endpoint surfaces buffer-cache hit ratio, top queries by total time and call count (from pg_stat_statements), and per-table sequential-vs-index scan health — the same data that justified the composite indexes above.