ai newsMi., 25. Nov.
EilmeldungYale’s Sonnenfeld: Nvidia is a ‘detriment’ to U.S. industrial might — not a champion

Multi-tenant AI agents: keeping one client's brand voice and data out of another client's posts

Three layers that stop AI agents from mixing up tenants: Postgres row-level security, per-tenant context assembly, and output checks, with code you can copy. If you build AI agents for agencies, or any product where one account manages many brands, there's one failure that matters more than any oth

dev.toMontag 08:51 · 23.11.6 Min. Lesezeit
Bild: dev.to

Posted on Nov 23 • Edited on Nov 23 • AI-assisted

Three layers that stop AI agents from mixing up tenants: Postgres row-level security, per-tenant context assembly, and output checks, with code you can copy.

If you build AI agents for agencies, or any product where one account manages many brands, there's one failure that matters more than any other. Not a weak post. A post in the wrong client's voice, with the wrong client's offer, published on the wrong client's account.

With people, the separation between clients lives in their heads. With AI agents, it has to live in your architecture. An agent that can see ten clients' data will eventually borrow from the wrong one.

We build Blooming, where 40+ AI agents run social, marketing, CRM, sales and support for agencies, with each client brand in its own isolated workspace. This post describes a three-layer pattern for this problem that you can use in your own product. The examples use PostgreSQL and Python.

In a classic multi-tenant SaaS app, a missing WHERE tenant_id =? leaks data on one screen. Bad, but contained.

With AI agents, leaks are quieter and spread further:

And the result doesn't look like an error. It looks like a perfectly good post, for the wrong brand.

Don't rely on every query remembering its WHERE brand_id =.... Use row-level security so the database enforces it:

CREATE TABLE brands ( id uuid PRIMARY KEY DEFAULT gen_random_uuid ( ), name text NOT NULL, voice jsonb NOT NULL DEFAULT '{}' ); CREATE TABLE content_items ( id bigserial PRIMARY KEY, brand_id uuid NOT NULL REFERENCES brands ( id ), channel text NOT NULL, body text NOT NULL, status text NOT NULL DEFAULT 'draft' ); -- The role your agent workers connect as CREATE ROLE agent_worker LOGIN PASSWORD '...'; GRANT SELECT ON brands TO agent_worker; GRANT SELECT, INSERT, UPDATE ON content_items TO agent_worker; GRANT USAGE ON SEQUENCE content_items_id_seq TO agent_worker; ALTER TABLE brands ENABLE ROW LEVEL SECURITY; ALTER TABLE content_items ENABLE ROW LEVEL SECURITY; -- NULLIF: see "Four details" below for why it's there CREATE POLICY brand_isolation ON brands USING ( id = NULLIF ( current_setting ( 'app.brand_id', true ), '' ):: uuid ); CREATE POLICY brand_isolation ON content_items USING ( brand_id = NULLIF ( current_setting ( 'app.brand_id', true ), '' ):: uuid ) WITH CHECK ( brand_id = NULLIF ( current_setting ( 'app.brand_id', true ), '' ):: uuid ); Enter fullscreen mode Exit fullscreen mode Each task sets the brand for its own transaction, and everything inside it can only see and write that brand's rows:

import psycopg def run_for_brand ( conn: psycopg. Connection, brand_id: str, work ): with conn. transaction ( ): # set_config(..., true) = SET LOCAL: it ends with the transaction conn. execute ( "SELECT set_config('app.brand_id', %s, true)", ( brand_id, ) ) return work ( conn ) Enter fullscreen mode Exit fullscreen mode We tested this on PostgreSQL 16. With the brand set to "Coffee Co.", the worker sees only Coffee Co.'s rows. Trying to insert a row for another brand fails:

ERROR: new row violates row-level security policy for table "content_items" Enter fullscreen mode Exit fullscreen mode An UPDATE aimed at another brand's posts updates 0 rows. And if a bug forgets to set the brand at all, the worker sees nothing. It fails closed, which is exactly what you want.

Wrap the setting in NULLIF(..., ''). We found this one in testing. On a fresh connection, an unset app.brand_id reads as NULL. But on a pooled connection where a previous task set it, it reads as an empty string after that transaction ends, and ''::uuid throws invalid input syntax for type uuid. NULLIF turns both cases into "no rows".

Table owners and superusers bypass RLS. Connect workers as a separate role, as above, or add ALTER TABLE... FORCE ROW LEVEL SECURITY.

Use SET LOCAL (or set_config(..., true) ), not SET. With connection pooling, a plain SET can leak into the next task that reuses the connection.

Your vector store needs the same rule. If you keep embeddings for retrieval, filter by tenant in the store itself (a tenant column with RLS, or a separate namespace per tenant), not by filtering results afterwards.

The database stops cross-tenant reads. The next risk is the prompt: anything you put in the context window can end up in the output.

Assemble the context for each task from scratch, from that brand's data only:

def build_context ( conn, brand_id: str, task: str ) -> str: def work ( c ): brand = c. execute ( "SELECT name, voice FROM brands" ). fetchone ( ) examples = c. execute ( "SELECT body FROM content_items WHERE status = 'approved' " "ORDER BY id DESC LIMIT 5" ). fetchall ( ) return brand, examples ( name, voice ), examples = run_for_brand ( conn, brand_id, work ) sample_posts = "\n". join ( f "- {row}" for row in examples ) return ( f "You write for {name}.\n" f "Voice: {voice}\n" f "Recent approved posts:\n{sample_posts}\n\n" f "Task: {task}" ) Enter fullscreen mode Exit fullscreen mode Notice the queries have no WHERE brand_id. They don't need one: RLS already limits them to this brand. And there's nothing in the function that could fetch another brand's examples.

Even with clean inputs, check drafts for the most damaging mistake: another client's name.

import re def other_brand_mentions ( draft: str, brand_id: str, all_brands: dict [ str, list [ str ] ] ) -> list [ str ]: """all_brands maps brand_id -> names, product names and handles for that brand.""" hits = [ ] for other_id, terms in all_brands. items ( ): if other_id == brand_id: continue for term in terms: if re. search ( rf "\b{re.escape(term)}\b", draft, re. IGNORECASE ): hits. append ( term ) return hits Enter fullscreen mode Exit fullscreen mode This check runs in a trusted service, not in the agent worker, because it needs to know every brand's names. A hit doesn't publish anything: the draft goes back with a clear flag.

Then, the last layer: a person approves before anything is published. Agents draft, schedule and sort; someone who knows the client presses the button.

Tenant isolation deserves real tests, not just code review:

Strict isolation has costs. A great campaign idea for one client can't be reused for another unless a person copies it on purpose. Agencies that run several brands for one parent company sometimes want some sharing. We think isolation is the right default, and sharing should be a deliberate, visible action, not something an agent does on its own.

Building multi-tenant AI? How are you keeping tenants apart: in the database, in the prompt layer, or both? Tell us in the comments.

Quelle: dev.to (dev.to). Original öffnen