Casbin
Advanced usage

Performance Optimization

Casbin performance optimization

Deploying Casbin in production with millions of users or permissions may lead to performance bottlenecks. These typically stem from two causes:

High Volume Traffic

When a single Casbin instance receives excessive requests (for example, 10,000 requests/s), it cannot process them all. Consider these solutions:

  1. Enable multi-threading to run multiple Casbin instances, utilizing all CPU cores on the machine. See Multi-threading for details.

  2. Deploy Casbin instances across a cluster (multiple machines) and use Watchers to synchronize policy changes. See Watchers for details.

Combine both approaches: deploy Casbin across a 10-machine cluster where each machine runs 5 threads handling enforcement requests simultaneously.

High Number of Policy Rules

Multi-tenant or cloud environments may require millions of policy rules, causing slow enforcement and initial policy loading. Mitigate this issue with these approaches:

  1. Review your Casbin model and policy design. Well-designed models abstract common logic across users and tenants, reducing rules to a small set (typically under 100). Share default rules across tenants and allow customization through override rules. Open a GitHub issue on the Casbin repository if you need design guidance.

  2. Use policy sharding to load only relevant rules per enforcer. For example, enforcer_0 serves tenant_0 through tenant_99, while enforcer_1 serves tenant_100 through tenant_199. See Policy Subset Loading for implementation details.

  3. Assign permissions to RBAC roles rather than directly to users. Casbin implements RBAC using a role inheritance tree (cached in memory), enabling O(1) lookup time for user-role relationships. When role assignments remain relatively stable, the RBAC tree requires infrequent updates. See this discussion for more details.

Apply all these methods simultaneously for optimal performance.

On this page