ai-usage-tracker ECONNREFUSED — MONGODB_URI not set at module load time
Symptom
Service logs contain:
connect ECONNREFUSED 127.0.0.1:27017
or:
ai-usage-tracker: failed to record usage
LLM calls succeed but usage logs are silently dropped.
Diagnosis
ai-usage-tracker.js sets _mongoUri at module load time:
let _mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
call-llm.js requires ai-usage-tracker at the top of the file (not lazily). If call-llm.js is loaded before the service's start() function runs its ENV_BRIDGE block — or if MONGODB_URI is absent from the config-service — the tracker defaults to localhost, which is unreachable inside a container.
Treatment
In the service's start() function, after the ENV_BRIDGE block, add:
try {
const aiUsageTracker = require('/app/agent-shared/ai-usage-tracker')
if (typeof aiUsageTracker.init === 'function') {
aiUsageTracker.init({
mongoUri: cfg.MONGODB_URI || process.env.MONGODB_URI,
mongoDb: cfg.MONGODB_DB_TELEGRAM || process.env.MONGODB_DB_TELEGRAM || 'telegram',
})
log.info('ai-usage-tracker re-initialised with config MongoDB URI')
}
} catch (trackerErr) {
log.warn('ai-usage-tracker init skipped — module unavailable', { error: trackerErr.message })
}
This calls init(), which invalidates the stale localhost connection and reconnects with the correct URI.
Validation
After deploying the fix, trigger an LLM call and confirm no ECONNREFUSED errors appear. Check ai_usage_logs collection in MongoDB to confirm records are being written.
Services fixed
zil-graph-worker(2026-05-08, migration 076)