Dev.to AI 🤖 Ai 👁 0 📖 6 min read

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

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.

Why AI makes tenant isolation harder

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:

  • Retrieval pulls "similar" past posts. Similar across all clients, unless you stop it.
  • Shared memory or few-shot examples carry one client's phrases into another's drafts.
  • Long-running agents that work for several clients in one session carry context over between tasks.

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

Layer 1: Make the database refuse to mix tenants

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);

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)

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"

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.

Four details that catch people out:

  • 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.

Layer 2: Build the agent's context from one tenant only

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[0]}" 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}"
    )

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.

The rules that matter here:

  • No shared memory between tenants. If an agent keeps notes or memory, it's per brand, stored with the brand's ID and protected the same way.
  • No cross-tenant few-shot examples. "Here are some great posts from other clients" is how voices bleed.
  • A fresh context per task. Don't let one long agent session work for several brands in a row.

Layer 3: Check the output before anyone sees it

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

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.

Test it like a security feature

Tenant isolation deserves real tests, not just code review:

  • A leak test in CI: create two brands with obviously different voices and data, generate drafts for brand A, and assert that nothing from brand B appears.
  • A "forgot the brand" test: run a task without setting app.brand_id and assert it returns no rows.
  • A pooling test: run tasks for brand A and brand B on the same pooled connection, one after the other, and assert the second task can't see the first brand's data.

The trade-off

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.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.