Production Deployment
Casbin is a library: the enforcer lives inside your process and keeps the whole policy in memory. That makes Enforce() fast, but it also means you decide how the enforcer is created, shared between threads, and kept in sync with other instances. This page is a checklist for doing that correctly.
Create one enforcer per process
Create the enforcer once at startup and share it. Loading policy is expensive: it reads every rule from the adapter and rebuilds the model and the role graph.
Do not call LoadPolicy() (or create a new enforcer) on every request:
// Don't: this reads the whole policy table on every request
func authorize(sub, obj, act string) (bool, error) {
if err := e.LoadPolicy(); err != nil {
return false, err
}
return e.Enforce(sub, obj, act)
}
Policy changes made through the enforcer's Management API (AddPolicy, RemovePolicy, AddGroupingPolicy, ...) update memory and, with AutoSave, the database at the same time. Changes made by other instances reach this one through a watcher. There is no need to reload before enforcing.
If the policy is too large to keep in memory, load only the part each instance needs with Policy subset loading.
Share the enforcer safely between threads
The plain Enforcer is not safe for concurrent use when policy can change while requests are being enforced: a LoadPolicy() or AddPolicy() running on one thread can race with Enforce() on another. Use the synchronized enforcer, which guards reads and writes with a read-write lock:
| Language | Synchronized enforcer |
|---|---|
| Go | casbin.NewSyncedEnforcer(), casbin.NewSyncedCachedEnforcer(), casbin.NewSyncedContextEnforcer() (for the *Ctx API, versions after v3.11.0) |
| Java | SyncedEnforcer, SyncedCachedEnforcer |
| Python | casbin.SyncedEnforcer |
| Node.js | newSyncedEnforcer() |
| C++ | casbin::SyncedEnforcer |
The synchronized enforcer has the same API as Enforcer. In Go, ContextEnforcer is not synchronized either: concurrent LoadPolicyCtx() / AddPolicyCtx() and Enforce() can crash the process with concurrent map read and map write, so use NewSyncedContextEnforcer() instead (versions after v3.11.0; in earlier versions guard it with your own sync.RWMutex). See Multithreading and Enforcers for details.
Cache decisions carefully
CachedEnforcer and SyncedCachedEnforcer remember the result of each Enforce() call. They help when the same requests repeat often, but a cached decision can outlive the policy that produced it. In Go:
LoadPolicy()clears the whole cache.- Adding or removing a policy rule drops at most the cache entry whose request matches that rule exactly. Decisions that depended on the rule indirectly, for example through a role assignment (
g), stay cached. - Call
InvalidateCache()after changing role assignments, and set a time limit withSetExpireTime()so no stale decision lives forever.