Multi-Tenanted Documents
Marten supports multi-tenancy to provide data isolation between tenants, aka groups of users. In effect, this allows scoping storage operations, such as persisting and loading data, so that no tenant can access data of others. Marten provides multi-tenancy at the logical level, by associating data records with a tenant identifier. In addition, multi-tenancy through separate databases is supported via separate database tenancy strategies.
By default, Marten operates in single-tenancy mode (TenancyStyle.Single) with multi-tenancy disabled.
Once configured for multi-tenancy, Marten exposes it via sessions (IQuerySession, IDocumentSession) scoped to specific tenants, as well as ForTenant() on a session and tenant overloads of BulkInsertAsync().
Scoping Sessions to Tenancy
The following sample demonstrates scoping a document session to tenancy identified as tenant1. With multi-tenancy enabled, the persisted User objects are then associated with the tenancy of the session.
// Write some User documents to tenant "tenant1"
using (var session = store.LightweightSession("tenant1"))
{
session.Store(new User { UserName = "Bill" });
session.Store(new User { UserName = "Lindsey" });
await session.SaveChangesAsync();
}As with storing, the load operations respect tenancy of the session.
// When you query for data from the "tenant1" tenant,
// you only get data for that tenant
using (var query = store.QuerySession("tenant1"))
{
(await query.Query<User>()
.OrderBy(x => x.UserName)
.Select(x => x.UserName)
.ToListAsync())
.ShouldHaveTheSameElementsAs("Bill", "Lindsey");
}To write to a different tenant from the same session, use session.ForTenant("tenant2").Store(doc). IDocumentStore.BulkInsertAsync() has an overload that takes a tenant id.
Default Tenancy
With multi-tenancy enabled, Marten associates each record with a tenancy. If no explicit tenancy is specified, either via policies, mappings, scoped sessions or overloads, Marten will default to StorageConstants.DefaultTenantId with a constant value of *DEFAULT*.
The following sample demonstrates persisting documents as non-tenanted, under default tenant and other named tenants then querying them back in a session scoped to a specific named tenant and default tenant.
using var store = DocumentStore.For(opts =>
{
opts.DatabaseSchemaName = "mixed_multi_tenants_conjoined";
opts.Connection(ConnectionSource.ConnectionString);
opts.Schema.For<Target>().MultiTenanted(); // tenanted
opts.Schema.For<User>(); // non-tenanted
opts.Schema.For<Issue>().MultiTenanted(); // tenanted
});
await store.Advanced.Clean.DeleteAllDocumentsAsync();
// Add documents to tenant Green
var greens = Target.GenerateRandomData(10).ToArray();
await store.BulkInsertAsync("Green", greens);
// Add documents to tenant Red
var reds = Target.GenerateRandomData(11).ToArray();
await store.BulkInsertAsync("Red", reds);
// Add non-tenanted documents
// User is non-tenanted in schema
var user1 = new User { UserName = "Frank" };
var user2 = new User { UserName = "Bill" };
await store.BulkInsertAsync(new[] { user1, user2 });
// Add documents to default tenant
// Note that schema for Issue is multi-tenanted hence documents will get added
// to default tenant if tenant is not passed in the bulk insert operation
var issue1 = new Issue { Title = "Test issue1" };
var issue2 = new Issue { Title = "Test issue2" };
await store.BulkInsertAsync(new[] { issue1, issue2 });
// Create a session with tenant Green
using (var session = store.QuerySession("Green"))
{
// Query tenanted document as the tenant passed in session
(await session.Query<Target>().CountAsync()).ShouldBe(10);
// Query non-tenanted documents
(await session.Query<User>().CountAsync()).ShouldBe(2);
// Query documents in default tenant from a session using tenant Green
(await session.Query<Issue>().CountAsync(x => x.TenantIsOneOf(StorageConstants.DefaultTenantId))).ShouldBe(2);
// Query documents from tenant Red from a session using tenant Green
(await session.Query<Target>().CountAsync(x => x.TenantIsOneOf("Red"))).ShouldBe(11);
}
// create a session without passing any tenant, session will use default tenant
using (var session = store.QuerySession())
{
// Query non-tenanted documents
(await session.Query<User>().CountAsync()).ShouldBe(2);
// Query documents in default tenant
// Note that session is using default tenant
(await session.Query<Issue>().CountAsync()).ShouldBe(2);
// Query documents on tenant Green
(await session.Query<Target>().CountAsync(x => x.TenantIsOneOf("Green"))).ShouldBe(10);
// Query documents on tenant Red
(await session.Query<Target>().CountAsync(x => x.TenantIsOneOf("Red"))).ShouldBe(11);
}In some cases, You may want to disable using the default tenant for storing documents, set StoreOptions.Advanced.DefaultTenantUsageEnabled to false. With this option disabled, Tenant (non-default tenant) should be passed via method argument or SessionOptions when creating a session using document store. Marten will throw an exception DefaultTenantUsageDisabledException if a session is created using default tenant.
WARNING
Marten.Exceptions.DefaultTenantUsageDisabledException now derives from JasperFx.Events.DefaultTenantUsageDisabledException rather than from MartenException, so code that handles this refusal across Critter Stack stores can catch the one shared type. If you were relying on a broad catch (MartenException) to handle it, catch the exception itself — or the JasperFx base — instead.
Querying Multi-Tenanted Documents
Inside the LINQ provider, when you open a session for a specific tenant like so:
// When you query for data from the "tenant1" tenant,
// you only get data for that tenant
using (var query = store.QuerySession("tenant1"))
{
(await query.Query<User>()
.OrderBy(x => x.UserName)
.Select(x => x.UserName)
.ToListAsync())
.ShouldHaveTheSameElementsAs("Bill", "Lindsey");
}Marten will automatically filter the LINQ query for the current tenant if the current document type is tenanted. However, if you want to query across multiple tenants or across documents for any tenant, you're still in luck with the TenantIsOneOf() LINQ filter:
// query data for a selected list of tenants
var actual = await query.Query<Target>().Where(x => x.TenantIsOneOf("Green", "Red") && x.Flag)
.OrderBy(x => x.Id).Select(x => x.Id).ToListAsync();Or the AnyTenant() filter:
// query data across all tenants
var actual =(await query.Query<Target>().Where(x => x.AnyTenant() && x.Flag)
.OrderBy(x => x.Id).Select(x => x.Id).ToListAsync());Configuring Tenancy
The two values of the TenancyStyle enum that Marten uses for logical (single-database) tenancy are:
Single, no multi-tenancyConjoined, multi-tenancy through tenant id
Multi-tenancy through separate databases is implemented via separate tenancy strategies (not a TenancyStyle enum value).
Tenancy can be configured at the store level, applying to all documents or, at the most fine-grained level, on individual documents.
Partitioning by Tenant 7.26
WARNING
This is an "opt in" model so as to not impact existing users. Moving from non-partitioned to partitioned tables may require some system downtime as this requires some potentially destructive changes to the database as Marten will have to copy, drop, and recreate the document storage.
If you are using conjoined multi-tenancy with Marten, you may be able to achieve a significant performance gain by opting into PostgreSQL table partitioning based on the tenant id. This can be a way to achieve greater scalability without having to take on the extra deployment complexity that comes with multi-tenancy through separate databases. In effect, this lets PostgreSQL store data in smaller, tenant specific table partitions.
To enable table partitioning by the tenant id for all document types, use this syntax:
storeOptions.Policies.AllDocumentsAreMultiTenantedWithPartitioning(x =>
{
// Selectively by LIST partitioning
x.ByList()
// Adding explicit table partitions for specific tenant ids
.AddPartition("t1", "T1")
.AddPartition("t2", "T2");
// OR Use LIST partitioning, but allow the partition tables to be
// controlled outside of Marten by something like pg_partman
// https://github.com/pgpartman/pg_partman
x.ByExternallyManagedListPartitions();
// OR Just spread out the tenant data by tenant id through
// HASH partitioning
// This is using three different partitions with the supplied
// suffix names
x.ByHash("one", "two", "three");
// OR Partition by tenant id based on ranges of tenant id values
x.ByRange()
.AddRange("north_america", "na", "nazzzzzzzzzz")
.AddRange("asia", "a", "azzzzzzzz");
// OR use RANGE partitioning with the actual partitions managed
// externally
x.ByExternallyManagedRangePartitions();
}, PrimaryKeyTenancyOrdering.TenantId_Then_Id);The primary key of a partitioned, conjoined table is (tenant_id, id) (PrimaryKeyTenancyOrdering.TenantId_Then_Id), both here and with the per-document MultiTenantedWithPartitioning(). Before Marten 10 the overload without a PrimaryKeyTenancyOrdering argument used (id, tenant_id) instead; pass PrimaryKeyTenancyOrdering.Id_Then_TenantId to keep that primary key.
To enable partitioning for a specific document type, use this option:
var store = DocumentStore.For(opts =>
{
opts.Connection("some connection string");
opts.Schema.For<User>().MultiTenantedWithPartitioning(x =>
{
x.ByExternallyManagedListPartitions();
});
});And lastly, if you need to use a mix of tenanted and global document types, but still want to use a consistent partitioning scheme for the document types that are tenanted, you have this option:
var store = DocumentStore.For(opts =>
{
opts.Connection("some connection string");
// This document type is global, so no tenancy
opts.Schema.For<Region>().SingleTenanted();
// We want these document types to be tenanted
opts.Schema.For<Invoice>().MultiTenanted();
opts.Schema.For<User>().MultiTenanted();
// Apply table partitioning by tenant id to each document type
// that is using conjoined multi-tenancy
opts.Policies.PartitionMultiTenantedDocuments(x =>
{
x.ByExternallyManagedListPartitions();
});
});Tenancy Through Policies
Tenancy can be configured through Document Policies, accessible via StoreOptions.Policies. The following sample demonstrates setting the default tenancy to TenancyStyle.Conjoined for all documents.
storeOptions.Policies.AllDocumentsAreMultiTenanted();
// Shorthand for
// storeOptions.Policies.ForAllDocuments(_ => _.TenancyStyle = TenancyStyle.Conjoined);Tenancy At Document Level & Policy Overrides
Tenancy can be configured at a document level through document mappings. This also enables overriding store-level configurations applied through Document Policies. The following sample demonstrates setting, through StoreOptions the tenancy for Target to TenancyStyle.Conjoined, making it deviate from the configured default policy of TenancyStyle.Single.
storeOptions.Policies.ForAllDocuments(x => x.TenancyStyle = TenancyStyle.Single);
storeOptions.Schema.For<Target>().MultiTenanted();You can also do it the other way round, having the default set to TenancyStyle.Conjoined and overriding it to TenancyStyle.Single for Target.
storeOptions.Policies.ForAllDocuments(x => x.TenancyStyle = TenancyStyle.Conjoined);
storeOptions.Schema.For<Target>().SingleTenanted();Make all documents start their index by tenant_id
When using conjoined multi tenancy it is often beneficial to have database indexes start with tenant_id. Even when a tenant is specified on the session and PostgreSQL can already restrict queries to the relevant table partition, this does not always fully isolate a single tenant. With hash partitioning, multiple tenants can end up in the same partition, so indexes that do not start with tenant_id may still scan entries belonging to other tenants. By consistently prefixing tenant_id on all indexes, either globally through policies or per document type, Marten allows PostgreSQL to efficiently filter within a partition as well, improving index selectivity and reducing unnecessary index scans in databases with many tenants.
This is opt in. With it on, a conjoined document's computed indexes start with tenant_id, and a unique index scoped per tenant leads with tenant_id instead of ending with it. A unique index scoped TenancyScope.Global never gets tenant_id, so it stays unique across tenants.
When to turn it on
Turn it on for a large conjoined table that's queried tenant by tenant, especially with many tenants. What it costs: turning it on rebuilds every computed index on the table, which blocks writes while each one builds, so run that migration in a maintenance window. A query across tenants (AnyTenant(), or reporting reads without a tenant) can no longer seek on those indexes, because their first column is unconstrained. That's why it isn't the default (#6144).
These are the settings:
_.Policies.ForAllDocuments(x =>
{
x.StartIndexesByTenantId = true;
});
_.Schema.For<User>()
.StartIndexesByTenantId()
.Index(x => x.UserName);Marten-Managed Table Partitioning by Tenant 7.28
Use this when you have many tenants, use conjoined tenancy, and want a table partition per tenant. Marten stores each tenant id and its partition name in a table it manages, and creates the partitions for every conjoined document type.
Here's a sample of using this feature. First, the configuration is:
var builder = Host.CreateApplicationBuilder();
builder.Services.AddMarten(opts =>
{
opts.Connection(builder.Configuration.GetConnectionString("marten"));
// Make all document types use "conjoined" multi-tenancy -- unless explicitly marked with
// [SingleTenanted] or explicitly configured via the fluent interfce
// to be single-tenanted
opts.Policies.AllDocumentsAreMultiTenanted();
// It's required to explicitly tell Marten which database schema to put
// the mt_tenant_partitions table
opts.Policies.PartitionMultiTenantedDocumentsUsingMartenManagement("tenants");
});The tenant to partition name mapping will be stored in a table created by Marten called mt_tenant_partitions with two columns:
partition_name-- really the partition table suffix name. If you want a one to one relationship, this is the tenant idpartition_value-- the value of the tenant id
Before the application is initialized, it's possible to load or delete data directly into these tables. At runtime, you can add new tenant id partitions with this helper API on IDocumentStore.Advanced:
await theStore
.Advanced
// This is ensuring that there are tenant id partitions for all multi-tenanted documents
// with the named tenant ids
.AddMartenManagedTenantsAsync(CancellationToken.None, "a1", "a2", "a3");The API above will try to add any missing table partitions to all known document types. There is also a separate overload that will take a Dictionary<string, string> argument that maps tenant ids to a named partition suffix. This might be valuable if you frequently query for multiple tenants at one time. We think that the 1 to 1 tenant id to partition model is a good default approach though.
TIP
You may want to tell Marten about all possible document types upfront, with opts.RegisterDocumentType<T>() or opts.Schema.For<T>(), so that it is better able to add the partitions for each tenant id as needed.
To exempt document types from having partitioned tables, such as for tables you expect to be so small that there's no value and maybe even harm by partitioning, you can use either an attribute on the document type:
[DoNotPartition]
public class DocThatShouldBeExempted1
{
public Guid Id { get; set; }
}or exempt a single document type through the fluent interface:
Options.Schema.For<DocThatShouldBeExempted2>().DoNotPartition();Partitioning your own tables by tenant 10.0
If you add your own tables to the store through opts.Storage.ExtendedSchemaObjects and want them partitioned per tenant the same way as the document tables, use opts.Storage.PartitionPerTenant(table):
var table = new Table(new DbObjectName(_schema, "ledger_entries"));
table.AddColumn<Guid>("id").AsPrimaryKey();
table.AddColumn<string>("tenant_id").NotNull();
table.AddColumn<int>("amount");
// One LIST partition per tenant, created as tenants are added,
// and left alone by later schema migrations
opts.Storage.PartitionPerTenant(table);The table needs a tenant_id column. Marten adds it to the table's primary key, because PostgreSQL requires the partition key there, and adds the table to ExtendedSchemaObjects if you haven't already. AddMartenManagedTenantsAsync() then creates each tenant's partition in your table along with the document tables.
You can wire this up by hand, but don't skip IgnorePartitionsInMigration. Without it, a schema migration compares the partitions it expects with the ones that exist, and on a database that already has tenants it can decide to rebuild the whole table through a _temp copy. PartitionPerTenant() sets it for you, just like Marten does for its own tables.
The store has to use Marten-managed tenant partitioning (Policies.PartitionMultiTenantedDocumentsUsingMartenManagement(), Events.UseTenantPartitionedEvents or sharded tenancy). If it doesn't, building the store throws.
Deleting Data For a Single Tenant
WARNING
This is permanent, and may not be the fastest operation in bigger databases. You may want to do this in off peak hours.
INFO
This API is probably mostly useful for the case of using "Conjoined" tenancy. In the case of doing multi-tenancy through a separate database for each tenant, just remove that database.
If you need to delete all the data for a single named tenant, you can do that in one step with this API:
public static async Task delete_all_tenant_data(IDocumentStore store, CancellationToken token)
{
await store.Advanced.DeleteAllTenantDataAsync("AAA", token);
}This API will:
- Delete all event and event stream data for the named tenant
- Delete tenant specific data out of any document table that is configured for
Conjoinedmulti-tenancy for that named tenant
This API is able to differentiate between documents that are configured for tenancy and document types that are global.
Row Level Security 8.31
Conjoined tenancy filters rows by tenant_id at Marten's query layer. PostgreSQL Row Level Security (RLS) adds a database-enforced safety net so any connection — including raw SQL, ad-hoc analytics, or code that bypasses Marten's session — can only see rows belonging to the current tenant.
When you opt in, Marten will:
- Call
set_config('<setting>', '<tenantId>', false)on every opened session connection, so PostgreSQL knows which tenant the session is acting as. - On conjoined-tenancy document tables, emit
ENABLE ROW LEVEL SECURITY,FORCE ROW LEVEL SECURITY, and amarten_tenant_isolationpolicy that restricts visible rows totenant_id = current_setting('<setting>'). These are produced through Marten's normal schema migration pipeline.
FORCE ROW LEVEL SECURITY ensures the policy applies to the table owner as well. Note that PostgreSQL superusers always bypass RLS regardless of the FORCE flag — run your application (and any ad-hoc verification) as a non-superuser role to see RLS in effect.
Enable for the whole store
options.UseRowLevelSecurity();The default GUC setting name is app.tenant_id. Pass a custom name when it conflicts with an existing GUC naming scheme in your database:
options.UseRowLevelSecurity("security.tenant");The setting name must be a qualified PostgreSQL custom GUC identifier of the form prefix.name using letters, digits, and underscores. Marten validates this at configuration time because the setting name is interpolated into CREATE POLICY ... current_setting('<name>') DDL. The tenant id is sent as a bound parameter so it accepts any value.
Per-document overrides
You can selectively exclude individual document types from RLS when it would otherwise apply store-wide — useful for tables such as audit logs, read-only reference data, or anything explicitly intended to be accessible across tenants:
options.UseRowLevelSecurity();
options.Schema.For<Target>().MultiTenanted().DisableRowLevelSecurity();Or use a different GUC setting name for a specific document type:
options.UseRowLevelSecurity();
options.Schema.For<Target>().MultiTenanted().UseRowLevelSecurity("app.org_id");The resolution order per mapping is: explicit mapping-level override, then the store-level setting, falling back to "app.tenant_id".
Caveat: Marten only sets the store-level GUC on each opened session connection. If you override a mapping to use a different setting name, your application is responsible for populating that GUC itself on any session that queries that document — Marten writes the policy but does not automatically set the custom GUC.
Reconfiguring and rolling back
Toggling RLS off store-wide, or adding DisableRowLevelSecurity() on a mapping that was previously RLS-enabled, produces a DROP POLICY delta on the next schema migration. Changing the setting name (globally or per mapping) is detected by comparing the policy expression against pg_get_expr(polqual, ...) and triggers a drop-and-recreate.
Limitations
- RLS applies only to
TenancyStyle.Conjoineddocument tables. Single-tenancy and per-database tenancy are unchanged. - Event store tables (
mt_events,mt_streams) do not currently get RLS policies.
Implementation Details
Within one database, Marten has two tenancy styles: single and conjoined. Database-per-tenant tenancy is configured separately; see Multi-Tenancy with Database per Tenant.
Conjoined Tenancy
The conjoined (TenancyStyle.Conjoined) multi-tenancy in Marten is implemented by associating each record with a tenant identifier. As such, Marten does not guarantee or enforce data isolation via database access privileges.
Effects On Schema
Once enabled, TenancyStyle.Conjoined introduces a tenant_id column to Marten tables. This column, of type varchar with the default value of *DEFAULT* (default tenancy), holds the tenant identifier associated with the record. Furthermore, Marten creates an index on this column by default.
A unique index may optionally be scoped per tenant (see unique indexes).

