DEV Community

Cover image for Spatial Row-Level Security (RLS) in PostgreSQL: Designing Multi-Tenant Geospatial Architectures
Alex G
Alex G

Posted on

Spatial Row-Level Security (RLS) in PostgreSQL: Designing Multi-Tenant Geospatial Architectures

Standard multi-tenant Row-Level Security (RLS) in PostgreSQL is well-trodden ground: you attach a tenant_id column to your tables, set a session variable, and let Postgres filter rows automatically.

That works great—until your authorization model becomes spatial.

In logistics, fleet management, field operations, or location-aware SaaS, tenancy isn't just about who you are; it's about where you are allowed to operate. A regional dispatcher shouldn't see telemetry outside their assigned city. A franchise partner shouldn't query assets outside their licensed territory—even if they share the same underlying dataset or tenant hierarchy.

Enforcing those boundaries exclusively in application code is fragile. One forgotten WHERE ST_Contains(...) clause in a new endpoint or reporting query turns into a cross-territory data leak (classic BOLA/IDOR, just with coordinates).

This is fine dog
Deploying a new reporting endpoint on Friday at 5 PM and forgetting WHERE ST_Contains(...).



In this first chapter of the series, we’ll design Spatial Row-Level Security (Spatial RLS) directly in PostgreSQL + PostGIS—and more importantly, cover the indexing, polygon subdivision, and connection-pooling traps that can silently wreck performance in production.


1. The Baseline Schema

Assume we have a multi-tenant platform ingesting real-time spatial events (assets, deliveries, or telemetry points) and a territories table defining the authorized boundaries for each tenant or role.

First, enable postgis and btree_gist (we’ll need btree_gist in a moment for composite spatial indexing):

CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE territories (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL,
  name TEXT NOT NULL,
  boundary GEOMETRY(MultiPolygon, 4326) NOT NULL
);

CREATE TABLE spatial_events (
  id BIGSERIAL PRIMARY KEY,
  tenant_id UUID NOT NULL,
  asset_id UUID NOT NULL,
  payload JSONB NOT NULL DEFAULT '{}'::jsonb,
  location GEOMETRY(Point, 4326) NOT NULL,
  recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

Enter fullscreen mode Exit fullscreen mode

2. Enabling Fail-Closed Spatial RLS

A common mistake when designing Spatial RLS is trying to pass raw WKT or GeoJSON polygons into SET LOCAL app.current_polygon = '...' on every request. Don't do that—parsing large geometries on every transaction adds unnecessary overhead and bloats your connection traffic.

Instead, pass lightweight identifiers (tenant_id and territory_id) via transaction-scoped settings, and let PostgreSQL resolve the spatial predicate against indexed geometry tables.

-- Always use a dedicated non-owner app role in production.
-- FORCE ensures even table owners don't accidentally bypass RLS during testing.
ALTER TABLE spatial_events ENABLE ROW LEVEL SECURITY;
ALTER TABLE spatial_events FORCE ROW LEVEL SECURITY;

CREATE POLICY spatial_territory_isolation
ON spatial_events
FOR SELECT
USING (
  tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid
  AND EXISTS (
    SELECT 1
    FROM territories t
    WHERE t.id = NULLIF(current_setting('app.current_territory', true), '')::uuid
      AND t.tenant_id = spatial_events.tenant_id
      AND ST_Intersects(t.boundary, spatial_events.location)
  )
);

Enter fullscreen mode Exit fullscreen mode

Why current_setting(..., true) + NULLIF matters

Passing true as the second argument (missing_ok) prevents PostgreSQL from throwing an unhandled runtime error if a developer forgets to set the context. Instead, it returns NULL, the = comparison evaluates to UNKNOWN (falsy), and the query returns 0 rows.

Your database is now fail-closed by default.


3. Three Performance Traps (and How to Fix Them)

Spatial RLS is deceptively easy to write—and deceptively easy to make slow. If you deploy the policy above onto a table with 10 million points and complex city boundaries, latency will spike fast unless you handle these three bottlenecks.

Trap 1: Giant Polygons (The Vertex Tax)

A real-world territorial boundary (a coastline, municipality, or custom delivery zone) can easily have 10,000+ vertices. Even with a GiST index, its bounding box is huge, forcing ST_Intersects to run expensive point-in-polygon math against thousands of vertices for every candidate row.

The Fix: Pre-subdivide territories with ST_Subdivide.

Break large polygons into small, indexed tiles (e.g., max 256 vertices each) whenever a territory is created or updated:

CREATE TABLE territory_tiles (
  territory_id UUID NOT NULL REFERENCES territories(id) ON DELETE CASCADE,
  tenant_id UUID NOT NULL,
  geom GEOMETRY(Polygon, 4326) NOT NULL
);

-- Populate subdivided tiles
INSERT INTO territory_tiles (territory_id, tenant_id, geom)
SELECT
  id,
  tenant_id,
  (ST_Dump(ST_Subdivide(boundary, 256))).geom
FROM territories;

CREATE INDEX idx_territory_tiles_lookup
ON territory_tiles USING GIST (territory_id, geom);

Enter fullscreen mode Exit fullscreen mode

Now point your RLS policy at territory_tiles instead of territories. Each tile has a tight bounding box and tiny vertex count, turning heavy geometric checks into sub-millisecond index lookups.

Trap 2: Separate Indexes Instead of Composite GiST

If you create a B-Tree index on tenant_id and a separate GiST index on location, PostgreSQL often has to choose between them or perform a costly BitmapAnd merge.

The Fix: Use btree_gist for a single composite spatial index.

CREATE INDEX idx_spatial_events_tenant_loc
ON spatial_events USING GIST (tenant_id, location);

Enter fullscreen mode Exit fullscreen mode

Now PostgreSQL can narrow down both the tenant and the spatial bounding box in a single GiST index scan.

Trap 3: Context Leakage in Connection Pools (PgBouncer / Node / Go)

If you use SET app.current_tenant = '...' on a pooled connection, that variable persists for the entire session. The next HTTP request that grabs the same connection from the pool inherits the previous tenant's territory.
Spider-Man pointing
Tenant A and Tenant B sharing the exact same PgBouncer session because someone used SET instead of SET LOCAL.

The Fix: Always use SET LOCAL inside an explicit transaction.

BEGIN;

SELECT set_config('app.current_tenant', $1, true);    -- true = local to transaction
SELECT set_config('app.current_territory', $2, true);

SELECT id, asset_id, ST_AsGeoJSON(location)
FROM spatial_events
WHERE recorded_at > NOW() - INTERVAL '1 hour'
LIMIT 100;

COMMIT;

Enter fullscreen mode Exit fullscreen mode

Once the transaction commits or rolls back, PostgreSQL wipes the local context automatically before the connection returns to the pool.


4. Defense in Depth: DB-Level vs. Edge-Level Spatial RLS

Database-level Spatial RLS is your ultimate safety net—it guarantees that even a buggy microservice or compromised query cannot pull rows outside an authorized boundary.

However, in high-concurrency systems, you don't want unauthorized requests hammering PostgreSQL just to get filtered out at the storage layer. While building GeoEngine and its IAM layer (GeoIdentity), we found the cleanest architecture splits this into two layers:

  1. API / Edge Layer (Fast Reject): Validate contextual location claims and territorial permissions before the request ever hits the database connection pool.
  2. PostgreSQL Layer (Hard Isolation): Enforce Spatial RLS with territory_tiles + SET LOCAL as the final, unbypassable guarantee.

What’s Next in This Series

Database isolation solves data access, but what about authentication itself? In Part 2, we’ll look at Why Traditional Auth Isn't Enough: Building Contextual Location Locks with Go and Redis—and how to validate location and network context in real time without storing sensitive credentials.

If you’ve implemented PostGIS + RLS in production (or hit weird query planner edge cases with ST_Intersects), drop your experience in the comments—I’d love to compare notes.


Enter fullscreen mode Exit fullscreen mode

Top comments (0)