Real-Time Email Verification: Developer's Guide
Real-time email verification patterns for signup, checkout, and lead capture. Code-heavy tutorial in Node.js, Python, and PHP with caching and circuit breakers.
Real-time email verification means checking an address while the user is still on your form, then deciding in code what to do with valid, invalid, unknown, or no answer at all. The API call itself is simple: one POST, one JSON response, 0.25 credits for a definitive result and nothing for unknown. The hard part is the integration: where in the request lifecycle do you call it, how long do you wait, what do you do when it is slow or down, and how do you avoid paying to re-verify the same address every time a user clicks submit twice.
This guide is a code-heavy developer tutorial. It covers the three architecture patterns for real-time verification (synchronous blocking, asynchronous, and hybrid), and ships working code in Node.js, Python, and PHP for each one. It covers caching, fail-open versus fail-closed fallbacks, rate-limit handling with backoff and circuit breakers, and the connection patterns that keep inline verification fast on a signup form.
For the underlying API contract (request shape, response fields, catch-all resolution, and credit economics), read our Email Verification API guide. For the product behavior behind the response, see Email Validation. For the canonical /docs/* reference, see the API reference. This guide assumes you already know what email_status: valid | invalid | unknown means and focuses on the engineering decisions around it.
The deliverability resource hub connects this integration to list hygiene and sender reputation, while the SMTP verification mechanics guide explains the network work behind the real-time verdict.
Architecture Patterns for Real-Time Verification
Every real-time verification integration falls into one of three architectural patterns. The pattern is not a preference; it is a function of where the verification call sits in the request lifecycle, how much latency the user flow can absorb, and what the cost of a wrong address is.
Synchronous Blocking
The form does not submit until the verification API returns. The user clicks submit, the request holds, the backend calls the verification API, reads the verdict, and either proceeds or rejects. This is the safest pattern because no bad address ever reaches the database. It is also the most latency-sensitive: the user is staring at a spinner, and every millisecond of verification latency is a millisecond of perceived slowness.
Synchronous blocking is correct for paid signups, checkout flows, contract signing, and any flow where a bad email has a downstream cost (failed payment receipt, lost receipt, broken account recovery). The latency budget is tight, which is why a hard client-side timeout with a deliberate fail-open or fail-closed fallback matters so much.
Asynchronous
The form submits immediately. The backend writes the user record with an email_verification: pending flag, enqueues a verification job, and returns a success response to the user. A worker picks up the job, calls the verification API, and updates the record. The user sees the result later: in a confirmation email that only sends if the address is valid, in a UI badge that flips from "pending" to "verified," or in a follow-up nudge if the address came back invalid.
Asynchronous is correct for free lead-capture forms, newsletter signups, content downloads, and any flow where the user's goal does not depend on the verification result arriving within the same request. The latency budget is loose (the worker can take seconds or minutes), which means you can retry aggressively, queue overflow gracefully, and never block the user on a slow or downed verification API.
Hybrid
Syntax and MX checks run synchronously in the request; the SMTP handshake runs asynchronously in the background. The synchronous slice is cheap and fast: a syntax check plus a DNS MX lookup usually returns quickly and catches obviously bad inputs (malformed addresses, domains with no mail server). The asynchronous slice handles the SMTP round-trip, which is slower and less predictable, especially on greylisting or catch-all servers.
Hybrid is correct when you want immediate rejection of garbage inputs without paying the SMTP latency cost on every request. The user gets instant feedback on syntax errors and dead domains, and the full deliverability verdict arrives in the background. The tradeoff is complexity: you maintain two code paths and a state machine for "syntax-checked, smtp-pending, smtp-valid, smtp-invalid."
The table below summarizes when to reach for each:
| Pattern | Latency budget | User blocked? | Cost of bad email | Typical flow |
|---|---|---|---|---|
| Synchronous | Hard timeout, set from your p95 | Yes | High (paid, contracts) | Checkout, paid signup |
| Asynchronous | Seconds-minutes | No | Low (free, lead gen) | Newsletter, content download |
| Hybrid | Fast sync slice, async SMTP | Partially | Medium | High-volume free signup |
Synchronous Blocking: Signup Form with a Hard Timeout
This is the highest-stakes integration. The verification call runs inline in the signup request, with a hard timeout and a fail-open fallback. The examples use 2.5 seconds; measure the API's latency from your own servers and tune it. If the API responds in time, we branch on the verdict. If it times out, we log the timeout, let the signup through, and trigger a background re-verification, because the cost of blocking a real user who typed their email correctly is higher than the cost of admitting an address we will re-check in five minutes.
Node.js: Express Signup Handler
import express from "express";
const app = express();
app.use(express.json());
const API_KEY = process.env.LEADMAGIC_API_KEY; // never hardcode
const BASE_URL = "https://api.leadmagic.io/v1";
const VERIFY_TIMEOUT_MS = 2500; // tune from your measured p95
// Use a single keep-alive agent across the process , see Connection Pooling section.
import https from "node:https";
const agent = new https.Agent({ keepAlive: true, maxSockets: 50 });
globalThis.fetch ??= (await import("undici")).fetch;
async function verifyInline(email) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);
try {
const res = await fetch(`${BASE_URL}/people/email-validation`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },
body: JSON.stringify({ email }),
signal: controller.signal,
dispatcher: undefined, // use global agent for keep-alive
});
clearTimeout(timer);
if (res.status === 429) {
return { status: "rate_limited", retry_after: res.headers.get("Retry-After") };
}
if (!res.ok) return { status: "error", code: res.status };
const data = await res.json();
return { status: "ok", email_status: data.email_status };
} catch (err) {
clearTimeout(timer);
if (err.name === "AbortError") return { status: "timeout" };
return { status: "error", code: "network" };
}
}
app.post("/api/signup", async (req, res) => {
const { email, name } = req.body;
const result = await verifyInline(email);
if (result.status === "timeout") {
console.warn(`[verify] timeout for ${email} , failing open, enqueuing bg recheck`);
// Fail open: let the signup through, schedule a background re-verification.
await createUser(email, name, { email_verification: "pending_bg_recheck" });
enqueueBackgroundVerification(email);
return res.status(201).json({ ok: true, notice: "verification_pending" });
}
if (result.status === "rate_limited") {
console.warn(`[verify] rate limited , failing open`);
await createUser(email, name, { email_verification: "pending_bg_recheck" });
enqueueBackgroundVerification(email, result.retry_after);
return res.status(201).json({ ok: true, notice: "verification_pending" });
}
if (result.status === "ok") {
if (result.email_status === "invalid") {
return res.status(400).json({ error: "Please enter a valid email address." });
}
if (result.email_status === "unknown") {
// Accept but mark for recheck: unknown isn't billed (0 credits) and may resolve later.
await createUser(email, name, { email_verification: "unknown_recheck" });
return res.status(201).json({ ok: true, notice: "verification_unknown" });
}
// valid
await createUser(email, name, { email_verification: "valid" });
return res.status(201).json({ ok: true });
}
// result.status === "error" , fail open on backend errors too, log loudly.
console.error(`[verify] error for ${email}:`, result);
await createUser(email, name, { email_verification: "pending_bg_recheck" });
enqueueBackgroundVerification(email);
return res.status(201).json({ ok: true, notice: "verification_pending" });
});
app.listen(3000);The two design choices to notice are the AbortController with a hard cutoff and the fail-open branch. A request that hits the timeout is aborted; it does not linger and consume a connection. The fail-open path writes a pending_bg_recheck flag so the background worker can resolve the unknown state later, and it enqueues a retry with the Retry-After value when the trigger was a rate limit.
Sample Response
This is the documented response shape from the API reference, trimmed (the full response also includes company fields derived from the domain):
{
"email": "alex.rivera@example.com",
"email_status": "valid",
"credits_consumed": 0.25,
"message": "Email is valid.",
"mx_record": "aspmx.l.google.com",
"mx_provider": "Google Workspace",
"mx_gateway": null,
"mx_security_gateway": false
}The field your signup handler branches on is email_status: valid, invalid, or unknown. Disposable domains, bad syntax, and domains with no MX records already come back as invalid, so you don't need a separate disposable check. If you want to treat role addresses (info@, sales@) differently, apply your own local-part rules on top; the role-based detection strategy covers the routing logic.
curl: Testing the Endpoint
curl -X POST https://api.leadmagic.io/v1/people/email-validation \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_API_KEY" \
-d '{
"email": "alex.rivera@example.com"
}'Swap YOUR_API_KEY for your actual key from the LeadMagic dashboard. Never commit the real key to source: load it from an environment variable or a secrets manager.
Fail-Open vs Fail-Closed: Choosing the Right Fallback
Every synchronous verification integration has to answer one question: when the API does not return a verdict in time, what does the user flow do? The two answers are fail-open and fail-closed, and the choice is governed by the cost of a bad email versus the cost of a blocked good user.
Fail-open returns true (or lets the flow through), logs the timeout, and schedules a background re-verification. It is correct when the cost of blocking a good user is high: free signups, newsletter forms, content downloads, low-stakes lead capture. A bad email that slips through fail-open costs you a bounced confirmation email and a CRM record to clean up later; a blocked good user costs you a conversion you never get back.
Fail-closed returns false (or rejects the flow), shows the user a "please try again" message, and does not schedule a silent retry; the user is the retry. It is correct when the cost of a bad email is high: paid checkout, contract signing, regulated industries, account recovery. A bad email that slips through fail-closed can break payment receipts, lock a user out of their account, or create a compliance record attached to a non-deliverable address.
The decision is not global; it is per-flow. A single product can fail-open on the free newsletter signup and fail-closed on the paid checkout within the same codebase. The rule of thumb: if removing the email breaks the product for that user, fail-closed; if the email is a nice-to-have contact channel, fail-open.
Fail-Open Code Pattern
function failOpen(result, email) {
// Return true on timeout + log; let the flow through.
if (result.status === "timeout" || result.status === "error" || result.status === "rate_limited") {
console.warn(`[verify:fail-open] ${result.status} for ${email}`);
metrics.increment("verify.fail_open", { reason: result.status });
enqueueBackgroundVerification(email, result.retry_after);
return { allowed: true, verification: "pending_bg_recheck" };
}
return { allowed: result.email_status !== "invalid", verification: result.email_status };
}Fail-Closed Code Pattern
function failClosed(result, email) {
// Return false on timeout + ask the user to try again.
if (result.status === "timeout" || result.status === "error" || result.status === "rate_limited") {
console.error(`[verify:fail-closed] ${result.status} for ${email}`);
metrics.increment("verify.fail_closed", { reason: result.status });
return {
allowed: false,
error: "We could not verify your email right now. Please try again in a moment.",
};
}
if (result.email_status === "invalid") {
return { allowed: false, error: "Please enter a valid email address." };
}
if (result.email_status === "unknown") {
return { allowed: false, error: "We could not confirm that address. Please try a different email." };
}
return { allowed: true, verification: "valid" };
}The structural difference is what the timeout branch returns and whether it enqueues a background retry. Fail-open lets the user through and fixes the data later. Fail-closed blocks the user and makes them the retry mechanism. Both log the timeout and increment a metric: silent swallows are the integration bug you discover three months later in a bounce report.
Checkout-Flow Blocking Verification (Fail-Closed)
Checkout is the canonical fail-closed flow. A bad email at checkout means a lost receipt, a broken payment-dispute trail, and a customer who cannot recover their account if they forget their password. The latency budget is still tight (the user is mid-purchase and any friction risks cart abandonment), but the verification call runs inline with a hard timeout and a fail-closed fallback.
Python: FastAPI Checkout Handler
import os
import asyncio
import aiohttp
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
API_KEY = os.environ["LEADMAGIC_API_KEY"]
BASE_URL = "https://api.leadmagic.io/v1"
VERIFY_TIMEOUT_S = 2.5 # hard cutoff; tune from your measured p95
# One shared session per process for connection pooling (see Connection Pooling).
_session: aiohttp.ClientSession | None = None
async def get_session() -> aiohttp.ClientSession:
global _session
if _session is None or _session.closed:
timeout = aiohttp.ClientTimeout(total=10, connect=1)
connector = aiohttp.TCPConnector(limit=50, keepalive_timeout=30)
_session = aiohttp.ClientSession(timeout=timeout, connector=connector)
return _session
async def verify_blocking(email: str) -> dict:
session = await get_session()
try:
async with session.post(
f"{BASE_URL}/people/email-validation",
json={"email": email},
headers={"Content-Type": "application/json", "X-API-Key": API_KEY},
timeout=aiohttp.ClientTimeout(total=VERIFY_TIMEOUT_S),
) as resp:
if resp.status == 429:
return {"status": "rate_limited", "retry_after": resp.headers.get("Retry-After")}
if resp.status == 401:
return {"status": "auth_error"}
if resp.status >= 500:
return {"status": "server_error"}
data = await resp.json()
return {"status": "ok", "email_status": data.get("email_status")}
except asyncio.TimeoutError:
return {"status": "timeout"}
except aiohttp.ClientError:
return {"status": "network_error"}
class CheckoutRequest(BaseModel):
email: str
payment_token: str
plan: str
@app.post("/api/checkout")
async def checkout(req: CheckoutRequest):
result = await verify_blocking(req.email)
if result["status"] != "ok":
# Fail-closed at checkout: never let a bad or unverified email through.
raise HTTPException(
status_code=422,
detail={
"error": "email_verification_failed",
"message": "We could not verify your email address. Please try again or use a different email.",
"reason": result["status"],
},
)
status = result["email_status"]
if status == "invalid":
raise HTTPException(status_code=400, detail={"error": "invalid_email"})
if status == "unknown":
raise HTTPException(
status_code=422,
detail={"error": "unknown_email", "message": "We could not confirm that address. Please use a different email."},
)
# Proceed with payment capture: the email is verified valid (disposables return invalid).
charge = await capture_payment(req.payment_token, req.plan)
await create_account(req.email, charge)
return {"ok": True, "account_id": charge.account_id}The checkout handler rejects on invalid (which includes disposable domains), unknown, and any non-ok status. It does not enqueue a background retry; the user is asked to try again, because the purchase should not complete against an unverified email. The ClientTimeout is the hard ceiling; anything that exceeds it is treated as a timeout and fail-closed.
Asynchronous Verification: Lead-Capture with Background Jobs
Lead-capture forms are the opposite of checkout. The user wants a content download or a newsletter signup, the conversion cost of blocking them is high, and the email is a contact channel rather than a transactional requirement. The correct pattern is to accept the form immediately and verify in the background.
Python: Lead Capture with Background Worker
import os
import asyncio
import aiohttp
from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel
app = FastAPI()
API_KEY = os.environ["LEADMAGIC_API_KEY"]
BASE_URL = "https://api.leadmagic.io/v1"
async def verify_async(email: str) -> dict:
"""Background verification , no hard timeout, retries on 429."""
async with aiohttp.ClientSession() as session:
for attempt in range(3):
try:
async with session.post(
f"{BASE_URL}/people/email-validation",
json={"email": email},
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
timeout=aiohttp.ClientTimeout(total=10),
) as resp:
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", 2 ** attempt))
await asyncio.sleep(retry_after)
continue
data = await resp.json()
return {"email": email, "email_status": data.get("email_status")}
except (asyncio.TimeoutError, aiohttp.ClientError):
await asyncio.sleep(2 ** attempt)
return {"email": email, "email_status": "unknown", "error": "max_retries"}
class LeadCapture(BaseModel):
email: str
name: str
source: str
@app.post("/api/lead")
async def capture_lead(req: LeadCapture, background: BackgroundTasks):
# Accept immediately, mark pending, verify in the background.
lead = await create_lead(req.email, req.name, req.source, status="email_pending")
background.add_task(verify_and_update, lead.id, req.email)
return {"ok": True, "lead_id": lead.id, "status": "email_pending"}
async def verify_and_update(lead_id: str, email: str):
result = await verify_async(email)
if result["email_status"] == "valid":
await update_lead(lead_id, status="email_valid")
await send_confirmation_email(email)
elif result["email_status"] == "invalid":
await update_lead(lead_id, status="email_invalid")
await notify_revops_for_manual_review(lead_id)
else:
await update_lead(lead_id, status="email_unknown")
await schedule_recheck(lead_id, email, delay_minutes=30)The lead-capture endpoint returns in milliseconds because the verification runs in a BackgroundTasks job after the response is sent. The worker retries on 429, branches on the verdict, and schedules a 30-minute recheck for unknown results, because unknown results aren't billed (0 credits) and often resolve when a temporarily unreachable mail server comes back online.
Hybrid Pattern: Syntax Sync, SMTP Async (PHP)
The hybrid pattern runs the cheap checks synchronously and defers the expensive SMTP handshake to a background job. PHP implementations often live in a WordPress or Laravel context where the request thread is precious and background workers need an external queue (Horizon, a cron worker, or a Redis-backed job).
PHP: Laravel Signup with Hybrid Verification
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
class EmailVerificationService
{
private string $apiKey;
private string $baseUrl = 'https://api.leadmagic.io/v1';
public function __construct()
{
// Load from env , never hardcode the API key.
$this->apiKey = env('LEADMAGIC_API_KEY', 'YOUR_API_KEY');
}
/**
* Synchronous phase: syntax + MX check only. Fast, rejects obvious garbage.
* Returns 'invalid' for malformed or no-MX, 'check_smtp' otherwise.
*/
public function quickCheck(string $email): array
{
// Syntax validation , RFC 5322 simplified.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return ['status' => 'invalid', 'reason' => 'syntax'];
}
$domain = substr(strrchr($email, '@'), 1);
$mx = dns_get_record($domain, DNS_MX);
if (empty($mx)) {
return ['status' => 'invalid', 'reason' => 'no_mx'];
}
return ['status' => 'check_smtp', 'mx' => $mx[0]['target'] ?? null];
}
/**
* Asynchronous phase: full SMTP verification via the API, run in a queued job.
*/
public function enqueueSmtpVerification(string $email, int $userId): void
{
Queue::push(new VerifyEmailJob($email, $userId));
}
/**
* The actual API call , invoked by the queued job, not inline.
*/
public function fullVerify(string $email): array
{
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'X-API-Key' => $this->apiKey,
])->post("{$this->baseUrl}/people/email-validation", [
'email' => $email,
]);
if ($response->status() === 429) {
$retryAfter = (int) $response->header('Retry-After', 5);
return ['status' => 'rate_limited', 'retry_after' => $retryAfter];
}
if ($response->status() === 401) {
Log::error('LeadMagic API auth failed , check LEADMAGIC_API_KEY');
return ['status' => 'auth_error'];
}
if (!$response->successful()) {
return ['status' => 'error', 'code' => $response->status()];
}
$data = $response->json();
return [
'status' => 'ok',
'email_status' => $data['email_status'] ?? 'unknown',
'credits_consumed' => $data['credits_consumed'] ?? 0,
];
}
}The signup controller calls quickCheck synchronously, rejects on invalid, and otherwise creates the user with an email_smtp_pending flag and calls enqueueSmtpVerification. The queued VerifyEmailJob calls fullVerify and updates the user record. The user experiences instant feedback on syntax and dead domains, and the full deliverability verdict arrives within seconds via the queue worker.
Caching Verification Results: Redis/Upstash Strategy
Caching is where most integrations waste credits. The naive approach (call the API every time the user submits), re-verifies the same address on every form retry, every double-click, and every return visit. A better approach caches the verdict with a TTL keyed to the result type. The TTLs below are starting points; tune them to how quickly your audience's mailboxes change.
The cache key is a hash of the normalized email address (lowercased, trimmed, Unicode-normalized). The TTL depends on the verdict:
| Verdict | TTL | Rationale |
|---|---|---|
valid | 24 hours | Email deliverability is stable on a daily horizon; re-verifying within 24h is unlikely to change. |
invalid | 7 days | An invalid address rarely becomes valid; long TTL saves credits on repeat submissions of the same bad address. |
unknown | Never cache | Unknown is inconclusive: caching it would mask a transient server issue. Always re-verify. |
The one invalidation trigger that overrides the TTL is a domain MX change. When a domain switches mail providers (e.g., from on-prem to Google Workspace), a previously valid address can flip to invalid overnight. A lightweight MX-change watcher (or invalidation on the next unknown result for that domain) keeps the cache from going stale.
Cache Key and Invalidation
import { createHash } from "node:crypto";
function cacheKey(email) {
const normalized = email.trim().toLowerCase().normalize("NFC");
return `verify:${createHash("sha256").update(normalized).digest("hex")}`;
}
const TTL_BY_VERDICT = {
valid: 60 * 60 * 24, // 24h
invalid: 60 * 60 * 24 * 7, // 7d
// unknown is intentionally absent , never cache it.
};
async function cacheGet(redis, email) {
const key = cacheKey(email);
const raw = await redis.get(key);
if (!raw) return null;
const entry = JSON.parse(raw);
return entry;
}
async function cacheSet(redis, email, verdict) {
if (verdict.email_status === "unknown") return; // never cache unknown
const ttl = TTL_BY_VERDICT[verdict.email_status];
if (!ttl) return;
const key = cacheKey(email);
await redis.set(key, JSON.stringify(verdict), "EX", ttl);
}
async function invalidateDomain(redis, domain) {
// On a domain MX change, invalidate all cached entries for that domain.
// Requires a domain-prefixed index , see the Lead-Capture form below.
const keys = await redis.smembers(`domain:${domain}`);
if (keys.length) await redis.del(...keys);
}Lead-Capture Form with Caching (Python + Redis/Upstash)
This combines the asynchronous pattern with caching. Before calling the API, the handler checks the cache; on a hit, it skips the API call entirely and returns the cached verdict. On a miss, it calls the API, caches the result per the TTL table, and returns. The "never cache unknown" rule is enforced by refusing to write unknown entries to Redis.
import os
import json
import hashlib
import asyncio
import aiohttp
from redis.asyncio import Redis
API_KEY = os.environ["LEADMAGIC_API_KEY"]
BASE_URL = "https://api.leadmagic.io/v1"
redis = Redis.from_url(os.environ["UPSTASH_REDIS_REST_URL"] or os.environ["REDIS_URL"])
TTL_BY_VERDICT = {
"valid": 60 * 60 * 24, # 24h
"invalid": 60 * 60 * 24 * 7, # 7d
# "unknown" intentionally absent , never cache.
}
def cache_key(email: str) -> str:
normalized = email.strip().lower()
digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()
domain = normalized.split("@")[-1]
return {"key": f"verify:{digest}", "domain": domain}
async def verify_with_cache(email: str) -> dict:
info = cache_key(email)
cached = await redis.get(info["key"])
if cached:
return json.loads(cached) # cache hit , no API call
# Cache miss , call the API.
async with aiohttp.ClientSession() as session:
for attempt in range(3):
try:
async with session.post(
f"{BASE_URL}/people/email-validation",
json={"email": email},
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
timeout=aiohttp.ClientTimeout(total=2),
) as resp:
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", 2 ** attempt))
await asyncio.sleep(retry_after)
continue
data = await resp.json()
verdict = {
"email": email,
"email_status": data.get("email_status", "unknown"),
}
# Cache only if the verdict is not unknown.
if verdict["email_status"] in TTL_BY_VERDICT:
ttl = TTL_BY_VERDICT[verdict["email_status"]]
pipe = redis.pipeline()
pipe.set(info["key"], json.dumps(verdict), ex=ttl)
pipe.sadd(f"domain:{info['domain']}", info["key"])
await pipe.execute()
return verdict
except (asyncio.TimeoutError, aiohttp.ClientError):
await asyncio.sleep(2 ** attempt)
return {"email": email, "email_status": "unknown", "error": "max_retries"}The pipeline writes the cache entry and adds the cache key to a per-domain set in one round-trip. The per-domain set is what invalidateDomain uses to bulk-invalidate on an MX change; it reads the set members and deletes the keys in one call. On a high-traffic lead form, returning users, form retries, and duplicate submissions all hit the cache instead of the API, so you stop paying twice for the same address.
Batch Verification Endpoint: CSV Upload with Webhook Callback
For list-cleaning workflows, such as importing a CSV of ten thousand addresses before loading them into a sequencer, inline calls are the wrong shape. The simplest option is LeadMagic's own Bulk Jobs API or CSV upload. If you'd rather wrap the sync endpoint in your own service, the pattern is a batch endpoint that accepts a CSV upload, processes it asynchronously, and POSTs results to a webhook callback URL as they complete. This keeps the upload request fast and lets the client disconnect while processing runs.
Node.js: Batch Endpoint with Webhook
import express from "express";
import multer from "multer";
import csv from "csv-parse";
import { createHmac } from "node:crypto";
const app = express();
const upload = multer({ storage: multer.memoryStorage() });
const API_KEY = process.env.LEADMAGIC_API_KEY;
const WEBHOOK_SECRET = process.env.BATCH_WEBHOOK_SECRET;
const BASE_URL = "https://api.leadmagic.io/v1";
const MAX_CONCURRENT = 8; // use a shared RPM limiter as well as this concurrency cap
app.post("/api/verify-batch", upload.single("file"), async (req, res) => {
const callbackUrl = req.body.callback_url;
if (!callbackUrl) return res.status(400).json({ error: "callback_url required" });
const rows = [];
const parser = csv.parse({ columns: true });
parser.on("data", (row) => rows.push(row.email));
parser.write(req.file.buffer);
parser.end();
res.status(202).json({ accepted: rows.length, callback_url: callbackUrl });
// Process in the background after the response is sent.
setImmediate(() => processBatch(rows, callbackUrl));
});
async function processBatch(emails, callbackUrl) {
const semaphore = new Semaphore(MAX_CONCURRENT);
const results = [];
await Promise.all(emails.map(async (email) => {
await semaphore.acquire();
try {
const result = await verifyOne(email);
results.push(result);
await postWebhook(callbackUrl, result); // stream results as they complete
} finally {
semaphore.release();
}
}));
await postWebhook(callbackUrl, { batch_complete: true, total: results.length });
}
async function verifyOne(email) {
for (let attempt = 0; attempt < 3; attempt++) {
try {
const res = await fetch(`${BASE_URL}/people/email-validation`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },
body: JSON.stringify({ email }),
});
if (res.status === 429) {
const retryAfter = parseInt(res.headers.get("Retry-After") || 2 ** attempt);
await new Promise((r) => setTimeout(r, retryAfter * 1000));
continue;
}
const data = await res.json();
return {
email,
email_status: data.email_status,
credits_consumed: data.credits_consumed,
};
} catch (err) {
if (attempt === 2) return { email, email_status: "error", error: err.message };
}
}
return { email, email_status: "unknown" };
}
async function postWebhook(url, payload) {
const body = JSON.stringify(payload);
const signature = createHmac("sha256", WEBHOOK_SECRET).update(body).digest("hex");
await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Batch-Signature": signature },
body,
});
}
class Semaphore {
constructor(max) { this.max = max; this.cur = 0; this.waiters = []; }
acquire() {
if (this.cur < this.max) { this.cur++; return Promise.resolve(); }
return new Promise((r) => this.waiters.push(r));
}
release() {
this.cur--;
if (this.waiters.length) { this.cur++; this.waiters.shift()(); }
}
}
app.listen(3000);The endpoint returns 202 Accepted immediately with the count and the callback URL, then processes in the background via setImmediate. Each result is POSTed to the webhook as it completes, so the client can stream progress to a UI rather than waiting for the entire batch. The webhook payload is signed with HMAC-SHA256 using a shared secret so the receiver can verify authenticity. LeadMagic's own batch webhooks use the same approach with an X-LeadMagic-Signature header.
Rate-Limit Handling: Exponential Backoff, Queue Overflow, Circuit Breaker
Every integration that calls the verification API at scale eventually hits a 429 Too Many Requests response. A dependable setup has three layers: exponential backoff with jitter on individual 429 responses, a queue overflow strategy when the inbound rate exceeds processing capacity, and a circuit breaker that protects the upstream and your own service when the verification API is degraded.
Exponential Backoff with Jitter
import random
import asyncio
async def backoff_delay(attempt: int, base: float = 1.0, cap: float = 60.0) -> float:
"""Exponential backoff with full jitter , prevents thundering herd."""
delay = min(base * (2 ** attempt), cap)
jitter = random.uniform(0, delay)
return jitter
async def call_with_backoff(fn, *args, max_retries=5):
for attempt in range(max_retries):
try:
result = await fn(*args)
if result.get("status") == "rate_limited":
retry_after = result.get("retry_after", await backoff_delay(attempt))
await asyncio.sleep(retry_after)
continue
return result
except Exception:
if attempt == max_retries - 1:
raise
await asyncio.sleep(await backoff_delay(attempt))
return {"status": "max_retries_exceeded"}Full jitter (a random duration between zero and the exponential ceiling) spreads retries across the full window, reducing the chance that a large batch of concurrent workers all retry at the same instant. The Retry-After header from the 429 response takes precedence over the computed backoff when present, because the server is telling you the exact wait (Retry-After). AWS's write-up on exponential backoff and jitter compares the variants.
Queue Overflow
When the inbound form-submission rate exceeds the verification API's throughput, the processing queue grows unboundedly. The strategy is to cap the queue depth and spill overflow to a durable store (Redis Streams, SQS, a database table) where a separate worker drains it at a controlled rate. Inbound requests that would overflow the in-memory queue are accepted with a pending flag and processed from the durable store; the user is never rejected because the queue is full.
import { Queue, Worker } from "bullmq";
import IORedis from "ioredis";
const connection = new IORedis(process.env.REDIS_URL);
const verifyQueue = new Queue("verify", { connection, defaultJobOptions: {
attempts: 3, backoff: { type: "exponential", delay: 2000 },
}});
app.post("/api/lead", async (req, res) => {
// Spill to the durable queue , never reject because the in-memory buffer is full.
await verifyQueue.add("verify", { email: req.body.email }, { removeOnComplete: true });
return res.status(202).json({ ok: true, status: "queued" });
});
new Worker("verify", async (job) => {
const result = await verifyWithCache(job.data.email);
await updateLead(job.data.email, result);
}, { connection, concurrency: 10 });The worker's concurrency: 10 caps in-flight calls regardless of how fast the queue fills. Pair it with BullMQ's rate limiter if you need a hard ceiling under the plan’s rolling 60-second allowance (Basic/Essential 300 RPM, Growth 600, Professional 1,000 and Ultimate 1,500, separately for Finder and Validation across the organization). BullMQ's built-in exponential backoff on failed jobs handles the retry layer.
Circuit Breaker
A circuit breaker wraps the verification call and tracks failures. When failures exceed a threshold within a window, the breaker opens and short-circuits all calls to a fallback for a cool-down period (say 30 seconds), without touching the API. After cool-down it enters half-open, letting one test request through; if it succeeds, the breaker closes and traffic resumes. This prevents a slow or downed verification API from cascading into a full outage of your signup and checkout flows.
class CircuitBreaker {
constructor({ threshold = 5, windowMs = 10000, coolDownMs = 30000, fallback }) {
this.threshold = threshold;
this.windowMs = windowMs;
this.coolDownMs = coolDownMs;
this.fallback = fallback;
this.state = "closed"; // closed | open | half-open
this.failures = [];
this.openedAt = 0;
}
async execute(fn, ...args) {
if (this.state === "open") {
if (Date.now() - this.openedAt > this.coolDownMs) {
this.state = "half-open";
} else {
return this.fallback(...args); // short-circuit to fail-open or fail-closed
}
}
try {
const result = await fn(...args);
if (this.state === "half-open") {
this.state = "closed";
this.failures = [];
}
return result;
} catch (err) {
this.recordFailure();
if (this.failures.length >= this.threshold) {
this.state = "open";
this.openedAt = Date.now();
}
if (this.state === "half-open") {
this.state = "open";
this.openedAt = Date.now();
}
throw err;
}
}
recordFailure() {
const now = Date.now();
this.failures = this.failures.filter((t) => now - t < this.windowMs);
this.failures.push(now);
}
}
const breaker = new CircuitBreaker({
threshold: 5,
windowMs: 10000,
coolDownMs: 30000,
fallback: (email) => ({ status: "timeout", email }), // fail-open for signup
});
// Usage wraps the verify call:
const result = await breaker.execute(verifyInline, email);The fallback is the same fail-open / fail-closed decision from earlier: the circuit breaker just automates the "stop calling the API for a while" decision so a degraded upstream does not consume your request budget. The threshold and cool-down are tunable: a tighter threshold (3 failures in 5s) opens faster but is more prone to false positives; a longer cool-down (60s) protects the upstream more aggressively but extends the window where your users see fallback behavior.
Low-Latency Integration: Connection Pooling, Keep-Alive, Regional Deployment
The API's own response time is the verification service's job. End-to-end latency, from your handler receiving the request to having the verdict in hand, is also a property of your code. Three patterns keep it down.
Connection Pooling and Keep-Alive
Every new TLS connection to api.leadmagic.io adds handshake round trips before the request is sent. A naive fetch() that opens a fresh connection per call pays that cost on every verification. A pooled client reuses the TCP connection across calls, amortizing the handshake to zero after the first request. In Node.js, this is the https.Agent({ keepAlive: true }) pattern shown in the signup handler; in Python, it is a shared aiohttp.ClientSession with a TCPConnector; in PHP, it is a persistent Guzzle client or curl multi-handle. Set maxSockets high enough to cover your concurrency but low enough to avoid exhausting file descriptors: 50 is a reasonable default for a single process.
Regional Deployment
Network latency between your server and the verification API adds linearly to the end-to-end time. A server on one continent calling an API on another pays a transatlantic or transpacific round trip on every call. Deploy your verification proxy in the same region as your application servers, and prefer a verification provider with multi-region edge presence. The capability is regional proximity: measure the round trip from your production region and co-locate if it's a large share of your budget.
HTTP/2 and Header Compression
HTTP/2 multiplexes multiple requests over a single connection and compresses headers, reducing both the per-request overhead and the bytes on the wire. Most modern HTTP clients negotiate HTTP/2 automatically when the server supports it. The benefit on a single verification call is small (a few ms), but at high concurrency it compounds: a pool of 50 concurrent HTTP/2 connections carries more throughput than 50 HTTP/1.1 connections at the same latency.
None of these is a guarantee. Your end-to-end budget depends on your application server, your network path, and the verification service. Measure the end-to-end latency in production with percentiles, and alert when the p99 drifts above the budget; that is the signal that a pool is exhausted, a region is misconfigured, or the upstream is degrading.
Decision Framework
The decisions in this guide collapse to a small set of forks. Use this table as the integration checklist:
| Decision | Options | Default |
|---|---|---|
| Architecture pattern | Sync / Async / Hybrid | Sync for paid, async for free, hybrid for high-volume free |
| Fallback on timeout | Fail-open / Fail-closed | Fail-open on free, fail-closed on paid |
| Cache TTL | valid 24h, invalid 7d, unknown never | As listed |
| Cache invalidation | TTL / domain MX change | TTL + MX-change watcher |
| Rate-limit handling | Backoff / queue / circuit breaker | All three, layered |
| Concurrency cap | 8 / 10 / custom | Use the plan’s organization-wide Email Validation allowance |
| Verification on found emails | Skip / re-validate | Re-validate for cold outreach; skip for transactional |
Related Resources
- Email Verification API guide, the underlying API contract and response fields.
- Email Validation strategy: the product behavior behind the verdict, and the routing logic for
valid,invalid,unknown. - Email Validation product, credit economics, and bulk options.
- API reference: the
/docs/*endpoint specification, request/response schemas, and authentication. - B2B Data Enrichment API integration guide: caching, rate limits, and webhook patterns for the broader enrichment API.
- Email Finder API developer's guide: the companion finder endpoint, for the discover-then-verify workflow.
Bottom Line
Real-time email verification is an architecture decision, not an API call. The call is cheap and fast; the integration is where the work is: where in the request lifecycle you call it, how long you wait, what you do when it is slow or down, and how you avoid paying to re-verify the same address every time a user double-clicks submit.
Build the synchronous pattern for paid flows with a hard timeout and a fail-closed fallback. Build the asynchronous pattern for free flows with a background worker and a pending flag. Build the hybrid pattern when you want instant garbage rejection without the SMTP latency cost. Cache with the 24h/7d/never TTL table, key on the email hash, invalidate on domain MX changes. Layer backoff, queue overflow, and a circuit breaker so a degraded upstream never takes your signup down. Hold the end-to-end budget with connection pooling, regional deployment, and HTTP/2.
The verification API returns a single email_status field (valid, invalid, or unknown), at 0.25 credits per definitive result, with unknown not billed. Branch on it. Fail-open or fail-closed around it. Cache it. And read the API reference for the contract you are integrating against. If you want to skip the integration and verify through a UI, the Email Validation tool handles single lookups instantly, and the CSV upload tool handles bulk lists without code. For everything else, start with the API reference.
Sources and review
Topic path
Go deeper on Deliverability & Verification
How email verification works, Valid/Invalid/Unknown results, 0.25 credits per check (1 credit = 4 validations), catch-all resolution, and send/no-send rules. help reduce preventable bounces with real-time validation.
Keep reading
Integrate email verification with curl, Python, and Node.js. Covers responses, catch-all handling, batching, and production error strategies.
SMTP verification is a short handshake: TCP, EHLO, STARTTLS, MAIL FROM, RCPT TO. How each step works, what the codes mean, and where verifiers fail.
Six mail-server response patterns break naive verifiers. Learn what each one is, why it misleads, and how to route results after verification.