/engineering:saas-entitlements-and-plan-gatingfrom engineering
Designs SaaS entitlements and plan gating: feature flags, seat/API/usage limits, tenant overrides, denial behaviour, and runtime permission resolution.
Ships in engineering. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.
| Input | Required | Use |
|---|---|---|
| Tenant, product, and lifecycle scope | yes | Bound the SaaS decision |
| Current architecture, plans, policies, and constraints | yes | Preserve enforceable behaviour |
| Production data or verified evidence | conditional | Validate thresholds and migrations |
Skill-specific inputs:
subscription-billing): tier names, features per tier, limits per tier.Default to read-only analysis. Change configuration, billing, identity, tenant data, infrastructure, or customer communications only with explicit authority, least-privilege credentials, tenant scope, rollback, and auditable approval. Never expose secrets or cross tenant boundaries.
If production access, policy, telemetry, or authoritative records are unavailable, produce a labelled design or dry-run plan. Do not claim deployment, reconciliation, deletion, delivery, or measured outcomes; list missing evidence and verification.
| Condition | Action | Stop condition |
|---|---|---|
| Tenant isolation, money, identity, or deletion is affected | Require approval and rollback evidence | Scope or authority is ambiguous |
| Evidence supports a reversible change | Stage, test, and record it | Acceptance checks fail |
| Only partial context is available | Return assumptions and validation | A production claim cannot be verified |
if tenant.plan == 'pro' checks with a single entitlements service.subscription-billing. This skill consumes those primitives.multi-tenant-saas-architecture.saas-sso-scim-enterprise-auth.SKILL.md end-to-end.if (user.plan == 'pro') { … } scattered across the codebase. Fix: single resolver.if tenant.id == 12345 branches in the code. Fix: data-driven override table.upgrade_url + reason.| Category | Artifact | Format | Example |
|---|---|---|---|
| Correctness | Entitlements model spec | Markdown doc | docs/saas/entitlements-model.md |
| Release evidence | Plan × Feature × Limit matrix | Markdown table | docs/saas/plan-feature-matrix.md |
| Operability | Gate-denial analytics dashboard | Dashboard link | docs/saas/gate-denials-dashboard.md |
references/entitlements-vs-feature-flags.md — when each applies; how they coexist.references/limit-enforcement-patterns.md — atomic counters, period rollover, distributed quotas.references/enterprise-override-model.md — data-driven overrides for custom contracts.subscription-billing, product-led-growth, saas-rate-limiting-and-quotas, saas-architecture-strategy.An entitlement is "this tenant is allowed to do X" — derived from the tenant's plan, contract overrides, add-ons, and trial state.
Examples:
The entitlements engine answers two questions:
plan baseline → plan_features (tier 'pro' has feature 'reporting')
plan_limits (tier 'pro' has limit 'users' = 10)
contract → tenant_overrides (tenant 123 has feature 'reporting' even on Free)
overrides tenant_overrides (tenant 123 has limit 'users' = 25 by negotiation)
add-ons → tenant_addons (tenant 123 purchased API add-on)
addon_features / addon_limits
Resolution precedence: override > add-on > plan baseline. Trial state is a special case — usually a tenant in trial inherits the target plan's entitlements.
| Entitlements | Feature Flags | |
|---|---|---|
| Purpose | Commercial gating (what plan allows) | Rollout / experimentation (who sees what) |
| Lifetime | Long-lived; tied to plan | Short-lived; removed after rollout |
| Audience | Tenants (by plan) | Users / tenants / cohorts (by criteria) |
| Source of truth | Billing system + entitlements DB | Feature-flag service (LaunchDarkly, Unleash, PostHog) |
| Default for new code | Inherit plan capabilities | Off (gradual rollout) |
| Audited? | Yes — overrides are commercial decisions | Lightly — flag state changes |
Keep them separate. Both runtimes can exist in the same app, but their data models, deploy cadence, and ownership differ. Commercial decisions don't belong in the feature-flag tool, and experimentation doesn't belong in the billing-driven entitlements DB.
-- Catalogue
CREATE TABLE plans (
code VARCHAR(32) PRIMARY KEY, -- 'free', 'starter', 'pro', 'enterprise'
display_name VARCHAR(64),
trial_days INT,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE features (
code VARCHAR(64) PRIMARY KEY, -- 'api_access', 'sso_saml', 'reporting_export'
display_name VARCHAR(128),
description TEXT
);
CREATE TABLE plan_features (
plan_code VARCHAR(32) NOT NULL,
feature_code VARCHAR(64) NOT NULL,
PRIMARY KEY (plan_code, feature_code),
FOREIGN KEY (plan_code) REFERENCES plans(code),
FOREIGN KEY (feature_code) REFERENCES features(code)
);
CREATE TABLE limits (
code VARCHAR(64) PRIMARY KEY, -- 'users', 'api_calls_monthly', 'storage_gb', 'projects'
display_name VARCHAR(128),
period ENUM('lifetime','monthly','daily','none') NOT NULL DEFAULT 'lifetime',
unit VARCHAR(32) -- 'count', 'bytes', 'tokens'
);
CREATE TABLE plan_limits (
plan_code VARCHAR(32) NOT NULL,
limit_code VARCHAR(64) NOT NULL,
value BIGINT, -- NULL = unlimited
PRIMARY KEY (plan_code, limit_code)
);
-- Per-tenant overrides (enterprise contracts)
CREATE TABLE tenant_feature_overrides (
tenant_id BIGINT UNSIGNED NOT NULL,
feature_code VARCHAR(64) NOT NULL,
enabled BOOLEAN NOT NULL,
reason VARCHAR(128),
expires_at DATETIME,
granted_by BIGINT UNSIGNED,
granted_at DATETIME NOT NULL,
PRIMARY KEY (tenant_id, feature_code)
);
CREATE TABLE tenant_limit_overrides (
tenant_id BIGINT UNSIGNED NOT NULL,
limit_code VARCHAR(64) NOT NULL,
value BIGINT,
reason VARCHAR(128),
expires_at DATETIME,
granted_by BIGINT UNSIGNED,
granted_at DATETIME NOT NULL,
PRIMARY KEY (tenant_id, limit_code)
);
-- Add-ons (e.g., extra seats, API package, storage pack)
CREATE TABLE addons (
code VARCHAR(64) PRIMARY KEY,
display_name VARCHAR(128)
);
CREATE TABLE addon_features (
addon_code VARCHAR(64) NOT NULL,
feature_code VARCHAR(64) NOT NULL,
PRIMARY KEY (addon_code, feature_code)
);
CREATE TABLE addon_limits (
addon_code VARCHAR(64) NOT NULL,
limit_code VARCHAR(64) NOT NULL,
value_delta BIGINT NOT NULL, -- added to base limit
PRIMARY KEY (addon_code, limit_code)
);
CREATE TABLE tenant_addons (
tenant_id BIGINT UNSIGNED NOT NULL,
addon_code VARCHAR(64) NOT NULL,
quantity INT NOT NULL DEFAULT 1,
starts_at DATETIME NOT NULL,
ends_at DATETIME,
PRIMARY KEY (tenant_id, addon_code)
);
-- Usage counters (for limit checks)
CREATE TABLE tenant_usage_counters (
tenant_id BIGINT UNSIGNED NOT NULL,
limit_code VARCHAR(64) NOT NULL,
period_key VARCHAR(16) NOT NULL, -- '2026-05' for monthly, '2026-05-11' for daily, 'lifetime'
used BIGINT NOT NULL DEFAULT 0,
updated_at DATETIME NOT NULL,
PRIMARY KEY (tenant_id, limit_code, period_key)
);
| Strategy | Latency | Freshness | Use case |
|---|---|---|---|
| JWT-embedded | < 0.1ms (no I/O) | Until token refresh (15min) | Boolean feature checks; tier-level limits |
| Runtime DB lookup | 1-5ms | Real-time | Limit checks needing current counter; just-changed plans |
| Redis cache + DB fallback | < 1ms hit / 5ms miss | Configurable TTL | High-traffic feature checks |
| Hybrid | Mixed | Mixed | Default: boolean checks in JWT, limit checks against Redis counter |
Default architecture:
Auth issues JWT with: plan, features[], limits[] (snapshot at issue)
On every request:
- Boolean feature check: read JWT (free, instant)
- Limit check: Redis INCR + compare against JWT limit (atomic, fast)
- Periodic re-issue (15min) refreshes JWT against DB
On plan change / override:
- Invalidate user's JWT (force re-issue)
- Update DB
- Emit `entitlements.changed` event
UI gates — Hide / disable features the user can't access. NEVER trust as enforcement.
Show "Upgrade to Pro" CTAs.
API gates — Primary enforcement. Reject with 402 Payment Required or 403 Forbidden + upgrade info.
Worker gates — Background jobs must check too. A bypass of API gates via direct queue insertion is an exploit.
DB constraints — For hard limits (max users per tenant), enforce at DB level too.
Pattern for an API gate:
@require_entitlement(feature='api_access')
@require_within_limit(limit='api_calls_monthly')
def api_endpoint(request):
Entitlements.consume_limit(tenant_id, 'api_calls_monthly', amount=1)
# ... work
Denial response:
{
"error": {
"code": "ENTITLEMENT_REQUIRED",
"feature": "api_access",
"message": "API access is available on the Pro plan and above.",
"upgrade_url": "https://app.example.com/billing/upgrade?target=pro&context=api"
}
}
The gate is a sales surface, not just a wall. Every denial:
gate.denied event for PQL scoring + lifecycle email.In-product approaching-limit UX:
Enterprise contracts often grant custom entitlements. Implement as data, never as code branches:
Admin Console → POST /admin/tenants/123/entitlements
body: { feature: 'sso_saml', enabled: true, reason: 'Q2 contract Acme', expires_at: '2027-04-01' }
→ writes to tenant_feature_overrides
→ writes audit_log entry
→ emits entitlements.changed event
Read-time resolution merges plan + add-ons + overrides automatically.
Every gate denial is a Product-Qualified-Lead signal. Materialize:
gate_denials_per_tenant_per_day (with feature/limit, severity)tenants_hitting_limit_80pct (the upgrade pipeline)feature_lock_topN (which features drive the most upgrade-intent signal)Feed into product-led-growth skill's PQL scoring; coordinate with saas-lifecycle-email-orchestration (don't email and in-app prompt the same denial — pick one or stagger).
plans.json file in the repo consumed by both UI and API at compile time — drift, redeploys to change limits.SELECT COUNT(*) on every request — slow + race-condition prone. Fix: maintained counter + atomic INCR.expires_at mandatory for promo overrides.upgrade_url carries context= param; post-upgrade redirects back to original action.subscription-billing — plan / price / subscription primitives.product-led-growth — PQL + activation; coordinate with gates.saas-rate-limiting-and-quotas — runtime quota enforcement.saas-architecture-strategy — the admin tool that issues overrides.saas-transactional-email-infrastructure + saas-lifecycle-email-orchestration — coordinate gate denials with upgrade email sequences.When the SaaS includes AI features, the entitlement catalogue extends with AI-specific keys (model tier, context length, generations/day, tools allow-list, KB size, agent steps, BYOK, fine-tune). The mapping and gateway-enforcement contract live in this skill (the retired ai-entitlements-and-feature-gating skill is an inactive alias of it).
Cross-references:
ai-usage-metering-and-billing — what is gated vs metered.ai-model-gateway — runtime enforcement chokepoint.ai-on-saas-architecture — control-plane positioning.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
entitlements, plan-gating, feature-flags, quotas, multi-tenant
npx claudepluginhub peterbamuhigire/chwezi-dev-engine --plugin engineering169 skills in this plugin
/accounting-engineUse when designing or implementing double-entry accounting policy and an embedded ledger engine for invoices, payments, stock, balanced postings, mapped accounts, idempotency, reversals, period locks, audit trails, and financial statements./accounting-finance-controllerUse when coordinating accounting and finance implementation reviews, doctrine routing, control evidence, remediation priorities, and release decisions across a software system./advanced-testing-strategyUse when designing or reviewing test strategy for production systems, APIs, mobile apps, SaaS platforms, ERP workflows, and AI-enabled systems. Covers unit, integration, contract, end-to-end, regression, release-gate, and risk-based testing decisions.Other plugins' skills for the same job