What are pooled, bridge and siloed models in a multi-tenant microservices database?

A multi-tenant microservices database can isolate tenants at three levels. Pooled puts every tenant in shared tables, with a tenant_id column on each row. Bridge gives each tenant its own schema inside a shared database. Siloed gives each tenant a dedicated database or cluster.

Each microservice owns its data, so you make this choice per service, not once for the whole platform. A billing service holding regulated payment records might be siloed, while a notification-preferences service stays pooled. The two services can make different trade-offs because neither depends on the other's storage.

Dimension Pooled Bridge (schema per tenant) Siloed (DB/cluster per tenant)
Isolation strength Logical; relies on query filters or policies Namespace boundary; shared engine Physical; separate engine or instance
Blast radius All tenants in the service All tenants on that database One tenant
Noisy-neighbor exposure High High (shared CPU, I/O, connections) Low at the data layer
Migration effort One migration per service One per schema One per database, plus fleet orchestration
Restore granularity Whole database; per-tenant restore needs extraction Per-schema dump possible Per-tenant native
Cost attribution Estimated from usage Estimated Direct

Bridge is often mistaken for strong isolation. In practice, every schema still competes for the same compute and buffer cache. With thousands of tenants, the system catalog grows large, and migration tooling has to apply each change thousands of times and track partial failures.

Siloing has its own trap. If you silo only the database while tenants still share caches, queues and application pods, a runaway tenant can still degrade everyone else. That isolation is weaker than "dedicated database" suggests to customers.

How does a per-service tenancy model work end to end?

The approach has four moving parts, each covered in detail in the sections below:

  1. A per-service placement decision. Each service is classified as pooled, bridge or siloed, and a service can mix models, for example pooling most tenants while siloing a few heavy or contractually isolated ones.
  2. Trusted tenant context. The edge derives the tenant from a verified token claim. Services forward that context over authenticated channels, and async messages carry an explicit tenant_id field.
  3. Enforcement in the database. In pooled tables, PostgreSQL row level security filters every query by the tenant set for the current transaction. Composite keys that lead with tenant_id make cross-tenant references structurally impossible.
  4. A routing catalog. Each service looks up where a given tenant's data lives (cluster, database, schema) and connects there. Moving a tenant between models then means copying data and updating a catalog row. The service code does not change.

A request flows like this: the edge verifies the token and extracts the tenant. The service sets the tenant in its request context, resolves the placement from the cached catalog, opens a transaction against the target, sets app.tenant_id transaction-locally, and runs its queries. In a silo the policy is redundant but harmless. In a pooled table the policy is what stops a missing filter from leaking data.

How do you decide which services should be pooled or siloed?

Classify each service on its own. Score it against five questions: how sensitive is the data, how skewed is load across tenants, do regulations or data-residency rules pin data to a location, has any contract promised dedicated storage, and how much damage would one tenant's bad query or leaked row cause? Default to pooled unless one of these answers forces a change. Pooling keeps capacity shared, and that shared capacity is the main reason multi-tenancy is cheaper.

Consider a hypothetical platform with four services:

Service Sensitivity Load skew Residency/contract Decision
Identity High (credentials) Low Sometimes Pooled with row level security; bridge for residency tenants
Billing High (financial) Low Contractual for enterprise Siloed only for tenants who pay for it
Analytics Medium Very high Rare Silo the few heavy tenants; pool the rest
Notifications Low Moderate No Pooled

Only billing and analytics warrant siloing, and only for some tenants. Siloing small tenants wastes capacity because each one pays for a database floor it never uses.

Illustrative estimate. Assume a shared cluster costs $2,000/month and serves 400 tenants, which works out to about $5 per tenant. Assume a minimal dedicated instance with a replica costs $150/month. A small siloed tenant then costs roughly 30 times more than a pooled one before you count backups and monitoring.

Mixed models have a cost beyond money. On-call engineers must know which model each service uses for each tenant. Runbooks branch by model, and migrations run in several shapes. Keep the number of combinations small.

Who should use a per-service tenancy model?

This approach fits teams building B2B SaaS on microservices where each service owns its own database and tenants differ meaningfully in size, sensitivity or contractual terms. Typical signs:

  • A mix of tenant sizes. Many small tenants that are only economical when pooled, alongside a few large ones whose load or data volume would dominate shared tables.
  • Uneven data sensitivity across services. Some services hold credentials, payment or regulated data; others hold low-risk preferences or caches.
  • Enterprise or regulated customers who ask for dedicated storage, specific data residency, or per-tenant restore and deletion guarantees.
  • Platform or infrastructure teams responsible for tenant onboarding, offboarding and migration tooling across many services, who need one consistent way to locate and isolate tenant data.

It is less relevant to single-tenant products, internal tools with one customer, or consumer applications where "tenant" means an individual user and there are no per-customer isolation contracts.

When should you use it?

Use a per-service choice of model, backed by row level security and a routing catalog, when:

  • Tenants share a codebase but not a risk profile. You want pooled economics for most tenants but need a path to isolate specific ones without forking the code.
  • Some services have stricter requirements than others. Siloing the whole platform would multiply operational work for services that do not need it.
  • You expect tenants to grow out of the pool. A routing catalog lets you promote a tenant to a silo, or move it to a residency-specific cluster, as a planned data operation.
  • You need defense in depth against filter bugs. Many engineers write queries against pooled tables, and one missed WHERE tenant_id should not expose every customer.
  • Async processing is significant. Queues, event streams and background jobs are common, so tenant context must be made explicit rather than implied by request scope.

When should you avoid it?

Choose something simpler, or something stronger, when:

  • Every tenant needs physical isolation. If contracts or regulations require dedicated infrastructure for all customers, a mixed model adds routing complexity with no pooling benefit. Deploy a full stack per tenant instead.
  • You have few tenants and few services. With a handful of customers, a single pooled database with row level security, or one database per tenant without a catalog, may be easier to run.
  • Services share a database today. Per-service placement assumes each service owns its storage. If services join across each other's tables, fix ownership first, or the per-service decision cannot be made independently.
  • The team cannot staff fleet operations. Siloed tenants need fan-out migrations, per-tenant backups, connection pooling and drift reporting. Without tooling and on-call capacity for that, keep everything pooled.
  • Workloads depend heavily on cross-tenant queries in the operational store. Row level security and silos both work against that pattern. Move such queries to a separate analytics store first.
  • Isolation stops at the database. If caches, queues and compute stay shared and cannot be separated, a "siloed" database may promise customers more isolation than you actually deliver.

How does tenant context propagate across services and async messages?

Tenant identity enters the system once, at the edge, from a verified token claim. It never comes from a URL parameter, query string, header the client controls, or request body. Those values are attacker-controlled: changing ?tenant=acme to ?tenant=globex is the cheapest cross-tenant attack there is. If a body field names a tenant, the service should compare it to the token claim and reject the request on mismatch, not trust it.

client --JWT--> [edge: verify sig, read tenant claim]
                   | (1) tenant in signed internal token/header
                   v
             [orders svc] --(2) forward same context--> [billing svc]
                   |                                         |
                   | (3) tenant_id field in event body       | (4) lookup
                   v                                         v
             [broker] --> [consumer: set context]      [routing catalog]
                                   |                    /            \
                                   +----(4)-------> pooled DB      silo DB
                                                    (RLS on)     (per tenant)

Service-to-service calls forward the original context over authenticated channels, such as mTLS plus a propagated or re-minted token. They never forward a bare header that any internal caller could set. Async hops are where context usually gets lost. Thread-local or request-scoped context does not survive a broker. Every event and queue message therefore needs an explicit tenant_id field, and consumers must establish context from that field before touching storage or the routing catalog. A message without a tenant should go to a dead-letter queue, not be processed under a default.

Caches leak quietly. A key like invoice:123 or feature-flags is shared across tenants, so whichever tenant fills it first serves everyone. Prefix every cache key with the tenant ID, including keys for "global-looking" data that turns out to vary per tenant.

import contextvars

current_tenant = contextvars.ContextVar("current_tenant")

class MissingTenant(Exception):
    pass

def check_body_tenant(claims: dict, body: dict) -> str:
    # The tenant comes only from the verified token claim. A body field
    # may name a tenant, but it must match the claim.
    tenant = claims["tenant_id"]
    if body.get("tenant_id") not in (None, tenant):
        raise PermissionError("tenant mismatch")
    return tenant

def cache_key(kind: str, obj_id: str) -> str:
    # Put the tenant in every key. "invoice:123" alone can return
    # another tenant's invoice.
    return f"t:{current_tenant.get()}:{kind}:{obj_id}"

def handle_message(msg: dict, process, dead_letter) -> None:
    tenant = msg.get("tenant_id")
    if not tenant:
        # Never fall back to a default tenant. Park the message for inspection.
        dead_letter(msg, reason="missing tenant_id")
        return
    token = current_tenant.set(tenant)
    try:
        # Storage and routing-catalog lookups read current_tenant from here on.
        process(msg)
    finally:
        current_tenant.reset(token)

A message consumer that sets tenant context from the explicit tenant_id field and dead-letters messages without one, a check that rejects a body tenant that differs from the token claim, and cache keys that include the tenant.

How does row level security enforce tenant isolation in PostgreSQL?

A policy is a predicate PostgreSQL appends to every query against the table, so isolation no longer depends on each query remembering a filter. Key it on a custom session setting: CREATE POLICY tenant_isolation ON orders USING (tenant_id = current_setting('app.tenant_id')::uuid) WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);. USING filters reads, updates and deletes. WITH CHECK rejects writes that would place a row under another tenant. Then run ALTER TABLE orders ENABLE ROW LEVEL SECURITY; and ALTER TABLE orders FORCE ROW LEVEL SECURITY;.

Scope the setting to the transaction, not the connection. Use SET LOCAL app.tenant_id = '…' or set_config('app.tenant_id', '…', true) after BEGIN. A transaction-mode pooler hands the same server session to different clients between transactions. A session-level SET would leak tenant A's identity into tenant B's next transaction. A transaction-local value is discarded at commit or rollback.

Who the policies apply to matters as much as the policies themselves. Table owners skip policies unless the table has FORCE ROW LEVEL SECURITY. Superusers and roles with BYPASSRLS skip them even when forcing is on. The application should therefore connect as a dedicated role that has neither attribute and owns none of the tables. Migrations should run under a separate owner role.

The trade-offs:

  • Planning: Index tenant_id, usually as the leading column. Non-leakproof functions in your own predicates cannot be evaluated ahead of the policy check, which can produce worse plans.
  • Debugging: A missing setting errors if you call current_setting without its missing_ok argument, which is the safer default. A wrong setting just returns zero rows, and that looks like a data bug rather than an access problem.
  • Accidental bypass: Backfills, ad-hoc fixes and cron jobs often run as the owner or a superuser. Those paths silently see and change every tenant's data.
-- Migration/owner role owns the tables; the app role owns nothing and cannot bypass RLS.
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE app_user LOGIN PASSWORD 'change-me' NOSUPERUSER NOBYPASSRLS;

CREATE TABLE orders (
  id          uuid PRIMARY KEY,
  tenant_id   uuid NOT NULL,
  total_cents bigint NOT NULL
);
ALTER TABLE orders OWNER TO app_owner;

-- tenant_id leads so the policy predicate can use the index.
CREATE INDEX orders_tenant_id_idx ON orders (tenant_id, id);

-- No missing_ok argument: an unset tenant raises an error instead of quietly matching nothing.
CREATE POLICY tenant_isolation ON orders
  USING      (tenant_id = current_setting('app.tenant_id')::uuid)  -- filters SELECT/UPDATE/DELETE
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid); -- rejects writes into another tenant

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;  -- the owner is filtered too (superusers/BYPASSRLS still are not)

GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_user;

-- Per request, connected as app_user (safe behind a transaction-mode pooler):
BEGIN;
-- Third argument true = transaction-local, equivalent to SET LOCAL.
SELECT set_config('app.tenant_id', '7b1e4c2a-0d3f-4a8e-9c61-2f5b8d0e1a11', true);
SELECT id, total_cents FROM orders;  -- only this tenant's rows are visible
COMMIT;  -- value is discarded here, so the next client on this server session cannot inherit it

A tenant-isolation policy keyed on current_setting('app.tenant_id'), with RLS enabled and forced on a table owned by a separate role, and the tenant set per transaction with set_config(..., true) so pooled sessions never carry one tenant's identity into another's transaction.

Why isn't 'remember to add WHERE tenant_id' enough?

A pooled service usually has hundreds of query paths written by dozens of engineers over years. A tenant filter enforced only in application code has to be correct on every one of them, every time. One missed predicate in a new endpoint, an ORM eager-load, or a reporting query returns rows from every customer in the table. In a pooled model, the blast radius of a single bug is the whole customer base.

Layer the defenses

  • Lead with tenant_id in keys and indexes. Use composite primary keys such as (tenant_id, order_id) and put tenant_id first in secondary indexes. Unscoped queries then fall back to full scans and become slow, so they show up in query review. Foreign keys that include tenant_id make it structurally impossible to attach one tenant's child row to another tenant's parent.
  • Use tenant-scoped repositories. Data access goes through helpers that take tenant context as a required argument. Raw query access should be uncommon and easy to grep for.
  • Write adversarial tests. For each repository and endpoint, create data for tenant A and then try to read, update and delete it as tenant B. The expected result is zero rows or a 404.

Make privileged paths explicit

Admin consoles, global search and aggregated reporting need cross-tenant access. Give them their own database role and code path, require a stated reason, and log who queried which tenants. That turns an implicit bypass into a reviewable capability.

When cross-tenant tests run in CI, a leak shows up as a failed build. Without them, the same leak may surface as a customer report and a forensic investigation.

-- PostgreSQL: tenant_id leads every key so tenant scoping is structural.

CREATE TABLE orders (
    tenant_id   uuid        NOT NULL,
    order_id    bigint      NOT NULL,
    customer_id bigint      NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now(),
    -- Composite PK: lookups by order_id alone cannot use this index efficiently.
    PRIMARY KEY (tenant_id, order_id)
);

CREATE TABLE order_items (
    tenant_id  uuid    NOT NULL,
    order_id   bigint  NOT NULL,
    line_no    int     NOT NULL,
    sku        text    NOT NULL,
    quantity   int     NOT NULL CHECK (quantity > 0),
    PRIMARY KEY (tenant_id, order_id, line_no),
    -- The FK includes tenant_id, so an item for tenant B cannot reference
    -- an order owned by tenant A. The database rejects the insert.
    FOREIGN KEY (tenant_id, order_id)
        REFERENCES orders (tenant_id, order_id)
        ON DELETE CASCADE
);

-- Secondary indexes also lead with tenant_id. A query that omits the
-- tenant predicate cannot seek on this index, which makes it stand out
-- in EXPLAIN output and query review.
CREATE INDEX orders_tenant_customer_idx
    ON orders (tenant_id, customer_id, created_at);

-- Separate role for privileged cross-tenant paths (admin, reporting).
-- The application role gets ordinary DML, the reporting role gets read-only
-- access, and connections made with the reporting role can be audited separately.
CREATE ROLE app_service   NOLOGIN;
CREATE ROLE cross_tenant_reporting NOLOGIN;
GRANT SELECT, INSERT, UPDATE, DELETE ON orders, order_items TO app_service;
GRANT SELECT ON orders, order_items TO cross_tenant_reporting;

This PostgreSQL schema puts tenant_id first in primary keys, foreign keys and indexes so cross-tenant references are rejected by the database, and it gives privileged cross-tenant reporting a separate role that can be audited on its own.

How does a tenant routing catalog let tenants move between models?

The catalog is a small, authoritative table that maps each tenant, per service, to a placement: the cluster, database and schema that hold its data. Services resolve it at request time, using the tenant ID from the propagated context, and open a connection to the returned target. Because no service hardcodes where a tenant lives, promoting a large tenant from pooled to siloed is a data operation, not a code change. The query logic stays the same. Only the target it runs against changes.

Resolution sits on the hot path, so cache placements in each service with a short TTL. Also publish an invalidation event whenever a row changes. The TTL bounds how stale a placement can get if the event is lost. The event makes cutover fast in the normal case.

Moving a tenant is a project with distinct phases:

  1. Copy the tenant's rows into the new silo from a consistent snapshot.
  2. Keep the copy current with dual writes or change-data capture. CDC is usually safer because application code does not need to handle partial failures.
  3. Verify row counts and checksums per table, and replay sampled reads against both stores.
  4. Cut over by updating the catalog entry. Briefly pause writes for that tenant so no transaction lands on the old placement.
  5. Keep a rollback path. Leave the old placement intact and reverse-replicate until you trust the new one, so rolling back is another catalog update.

Analytics usually goes the other way. Siloed operational stores feed a pooled warehouse where every table carries tenant_id and the same row-level policies apply. Cross-tenant reporting stays possible without weakening isolation in the operational stores.

-- Authoritative tenant routing catalog (PostgreSQL).
-- One row per (tenant, service). Services cache rows and resolve at request time.
CREATE TABLE tenant_placement (
  tenant_id     text        NOT NULL,
  service       text        NOT NULL,
  cluster       text        NOT NULL,  -- e.g. 'pg-pool-02' or 'pg-silo-acme'
  database_name text        NOT NULL,
  schema_name   text        NOT NULL,
  model         text        NOT NULL CHECK (model IN ('pooled', 'siloed')),
  previous      jsonb,                 -- last placement, kept for rollback
  version       bigint      NOT NULL DEFAULT 1,
  updated_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, service)
);

-- Request-time lookup (on a cache miss or after an invalidation event).
SELECT cluster, database_name, schema_name, version
FROM tenant_placement
WHERE tenant_id = 'tenant-acme' AND service = 'orders';

-- Cutover: run only after copy, CDC catch-up and verification have passed,
-- and while writes for this tenant are paused.
BEGIN;
UPDATE tenant_placement
SET previous      = jsonb_build_object('cluster', cluster,
                      'database_name', database_name, 'schema_name', schema_name),
    cluster       = 'pg-silo-acme',
    database_name = 'orders',
    schema_name   = 'public',
    model         = 'siloed',
    version       = version + 1,
    updated_at    = now()
WHERE tenant_id = 'tenant-acme' AND service = 'orders';
-- Tell service caches to drop this entry. Delivered only if the transaction commits.
-- If the message is lost, the cache TTL bounds how stale an entry can get.
SELECT pg_notify('tenant_placement_changed', 'tenant-acme:orders');
COMMIT;
-- Rollback is the same kind of update, restoring the values in "previous".

A PostgreSQL routing catalog that maps each tenant and service to a cluster, database and schema, with the lookup query services run and a cutover transaction that moves a tenant to a silo, saves the old placement for rollback and notifies caches to invalidate.

What does each model cost to operate day to day?

Day-to-day cost diverges once you count operations instead of tables.

Concern Pooled Siloed
Schema migrations One run; must stay compatible with code already deployed N fan-out runs; needs per-tenant status, retries and a drift report when some tenants fail midway
Backup and restore One backup; restoring one tenant means loading a copy and extracting its rows Per-tenant restore is native
Offboarding Delete across every table, then verify zero rows by tenant_id Drop the database; verify it no longer exists
Connections One shared pool Pools multiply per tenant
Monitoring Needs tenant_id on metrics and query tags Database metrics are already per tenant

In both models, deleted data persists in backups until retention expires, so "verified deletion" includes that window.

Illustrative estimate (assumed numbers, not a benchmark): connections = tenants × service instances × pool size per tenant. With 200 tenants, 6 instances and a pool size of 5, that is 6,000 connections. That is why siloed services usually need a connection pooler in front.

Pooled services contain noisy neighbors in four ways:

  • Per-tenant rate limits at the API edge.
  • Per-transaction SET LOCAL statement_timeout.
  • Exports and backfills moved to separate workers or read replicas.
  • Per-tenant latency and query-time metrics, so you can see who consumes capacity.

These mitigations are enough when one tenant's spikes stay contained and throttling rarely hits well-behaved tenants. Silo the tenant or service when any of these hold:

  • A tenant hits limits during legitimate use.
  • You keep raising timeouts for one customer.
  • One tenant dominates table size and vacuum time.
  • Contracts require isolation or restore times that pooled extraction cannot meet.

What are the alternatives?

Per-service placement with a routing catalog is one point in a wider design space. The main alternatives:

  • One model for the whole platform. Every service is pooled, or every service is siloed. This is simpler to reason about and gives on-call a single runbook shape. The cost is either weaker isolation everywhere or fleet-scale operations everywhere.
  • Application-level filtering only. Pooled tables without row level security, relying on repositories and code review to add tenant_id. Less database configuration, but a single missed predicate exposes every tenant, as described above.
  • Stack per tenant (cell or deployment per tenant). Each tenant, or each group of tenants, gets its own copy of the full application, including databases, caches, queues and compute. Isolation extends beyond the data layer and avoids the "siloed database, shared everything else" trap. Deployments, upgrades and monitoring multiply with the number of cells.
  • Sharding by tenant. Pooled tables are distributed across several database nodes with tenant_id as the shard key. This keeps pooled economics while spreading load, but isolation remains logical, and moving a hot tenant still requires a rebalancing operation.
  • Bridge (schema per tenant) everywhere. Gives per-tenant dumps and namespace separation without separate instances. As covered earlier, compute stays shared and migration fan-out grows with tenant count.
  • Per-tenant encryption keys in pooled storage. Encrypting sensitive columns with a key per tenant limits what a leaked row reveals and allows crypto-shredding on offboarding. It complements row level security but does not replace it, and it complicates indexing and querying encrypted columns.

These can be combined. A common shape is pooled with row level security by default, per-tenant encryption for the most sensitive fields, and a dedicated cell for the small number of customers whose contracts require full-stack isolation.

How can it save engineering time?

The time savings come from making isolation and placement structural instead of a matter of discipline:

  • Fewer filter reviews. With row level security forced on pooled tables, reviewers no longer need to confirm that every new query includes a tenant predicate. A missing filter returns only the current tenant's rows instead of everyone's.
  • Leaks caught in CI, not in incidents. Adversarial cross-tenant tests turn a potential security investigation into a failed build that the author fixes before merge.
  • Tenant moves without code changes. Because services resolve placement through the catalog, promoting a tenant to a silo or moving it for residency is a repeatable data runbook. It does not require changes to every service that touches that tenant.
  • No over-siloing. Deciding per service keeps fan-out migrations, per-tenant backups and connection pooling confined to the few services that need them. The rest run one migration and one backup.
  • Less debugging of async bugs. Explicit tenant_id fields on messages and dead-lettering of messages without one surface context bugs immediately. Without them, the same bug shows up later as data written under the wrong tenant.

Illustrative estimate (assumed inputs): assume a platform with 10 services, of which 2 need siloing for some tenants, and 50 siloed tenants in each of those 2 services. If every service were siloed, each schema change would mean 500 per-tenant migration runs to track (10 services × 50 tenants). With per-service placement, the 8 pooled services need 8 runs and the 2 siloed services need 100. The total is 108 runs instead of 500, which reduces the retry and drift-report work on every release by a similar proportion. The actual savings depend on how much of your migration process is automated.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to multi-tenant microservices database, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.