A production-ready Node.js service that routes inbound leads across three Close CRM organizations using atomic round robin distribution with full duplicate detection.
Built for: custom HTML form → existing API → this service → Close CRM
- Atomic round robin — SQLite
BEGIN IMMEDIATEtransactions guarantee no two concurrent requests route to the same org - Parallel duplicate detection — searches all 3 orgs simultaneously (email + phone), returns in ~300ms
- Phone normalization —
555-123-4567,+15551234567, and5551234567all match correctly - Smart update routing — duplicates route back to the org where they already exist, never creating a second record
- Conflict resolution — if a lead somehow exists in multiple orgs, routes to the most recently updated
- Retry queue — failed Close API calls are queued in SQLite with exponential backoff (1min → 5min → 15min)
- Full audit log — every routing decision written to SQLite with timestamp, email, phone, action, org, Close lead ID
- Admin endpoints —
/health,/stats,/logfor monitoring
[Landing Page Form]
│
▼
[Your Existing API] (GitHub-hosted)
│
│ POST /route-lead
│ X-Api-Key: your_router_key
▼
[Lead Router] (this service)
│
├── 1. Normalize email + phone
│
├── 2. Parallel dedup search ──────────────────────────────────────┐
│ Promise.all([searchOrg1, searchOrg2, searchOrg3]) │
│ │
├── 3a. Duplicate found ───────────────────────────────────────── │
│ └── UPDATE existing lead in that org │
│ │
└── 3b. No duplicate ───────────────────────────────────────────── │
└── Atomic counter increment (SQLite BEGIN IMMEDIATE) │
└── CREATE lead in next org (round robin) │
│
◄──────────────────────────────────────────────────────────────────┘
│
├── 4. Write audit log entry to SQLite
│
└── 5. Return { success, action, org, closeLeadId }
npm installcp .env.example .envEdit .env with your Close CRM API keys and a secure router API key:
CLOSE_ORG_1_API_KEY=api_xxxx
CLOSE_ORG_2_API_KEY=api_yyyy
CLOSE_ORG_3_API_KEY=api_zzzz
ROUTER_API_KEY=your_secure_random_key
PORT=3100Get Close API keys: Close CRM → Settings → API Keys → Generate API Key
Generate a secure router key:
openssl rand -hex 32# Development (auto-restart on file changes)
npm run dev
# Production
npm startYour existing form API sends a POST request to this service after receiving a form submission:
// In your existing API (Node.js example)
const axios = require('axios');
async function routeLead(formData) {
const response = await axios.post('http://your-router-host:3100/route-lead', {
name: formData.name,
email: formData.email,
phone: formData.phone,
company: formData.company,
source: 'landing-page-v2',
}, {
headers: {
'X-Api-Key': process.env.ROUTER_API_KEY,
'Content-Type': 'application/json',
},
});
return response.data;
}| Field | Type | Required | Description |
|---|---|---|---|
email |
string | Recommended | Used for dedup. At least email or phone required. |
phone |
string | Recommended | Used for dedup. Auto-normalized. |
name |
string | Optional | Contact name |
company |
string | Optional | Lead/company name in Close |
source |
string | Optional | Traffic source (stored in Close) |
customFields |
object | Optional | Any additional Close CRM fields |
Success — Lead created:
{
"success": true,
"action": "created",
"org": 2,
"closeLeadId": "lead_abc123",
"counterValue": 47
}Success — Duplicate updated:
{
"success": true,
"action": "updated",
"org": 1,
"closeLeadId": "lead_xyz789",
"counterValue": null
}Queued (Close API temporarily unavailable):
{
"success": false,
"queued": true,
"message": "Lead routing failed but has been queued for retry.",
"error": "connect ECONNREFUSED"
}All endpoints require X-Api-Key header except /health.
{
"status": "ok",
"uptime_seconds": 3600,
"db": "ok",
"timestamp": "2026-04-07T01:00:00.000Z"
}{
"round_robin": {
"total_counter": 47,
"leads_created_per_org": {
"org_1": 16,
"org_2": 16,
"org_3": 15
}
},
"retry_queue": {
"pending": 0,
"permanently_failed": 0
},
"recent_decisions": [...]
}Returns paginated routing decisions with full audit trail.
# Clone the repo
git clone https://github.com/ItsThierry/lead-router.git
cd lead-router
# Install dependencies
npm install --production
# Configure
cp .env.example .env
nano .env # add your API keys
# Start with PM2 (keeps it running after server restart)
npm install -g pm2
pm2 start src/app.js --name lead-router
pm2 save
pm2 startupcurl http://localhost:3100/healthSQLite database is stored at data/lead_router.db. Three tables:
round_robin— single row, atomic counterrouting_log— full audit trail of every routing decisionretry_queue— failed requests pending retry
The data/ directory is gitignored. Back it up periodically if you need the audit log.
MIT