Database Documentation
Complete guide to SveltyCMS database architecture, covering both database-agnostic infrastructure and MongoDB-specific implementation.
Last updated: 2/15/2026
Database Documentation
Complete guide to SveltyCMS database architecture, covering both database-agnostic infrastructure and MongoDB-specific implementation.
π Documentation Structure
Database-Agnostic Architecture
These documents explain the core database infrastructure that works with any database backend (MongoDB, PostgreSQL, MySQL, SQLite, etc.):
-
db.ts- Database manager/orchestratordb-interface.ts- Database adapter contracttheme-manager.ts- Theme service- How the adapter pattern enables database agnosticism
-
cache-service.ts- Dual-layer caching (Redis + MongoDB)CacheMetrics.ts- Performance monitoringCacheWarmingService.ts- Predictive prefetching- 8 cache categories with dynamic TTL
- NEW: Pattern-based predictive prefetching with custom fetchers
- ContentManager: LRU cache & batch initialization optimization
-
- Complete auth infrastructure (12 files)
- User authentication & authorization
- Session management & cleanup
- OAuth integration (Google)
- Two-factor authentication (2FA/TOTP)
- Permission system (RBAC)
Database-Specific Implementations
Implementation guides for specific database backends:
-
- Enterprise connection pool configuration
- 29 optimized indexes (4 TTL + 25 compound)
- Cursor pagination (99.9% faster)
- Streaming API (97% memory savings)
- Query hints & optimization
- 70-90% performance improvement
- NEW: Optimized
upsertManywithbulkWritefor high-volume writes
-
MariaDB Implementation β Production-Ready
- Drizzle ORM with mysql2 driver
- 13 relational tables with proper indexes
- Connection pooling and health monitoring
- Automatic migration system
- Multi-tenant support (nullable tenantId)
- Type-safe queries with full TypeScript support
- Status: Implementation Complete (100%)
-
PostgreSQL Implementation β Production-Ready
- Drizzle ORM with postgres.js driver
- Full schema with PostgreSQL-specific types (UUID, JSONB with GIN indexes)
- Connection management and health checks
- Status: Production-Ready (100%)
-
SQLite Implementation β Production-Ready
- Drizzle ORM with better-sqlite3/bun:sqlite
- Zero-config single-file database with 7 performance PRAGMAs
- Ideal for local development and edge
- Status: Production-Ready (100%)
π― Quick Navigation
I want toβ¦
- Understand the overall architecture β Read Core Infrastructure
- Learn about caching β Read Cache System
- Understand authentication β Read Authentication System
- Optimize MongoDB β Read MongoDB Implementation
- Implement MariaDB β Read MariaDB Implementation
- Implement PostgreSQL β Read PostgreSQL Implementation
- Implement SQLite β Read SQLite Implementation
- Add a new database β Read Core Infrastructure section βAdding New Adaptersβ
- Check cache performance β Read Cache System section βMetricsβ
- Implement permissions β Read Authentication System section βPermissionsβ
π Getting Started
For New Developers
- Start with Core Infrastructure to understand the 3-layer architecture
- Read Cache System to understand performance optimization
- Read Authentication System to understand security
For MongoDB Users
- Read MongoDB Implementation for best practices
- Check the βQuick Referenceβ section for common operations
- Review index strategy for your use case
For MariaDB Users
- Read MariaDB Implementation for setup guide
- Review the schema design and migration system
- Check implementation roadmap for completion status
For PostgreSQL Users
- Read PostgreSQL Implementation for setup and optimization details
- JSONB columns with GIN indexes enable efficient metadata queries
- All modules fully implemented β production-ready
For Adding New Database Support
- Read Core Infrastructure β βAdding New Adaptersβ
- Implement the
DatabaseAdapterinterface - Follow the PostgreSQL or MariaDB example
- Test against the database-agnostic tests
π Architecture Overview
π§ Key Features
Database Agnostic
- β Works with MongoDB, MariaDB, PostgreSQL, MySQL, SQLite
- β
Unified
DatabaseAdapterinterface - β No database-specific code in business logic
- β
DatabaseResult<T>pattern (no exceptions)
High Performance
- β Dual-layer cache (Redis L1 + MongoDB L2)
- β 92% cache hit rate
- β 97% faster response times
- β 29 optimized MongoDB indexes
- β Cursor pagination (O(1) time)
- β Streaming API (O(1) memory)
- β Batch Widget API (Solves N+1 problem for relations)
Enterprise Security
- β Multi-factor authentication (2FA/TOTP)
- β OAuth integration (Google)
- β
Advanced RBAC (Role-Based Access Control): Deep authorization system with isolated
tenantIdenforcement, natively preventing cross-tenant and cross-collection data leakage. - β Granular permissions
- β Session management with automatic cleanup
- β API endpoint protection
- β
Native Database Protection (Out-of-the-box):
- UUIDv4 Primary Keys: Prevents serial-based IDOR (Insecure Direct Object Reference) access attacks commonly found in multi-auth systems.
- Safe Query Mapping: Strict mapping and Drizzle ORM parameterization intrinsically protect all JSON and RichText property requests against SQL Injection.
Developer Experience
- β TypeScript throughout
- β Comprehensive documentation
- β Code examples for every feature
- β Performance metrics built-in
- β Best practices documented
- β Query builder API
π Performance & Scalability
SveltyCMS achieving sub-millisecond latency is not just about the database; itβs about the Unified Caching Layer that sits between the application and the persistent storage. This architecture ensures high performance regardless of your database choice.
Unified Caching Flow
Benchmarking Environment
Benchmarks were conducted on the following production hardware:
- CPU: AMD Ryzen 5 3600 6-Core Processor (12 threads)
- RAM: 64GB DDR4
- OS: Ubuntu 24.04.3 LTS
- Environment: Node.js v24.x, Local Database Instance
Performance Matrix
The following metrics represent benchmarks across different environments. High-level gains like the 99.9% steady-state cache hit rate apply across all supported databases due to the agnostic infrastructure.
| Metric | MongoDB | MariaDB | PostgreSQL | SQLite (Drizzle) | Why it matters |
|---|---|---|---|---|---|
| Cache Hit Rate (Warmed) | 99.9% | 99.9% | 99.9% | 99.9% | Steady-state serving |
| Cache Hit Rate (Cold) | <5% | <5% | <5% | <5% | Initial bootstrap misses |
| Response Time (Warmed) | <0.1ms | 1.2ms | 1.8ms | 0.2ms | In-memory content serving |
| Response Time (Cold) | 50-100ms | 120-200ms | 150-250ms | 10-30ms | First-request latency |
| P99 Latency (Batch Init) | <15ms | <6ms | <8ms | <5ms | Structural hydration speed |
| Storage Engine | WiredTiger | InnoDB | Heap/B-Tree | SQLite WAL | Data integrity and speed |
| JSON Performance | Excellent | Good | Excellent | JSON1 Enabled | Native document handling |
| Scaling | Sharding | Replication | Clustering | Local/Embedded | Expansion strategy |
Cache Performance: In-Memory vs. Redis
SveltyCMS supports two primary caching modes, both integrated into the Unified Caching Layer:
| Feature | In-Memory (Local) | Redis (Distributed) |
|---|---|---|
| Response Time (Warmed) | <0.1ms - 1.5ms | 1.2ms - 2.5ms |
| Persistence | Lost on restart | Persistent (Docker/Cloud) |
| Scalability | Single instance only | Multi-instance / Cluster |
| Setup Overhead | Zero-config | Requires Docker/External Host |
| Best For | Development, Single-user, Edge | Production, SaaS, High-Traffic |
While In-Memory caching offers the absolute lowest latency due to zero network overhead, Redis ensures that the 99.9% Cache Hit Rate is maintained across server restarts and shared across multiple application instances in a distributed environment.
Automated Benchmarking
You can replicate these performance tests on your own hardware using the integrated benchmark script:
# Ensure server is running
bun run dev
# Run benchmark for a specific database
# Usage: bun run tests/benchmarks/database-performance.ts <dbType> <useRedis>
bun run tests/benchmarks/database-performance.ts mongodb false
bun run tests/benchmarks/database-performance.ts sqlite false
This tool measures Setup Speed, Cold Start latency, and Steady State (Warmed) response times across all supported adapters.
Performance Note: MongoDB vs. SQL
You may notice that SQLite and other SQL-based adapters have lower P99 Batch Initialization times than MongoDB. This is due to architectural differences:
- SQLite: Runs in-process via C-bindings. Model registration is an in-memory operation with zero network overhead.
- MongoDB: Requires a TCP handshake and complex model compilation via Mongoose. While slightly slower during the initial 8-15ms handshake, MongoDBβs true power is revealed in Horizontal Scaling and High-Volume JSON throughput where it outperforms relational systems at scale.
SveltyCMS mitigates this initial overhead through its Unified Caching Layer, ensuring that after the first few milliseconds of βCold Start,β all adapters deliver sub-millisecond response times.
π Related Documentation
API Documentation
- Database Agnostic Verification - API endpoint verification
Development Guides
- Contributing - How to contribute to docs
π Documentation Standards
All database documentation follows these standards:
- β
.mdxformat with complete frontmatter - β Code examples with syntax highlighting
- β Clear explanations of purpose and usage
- β Performance metrics where applicable
- β Best practices sections
- β How components work together
- β Real-world usage examples
See Contributing Guidelines for more details.
π€ Contributing
Want to improve the database documentation?
- Follow the Contributing Guidelines
- Ensure
.mdxformat with proper frontmatter - Include code examples and performance data
- Add to this README if adding new docs
- Test all code examples before submitting
Last Updated: 2026-03-01
Maintained by: SveltyCMS Team