← Back to All Analyses
Applied AI & Automation•8 min read•

How We Built an Automated WhatsApp Lead Dispatch System with Meta Cloud API & PostGIS

Architecting sub-900ms conversational lead ingestion, geospatial radius matching, and deterministic agent guardrails for real estate operations.

Pawan Pratap
Pawan PratapFounder & Lead Architect

1. The Operational Bottleneck in Traditional Lead Routing

In high-velocity real estate operations, buyer inquiries deteriorate in value by 391% if not addressed within the first minute. When prospective buyers inquire about residential or commercial properties via WhatsApp, typical brokerages rely on human coordinators to read messages, verify listing IDs, locate the assigned agent on a spreadsheet, and forward the contact number.

During peak hours or weekends, this manual telephone-relay caused average response latencies of 45 minutes to 4 hours. By the time a broker answered, the buyer had already messaged two competing portals.

Our mandate at Dendrite Technologies was clear: engineer an autonomous conversational system on the official Meta WhatsApp Cloud API that ingests the inquiry, extracts natural-language intent, queries our geospatial database for the closest verified listing broker, and delivers warm buyer dispatch in under 15 seconds.

2. High-Throughput Event-Driven Architecture

To ensure high availability and prevent webhook backpressure from Meta's API clusters, we designed a decoupled pipeline:

[Meta WhatsApp Cloud API] │ (HTTPS POST Webhook) ▼ [FastAPI Webhook Gateway] ──► [Redis Stream Queue & De-dupe] │ ▼ [Async Worker Cluster] ├── Extract Buyer Intent (LLM + Guardrails) ├── PostGIS Spatial Radius Query (PostgreSQL) └── Two-Way Dispatch (Buyer Confirmation + Broker Alert)

By delegating the inbound webhook validation immediately to Redis and returning an HTTP 200 OK within 45ms, Meta never retries or throttles our webhook endpoint.

3. Sub-Second Webhook Ingestion & Deduplication

Meta webhooks can fire duplicate events under network jitter. A robust distributed de-duplication layer using Redis atomic keys is mandatory:

# Atomic idempotency check in FastAPI webhook listener
@app.post("/webhook/whatsapp")
async def handle_whatsapp_webhook(payload: WhatsAppPayload, background_tasks: BackgroundTasks):
    message_id = payload.entry[0].changes[0].value.messages[0].id
    redis_key = f"wa_msg_seen:{message_id}"
    
    # 24-hour expiration atomic lock
    is_new = await redis_client.set(redis_key, "1", nx=True, ex=86400)
    if not is_new:
        return {"status": "duplicate_ignored"}
        
    background_tasks.add_task(process_inbound_message, payload)
    return {"status": "queued"}

4. PostGIS Geospatial Radius Matching

Instead of matching properties by brittle city text names, we index all verified listings and registered broker territories using spatial geometry polygons in PostgreSQL with PostGIS:

-- Find verified brokers within a 3km radius of the property location
SELECT 
    b.id AS broker_id,
    b.phone_number,
    b.name,
    ST_Distance(b.service_polygon, ST_SetSRID(ST_MakePoint(:longitude, :latitude), 4326)) AS distance_meters
FROM brokers b
WHERE b.is_active = TRUE
  AND b.tier = 'verified_partner'
  AND ST_DWithin(b.service_polygon, ST_SetSRID(ST_MakePoint(:longitude, :latitude), 4326), 3000)
ORDER BY distance_meters ASC
LIMIT 1;

This spatial query executes in under 4 milliseconds over an R-Tree index, regardless of dataset size.

5. Deterministic AI Safety Guardrails

One of the biggest concerns for enterprise clients is hallucination. When an AI agent quotes an incorrect property price or makes false legal guarantees, it creates legal liability.

We solved this by establishing a strict three-tier deterministic guardrail:

  • Intent Extraction Only: The LLM is strictly constrained to output JSON schema parameters (budget min/max, bedroom count, preferred locality).
  • Database Truth Gate: The agent never invents inventory. Only listings returned from PostgreSQL with verified status can be sent to the user.
  • Human Escalation Trigger: If sentiment analysis detects frustration or if the user asks for financing, mortgage guarantees, or legal contracts, the agent cleanly transfers the session to an operational manager with full transcript logging.

6. Production Latency & Results

In production for our real estate marketplace partner FEETA, this automated architecture yielded dramatic operational benchmarks:

  • Average Lead Dispatch Latency: Dropped from 45+ minutes to 14.2 seconds.
  • Lead-to-Viewing Conversion Rate: Increased by +68%.
  • Unassisted 24/7 Hours: 42% of qualified inquiries were processed between 8:00 PM and 7:00 AM without human intervention.

If you're looking to automate your WhatsApp customer operations with enterprise-grade reliability, explore our dedicated Autonomous WhatsApp AI Agents or schedule a scoping call directly.

Building a Similar Architecture?

Discuss user flows, database models, and WhatsApp agent pipelines directly with Pawan Pratap. Zero middlemen.

Schedule Technical Scoping→