kaccy-db
Comprehensive database layer for Kaccy Protocol with enterprise-grade features.
Overview
This crate provides a complete PostgreSQL database solution with:
- Connection pooling with retry logic and health monitoring
- Repository pattern for all domain entities
- Redis caching layer with rate limiting and distributed locks
- Read replica support with automatic query routing and load balancing
- Database sharding with consistent hashing
- Multi-region replication with automatic failover
- TimescaleDB integration for time-series analytics
- Query performance monitoring and index analysis
- Transaction management with savepoints
- Comprehensive audit logging
- Backup/recovery automation with PITR support
Core Modules
Connection Management
pool- Connection pool with retry logic and health checksreplica- Read replica management with load balancing strategiesmulti_region- Geographic replication with proximity-based routingsharding- Database sharding with consistent hashing
Repositories
All repositories provide type-safe, async database operations:
UserRepository- User accounts, profiles, KYC, reputationTokenRepository- Personal tokens with bonding curvesBalanceRepository- Token balances with locking supportOrderRepository- Buy/sell orders with BTC integrationTradeRepository- Trade execution and analyticsReputationEventRepository- Reputation scoring and historyCommitmentRepository- User commitments with deadlinesAuditRepository- Compliance reporting and audit logs
Performance & Analytics
cache- Redis caching with rate limiting and distributed locksquery_logger- Query performance monitoring and slow query detectionindex_analyzer- Index optimization recommendationsanalytics- TimescaleDB integration with materialized views for dashboards
Operations
backup- Automated backups with pg_dump/restore and PITRtransaction- Transaction management with isolation levels and savepoints
Quick Start
use ;
async
Advanced Features
Redis Caching
use ;
let cache_config = default;
let cache = connect.await?;
// Cache user sessions
cache.set_session.await?;
// Rate limiting
let allowed = cache.check_rate_limit.await?;
Read Replicas
use ;
let manager = new.await?;
let client = new.build;
// Automatically routes SELECTs to replicas, writes to primary
Database Sharding
use ;
let shard_manager = new.await?;
// Route queries to appropriate shard
let user = shard_manager.execute_on_shard.await?;
Analytics & Time-Series
use AnalyticsService;
let analytics = new;
// Get dashboard metrics from materialized views
let metrics = analytics.get_dashboard_metrics.await?;
// Query time-series data (requires TimescaleDB)
let prices = analytics.get_price_history.await?;
Configuration
Environment variables:
DATABASE_URL- PostgreSQL connection stringREDIS_URL- Redis connection string (optional)
Architecture
kaccy-db/
├── src/
│ ├── lib.rs # Public API
│ ├── pool.rs # Connection pooling
│ ├── cache.rs # Redis caching
│ ├── replica.rs # Read replicas
│ ├── sharding.rs # Database sharding
│ ├── multi_region.rs # Geographic replication
│ ├── analytics.rs # TimescaleDB & materialized views
│ ├── query_logger.rs # Performance monitoring
│ ├── index_analyzer.rs # Index optimization
│ ├── backup.rs # Backup/recovery
│ ├── transaction.rs # Transaction management
│ ├── error.rs # Error types
│ └── repositories/
│ ├── user.rs
│ ├── token.rs
│ ├── balance.rs
│ ├── order.rs
│ ├── trade.rs
│ ├── reputation_event.rs
│ ├── commitment.rs
│ └── audit.rs
├── migrations/ # SQL migrations
└── Cargo.toml
Dependencies
sqlx- Async SQL with compile-time checkingredis- Async Redis clienttokio- Async runtimeserde- Serializationchrono- Date/time handlinguuid- UUID supportrust_decimal- Decimal arithmetic
Database Schema
See migrations/ directory for the current schema. Key tables:
users- User accounts with DID, KYC status, reputationtokens- Personal tokens with bonding curve parametersbalances- User token balancesorders- Buy/sell orders with BTC payment infotrades- Executed trade recordsreputation_events- Reputation score changesoutput_commitments- User commitments with deadlines
Testing
# Run with test database
DATABASE_URL=postgresql://test@localhost/kaccy_test
# Run migrations