Date: October 8, 2025 Version: 2.2.0 Status: β Implemented
The ChittyID service now includes self-healing connection management that automatically handles connection failures, performs health monitoring, and reconnects to id.chitty.cc when connectivity is restored.
This feature complements the existing resilience features (retry logic, circuit breaker, caching) to provide a production-grade, fault-tolerant ChittyID integration.
Exponential Backoff Reconnection:
- Starts with 1-second delay
- Doubles on each attempt (2s, 4s, 8s, ...)
- Caps at 60 seconds maximum
- Configurable max attempts (default: unlimited)
Connection States:
DISCONNECTED- Initial state, no connectionCONNECTING- Attempting to establish connectionCONNECTED- Healthy connection to id.chitty.ccRECONNECTING- Attempting to recover from failureFAILED- Max attempts reached or permanent failure
Periodic Health Checks:
- Runs every 30 seconds (configurable)
- Uses
/healthendpoint on id.chitty.cc - 5-second timeout per check
- Tracks success/failure rates
Automatic Failure Detection:
- Detects service unavailability
- Triggers reconnection automatically
- Emits events for monitoring
Tracked Metrics:
{
totalConnections: 15,
totalReconnections: 3,
totalFailures: 2,
totalHealthChecks: 245,
successfulHealthChecks: 240,
failedHealthChecks: 5,
healthCheckSuccessRate: "97.96%",
currentState: "CONNECTED",
uptime: 3600000 // 1 hour in ms
}Available Events:
connected- Successfully connected to servicedisconnected- Gracefully disconnectedreconnecting- Attempting reconnectionunhealthy- Health check failedstateChange- Connection state changederror- Error occurredmaxReconnectAttemptsReached- Reconnection limit hit
import { getSharedConnectionManager } from './lib/chittyid-connection-manager.js';
// Get shared connection manager (auto-connects)
const manager = getSharedConnectionManager({
serviceUrl: 'https://id.chitty.cc',
apiKey: process.env.CHITTY_ID_TOKEN
});
// Check connection status
const status = manager.getState();
console.log(status.state); // CONNECTED, DISCONNECTED, etc.
console.log(status.isHealthy); // true/falseThe connection manager is automatically integrated into chittyid-service.js:
import { generateChittyID, getServiceHealth } from './lib/chittyid-service.js';
// Generate ChittyID (connection manager handles connectivity)
const chittyId = await generateChittyID('INFO', { test: true });
// Get health including connection status
const health = getServiceHealth();
console.log(health.connection);
// {
// initialized: true,
// state: 'CONNECTED',
// isHealthy: true,
// uptime: 3600000,
// stats: { ... }
// }const manager = getSharedConnectionManager();
// Listen for connection events
manager.on('connected', ({ serviceUrl }) => {
console.log(`Connected to ${serviceUrl}`);
});
manager.on('disconnected', ({ serviceUrl }) => {
console.log(`Disconnected from ${serviceUrl}`);
});
manager.on('reconnecting', ({ attempt, delay }) => {
console.log(`Reconnecting (attempt ${attempt}) in ${delay}ms`);
});
manager.on('unhealthy', () => {
console.warn('Service health check failed');
});
manager.on('stateChange', ({ from, to, timestamp }) => {
console.log(`State: ${from} β ${to}`);
});const manager = getSharedConnectionManager();
// Manual connection
await manager.connect();
// Manual disconnection
manager.disconnect();
// Check health
const isHealthy = await manager.performHealthCheck();
// Reset all state
manager.reset();import { ChittyIDConnectionManager } from './lib/chittyid-connection-manager.js';
const manager = new ChittyIDConnectionManager({
serviceUrl: 'https://id.chitty.cc',
apiKey: process.env.CHITTY_ID_TOKEN,
// Health monitoring
healthCheckInterval: 30000, // 30 seconds
// Reconnection strategy
reconnectDelay: 1000, // Start at 1s
maxReconnectDelay: 60000, // Cap at 60s
reconnectMultiplier: 2, // Double each time
maxReconnectAttempts: 10 // Max 10 attempts (default: Infinity)
});
await manager.connect();βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DISCONNECTED β
β (Initial State) β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β connect()
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CONNECTING β
β (Performing Health Check) β
βββββββββββ¬βββββββββββββββββββββββββββ¬βββββββββββββββββ
β Health Check OK β Health Check Failed
βΌ βΌ
βββββββββββββββββββββββ ββββββββββββββββββββββββββββ
β CONNECTED β β FAILED β
β (Start Monitoring) β β (Schedule Reconnect) β
βββββββββββ¬βββββββββββββ ββββββββββββ¬ββββββββββββββββ
β β
β Health Check Failed β Reconnect Timer
βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β RECONNECTING β
β (Attempting to Restore Connection) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β Success β Max Attempts
βΌ βΌ
CONNECTED FAILED
Client Request
β
getSharedClient()
β
Connection Manager (health monitoring, auto-reconnect)
β
Circuit Breaker (fail-fast when service down)
β
Retry Logic (3 attempts with backoff)
β
ChittyIDClient
β
id.chitty.cc
# Run all connection tests
npm run test:connection
# Watch mode
npm run test:connection:watch
# Full test suite (includes connection tests)
npm testConnection Management (5 tests):
- β Initialize in DISCONNECTED state
- β Connect to ChittyID service
- β Handle multiple connect calls
- β Disconnect gracefully
Health Monitoring (3 tests):
- β Perform health check
- β Start monitoring after connection
- β Stop monitoring on disconnect
Reconnection Logic (4 tests):
- β Schedule reconnection on failure
- β Use exponential backoff
- β Respect max attempts
- β Reset attempts on success
State Management (3 tests):
- β Transition states correctly
- β Get current state
- β Track statistics
Event Emitters (4 tests):
- β Emit connected event
- β Emit disconnected event
- β Remove listeners
- β Handle listener errors
Shared Instance (3 tests):
- β Create shared instance
- β Return same instance
- β Reset shared instance
Reset Functionality (1 test):
- β Reset manager state
# Required
CHITTY_ID_TOKEN=your_token_here
# Optional
CHITTYID_SERVICE_URL=https://id.chitty.cc # Override default URL{
serviceUrl: 'https://id.chitty.cc',
healthCheckInterval: 30000, // 30 seconds
reconnectDelay: 1000, // 1 second
maxReconnectDelay: 60000, // 60 seconds
reconnectMultiplier: 2, // Exponential backoff
maxReconnectAttempts: Infinity // Unlimited retries
}Per Connection Manager Instance:
- Base object: ~1 KB
- Event listeners: ~0.5 KB per listener
- Statistics tracking: ~0.2 KB
- Total: ~2-3 KB (negligible)
Health Check Overhead:
- Runs every 30 seconds
- ~10-50ms per check
- Impact: <0.2% CPU on average
Health Check Traffic:
- 1 request per 30 seconds
- ~200 bytes per request
- Total: ~400 bytes/min (~24 KB/hour)
// β
Good - Use shared instance
const manager = getSharedConnectionManager();
// β Bad - Don't create multiple instances
const manager1 = new ChittyIDConnectionManager();
const manager2 = new ChittyIDConnectionManager();// Add to health check endpoint
app.get('/health', (req, res) => {
const health = getServiceHealth();
res.json({
status: health.connection.isHealthy ? 'ok' : 'degraded',
chittyid: health
});
});manager.on('unhealthy', () => {
// Alert ops team
sendAlert('ChittyID service unhealthy');
});
manager.on('maxReconnectAttemptsReached', ({ attempts }) => {
// Critical alert
sendCriticalAlert(`ChittyID reconnection failed after ${attempts} attempts`);
});process.on('SIGTERM', () => {
const manager = getSharedConnectionManager();
manager.disconnect();
process.exit(0);
});- Connection State - Should stay CONNECTED
- Health Check Success Rate - Target: >99%
- Reconnection Attempts - Should be low
- Uptime - Time since last successful connection
const health = getServiceHealth();
const stats = health.connection.stats;
// Alert if health check success rate below 95%
if (parseFloat(stats.healthCheckSuccessRate) < 95) {
sendAlert('ChittyID health degraded');
}
// Critical alert if FAILED state
if (health.connection.state === 'FAILED') {
sendCriticalAlert('ChittyID connection failed');
}
// Warning if reconnecting
if (health.connection.state === 'RECONNECTING') {
sendWarning(`ChittyID reconnecting (attempt ${health.connection.reconnectAttempts})`);
}No changes required! The connection manager integrates automatically:
// This code continues to work without modification
import { generateChittyID } from './lib/chittyid-service.js';
const chittyId = await generateChittyID('INFO', { test: true });import { getServiceHealth, getConnectionStatus } from './lib/chittyid-service.js';
// Check connection status
const connectionStatus = getConnectionStatus();
// Get full health (includes connection)
const health = getServiceHealth();Cause: Service unavailable or network issues Solution: Check id.chitty.cc availability
curl https://id.chitty.cc/healthCause: Intermittent connectivity
Solution: Review network stability, consider increasing maxReconnectDelay
Cause: Invalid API key or service misconfiguration
Solution: Verify CHITTY_ID_TOKEN environment variable
echo $CHITTY_ID_TOKEN # Should not be emptysrc/lib/chittyid-connection-manager.js(360 lines)test/chittyid-connection-manager.test.js(245 lines)
-
src/lib/chittyid-service.js- Added connection manager import
- Integrated connection initialization
- Added
getConnectionStatus()function - Updated
getServiceHealth()to include connection status
-
package.json- Added
test:connectionscript - Added
test:connection:watchscript - Updated main
testscript
- Added
- New Code: ~600 lines
- Modified Code: ~30 lines
- Total: ~630 lines
- β Connection manager implemented
- β Tests created (23 test cases)
- β Integration with chittyid-service.js
- β³ Documentation completed
- β³ Commit changes
- Add Prometheus metrics export
- Implement connection pooling
- Add distributed tracing
- Create monitoring dashboard
- WebSocket support for real-time health
- Service mesh integration
- Multi-region failover
- Load balancing across ChittyID replicas
The ChittyID Self-Healing Connection Manager provides:
β Automatic Reconnection - Exponential backoff with configurable limits β Health Monitoring - Periodic checks every 30 seconds β Event System - React to connection state changes β Statistics Tracking - Monitor uptime and success rates β Zero Breaking Changes - Backward compatible β Comprehensive Tests - 23 test cases covering all features
Production-ready, fault-tolerant, self-healing ChittyID integration.
Document Version: 1.0 Implementation Date: October 8, 2025 ChittyOS Framework: v1.0.1 ChittyID Service: v2.2.0