System Architecture
Abrianto is built on a modern, scalable architecture designed for high-performance debt collection operations. Understanding the system architecture is essential for developers, administrators, and integrators.
High-Level Architecture
┌─────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Browser │ │ Mobile │ │ Desktop │ │ Mobile │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │
│ └─────────────┴─────────────┴─────────────┘ │
└───────────────────────┬────────────────────────────────────┘
│ HTTPS / WebSocket
┌───────────────────────┴────────────────────────────────────┐
│ Application Layer │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ SvelteKit 2.0 Server Components │ │
│ │ - Server-Side Rendering │ │
│ │ - API Routes │ │
│ │ - Server Actions │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ │
│ ┌────────────────────┴────────────────────────────────┐ │
│ │ SvelteKit 2.0 Client Components │ │
│ │ - Runes-based Reactivity │ │
│ │ - Client-Side State Management │ │
│ │ - Client-Side Validation │ │
│ └────────────────────┬────────────────────────────────┘ │
└───────────────────────┬────────────────────────────────────┘
│
┌───────────────────────┴────────────────────────────────────┐
│ Service Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Task Engine │ │ Workflow Eng │ │ Auth Service│ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Storage Svc │ │ Import Svc │ │ Expression │ │
│ │ │ │ Engine │ │ Evaluator │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└───────────────────────┬────────────────────────────────────┘
│
┌───────────────────────┴────────────────────────────────────┐
│ Data Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ PostgreSQL │ │ Valkey/Redis│ │ File S3 │ │
│ │ (Primary) │ │ (Cache) │ │ (Storage) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Migration System (postgres-shift) │ │
│ └─────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘ Core Technology Stack
Frontend Framework
SvelteKit 2.0 with Svelte 5
- Server-Side Rendering - SSR for optimal SEO and initial load performance
- Server Actions - Direct server-side function execution
- Runes-based Reactivity - Modern state management with
$state,$derived,$effect - Hydration on Demand - Client-side components loaded only when needed
Key Svelte 5 Features:
// State
let count = $state(0);
// Derived values
let doubled = $derived(count * 2);
// Side effects
$effect(() => {
console.log(count);
}); Backend Framework
SvelteKit 2.0
- Async server components and actions
- Type-safe route data loading
- Automatic response formatting
- Error handling middleware
Database
PostgreSQL 15+
- Primary Data Store - All core data (accounts, debtors, tasks, workflows)
- Connection Pooling - Configurable pool size and timeout
- CamelCase Transform - Automatic column name conversion
- Dynamic SQL - Tagged template literals for security
Caching Layer
Valkey/Redis
- Route-based Caching - Individual endpoint TTLs
- Tag-based Invalidation - Centralized cache control
- Multi-level Caching - List and detail endpoint optimization
- Cache-Control Headers - HTTP-level cache control
Authentication
Dual Authentication System
Session-based Auth
- Cookie-based sessions
- Secure session management
- Automatic session cleanup
- Role-based access control
API Key Auth
- Bearer token authentication
- Hashed key storage
- Per-key permissions
- Automatic key revocation
Multi-Tenancy Architecture
Tenant Isolation Strategy
Database-level Isolation
// All queries are scoped to tenant_id
sql`
SELECT * FROM accounts
WHERE tenant_id = ${tenantId}
`; Tenant Context Management
// Context established in hooks.server.js
event.locals.tenant.id;
event.locals.tenant.name;
event.locals.user; Authentication Isolation
- Tenant-specific API keys
- Tenant-scoped sessions
- Tenant data access control
- Tenant resource limits
Data Separation
Core Entities (Tenant-Scoped)
- accounts - Collection accounts
- debtors - Debtor information
- tasks - Collection tasks
- workflows - Workflow configurations
- agent_groups - Team organizations
- sessions - User sessions
- api_keys - API authentication keys
Shared/Global Entities
- users - User accounts (tenant-scoped)
- roles - Role definitions (global)
- settings - System settings
Key Components
Authentication Service
Location: src/lib/server/auth.js
Features:
- Session validation and management
- API key generation and validation
- Role-based permission checking
- Multi-tenant authentication isolation
Authentication Flow:
- User provides credentials or API key
- System validates credentials against database
- Creates session or validates API key
- Sets authentication context
- Validates permissions for requested resource
Task Engine
Location: src/lib/server/task-engine.js
Purpose: Automated task creation based on configurable rules
Key Features:
- Condition-based task generation
- Multiple assignment strategies
- Duplicate prevention
- Tenant-scoped processing
Supported Conditions:
- Outstanding balance (greater than, less than, equal to)
- Account due date (passed by days, approaching in days)
Assignment Strategies:
- Specific agent
- Account owner
- Fewest tasks
- Agent group
- Task queue
Workflow Engine
Location: src/lib/server/workflows/
Purpose: Event-driven automation for debt collection processes
Architecture:
- engine.js - Main orchestration
- conditions.js - Condition evaluation logic
- actions.js - Action execution system
- trigger-engine.js - Event triggers
Workflow Components:
- Triggers - Events that start workflows (payment received, promise made)
- Conditions - Logic to determine when to execute actions
- Actions - Executable operations (email, SMS, update status)
- Branches - A/B testing and conditional execution paths
Example Workflow:
triggerWorkflowEngine(accountId, 'PAYMENT_RECEIVED', {
outstandingBalance: 1500,
dueDate: '2024-12-31'
});
// Will execute workflow if conditions are met Database Layer
Location: src/lib/server/db.js
Features:
- Connection pooling
- Query building with tagged templates
- Automatic camelCase transformation
- Dynamic SQL identifier support
Dynamic SQL Pattern:
// Safe dynamic column/table names
sql`ORDER BY ${sql(columnName)} ${sortDirection}`;
// Safe dynamic WHERE clauses
const conditions = [sql`tenant_id = ${tenantId}`];
if (type) conditions.push(sql`type = ${type}`);
sql`
SELECT * FROM templates
WHERE ${conditions.reduce((acc, cond, i) => (i === 0 ? cond : sql`${acc} AND ${cond}`), sql``)}
`; Real-time System
Technology: Socketi (self-hosted Pusher) with PusherJS client
Server-side:
// Publish events after mutations
pusherClient.publish(`account-${accountId}`, 'update', {
account,
balance: updatedBalance
}); Client-side:
// Subscribe with automatic cleanup
$effect(() => {
const channel = pusherClient.subscribe(`account-${accountId}`);
channel.bind('update', () => invalidateAll());
return () => pusherClient.unsubscribe(`account-${accountId}`);
}); Event Types:
- Account updates
- Task assignments
- Payment notifications
- Workflow triggers
- Interaction logs
File Storage
Location: src/lib/server/storage/
Features:
- Multi-provider support (MinIO, S3 compatible)
- Presigned URL generation
- File metadata management
- Tenant-isolated storage
Storage Flow:
- Upload file to provider
- Get presigned URL for secure access
- Store metadata in database
- Reference file via metadata
Import/Export Engine
Location: src/lib/server/import.js
Features:
- CSV import with field mapping
- Multi-entity processing
- Data validation
- Error handling
- Batch operations
Import Process:
- Parse CSV file
- Map columns to fields
- Validate data
- Insert with transactions
- Handle conflicts
- Report errors
Custom Parameters System
Location: src/lib/server/custom-params.js
Features:
- Dynamic field definitions
- Expression-based values
- Data type validation
- Bulk operations
- Audit logging
Supported Data Types:
- String, Number, Boolean
- Date, Email, Phone, URL
- JSON, Select, Multi-select
- Expression
Data Flow Patterns
User Action Flow
1. User performs action (create account, assign task)
2. Client validates input
3. Server action processes request
4. Database updates with tenant scoping
5. Real-time event published
6. Client receives update via WebSocket
7. UI refreshes with invalidation Workflow Execution Flow
1. Event triggers workflow
2. System evaluates conditions
3. Workflow engine validates context
4. Actions executed in sequence
5. Branch selection (A/B testing)
6. Results logged
7. Notifications sent Task Creation Flow
1. Task rule evaluated
2. Conditions matched against accounts
3. Assignment strategy selected
4. Task created with tenant scoping
5. Agent notified (real-time)
6. Task added to agent queue Security Architecture
Authentication Security
Secure Session Management
- HttpOnly cookies
- CSRF protection
- Secure flags
- Session expiration
API Key Security
- SHA-256 hashing
- Random key generation
- Per-key permissions
- Key rotation support
Data Security
Encryption
- SSL/TLS for all connections
- Database encryption at rest (optional)
- Secure file storage
Authorization
- Role-based access control
- Resource-level permissions
- Tenant isolation
- Audit logging
Input Validation
- Server-side validation
- SQL injection prevention
- XSS prevention
- CSRF protection
Performance Considerations
Caching Strategy
Route-level Caching:
- Configurable TTL per endpoint
- Tag-based invalidation
- Multi-level caching (list/detail)
- Cache-Control headers
Cache Pattern:
// Example with cache tags
const cached = await getFromCache(key, { ttl: 300 }, tags: ['accounts']);
if (!cached) {
const data = await loadData();
setCache(key, data, { ttl: 300 }, tags: ['accounts']);
} Database Optimization
Indexes:
- Foreign key indexes
- Query pattern indexes
- Tenant-scoped indexes
- Composite indexes for common queries
Query Optimization:
- N+1 query prevention
- Eager loading for relationships
- Pagination for large datasets
- Batch operations
Frontend Performance
- Server-side rendering for initial load
- Client-side hydration
- Code splitting
- Lazy loading
- Optimistic updates
- Debouncing and throttling
Scalability
Horizontal Scaling
Stateless Server Architecture:
- No server-side state in app code
- Session data in external store
- Database as single source of truth
- Shared caching layer
Database Scaling:
- Connection pooling
- Read replicas (optional)
- Sharding for very large tenants
Cache Scaling:
- Distributed cache (Redis cluster)
- Cache partitioning by tenant
- Automatic cache invalidation
Load Balancing
Nginx/Caddy:
- Reverse proxy
- SSL termination
- Load balancing
- Static file serving
Monitoring & Logging
Application Logging
Log Levels:
- DEBUG - Development information
- INFO - General application flow
- WARN - Warning conditions
- ERROR - Error conditions
- FATAL - Critical failures
Structured Logging:
- Tenant ID context
- User ID context
- Request IDs
- Performance metrics
Monitoring Points
- Database query performance
- API response times
- Cache hit/miss ratios
- Workflow execution times
- Task processing rates
- Real-time event latency
Development Workflow
Local Development
# Start development server
npm run dev
# Run database migrations
npm run db:migrate
# Start test suite
npm run test:unit
# Type checking
npm run check Environment Variables
Required:
DATABASE_URL- PostgreSQL connection stringREDIS_URL- Valkey/Redis connection (optional)PUSHER_APP_KEY- Socketi configuration
Optional:
ENVIRONMENT- Development/production/stagingNODE_ENV- Development/production
Integration Points
External Services
Payment Gateways:
- Payment processing
- Webhook notifications
- Refund management
Communication:
- Email providers (SMTP)
- SMS providers (API)
- WhatsApp services
File Storage:
- S3-compatible storage
- Cloud storage providers
- Local filesystem (dev)
API Integration
REST API:
- All CRUD operations
- OpenAPI specification
- Versioned endpoints
- Rate limiting
Webhooks:
- Real-time event notifications
- Custom event types
- Signature verification
- Retry logic
Future Enhancements
Planned Features
- Multi-region Deployment
- Advanced Analytics
- Mobile Apps
- AI-Powered Recommendations
- Custom Integrations
- API Rate Limiting
Technical Improvements
- GraphQL API
- CQRS Pattern
- Event Sourcing
- Microservices Architecture
- Serverless Deployment
This documentation describes the current system architecture. For implementation details, refer to the source code in the repository.