Architecture Overview
AltBase compiles 23 Rust crates into a single binary with a dual-context database, event-driven core, and defense-in-depth security — all deployable with four infrastructure containers.
The Single Binary
AltBase compiles into one Rust binary (atlas-server) that contains 23 crates. There are no microservices, no sidecars, and no inter-service HTTP calls. Every feature — REST APIs, auth, storage, realtime, workflows, vector search, GraphQL, MCP — runs in the same process.
The atlas-server crate is a thin orchestrator with zero business logic. It imports all other crates, builds the Axum HTTP router, spawns background workers, and serves the dashboard as static files.
This architecture means:
- Zero inter-service latency — function calls between subsystems, not network hops
- Single deployment artifact — one binary (~50MB with LTO) plus four infrastructure containers
- Simple operations — no service mesh, no container orchestration complexity for the application layer
- Mechanical extraction — crate boundaries are designed so any subsystem can be extracted into a separate service later
Crate Dependency Graph
The 23 crates are organized in five layers:
Layer 1: Foundation
| Crate | Responsibility |
|---|---|
atlas-common | Config (environment variables), error types (mapped to HTTP status codes), structured logging with tracing |
atlas-db | Connection pool creation for control plane and tenant databases, migration runner |
atlas-gateway | API key auth middleware, rate limiting middleware, TenantContext injection |
Layer 2: Platform Management
| Crate | Responsibility |
|---|---|
atlas-control-plane | Organizations, projects, API keys, environment provisioning, request logs, backup |
Layer 3: Core Features
| Crate | Responsibility |
|---|---|
atlas-api-engine | REST CRUD, SQL endpoint, schema introspection, query compiler, vector search, index advisor |
atlas-auth | All authentication: password, OAuth, OIDC, SAML, magic link, OTP, RLS, SSO, customer orgs, setup wizard |
atlas-storage | Buckets, objects, TUS resumable uploads, signed URLs, image transforms, policies, cleanup |
atlas-realtime | WebSocket connections, CDC delivery, broadcast channels, presence, cron jobs |
atlas-cdc-fanout | Postgres WAL listener via pgwire replication protocol, fan-out to NATS JetStream |
Layer 4: Subsystems
| Crate | Responsibility |
|---|---|
atlas-events | NATS pub/sub, JetStream stream and consumer management |
atlas-jobs | Background job queue, pull-based worker, SSRF protection |
atlas-search | Tantivy full-text indexing, CDC-triggered index updates |
atlas-analytics | Materialized view creation, background refresh, DashMap concurrent cache |
atlas-billing | Stripe checkout, subscriptions, usage tracking, webhooks |
Layer 5: Automation and AI
| Crate | Responsibility |
|---|---|
atlas-integrations | Nango OAuth connections, 500+ SaaS connectors, webhooks, circuit breaker |
atlas-functions | Dual engine: QuickJS for JavaScript with host API access, Wasmtime for sandboxed WebAssembly |
atlas-triggers | Unified trigger system — fires on CDC events, auth events, storage events, and cron schedules |
atlas-workflows | DAG workflow engine with step execution, approvals, and NATS consumers |
atlas-vector | Embeddings (4 providers), vector search (4 backends), hybrid search (RRF), RAG pipeline, LLM generation |
atlas-graphql | Auto-generated GraphQL schema from database introspection, subscriptions, DataLoader |
atlas-mcp | Model Context Protocol server: JSON-RPC, auto-generated tools and resources from schema |
Dual-Context Database
AltBase uses two PostgreSQL databases on the same Postgres 16 instance:
Control Plane Database (atlas_control_plane)
Stores platform metadata — the entities that describe the platform itself:
organizations— top-level tenant groupingplatform_users— operator accountsprojectsandenvironments— the containers for application dataapi_keys— SHA-256 hashed keys with prefix lookupproject_auth_settings— RSA public keys, JWT TTL, provider configproject_sso_settingsandorg_sso_connections— SSO configurationconnector_templatesandembedding_configs— integration and AI configknowledge_collections,knowledge_documents,knowledge_chunks— RAG contentcron_jobs,event_triggers— automation definitionsrequest_logs— per-request audit trail
Tenant Database (atlas_tenants)
Stores application data, isolated per project:
- Each project gets its own PostgreSQL schema:
proj_{project_id} - Schema contains auth tables (
users,sessions,refresh_tokens,oauth_providers,sso_connections,customer_orgs,rls_policies), storage tables (storage_buckets,storage_objects,storage_policies), and user-created tables - Tables are provisioned at project creation and extended via the SQL endpoint
Tenant Isolation Model
| Tier | Isolation | Mechanism |
|---|---|---|
| Free | Schema-per-tenant | SET LOCAL search_path TO "proj_{id}" per transaction |
| Paid | Database-per-tenant | Separate Postgres database with dedicated connection pool |
Every SQL query runs inside a transaction that sets search_path to the project's schema. This prevents cross-tenant data access at the database level.
Request Lifecycle
Public Routes
Public routes skip the gateway middleware entirely. These include health checks (/health/*), platform auth (/v1/platform/*), organization management (/v1/organizations/*), and webhooks.
Protected Routes
Protected routes pass through the gateway middleware pipeline:
1. API Key Middleware
- Extracts the key from the
Authorizationheader or?apikey=query parameter - Computes SHA-256 hash and looks up in the
api_keystable - Resolves:
project_id, tier, role, andschema_name - Loads auth settings: RSA public key, JWT TTL
- Injects a
TenantContextstruct into request extensions
2. Rate Limit Middleware
- Reads the tier from
TenantContext - Increments a Redis counter:
rl:{project_id}:{read|write}:{window} - Compares against tier limits (60 / 600 / 6,000 requests per minute)
- Returns
429 Too Many RequestswithRetry-Afterheader if exceeded
3. Feature Handler
- Extracts
TenantContextfrom the request extension - Begins a transaction with
SET LOCAL search_path TO "proj_{id}" - Executes business logic
- Commits and returns the response
Event-Driven Architecture
AltBase operates both synchronously (HTTP request/response) and asynchronously (NATS-driven background processing).
Synchronous Path
REST CRUD, GraphQL queries, auth login/signup, storage uploads, MCP tool calls, and search queries all follow the standard request/response pattern. Many of these fire NATS events as side effects on state changes.
Asynchronous Paths
CDC Pipeline (Change Data Capture):
Postgres WAL --> CDC Listener (pgwire) --> NATS JetStream --> Fan-out
|
+-------------------+-------------------+
| | |
WebSocket Search Trigger
delivery indexer evaluator
The CDC listener connects to Postgres using the logical replication protocol, reads WAL changes, and publishes them to NATS JetStream. Downstream consumers deliver changes to WebSocket clients, update Tantivy search indexes, and evaluate trigger conditions.
Durable Job Queue:
API Request --> NATS JetStream (durable) --> Worker (pull consumer) --> Execute --> Callback
Background jobs, workflow steps, and integration webhook deliveries use durable NATS JetStream queues with pull-based consumers.
Fire-and-Forget Events:
Handler --> NATS publish (non-blocking) --> Response returns immediately
|
+--> Consumer (background) --> Side effect
Auth events, index advisor pattern recording, and storage events use non-blocking publish.
NATS Subject Naming Convention
atlasdb.events.{project_id}.{event_type}
atlasdb.{project_id}.{environment_id}.{table}.{INSERT|UPDATE|DELETE}
atlasdb.jobs.{project_id}
atlasdb.workflows.{project_id}.{run_id}
atlasdb.triggers.{project_id}
Security Architecture
AltBase implements defense-in-depth with nine layers:
| Layer | Mechanism |
|---|---|
| Transport | HTTPS with TLS termination at ingress |
| Authentication | API key (SHA-256 hashed, prefix lookup) or JWT (RSA-signed) |
| Authorization | Role-based access: Anon, Service, and Custom roles per request |
| Row-Level Access | Postgres RLS policies evaluated per query |
| Tenant Isolation | Schema-per-tenant with SET LOCAL search_path per transaction |
| Data Encryption | AES-256-GCM for secrets at rest (OAuth client secrets, SSO credentials, integration tokens) |
| Password Hashing | Argon2id |
| Rate Limiting | Per-project and per-IP (auth endpoints), Redis-backed sliding windows |
| SSRF Prevention | Allow-list for outbound HTTP in jobs and integrations |
Encryption at Rest
| Data | Algorithm | Storage Location |
|---|---|---|
| Passwords | Argon2id | users.password_hash |
| API keys | SHA-256 | api_keys.key_hash (prefix stored separately for fast lookup) |
| OAuth client secrets | AES-256-GCM with master key | oauth_providers.client_secret_encrypted |
| SSO connection secrets | AES-256-GCM with master key | sso_connections.client_secret_encrypted |
| Integration credentials | AES-256-GCM with master key | connections.credentials_encrypted |
SQL Injection Prevention
All queries use parameterized statements. Table and column identifiers are validated against the schema cache before being interpolated. The query compiler (built with sea-query and nom) never concatenates raw user input into SQL.
Infrastructure Stack
AltBase requires four infrastructure services (plus one optional integration service):
| Service | Version | Role |
|---|---|---|
| PostgreSQL | 16 | Primary data store. WAL-level set to logical for CDC. Extensions: pgvector for vector search. |
| Redis | 7 | Distributed cache, session store, rate limit counters, TUS upload state |
| NATS | 2 (JetStream) | At-least-once messaging for CDC fan-out, events, jobs, workflows, triggers |
| Object Storage | S3 / Azure / Filesystem | Pluggable via StorageProvider trait. Azurite for local dev, S3 or Azure Blob in production. |
| Nango (optional) | Latest | Integration platform for 500+ SaaS OAuth connectors |
Compare with Supabase's 11-13 containers: AltBase achieves comparable functionality with 4 infrastructure containers and 1 application binary.
Performance Characteristics
| Metric | Value | How |
|---|---|---|
| REST query latency | <5ms (cached schema) | Pre-compiled prepared statements, moka in-memory LRU cache |
| WebSocket fan-out | <50ms from WAL to client | NATS JetStream, in-process delivery |
| Function invocation | <10ms (QuickJS) | In-process V8-lite engine, no container cold start |
| Cold start | <100ms | Native Rust binary — no JVM, no V8 startup |
| Memory baseline | 50-100MB | No garbage collector, deterministic allocation |
| Binary size | ~50MB | Release build with LTO |
| Container count | 4 (self-hosted) | Single binary architecture |
Performance Strategies
- Connection pooling —
sqlx::PgPoolwith configurable size, separate pools for control plane and tenant databases - Tiered caching — moka (in-memory LRU) for hot-path data (schema, JWKS), Redis for distributed state, DashMap for concurrent reads
- Async I/O — Tokio runtime, all I/O is non-blocking
- Zero-copy transfers —
bytes::Bytestype for upload/download paths - Query compilation —
sea-queryandnomfor safe, parameterized SQL generation
API Surface
AltBase exposes 165+ HTTP endpoints across all subsystems:
| Category | Count | Path Prefix |
|---|---|---|
| Health | 2 | /health/* |
| Platform | 16 | /v1/platform/*, /v1/organizations/*, /v1/projects/* |
| REST API | 7 | /rest/v1/* |
| Auth | 30+ | /auth/v1/* |
| SSO Management | 26 | /v1/orgs/*/sso/*, /v1/projects/*/sso/* |
| Customer Orgs | 7 | /auth/v1/customer-orgs/* |
| Setup Wizard | 4 | /v1/projects/*/setup/* |
| Storage | 18 | /storage/* |
| TUS Uploads | 5 | /storage/v1/upload/tus/* |
| Realtime | 1 | /realtime/socket |
| Cron | 6 | /v1/projects/*/cron/* |
| Events | 5 | /events/v1/* |
| Jobs | 2 | /jobs/v1/* |
| Search | 2 | /search/v1/* |
| Analytics | 2 | /analytics/v1/* |
| Billing | 5 | /billing/v1/* |
| Integrations | 20+ | /integrations/* |
| Functions | 5 | /functions/v1/* |
| Triggers | 5 | /v1/projects/*/triggers/* |
| Workflows | 11+ | /workflows/v1/* |
| Vector/AI | 11 | /v1/projects/*/embeddings/*, /v1/projects/*/knowledge/* |
| GraphQL | 4 | /graphql* |
| MCP | 6 | /mcp*, /v1/projects/*/mcp/* |
Key Technology Choices
| Decision | Choice | Rationale |
|---|---|---|
| Language | Rust (Axum + Tokio + sqlx) | Compiled binary, no GC, zero-cost abstractions. 50-100MB memory vs multi-GB for polyglot microservices. |
| Architecture | Modular monolith (23 crates, 1 binary) | Fastest to build for a small team. Crate boundaries enable extraction later. Zero inter-service latency. |
| Database | PostgreSQL 16 | Extensions ecosystem (pgvector), logical replication for CDC, RLS for tenant isolation. |
| Message broker | NATS JetStream | At-least-once delivery, replay, consumer groups. Simpler than Kafka, more durable than Redis pub/sub. |
| Cache | Redis 7 + moka | Redis for distributed state, moka for hot-path in-memory caching. |
| Storage | S3/Azure/Filesystem (pluggable) | StorageProvider trait with config-based backend selection. |
| Function runtime | QuickJS + Wasmtime | Dual engine: QuickJS for fast JS with host APIs, Wasmtime for sandboxed compiled Wasm. |
| Search | Tantivy + pgvector | Tantivy for full-text, pgvector for embeddings, hybrid search with Reciprocal Rank Fusion. |
| Query building | sea-query + nom | Safe parameterized SQL generation with parser combinators for the SQL endpoint. |
Frontend and Client Libraries
| Component | Technology | Purpose |
|---|---|---|
| Dashboard | React 19 + Vite 8 + TypeScript | Platform admin UI with 14+ feature pages, workflow builder, and setup wizard |
| JavaScript SDK | TypeScript (@altbasedb/sdk) | Client library for auth, queries, storage, realtime, vector, functions, and more |
| React SDK | TypeScript (@altbase/react) | React hooks with TanStack Query — useQuery, useRealtime, useAuth, useStorage |
| Python SDK | Python (altbasedb) | Async-first client with httpx and websockets |
| Dart SDK | Dart (altbasedb) | Cross-platform client with Streams and built-in resilience |
| Workflows SDK | TypeScript (@altbase/workflows) | Workflow definition types and client |
| CLI | TypeScript (@altbasedb/cli) | Platform management: orgs, projects, keys, db schema, type generation |
Where to Start Reading Code
| Goal | Entry Point |
|---|---|
| Server startup and router assembly | crates/atlas-server/src/main.rs |
| Gateway middleware (auth, rate limiting) | crates/atlas-gateway/src/ |
| REST API query compiler | crates/atlas-api-engine/src/ |
| Authentication flows | crates/atlas-auth/src/routes/ |
| CDC pipeline | crates/atlas-cdc-fanout/src/ |
| Trigger evaluation | crates/atlas-triggers/src/ |
| Workflow engine | crates/atlas-workflows/src/ |
| Full feature inventory | docs/testing/feature-inventory.md |