Skip to content

About

Round robin lead routing across multiple Close CRM organizations with duplicate detection and retry queue

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Lead Router — Close CRM Round Robin + Dedup

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


Features

  • Atomic round robin — SQLite BEGIN IMMEDIATE transactions 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, and 5551234567 all 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, /log for monitoring

Architecture

[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 }

Setup

1. Install dependencies

npm install

2. Configure environment

cp .env.example .env

Edit .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=3100

Get Close API keys: Close CRM → Settings → API Keys → Generate API Key

Generate a secure router key:

openssl rand -hex 32

3. Start the server

# Development (auto-restart on file changes)
npm run dev

# Production
npm start

Integration

Your 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;
}

Request body

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

Response

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"
}

Admin Endpoints

All endpoints require X-Api-Key header except /health.

GET /health

{
  "status": "ok",
  "uptime_seconds": 3600,
  "db": "ok",
  "timestamp": "2026-04-07T01:00:00.000Z"
}

GET /stats

{
  "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": [...]
}

GET /log?limit=50&offset=0

Returns paginated routing decisions with full audit trail.


Deployment

On your existing server

# 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 startup

Verify it's running

curl http://localhost:3100/health

Database

SQLite database is stored at data/lead_router.db. Three tables:

  • round_robin — single row, atomic counter
  • routing_log — full audit trail of every routing decision
  • retry_queue — failed requests pending retry

The data/ directory is gitignored. Back it up periodically if you need the audit log.


License

MIT

About

Round robin lead routing across multiple Close CRM organizations with duplicate detection and retry queue

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages