Shared-Realm Multi-Tenancy in Keycloak
A zero-prior-knowledge guide to running thousands of separate customer organizations out of a single Keycloak realm — using groups, roles, and careful discipline instead of one realm per tenant.
Imagine a large accounting firm that serves thousands of separate small-business clients. It would be absurd to build a brand-new, physically separate office building for every single client — instead, the firm operates from one shared building, with clearly labeled floors, locked filing cabinets, and strict internal rules about which staff member can open which client’s records. Everyone works under one roof, but nothing meant for one client is ever visible to another. This is exactly the challenge Shared-Realm Multi-Tenancy solves inside Keycloak: serving many separate customer organizations, called tenants, from a single realm, rather than giving each one its own entirely separate realm. This article explains, from first principles, what this approach actually means, how it is structured, and the very real discipline it demands to keep one tenant’s world properly separated from another’s.
Foundations
Core Concepts
Before comparing multi-tenancy approaches, it helps to be precise about what a “tenant” actually is, and why Keycloak has to make a deliberate architectural choice about how to host many of them.
What is a tenant?
In a multi-tenant application, a tenant is a distinct customer organization — a separate company, team, or account — whose users, data, and configuration must remain logically isolated from every other tenant sharing the same underlying software. A single software-as-a-service product might serve thousands of tenants, each believing, correctly, that their data and users are entirely their own, even though they are all running on the exact same infrastructure underneath.
Two fundamentally different ways to model tenants in Keycloak
Keycloak offers two broad architectural approaches for supporting multiple tenants. In realm-per-tenant, each tenant gets its own completely separate Keycloak realm, with its own isolated users, clients, and settings. In Shared-Realm Multi-Tenancy, every tenant’s users live together inside one single realm, and tenant separation is instead achieved through internal structures — most commonly Groups — within that shared realm, rather than through Keycloak’s own realm boundary.
Realm-per-tenant is like giving each accounting client their own separate, physically distinct office building, complete with its own front door, its own staff, and its own filing system. Shared-Realm Multi-Tenancy is like the single shared office building described earlier — one front door, one shared staff directory, but strict internal walls, labeled cabinets, and access rules ensuring each client’s specific records only reach the right eyes.
Why anyone would choose the shared-realm approach at all
Realm-per-tenant is conceptually simple and offers very strong, structural isolation, but it does not scale gracefully to very large numbers of tenants — creating, configuring, and maintaining tens of thousands of individual realms becomes a genuinely heavy operational burden. Shared-Realm Multi-Tenancy exists specifically for organizations that need to support a very large number of tenants efficiently, accepting a different set of trade-offs in exchange for that scalability.
Realm-Per-Tenant
Each tenant gets a fully separate realm. Simple to reason about, but heavy at very large scale.
Shared-Realm Multi-Tenancy
All tenants share one realm. Scales efficiently, but isolation must be deliberately engineered rather than structurally guaranteed.
Groups
Keycloak’s Groups feature is what most commonly represents each individual tenant inside the shared realm.
Cross-Tenant Leakage
Without careful design, a mistake can let one tenant’s users or data become visible to another.
Structure
Architecture & Components
Shared-Realm Multi-Tenancy is built from a handful of Keycloak features, none of which were designed exclusively for multi-tenancy, but which combine effectively to produce it.
Groups as tenant boundaries
Keycloak’s Groups feature, ordinarily used to organize users for convenience and role assignment, becomes the primary mechanism representing each individual tenant. Every user belonging to a specific tenant is placed into that tenant’s dedicated group, and group membership becomes the practical, enforced signal of which tenant a given user actually belongs to.
Group-based role and attribute mapping
Roles and custom attributes can be assigned at the group level rather than individually per user, meaning every member of a given tenant’s group automatically inherits the roles and attributes appropriate for that tenant, without needing to configure each user one by one. This is what lets tenant-specific permissions scale cleanly even as the number of users within each tenant grows.
Client structure: shared clients versus per-tenant clients
Applications connecting to the shared realm — the Keycloak clients — can themselves be structured in different ways. A single shared client might serve every tenant, relying entirely on group membership to distinguish between them at runtime, or, in some designs, individual clients might still be created per tenant even while users remain in one shared realm, striking a different balance between isolation and shared configuration.
Custom protocol mappers carrying tenant context
Because applications need to know which tenant a logged-in user actually belongs to, custom or configured protocol mappers are commonly used to place a tenant identifier — often derived from the user’s group membership — directly into the issued token as a claim, giving every connected application a reliable, consistent way to know which tenant’s data a given request should be scoped to.
flowchart TD
A["Single Shared Realm"] --> B["Tenant A Group"]
A --> C["Tenant B Group"]
A --> D["Tenant C Group"]
B --> E["Tenant A Users + Roles + Attributes"]
C --> F["Tenant B Users + Roles + Attributes"]
D --> G["Tenant C Users + Roles + Attributes"]
E --> H["Login produces token with Tenant A claim"]
F --> I["Login produces token with Tenant B claim"]
G --> J["Login produces token with Tenant C claim"]
H --> K["Application enforces Tenant A data scoping"]
I --> K
J --> K
Fig 1 — How Groups inside one shared realm become the practical boundary separating each tenant’s users and claims.
Notice that Keycloak itself does not enforce tenant isolation as a hard, structural boundary the way it does between separate realms. Every one of these pieces — group structure, mapped attributes, protocol mappers, and the application’s own enforcement — has to work correctly together for the isolation to actually hold in practice.
Understanding exactly how tenant context flows from a user’s login through to an application’s own data access decision reveals where the real responsibility for isolation actually sits.
How a user becomes associated with a tenant
When a new user is provisioned — whether by an administrator, a self-service signup process, or an automated provisioning pipeline — they are added as a member of the specific group representing their tenant. This group membership becomes the durable, ongoing record of which tenant this user belongs to, checked and relied upon every time that user logs in.
How tenant context reaches the token
During login, Keycloak’s protocol mappers read the user’s group memberships and, using whatever mapping logic has been configured, place a corresponding tenant identifier directly into the issued token as a claim. From the application’s point of view, this claim arrives exactly like any other token claim — a labeled piece of information the application can read and trust, having been signed by Keycloak itself.
Picture that shared accounting office building again, where every employee wears a badge printed not just with their name, but also with a colored stripe indicating which client’s floor they are authorized to work on today. The badge itself — like the token — is issued by the front desk and trusted throughout the building, but it is still each individual door’s own responsibility to actually check that stripe before letting someone through, rather than assuming the badge alone guarantees correct behavior everywhere.
Where the actual enforcement happens
Crucially, Keycloak’s role in this system ends at correctly identifying and asserting which tenant a user belongs to, inside a trustworthy, signed token. It is entirely the responsibility of the applications receiving that token — the Resource Servers — to actually read the tenant claim and enforce that a given request only ever touches data belonging to that specific tenant. Keycloak provides the trustworthy signal; the application must act on it correctly every single time.
Fine-grained admin permissions scoped by group
Keycloak’s fine-grained admin permissions can be applied specifically to a tenant’s own group, allowing an organization to delegate limited administrative capability — such as managing users within one specific tenant — to a designated tenant administrator, without granting that administrator any visibility or control over other tenants’ groups or users elsewhere in the same shared realm.
Lifecycle
Data Flow & Lifecycle
Following a single new tenant from onboarding through to a live, working login shows exactly how each piece of the shared-realm model comes into play in order.
A new customer organization signs up
The platform’s provisioning process creates a new, dedicated Group within the single shared realm, specifically representing this new tenant.
Tenant-specific roles and attributes are configured
The new tenant’s group is configured with the appropriate default roles and any tenant-specific attributes, such as a subscription tier or a tenant identifier value.
The tenant’s first users are created
As employees of this new customer organization are invited or self-register, each one is added as a member of this specific tenant’s group.
A user logs in
Keycloak authenticates the user normally, and, through configured protocol mappers, includes a tenant identifier claim in the issued token, reflecting this user’s group membership.
The application reads the tenant claim
The application receiving the token reads the tenant claim and uses it to scope every subsequent data request specifically to that one tenant’s own records.
A tenant administrator manages their own users
Using fine-grained admin permissions scoped to their tenant’s specific group, a designated tenant administrator can add or remove users within their own organization, without any visibility into other tenants sharing the same realm.
Weighing the Choice
Advantages, Disadvantages & Trade-offs
Choosing Shared-Realm Multi-Tenancy over realm-per-tenant is a genuine architectural trade-off, not a strictly better or worse option in every situation.
Advantages
- Scales efficiently to a very large number of tenants, without the operational burden of creating and maintaining thousands of individual realms
- Simplifies platform-wide configuration changes, since a single update to shared authentication flows or policies applies uniformly across every tenant at once
- Reduces the resource overhead per tenant compared to fully separate realms, each of which carries its own baseline configuration and storage footprint
- Makes cross-tenant platform administration and reporting more straightforward, since all users live within one queryable, unified realm
Disadvantages & Trade-offs
- Tenant isolation is not structurally guaranteed by Keycloak itself, and depends entirely on correct group design and correct application-side enforcement
- A configuration mistake — an overly broad role, a missing tenant-scoping check — carries the risk of exposing one tenant’s data or users to another
- Highly tenant-specific customizations, such as entirely different authentication flows per tenant, are harder to support cleanly within one shared realm
- Auditing and reasoning about per-tenant security posture requires more deliberate tooling, since tenants are not separated by Keycloak’s own realm boundary
Where the trade-off tends to land
Organizations expecting to serve a very large number of relatively similar tenants, where deep per-tenant customization is not a core requirement, generally find Shared-Realm Multi-Tenancy’s scalability advantages compelling enough to accept the added discipline it demands. Organizations serving a smaller number of tenants with significantly different, highly customized requirements per tenant often find realm-per-tenant’s stronger, structural isolation the safer and simpler starting point.
Defense
Security
Because Shared-Realm Multi-Tenancy relies on carefully engineered isolation rather than a structural boundary, its security depends heavily on disciplined, deliberate design at every layer.
The central risk: cross-tenant data leakage
The single most serious risk in this model is a scenario where a user from one tenant is able to see or affect data belonging to a different tenant, either because a token’s tenant claim was misconfigured, or because a connected application failed to properly enforce tenant scoping on a specific request. Because every tenant shares the same underlying realm and often the same application infrastructure, this kind of mistake can be significantly more consequential than an equivalent bug in a realm-per-tenant deployment, where the realm boundary itself provides an additional layer of protection.
It is tempting to assume that as long as users are correctly placed into the right group, tenant isolation is effectively guaranteed. In reality, correct group membership only ensures the right claim is placed into the token — it is still entirely up to every single connected application to actually check that claim and enforce tenant scoping on every relevant request. Keycloak asserting the correct tenant is not the same as an application correctly acting on it.
Role and permission design across tenants
Roles defined at the realm level, rather than scoped specifically to a tenant’s group, risk being inadvertently applicable across every tenant at once if not carefully designed. Deliberate attention to whether a given role or permission is meant to apply platform-wide, or only within a specific tenant’s boundary, is essential to avoid unintentionally granting broader access than intended.
Securing tenant administrator delegation
When fine-grained admin permissions delegate limited administrative capability to a tenant’s own designated administrator, careful scoping is essential to ensure that delegation genuinely stays confined to that one tenant’s group and users, rather than inadvertently granting visibility or control reaching into other tenants sharing the same realm.
Regular tenant-isolation testing
Given that isolation here is engineered rather than structural, deliberately testing tenant boundaries — attempting, in a controlled way, to access another tenant’s data using a legitimately authenticated user from a different tenant — is a valuable and appropriate practice, specifically because the consequences of an undetected gap are more severe than in an architecture with a stronger built-in boundary.
Visibility
Monitoring, Logging & Metrics
Because tenant boundaries in this model are enforced rather than structurally guaranteed, ongoing visibility into how they are actually holding up in practice is especially important.
Monitoring group membership changes
Since group membership is the practical mechanism determining tenant boundaries, closely monitoring changes to group membership — particularly unexpected additions or removals — is an important part of maintaining confidence in tenant isolation over time, since an incorrect group change directly translates into an incorrect tenant assignment for the affected user.
Auditing tenant administrator actions
Because tenant administrators are granted real, if scoped, administrative power over their own tenant’s users, their actions deserve the same level of audit visibility as any other administrative activity, ensuring that delegated administration remains transparent and reviewable rather than operating as an unmonitored blind spot.
Application-level tenant-scoping metrics
Beyond Keycloak’s own logs, applications relying on tenant claims should themselves log and monitor cases where a request’s tenant scoping check fails or behaves unexpectedly, since this is often the most direct signal of either a genuine cross-tenant attempt or a subtle bug in how tenant context is being enforced downstream.
Periodic structural review as the tenant count grows
As the number of tenants sharing a realm grows into the thousands, periodically reviewing the overall group structure, naming conventions, and role assignment patterns helps catch drift or inconsistency before it becomes difficult to untangle, especially since the scale that makes shared-realm multi-tenancy attractive in the first place also makes manual, ad hoc review increasingly impractical without good tooling.
Shape
Design Patterns & Anti-patterns
Organizations running Shared-Realm Multi-Tenancy at real scale tend to converge on a handful of proven structural patterns.
Pattern: A dedicated top-level group per tenant
Mature deployments consistently create one clearly named, top-level group per tenant, avoiding ad hoc or inconsistent naming, and using this same structure uniformly as the single source of truth for tenant membership, role inheritance, and administrative delegation.
Pattern: Tenant identifier as a first-class, mapped claim
Rather than relying on applications to infer tenant context indirectly — for example, by parsing a group name string themselves — well-designed deployments configure a dedicated protocol mapper that places a clean, explicit tenant identifier directly into the token as its own claim, giving every connected application a simple, reliable, and consistent way to read it.
Pattern: Hierarchical groups for tenant sub-structure
Some deployments use nested sub-groups within a tenant’s top-level group to represent departments or teams inside that one customer organization, while still keeping the top-level group as the single, authoritative tenant boundary that everything else in the system relies on.
Anti-pattern: Realm-wide roles doubling as tenant-specific ones
A common and risky mistake is defining what is conceptually a tenant-specific role — such as “Tenant Administrator” — as a plain, realm-wide role rather than one properly scoped to a specific tenant’s group, creating a real risk that the role could be inadvertently assigned to, or interpreted as applying across, more than the one intended tenant.
Situation
A platform team, early in development, creates a single realm-wide role called “Tenant Admin” intended to represent administrative privilege within whichever tenant a user happens to belong to, planning to rely on application-level logic to scope its effect correctly at runtime.
Consequence
As the platform grows, one application component is later found to check only for the presence of the “Tenant Admin” role, without separately verifying the user’s specific tenant claim matched the tenant of the data being modified, allowing a user with this role in one tenant to inadvertently affect another tenant’s data through that one overlooked code path.
Better Approach
Scope administrative roles like this specifically to each tenant’s own group from the outset, and require every application component handling tenant-scoped actions to explicitly verify the tenant claim alongside the role itself, rather than trusting the role name alone to imply correct scoping.
Getting It Right
Best Practices & Common Mistakes
A disciplined set of habits is what allows Shared-Realm Multi-Tenancy to deliver real scalability without quietly accumulating cross-tenant risk over time.
Establish one consistent tenant-group convention early
Retrofitting a consistent structure after thousands of tenants already exist is far harder than establishing it from the very first tenant onward.
Always pair a role check with a tenant claim check
Applications should never treat a role alone as sufficient proof of authorization to act on a specific tenant’s data.
Test cross-tenant isolation deliberately and regularly
Treat this as an explicit, ongoing verification exercise rather than an assumption that correct group design alone guarantees it.
Scope delegated tenant administration tightly
Ensure a tenant administrator’s fine-grained permissions genuinely stop at that tenant’s own group and users.
Defining conceptually tenant-specific roles at the realm level
This creates exactly the kind of ambiguity that led to the anti-pattern described above.
Assuming Keycloak enforces isolation Keycloak was never asked to enforce
Every application receiving a token remains fully responsible for its own tenant-scoping logic, every single time.
Before onboarding your very first real tenant onto a shared-realm design, write an explicit, documented checklist describing exactly how tenant identity flows from group membership through to a token claim and finally to an application’s own enforcement logic — and use that same checklist to test every new application or integration added afterward.
In Practice
Real-World & Industry Examples
Shared-Realm Multi-Tenancy tends to appear specifically at the point where the sheer number of tenants makes realm-per-tenant operationally impractical.
Large business-to-business SaaS platforms
Software-as-a-service platforms serving tens of thousands of small and medium-sized business customers frequently adopt Shared-Realm Multi-Tenancy specifically because creating and maintaining a separate realm for every single customer, at that scale, would introduce unacceptable operational overhead compared to a well-designed shared-realm structure.
Marketplace and platform ecosystems
Platforms hosting a large number of independent seller or partner organizations, each needing its own isolated user base and data, often use this model to accommodate rapid, self-service onboarding of new tenants without requiring manual realm provisioning for each new participant joining the marketplace.
Education technology platforms
Platforms serving many separate schools or educational districts often use shared-realm multi-tenancy, treating each institution as its own group, since the sheer number of institutions involved would make realm-per-tenant an impractical administrative burden, while still requiring strict data separation between one school’s students and another’s.
Franchise and multi-location business platforms
Companies operating software used by many independently managed franchise locations under one parent brand frequently model each franchise location as a tenant within a shared realm, balancing centralized platform management with the need to keep each location’s own staff and operational data properly separated from every other location.
Questions Answered
FAQ
Wrapping Up
Summary & Key Takeaways
Shared-Realm Multi-Tenancy is what makes it practical to serve thousands of separate customer organizations from a single Keycloak deployment, without drowning in the operational overhead of maintaining a separate realm for each one. It achieves this not through a structural boundary Keycloak enforces automatically, but through disciplined use of Groups, roles, attributes, and protocol mappers, combined with careful, consistent enforcement inside every connected application. The scalability this model offers is real and valuable — but it is earned, not free, and it depends entirely on treating tenant boundaries with the same seriousness an organization would give to any other critical security control, precisely because Keycloak itself is not the one drawing that line.
Key Takeaways
- Shared-Realm Multi-Tenancy hosts many tenants inside one realm — trading the structural isolation of realm-per-tenant for significantly better scalability.
- Groups are the primary building block representing each tenant — group membership becomes the practical signal of tenant identity throughout the system.
- Tenant context reaches applications through a mapped token claim — typically derived from group membership via a configured protocol mapper.
- Keycloak asserts tenant identity; applications must enforce it — correct group design alone does not guarantee correct data isolation downstream.
- Roles conceptually tied to a tenant should be scoped to that tenant’s group — never left as ambiguous, realm-wide roles relying on application logic alone.
- Fine-grained admin permissions enable safe, scoped tenant delegation — letting tenant administrators manage their own users without reaching into others.
- This model demands ongoing discipline, not a one-time setup — regular isolation testing and structural review matter more here than in a realm-per-tenant design.