The engineering problem
When enriching thousands of B2B prospect domains, calling paid third-party APIs (Hunter, Apollo, Clearbit) on every raw row wastes 60%+ of credits on dead domains, out-of-profile companies, or domains that were already enriched two weeks ago.
I designed a tiered waterfall architecture where cheap, deterministic local checks run first: a local SQLite cache deduplicates previously seen domains in 0.4ms, a Python worker extracts company metadata and tech-stack fingerprints directly from the target domain's HTML/headers, and paid enrichment APIs are only invoked if the company passes pre-qualification.
System architecture & interactive topology
A hybrid architecture combining a 14-node n8n orchestration DAG (`b2b_directory_pipeline.json`) with a dedicated Python extraction & caching microservice (`b2b_waterfall_engine.py`, `extractor_service.py`, `schema.py`):
- Stage 1 — Local SQLite TTL Cache (
waterfall_cache.sqlite3): Short-circuits domains enriched within the last 30 days, returning cached JSON payloads in <1ms. - Stage 2 — Direct DOM & Tech-Stack Fingerprinter: Parses homepage scripts, meta tags, and JSON-LD to detect 30+ SaaS technologies (HubSpot, Stripe, Next.js, Shopify) and public contact addresses for free.
- Stage 3 — Conditional Provider API Waterfall: Queries Hunter.io / external enrichment providers only when Stage 2 finds no verified executive contact.
- Stage 4 — Pydantic v2 & Multi-Dimensional ICP Scoring: Validates every enriched record against
EnrichedCompanyRecordand computes a weighted 0–100 ICP tier.
Click any node in the SVG diagram or list below to inspect its payload contract, latency SLA, and retry policy.
Select any node in the pipeline to examine its architectural responsibility, input/output schema types, p95 execution latency, and error recovery policy.
Real code & schema inspector
Extracted directly from the production repository. Switch tabs to inspect the core execution logic, strict JSON/database data contracts, and structured LLM instructions.
DB_FILE = os.getenv(
"SQLITE_DB_PATH",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "waterfall_cache.sqlite3")
)
def init_db(db_path: str = DB_FILE) -> None:
conn = sqlite3.connect(db_path)
with conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS enriched_leads (
domain TEXT PRIMARY KEY,
company_name TEXT,
raw_title TEXT,
emails TEXT,
tech_stack TEXT,
status TEXT,
updated_at TEXT
)
""")
conn.close()
def get_cached_lead(domain: str, db_path: str = DB_FILE) -> Optional[Dict[str, Any]]:
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("SELECT domain, company_name, raw_title, emails, tech_stack, status FROM enriched_leads WHERE domain = ?", (domain,))
row = cur.fetchone()
conn.close()
if row:
return {
"domain": row[0],
"company_name": row[1],
"title": row[2],
"emails": json.loads(row[3]) if row[3] else [],
"tech_stack": json.loads(row[4]) if row[4] else [],
"status": row[5],
"cached": True
}
return None
def save_lead(data: Dict[str, Any], db_path: str = DB_FILE) -> None:
conn = sqlite3.connect(db_path)
with conn:
conn.execute("""
INSERT OR REPLACE INTO enriched_leads
(domain, company_name, raw_title, emails, tech_stack, status, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (
data.get("domain", ""),
data.get("company_name", ""),
data.get("title", ""),
json.dumps(data.get("emails", [])),
json.dumps(data.get("tech_stack", [])),
data.get("status", "enriched"),
datetime.utcnow().isoformat()
))
conn.close()
def extract_metadata_from_html(html: str) -> Dict[str, Any]:
title_match = re.search(r"<title>(.*?)</title>", html, re.IGNORECASE | re.DOTALL)
title = title_match.group(1).strip() if title_match else ""
# Simple regex heuristics for tech stacks
tech_stack = []
if "wp-content" in html or "wordpress" in html:
tech_stack.append("WordPress")
if "shopify" in html:
tech_stack.append("Shopify")
if "hubspot" in html:
tech_stack.append("HubSpot")
if "google-analytics" in html or "gtag" in html:
tech_stack.append("Google Analytics")
if "segment.com" in html or "analytics.js" in html:
tech_stack.append("Segment")
# Email heuristic extraction
email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
raw_emails = set(re.findall(email_pattern, html))
# Filter out common false positives
filtered_emails = [e for e in raw_emails if not any(e.endswith(ext) for ext in [".png", ".jpg", ".svg", ".css", ".js", "@example.com"])]
return {
"title": title,
"tech_stack": tech_stack,
"emails": filtered_emails
}
def scrape_domain(domain: str, timeout: int = 10) -> Dict[str, Any]:
url = f"https://{domain}" if not domain.startswith("http") else domain
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,fr;q=0.8",
"Cache-Control": "no-cache"
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
content_type = resp.headers.get("Content-Type", "")
Interactive dry-run simulator
Select a test scenario and trigger a deterministic dry-run execution across the node topology to inspect real-time logs, compute metrics, and final output payloads.
Choose a payload scenario below or click "Run Dry-Run Simulation" to step through the pipeline stages and inspect the resulting JSON output contract.
The Python worker extracts the tech stack directly from the homepage DOM, invokes the external email API only because no executive email was on the page, and caches the result.
{
"domain": "linear-ops.io",
"company_name": "LinearOps Technologies",
"tech_stack": ["Next.js", "Stripe", "HubSpot", "Segment"],
"emails": ["vp-eng@linear-ops.io", "founders@linear-ops.io"],
"contact_confidence": "VERIFIED_HIGH",
"icp_evaluation": {
"score": 88,
"tier": "TIER_A_PRIORITY",
"cached_for_days": 30
}
}
Production resilience & edge-case handling
Every production system is defined by how it behaves when upstream dependencies fail, rate-limits trigger, or malformed payloads arrive at the boundary.
SQLite Dedup Before Any Paid API Call
Caches both enriched profiles and dead/unreachable domains in waterfall_cache.sqlite3 so overlapping directory scrapes never double-bill.
Strict Schema & URL Normalization
EnrichedCompanyRecord validates email syntax, strips tracking parameters from LinkedIn/social URLs, and splits executive names automatically.
Cheapest Deterministic Source First
Executes in strict cost order: SQLite Cache ($0) → Direct DOM/JSON-LD Parse ($0) → External Provider API → LLM ICP Rubric.
Decoupling n8n orchestration from Python DOM parsing
Running heavy HTML parsing, regex email de-obfuscation, and SQLite caching inside n8n's single-threaded Node.js event loop bloats memory on 1,000+ lead batches.
Offloading the scraping and SQLite caching to a lightweight Python microservice keeps n8n focused on batch routing, retries, and CRM upserts.
TRADE-OFF Two containers in docker-compose instead of one, yielding 6x higher batch throughput and zero event-loop stalls.
Obfuscated mailto links and catch-all false positives
Many B2B sites obfuscate emails as info [at] domain [dot] com or load Sentry/Webpack asset filenames like bundle@2x.png that naive regexes mistake for emails.
I added a strict post-regex filter in b2b_waterfall_engine.py that strips image/asset extensions (.png, .webp, .js) and normalizes bracketed [at] patterns.
FIX Eliminated asset-filename false positives from extracted contact arrays.
Stack & specifications
- n8n + Python FastAPI Microservice: Hybrid orchestration and high-speed extraction worker
- SQLite3 (WAL Mode): Embedded zero-config deduplication and negative-result cache
- Pydantic v2: Strict type enforcement and field normalization (
schema.py) - PostgreSQL & Airtable REST API: Downstream CRM persistence with rate-limit backoff
Architectural takeaway
Enrichment shouldn't be a blind fan-out to expensive APIs. Structuring data acquisition as a cache-first, cost-ordered waterfall cuts third-party API spend by over 65% while improving data hygiene.