Database Optimization
Connection Pooling
PostgreSQL connection pool configuration is critical for performance:| Workload | Max Open | Max Idle | Rationale |
|---|---|---|---|
| Low (< 100 TPS) | 10 | 5 | Minimize resource usage |
| Medium (100-1000 TPS) | 25 | 10 | Default configuration |
| High (1000-5000 TPS) | 50 | 20 | Support burst traffic |
| Very High (> 5000 TPS) | 100 | 40 | Maximum parallelism |
conn_max_lifetime: 30m (prevents stale connections)conn_max_idle_time: 5m (releases idle connections faster)
Index Optimization
Blnk creates optimized indexes on frequently queried fields: Critical Indexes:Query Optimization
Use EXPLAIN ANALYZE:- Sequential scans (should use indexes)
- High cost estimates
- Slow execution time
PostgreSQL Configuration
Recommended postgresql.conf settings for production:Redis Caching
Blnk uses a two-tier caching strategy with Redis and in-memory LRU.Cache Architecture
Implementation (internal/cache/cache.go:84-114):- L1 Cache (Local): TinyLFU in-memory cache (128K entries, 1-minute TTL)
- L2 Cache (Redis): Distributed Redis cache (configurable TTL)
- Sub-millisecond L1 cache hits
- Shared L2 cache across instances
- Automatic eviction (LFU policy)
Cache Configuration
- Database connections: 50
- Transaction queues: 20
- Overhead: 20
- Total pool_size: 90 (round to 100)
Caching Strategy
Balance Caching: Balances are cached with short TTL to ensure consistency:Redis Memory Optimization
Set Eviction Policy:used_memory_human: Current memory usageused_memory_peak_human: Peak usagemem_fragmentation_ratio: Should be close to 1.0
Batch Processing
Transaction Batching
Process multiple transactions in parallel:MaxWorkers: Number of concurrent transaction processorsBatchSize: Batch size for bulk operationsMaxQueueSize: In-memory queue size
Reindex Batching
Reindexing uses configurable batch sizes:- 1,000: Default, balanced performance
- 5,000: High throughput, more memory
- 10,000: Maximum speed, requires 8GB+ RAM
Monitoring and Metrics
Database Metrics
Connection Pool Stats:numbackends: Active connections (should be < max_connections)blks_hit / (blks_hit + blks_read): Cache hit ratio (target: > 0.99)xact_commit / (xact_commit + xact_rollback): Commit ratio (target: > 0.95)
Queue Metrics
Monitor Asynq queues:- Queue depth (should be < 10,000)
- Processing latency (p99 < 1s)
- Failure rate (< 1%)
- Retry rate
Application Metrics
Blnk exposes Prometheus-compatible metrics:blnk_transactions_total: Total transactions processedblnk_transaction_duration_seconds: Transaction processing timeblnk_balance_operations_total: Balance operation countblnk_cache_hits_total: Cache hit countblnk_cache_misses_total: Cache miss count
Performance Benchmarks
Hardware Specifications
Test Environment:- CPU: 8 cores (Intel Xeon or equivalent)
- RAM: 16GB
- Disk: SSD (NVMe recommended)
- Network: 1Gbps
Throughput
Simple Transactions (A → B):- Sequential: ~500 TPS
- Queued (20 queues): ~5,000 TPS
- Queued (50 queues): ~12,000 TPS
- Sequential: ~200 TPS
- Queued (20 queues): ~2,000 TPS
- Queued (50 queues): ~5,000 TPS
- Bulk insert (1,000 txns): ~2 seconds
- Reindex (1M records): ~10 minutes
Latency
Transaction Processing:- p50: 10ms
- p95: 50ms
- p99: 100ms
- Cache hit: < 1ms
- Cache miss: 5-10ms
- Simple filter: 10-20ms
- Complex query: 50-100ms
- Full-text search: 100-200ms
Scaling Strategies
Vertical Scaling
PostgreSQL:- Increase
shared_buffers(25% of RAM) - Add CPU cores for parallelism
- Use faster disks (NVMe SSD)
- Increase connection pool
- Increase
maxmemory - Use Redis Cluster for distribution
- Enable persistence (RDB + AOF)
Horizontal Scaling
Application Tier:- Run multiple Blnk instances
- Use load balancer (nginx, HAProxy)
- Share Redis and PostgreSQL
- PostgreSQL read replicas
- Connection pooling (PgBouncer)
- Partitioning for large tables
- Increase
number_of_queues - Redis Cluster for queue distribution
- Multiple Asynq workers
Partitioning
Partition transactions by date:- Faster queries (partition pruning)
- Easier archival (drop old partitions)
- Improved vacuum performance
Best Practices
-
Monitor Continuously: Set up alerts for key metrics
- Database connection pool exhaustion
- Queue depth > 10,000
- Cache hit ratio < 95%
- Transaction failure rate > 1%
- Use Connection Pooling: Always configure proper pool sizes
- Enable Caching: Leverage Redis cache for hot data
- Batch Operations: Group related operations when possible
- Index Strategically: Add indexes for query patterns, not every column
-
Regular Maintenance:
-
Archive Old Data: Move historical data to archive tables
-
Load Testing: Regular load tests to validate configuration
Troubleshooting
High Database CPU
Symptoms:- PostgreSQL CPU > 80%
- Slow query performance
- Check for missing indexes (see Index Optimization)
- Review slow query log
- Optimize queries with EXPLAIN ANALYZE
- Increase
work_memfor complex queries - Add read replicas
Connection Pool Exhaustion
Symptoms:- Increase
max_connectionsin PostgreSQL - Increase
max_open_connsin Blnk - Use connection pooler (PgBouncer)
- Check for connection leaks
Redis Memory Issues
Symptoms:- High memory usage
- OOM errors
- Slow cache performance
- Increase
maxmemory - Enable eviction policy
- Reduce cache TTL
- Check for memory leaks
- Use Redis Cluster
High Queue Latency
Symptoms:- Transactions taking minutes to process
- Growing queue depth
- Increase
number_of_queues - Increase
max_workers - Check for slow transactions (enable query logging)
- Scale horizontally (more workers)
- Optimize transaction logic