Private Specification
RAIA™ (Real estate Artificial Intelligence Agent) Protocol Security Private Specification This document contains proprietary B2B property management protocols and agentic swarm blueprints. For security and
RAIA™ (Real estate Artificial Intelligence Agent) Protocol Security Private Specification This document contains proprietary B2B property management protocols and agentic swarm blueprints. For security and
Map Pin Architecture & BigQuery Speed Optimization
Like a private detective agency with a massive filing cabinet of GPS coordinates, this system retrieves and displays thousands of property map pins on the dashboard without slowing down — using BigQuery optimization.
Map Pin Architecture & BigQuery Speed Optimization
Let’s explain this with a simple analogy. Imagine we are running a private detective agency. We have a massive, super-smart filling cabinet (BigQuery) that stores the exact GPS map coordinates of every single property in our country. We want to show these properties as dots on a giant wall map (our dashboard). But there are three catch points:
1. ELI5: How Does the Map Load Instantly?
Concept For HumansLet’s explain this with a simple analogy. Imagine we are running a private detective agency. We have a massive, super-smart filling cabinet (BigQuery) that stores the exact GPS map coordinates of every single property in our country. We want to show these properties as dots on a giant wall map (our dashboard). But there are three catch points:
No Peeking! (Security)
We are a B2B platform. Agency A must never see Agency B's secret leads (like Farming or Lost properties). Our giant coordinate table has no "owner" labels. To keep it safe, the server acts as a guard. It first checks your ID badge, fetches a whitelist of properties your agency owns, and then whispers only those specific dots to your screen.
The Webhook Hot Path
Normally, a heavy robot sweeps through the entire database at midnight to rebuild the map table. But what if you edit a property name at 2:00 PM? You don't want to wait until midnight! We built a "hot path" webhook. The instant you click save, a target laser deletes just that single property from BigQuery and inserts its fresh details in 1 second.
The Speed Cheat Sheet
Why is it so fast? First, we don't load property pictures (thumbnails) when drawing the pins. We draw the pins instantly and fetch pictures in the background. Second, if a house is listed for rent AND sale, we don't draw overlapping duplicate pins; SQL magic merges them into one clean pin before sending.
2. Architectural Visualizations
Inline Interactive SVGsA. Multi-Organisation Security Scoping & Pin Retrieval (ADR-097)
How `/api/pins` resolves roles, overrides default Supabase query limits, and injects scopes as whitelists into BigQuery parameter vectors.
B. Two-Speed ETL Architecture (Nightly Load vs Webhook Hot Path)
Comparing the heavy-duty nightly sync (optimized via Load Jobs) and the real-time hot path updates (optimized via single asset DML queries).
3. Technical Deep Dive
For DevelopersA. Multi-Tenant Org Scoping without DB Pollution
Standard multi-tenant models pollute every single table with an organisation_id column. In BigQuery, our spatial datasets (specifically map_pins) are intentionally general-purpose, optimized for geography rather than tenancy. Keeping them decoupled prevents database drift and lets us run global spatial calculations without cross-org table contamination.
To secure the data on retrieval, the /api/pins endpoint acts as an active security mediator:
- The API never trusts a client-passed role or organisation identifier. It reads the caller's session token directly from the request headers/cookies.
- It looks up the user's verified profile in Supabase to extract their true
roleandorganisation_id. - If the user is an operator or branch manager, the API executes a server-side query on Supabase
tbl_assetsto compile a clean array of all asset IDs belonging to their organization. - This array is passed to BigQuery as a parameter (
@asset_ids), restricting the results instantly via:AND asset_id IN UNNEST(@asset_ids).
Supabase enforces a strict default pagination limit of 1,000 rows. Our core Rescue Live Full (Sovereign Node) organization currently owns
The live codebase implementation for this specification sits within the following repository folder:
Repository Code
.select("asset_id") query would silently truncate at 1,000, leaving out 491 properties from the map! The API explicitly overrides this with a 5,000-row buffer:
const { data: assets } = await supabaseAdmin
.from("tbl_assets")
.select("asset_id")
.eq("organisation_id", orgId)
.limit(5000); // Override default 1000 page size
B. The Webhook Hot Path vs Streaming Buffer Locks
Under standard BigQuery setups, developers push real-time updates via Streaming Inserts (table.insert()). However, this creates a major architectural flaw in active systems:
"Rows written via Streaming Inserts enter a temporary write buffer. These rows cannot be modified or deleted by Data Manipulation Language (DML) queries (likeDELETEorUPDATE) for up to 90 minutes. Attempting to delete them throws a streaming buffer error."
This poses a serious challenge for our real-time updates. If an operator edits a property, and then edits it again 5 minutes later, the secondary webhook would fail with an active lock!
How RAIA (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) solves this:
- Nightly Batch ETL: The nightly sync script (
sync-pins.js) compiles an NDJSON file, runs aTRUNCATE TABLEquery, and loads the data via a formal BigQuery Load Job (table.load()). Load jobs write directly to permanent storage, bypassing the streaming buffer entirely. - Real-time Webhook Hot Path: Our webhook endpoint (
/api/webhooks/asset-updated) is triggered on Supabase inserts, updates, and deletes. It executes a clean, standard DMLDELETE FROM map_pins WHERE asset_id = @asset_idquery (~1.5s execution) followed immediately by a DMLINSERT INTO. This guarantees instant updates with zero locks.
C. Architectural Optimization Secrets for speed
Beyond datastore tuning, the map loads in milliseconds due to several front-end and query optimizations:
QUALIFY ROW_NUMBER() OVER ( PARTITION BY asset_id ORDER BY service_type ) = 1
thumbnailUrl key. The map plots immediately, and photos are lazy-loaded on hover/draw via /api/pins/thumbs.
Instructed live listings. This is non-confidential, slow-changing data, so it gets cached aggressively at the Cloudflare Edge. Operators get high-security, real-time data, so their lookups bypass CDN layers entirely.
D. Front-End Map Function Stack Explainer (useMapPins)
When a user loads our dashboard map, the client-side React code orchestrates a three-phase coordinate rendering stack to achieve near-instantaneous load times (under 600ms) with zero layout thrashing:
The custom React hook useMapPins immediately queries /api/pins. This endpoint fetches strictly coordinates, status indicators, and asset references from our BigQuery spatial dataset. It returns a lightweight JSON payload (no images/descriptions) in under 600ms. The Leaflet/Google Maps canvas immediately draws all interactive markers with lightweight placeholders in tooltips.
The moment Phase 1 resolves, the hook triggers a secondary background fetch to /api/pins/thumbs. This endpoint queries Supabase to fetch CDN thumbnail image URLs and alert states for those assets. They are dynamically backfilled into the React state. When an operator hovers over a pin, its image is displayed instantly without causing any page lag during initial loads.
To eliminate visual flickering when switching pages, the final merged pin payload is written to local storage. On return visits, the map reads the cache instantly. If the cache is under 2 minutes old, it serves it directly. If it is 2-30 minutes old, it serves the cached pins immediately and fetches fresh ones in the background, keeping our user experience flawlessly fast.
4. Code Highlights
Production ExcerptsA. Parameterized BigQuery SQL Builder with Distinct Collapsing
function buildQuery(
unLocode: string,
role: string,
timeline: string,
listingType: string,
assetIds: string[] | null // Whitelist of verified, server-resolved asset IDs
): string {
const isRestricted = role === "public" || role === "tenant";
// Public/tenant users are restricted to 'Instructed' (live) assets only
const roleFilter = isRestricted ? `AND asset_status = 'Instructed'` : "";
const locodeFilter = unLocode ? `AND un_locode = @un_locode` : "";
const assetFilter = assetIds ? `AND asset_id IN UNNEST(@asset_ids)` : "";
// Collapses multi-listing properties into 1 pin to avoid map markers rendering on top of each other
return `
SELECT DISTINCT
asset_id,
asset_ref,
property_tag,
latitude,
longitude,
asset_status,
fee_value,
fee_currency,
service_type
FROM \`\${PROJECT}.\${DATASET}.\${TABLE}\`
WHERE latitude IS NOT NULL
AND longitude IS NOT NULL
\${locodeFilter}
\${assetFilter}
\${roleFilter}
QUALIFY ROW_NUMBER() OVER (PARTITION BY asset_id ORDER BY service_type) = 1
ORDER BY asset_ref
`;
}
5. Verification & Operations Guide
Testing & CommandsDevelopers can manually trigger coordinate syncs, trace webhook logs, or inspect the BigQuery table to verify changes are live.
To preview how many assets have valid GPS coordinates and what the schema shape is without writing to BigQuery:
node /root/projects/raia/03_technology/09_pipelines/programs/sync-pins.js --dry-run
To manually clear the BigQuery table and load the latest authoritative Supabase assets:
node /root/projects/raia/03_technology/09_pipelines/programs/sync-pins.js
You can trigger a database webhook event from the Supabase admin panel or manually simulate a database payload locally via curl to test the instant delete/insert cycle.
Architecture Details
The security architecture implements a defence-in-depth model with perimeter authentication, internal authorisation, data encryption, and audit logging at every layer. Access is gated through a two-gate system: Tailscale identity verification at the network level, followed by role-based access control within the application.
- Core Component: Security gate guard and RBAC enforcement
- Data Flow: Request → Tailscale Gate → Authentication → Authorisation → Audit Log → Response
- Integration Points: Tailscale ACLs, Supabase Row-Level Security, session tokens, and audit log sinks
Configuration Reference
Key configuration parameters for this system:
| Parameter | Type | Default | Description |
|---|---|---|---|
| gate_enabled | boolean | true | Enable Tailscale gate guard for all pages |
| allowed_hosts | string[] | dev.estateaigents.com, localhost | Whitelist of permitted hostnames |
| session_ttl_minutes | integer | 60 | Session token time-to-live |
Figure 2: Security architecture — component interaction and data flow.
Troubleshooting
| Issue | Cause | Resolution |
|---|---|---|
| 401 Unauthorized on tailnet | Tailscale not running or wrong node | Verify Tailscale is connected and node is authorised |
| Gate guard redirect loop | Hostname not in allowed_hosts list | Add hostname to the gate guard whitelist |
This component is part of the RAIA (Real estate Artificial Intelligence Agent) platform mono-repo. Implementation details, API contracts, and integration tests are available in the repository.