Enterprise luxury real estate intelligence & multimodal AI ecosystem. Features two-way realtime voice profiling, two-stage hybrid semantic matching with pgvector, and automated cloud infrastructure.

ArchitectureDecoupled Monorepo
Primary AI StackVertex AI (Gemini 2.5)
Database & SearchSupabase + pgvector
InfrastructureGCP Cloud Run & Cloud Build
Key Performance & Engineering Metrics
Production Verified
Hybrid Query Latency
<100ms

Stage 1 SQL boundary pruning + Stage 2 pgvector HNSW index.

Token Cost Reduction
~75%

Eliminated full-catalog LLM prompts via hard boundary pre-filtering.

Live Voice Turnaround
<1.2s

Bidirectional WebSocket streaming on Vertex AI Gemini Live API.

Automated Test Pass Rate
46/46

100% pass across Vitest (30) & Pytest (16) hermetic CI suites.

Voice Session Ceiling
600s

Async watchdog hard-cap preventing runaway Cloud Run costs.

Executive Summary & Mission

Traditional real estate portals trap buyers in rigid scalar filters (e.g. price, room count, city), completely missing subjective lifestyle nuances such as architectural ambiance, privacy, and geographic constraints.

Lokus reimagines this paradigm by deploying conversational voice profiling agents capable of extracting nuanced buyer intents, crystalizing them into structured dossiers, and executing a two-stage hybrid matching algorithm that balances hard constraints with semantic embeddings.

System Architecture & Data Flow

Lokus employs a strictly decoupled monorepo architecture separating the presentation shell from the realtime voice engine and semantic persistence tier, eliminating event loop starvation and secret exposure.

Tier 1: Presentation & Proxy

Next.js 15 (App Router) + React 19

Captures browser Web Audio PCM, manages RBAC session state, and proxies single-use ephemeral JWT tickets via internal /api/live/token endpoint.

Tier 2: Realtime Streaming Engine

FastAPI + Async Concurrency (Cloud Run)

Operates /ws/live WebSocket endpoint using non-blocking client.aio async models and a 10-minute async watchdog task.

Tier 3: Multimodal Intelligence

Vertex AI (Gemini 2.5 Flash Live API)

Streams low-latency bidirectional voice, conducts phased buyer discovery, and extracts structured buyer intent JSON using WHEN_IDLE tool scheduling.

Tier 4: Hybrid Semantic Persistence

Supabase PostgreSQL + pgvector (HNSW)

Houses property listings, 768-dim embeddings (text-embedding-004), PgBouncer connection pooler on port 6543, and direct migration tunnel on port 5432.

// End-to-End Pipeline Execution
01
Ticket Minting & Audio Handshake:Client verifies credentials via NextAuth, requests 60s single-use HS256 JWT ticket, and establishes WebSocket stream to FastAPI on Cloud Run.
02
Bidirectional Voice Dialogue:FastAPI initiates full-duplex session with Vertex AI Live API. Audio chunks stream with sub-second turnaround; tool calls crystallize buyer constraints without stalling speech.
03
Two-Stage Hybrid Search Execution:Stage 1 applies strict SQL boundary filtering (budget ceiling, room count, excluded locations) pruning catalog to ~50 candidates. Stage 2 executes cosine distance re-ranking over pgvector HNSW index.
04
Instant Ingestion Match & Notification:When real estate agents ingest portfolios via Hermes extension or dashboard, reverse matching evaluates active buyer liquidity and immediately triggers qualified lead dossiers.

Top 3 Architectural Decisions (ADR)

ADR 039Security / WebSockets

Two-Tiered Authentication with Ephemeral JWT Tickets

Eliminated public master secret leakage in realtime WebSocket connections. Client browsers request single-use, 60-second HS256 JWT tickets via an internal authenticated Next.js route (/api/live/token). The FastAPI backend verifies the signature on handshake, closing connections immediately if expired.

Zero secret leakage in client-side bundles; automated replay protection.
ADR 045 & 046Search / AI Matching

Two-Stage Hybrid Matching Engine (Hard SQL + pgvector)

Pure LLM matching causes excessive token costs and latency, while pure SQL destroys semantic discovery. Lokus executes hard boundary constraints in Stage 1 (budget ceiling, room tolerances, strict negative location filtering via NOT IN SQL queries) to prune thousands of listings down to ~50 candidates. Stage 2 executes cosine distance re-ranking over 768-dim embeddings via pgvector HNSW indexes.

Sub-100ms response time with rich semantic awareness and zero filter evasion.
ADR 044CI/CD / Database

Automated Database Migration Pipeline in Cloud Build

Segregated runtime connection pooling (Supabase PgBouncer on port 6543) from direct migration tunnels (DIRECT_URL on port 5432). Integrated mandatory prisma migrate deploy steps into Cloud Build deployment triggers, eliminating schema desync downtime.

Eliminated PgBouncer migration hangs; fully automated zero-touch deployments.

Top 3 Engineering Challenges & Solutions

Challenge #01

Vertex AI Live Audio Race Conditions & Silent Scheduling

React 18/19 StrictMode double-mounted client audio contexts, causing ghost WebSocket connections, audio feedback loops, and double-farewell dialogues. Simultaneously, background data extraction tools configured with SILENT scheduling halted audio generation, freezing client microphones in infinite listening states.

// Solution Pattern:
1. Enforced useRef teardown handlers to close orphaned WebSockets before remount.
2. Migrated all background tools to WHEN_IDLE scheduling to sustain natural conversational turns.
Challenge #02

The Raw Cosine Distance Perception Trap

Surfacing raw mathematical similarity percentages (e.g. 82%) confused luxury buyers, who perceived 82% as an exam failure or incomplete property match, despite 0.82 representing high semantic congruence.

// Solution Pattern:
1. Applied a weighted sigmoid mapping curve to translate raw cosine distance into human-intuitive tiers.
2. Built In-Card Breakdown Popovers displaying isolated criteria (Location: 100%, Budget: 95%, Style: 90%).
Challenge #03

Next.js NEXT_PUBLIC_ Build-Time vs Runtime Injection

Deploying Next.js inside Cloud Run containers caused client WebSocket URLs to resolve as undefined. Updating environment variables on the running container failed because Next.js inlines NEXT_PUBLIC_ keys strictly during npm run build.

// Solution Pattern:
1. Parameterized Docker build steps in cloudbuild.yaml using --build-arg injections.
2. Hardened multi-stage Dockerfiles to consume ARG definitions prior to compiler execution.

Key Learnings & Mental Models

Paradigm 01

Dumb Pipe, Smart Engine

Frontend interfaces should act as dumb streaming conduits for audio and user intent. Complex business state, slot filling, and fallback guarantees must live strictly inside the backend and model orchestration layers.

Paradigm 02

Fail Loudly in Development

Never use silent fallback values (e.g. localhost:3000) for critical cloud configurations. Failing fast at startup surfaces secret and network misconfigurations immediately before they reach production.

Tech Stack Matrix

// Frontend & Client
Next.js 15 (App Router)React 19TailwindCSSFramer MotionNextAuth.js
// Backend & Microservices
Python 3.11FastAPIUvicornWebSockets
// AI & Search Engine
Vertex AI Live APIGemini 2.5 Flashtext-embedding-004pgvector (HNSW)
// Database & ORM
Supabase PostgreSQLPrisma ORMPgBouncer Pooler
// Cloud & DevOps
Google Cloud RunGoogle Cloud BuildSecret ManagerArtifact Registry

Production Guardrails

Zero Fallback Policy

Strict require_env() validation across all microservices; silent defaults strictly forbidden.

Security Perimeter

Constant-time hmac.compare_digest secret validation, single-use JWT tickets, and server-side PII shielding.

Concurrency Protection

Non-blocking async event loop with asynchronous GenAI client (client.aio) to eliminate audio packet drop.

CI/CD Automation

Google Cloud Build triggers multi-stage Docker builds, parameterized ARG injection, and automated Prisma migrations.