SaaS Entitlements: Feature Gating, Plan Limits and Stripe, Tested

SaaS entitlements are the record of what each customer's plan lets them use right now: which features are on, how many seats or projects they get, and settings like data retention. To implement them, put plans, features and limits in a catalog, resolve each account's entitlements from its plan, subscription status and grants (add-ons, overrides, trials), check them on the server with one function, and enforce numeric limits in the database, not in app code that counts first.
That last step is where the obvious implementation breaks. In the first run of our race test on PostgreSQL 18.7, 50 concurrent "add seat" requests against a 10-seat limit produced 50 seats in 20 of 20 trials when the code counted and then inserted, and in all 3 runs every trial went over the limit. Locking the tenant row first kept every trial in every run at exactly 10.
Stripe Entitlements doesn't solve this for you. Per Stripe's docs, read on 2026-11-18, a Stripe Feature has no quantity or limit field, so seat and project limits stay in your own catalog, and adding a feature to a product reaches existing subscribers only at their next billing period.
The top results we read for "saas entitlements" and "entitlements vs feature flags" on 2026-11-18 were mostly vendor posts arguing their own side (entitlement platforms say flags aren't enough, flag platforms say they can be), and none of them showed a test run or a concurrency result. Keplaris, a New York product engineering studio, wrote the check function and its 13 tests, ran the race test three times on 2026-11-18, and read Stripe's Entitlements docs the same day. We build plan logic, Stripe billing and webhooks for clients as part of our API and SaaS development work, and we don't sell an entitlement product, so the build or buy section has no side to take. The full code and unedited output are at the end.
The four steps, in order:
- Catalog: plans, features, limits and config values as data, never as
if (plan === "pro")in handlers. - Resolve: one pure function turns plan, status and grants into an entitlement set, failing closed on anything unknown.
- Check on the server: every write path calls
hasFeatureorcheckLimit; feature gating that only hides a button in the UI is cosmetic. - Enforce limits in Postgres: lock the tenant row (or use a guarded counter) in the same transaction as the insert.
What SaaS entitlements are: features, limits and config values
An entitlement is a plan's promise turned into something code can check, which is what plan-based feature access means in practice. Feature gating is the enforcement side: allowing or blocking a feature, or an action past a limit, at the point of use, based on those entitlements. Three kinds cover almost every SaaS pricing page:
| Kind | Example | How the code asks | Unknown value means |
|---|---|---|---|
| Boolean feature | SAML SSO, audit log, CSV export | hasFeature(e, "sso") | Denied |
| Numeric limit | 5 seats, 50 projects | checkLimit(e, "seats", used) | 0 allowed |
| Config value | 90 days of retention, max file size | read e.limits.retention_days | Missing, so use the most restrictive default |
Stigg's engineer's guide (updated July 9, 2025) adds a fourth, enum entitlements, which it marks as coming soon to its own product. In our module a config value is just a numeric limit read as a setting, and an enum (support level: standard or priority) can be one feature key per option, which kept the code to two check functions.
A periodic limit, such as 1,000 exports a month, is a numeric limit counted over the billing period: used comes from a period-scoped count or a usage ledger (the ledger is covered in usage-based billing for SaaS, request quotas in SaaS API rate limiting).
One naming trap: in identity and access management, "entitlement" means a user's access rights to systems, and some top results for "saas entitlements" are about that. This post is about plan access in a product you build.
Entitlements vs feature flags vs permissions
A feature flag decides who sees code that is still rolling out, an entitlement decides what a customer paid for, and a permission decides what one user may do inside that customer's account. They answer different questions, change for different reasons and should live in different code.
| Feature flag | Entitlement | Permission | |
|---|---|---|---|
| Question | Is this code released to you yet? | Does your plan include it? | May your role do it? |
| Scope | Any context: user, account, region | Account (tenant) | User inside a tenant |
| Changed by | Engineers, during a rollout | Billing: upgrades, cancels, add-ons | Tenant admins |
| Lifetime | Removed when the rollout ends | As long as the plan exists | As long as the role exists |
| Safe default | Off | Denied | Denied |
Can a flag tool hold entitlements? It can. LaunchDarkly's entitlements guide describes them as "a permanent or long-lived targeting rule," built on segments, and warns that if your app can't reach LaunchDarkly, "some of your end users could receive too much or too little access" through the fallback variation; it suggests the Relay Proxy with a persistent store to serve the last known state. That covers boolean access. Seat limits, grace periods and billing sync are still yours to build.
In practice the checks stack. A new export format shipped behind a flag to a paid tier passes both:
const allowed =
flags.isEnabled("csv_export_v2", ctx) && // rollout: released to this account yet?
hasFeature(ent, "export_csv") && // entitlement: does the plan include export?
user.role === "admin"; // permission: may this user run it?
When the rollout ends, the flag line is deleted and the other two stay.
The data model: plans, features, limits and grants
An entitlement data model needs five parts: plans, plan features, plan limits, per-account grants that change one account without changing its plan, and the account's billing state (plan, subscription status, past_due_since). "Account" here is the tenant; Stripe calls it the customer. Precedence, from the module below: the plan sets the base, set grants (a negotiated limit) replace a plan value, add grants (an add-on pack) stack on top of whatever is there, and an expired grant does nothing.
A Postgres sketch of that model (the tested module is pure TypeScript and takes this data as input; this schema was not part of the test run):
CREATE TABLE plans (
id text PRIMARY KEY -- versioned: 'pro_2025', 'pro_2026'
);
CREATE TABLE features (
key text PRIMARY KEY, -- 'sso', 'audit_log'
stripe_lookup_key text UNIQUE -- same key as the Stripe Feature, if you use one
);
CREATE TABLE plan_features (
plan_id text REFERENCES plans, feature_key text REFERENCES features,
PRIMARY KEY (plan_id, feature_key)
);
CREATE TABLE plan_limits (
plan_id text REFERENCES plans, limit_key text NOT NULL,
value int, -- NULL = unlimited
PRIMARY KEY (plan_id, limit_key)
);
CREATE TABLE grants (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL REFERENCES tenants(id),
source text NOT NULL CHECK (source IN ('addon', 'override', 'trial')),
feature_key text REFERENCES features,
limit_key text, limit_value int,
limit_mode text CHECK (limit_mode IN ('add', 'set')),
expires_at timestamptz,
created_by text NOT NULL -- who granted it, for the audit trail
);
-- tenants carries plan_id, subscription status, past_due_since and seats_used
Version plans instead of editing them. When you raise the price of Pro, create pro_2026 and leave existing customers on pro_2025 until you move them. The module fails closed on unknown plans, which is the right default but has a consequence: one of the 13 tests checks that an account on a plan missing from the catalog (legacy_2019) resolves to free. Delete a grandfathered plan while customers still sit on it, and they lose their features on the next request.
Enterprise deals become grants, not new plans. A customer who negotiated 40 seats on Pro gets an override grant with mode: "set", and if they later buy a 10-seat pack, that addon grant adds to the override: 50 seats, which is what the precedence test asserts.
Feature gating in code: an entitlement check in TypeScript, with tests
The whole module is under 100 lines of pure functions: resolve turns an account into an entitlement set, and hasFeature and checkLimit answer questions about it. No I/O, so every billing rule has a unit test. The trimmed core, with the full file at the end:
export function effectivePlan(a: Account, catalog: Catalog, now: Date) {
if (!catalog[a.planId]) return { plan: FALLBACK_PLAN, reason: `unknown plan ${a.planId}` };
if (a.status === "active" || a.status === "trialing") return { plan: a.planId, reason: a.status };
if (a.status === "past_due" && a.pastDueSince &&
now.getTime() - a.pastDueSince.getTime() < GRACE_DAYS * DAY) {
return { plan: a.planId, reason: "past_due, inside grace period" };
}
return { plan: FALLBACK_PLAN, reason: `status ${a.status}` };
}
// in resolve(): grants only ride on the paid plan; "set" grants first, then "add" stacks on top
const live = plan !== a.planId ? [] :
a.grants.filter(g => !g.expiresAt || g.expiresAt.getTime() > now.getTime());
for (const g of live) {
if (g.feature) features.add(g.feature);
if (g.limit?.mode === "set") limits[g.limit.key] = g.limit.value;
}
for (const g of live) {
if (g.limit?.mode !== "add") continue;
const cur = limits[g.limit.key] ?? 0;
limits[g.limit.key] = cur === null || g.limit.value === null ? null : cur + g.limit.value;
}
// Unknown limit key = 0 allowed. `used` must come from the source of truth, not a cache.
export function checkLimit(e: Entitlements, key: string, used: number, requested = 1) {
const limit = key in e.limits ? e.limits[key] : 0;
if (limit === null) return { allowed: true, limit, remaining: null };
const remaining = Math.max(0, limit - used);
return { allowed: requested <= remaining, limit, remaining };
}
The rules it encodes:
- Fail closed. An unknown feature is denied and an unknown limit allows 0. A typo in a feature key shows up as a denial in testing, not as free access in production.
nullmeans unlimited, so "unlimited projects" is data, not a special case in handlers.- Trialing counts as paying. A trial of Business gets Business.
past_duekeeps the plan for 7 days, then falls back to free. The 7 days is our choice, not a Stripe rule; pick yours with whoever owns collections.canceled,unpaid,paused,incomplete,incomplete_expiredand unknown plans fall back to free.- Grants ride on the paid plan. When billing drops an account to free, its add-ons and overrides stop applying too.
- Every result carries a
reason. Log it on each denial; "status past_due" in a support ticket saves an hour.
Traced through one account with 12 seats in use: a Pro customer (5 seats on the plan) with a 40-seat override and a 10-seat add-on resolves to 50 seats. Three days after a failed payment, resolve still returns pro with reason past_due, inside grace period, and checkLimit(e, "seats", 12) gives { allowed: true, limit: 50, remaining: 38 }. On day 8 the plan becomes free: the Pro features (api_access, export_csv) are gone, projects drop to 3 and seats drop to 1, because grants stop with the paid plan. Our first version of resolve(), written on 2026-11-18, got that wrong: it applied grants after the fallback to free, so the same account kept 50 seats on the free plan. We caught it while writing this post, by tracing this example account, then fixed it and added the test "grants stop when billing drops the account to free".
The 13 tests ran on Node 24.20.0 with built-in type stripping, so there is no build step: node --test entitlements.test.ts. Output from 2026-11-18, per-test durations removed:
✔ active plan gets its features and limits
✔ unknown feature and unknown limit fail closed
✔ trialing counts as paying
✔ past_due keeps the plan for 7 days, then falls back to free
✔ canceled, unpaid, paused and unknown plans fall back to free
✔ seat limit: at the limit, one more is denied
✔ null limit means unlimited
✔ add-on pack stacks on the plan limit
✔ sales override replaces the limit, and add-ons stack on the override
✔ feature trial grant expires on time
✔ grants stop when billing drops the account to free
✔ downgrade keeps data but blocks new usage over the new limit
✔ Stripe lookup keys map to known features only
ℹ tests 13
ℹ pass 13
ℹ fail 0
Where to call it: in the request handler or service method that does the work, in background jobs that do work on a tenant's behalf, and in every tool an AI agent can call for the tenant, the same server-side check our AI agent guardrails put in front of each tool call. Resolve once per request from the tenant row and its grants, which you usually load anyway. The one value you must not cache is used: the next section shows why even a fresh count isn't enough.
The frontend needs the same answer for locked states and upgrade prompts. Send it the resolved entitlement set (features, limits and current usage, without grant internals) from one endpoint or with the session, and render "upgrade to unlock" or "12 of 5 seats" from it. That copy of the set only decides what the user sees. The server check stays authoritative, because anyone can call your API without your UI.
Enforcing seat and project limits under concurrency
A limit check in app code is a check-then-act race, and under load it can let nearly every request through. With a 10-seat limit and 50 concurrent add-seat requests per trial, both "count first" strategies ended at 50 seats in all 20 trials of run 1, so every request was accepted. In all 3 runs, 20 of 20 trials went over the limit (worst case 50 seats, mean 49.2 to 50.0). Both strategies that serialize writers per tenant ended at exactly 10 in every trial.
The setup: PostgreSQL 18.7 in the official postgres:18 Docker image on a laptop, default isolation (READ COMMITTED), Node 24.20.0 with pg 8.23.1, one pooled connection per request, 20 trials per strategy, a fresh tenant per trial. Four strategies:
- Count, then insert:
SELECT count(*), compare in app code,INSERT. - One statement:
INSERT INTO seats ... SELECT $1, $2 WHERE (SELECT count(*) ...) < (SELECT seat_limit ...). - Lock the tenant row:
BEGIN,SELECT seat_limit FROM tenants WHERE id = $1 FOR UPDATE, then count, insert,COMMIT. - Guarded counter:
BEGIN,UPDATE tenants SET seats_used = seats_used + 1 WHERE id = $1 AND seats_used < seat_limit, insert only if a row was updated,COMMIT.
Run 1, unedited:
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+2), isolation read committed, Node v24.20.0, pg 8.23.1
seat limit 10, 50 concurrent add-seat requests per trial, 20 trials per strategy
strategy | trials over the limit | worst case seats | mean seats | median ms per trial
count, then insert | 20 of 20 | 50 | 50.0 | 7.0
single INSERT ... WHERE count < limit | 20 of 20 | 50 | 50.0 | 4.0
SELECT ... FOR UPDATE on the tenant, then count and insert | 0 of 20 | 10 | 10.0 | 38.3
guarded UPDATE on a seats_used counter | 0 of 20 | 10 | 10.0 | 43.8
Runs 2 and 3 showed the same pattern, with some racy trials ending below 50 seats (all still above 10) and both locked strategies at exactly 10. Both outputs are in the last section.
Strategy 2 is the one that looks safe and isn't. One SQL statement looks atomic, but at READ COMMITTED it isn't a lock. The PostgreSQL docs say a plain SELECT (and the count inside this INSERT is one) "sees only data committed before the query began; it never sees either uncommitted data or changes committed by concurrent transactions during the query's execution." Fifty inserts running at once each count the seats committed before they started, which is close to zero, and nearly all pass.
Strategies 3 and 4 work because a row lock makes the next writer wait. Per the same page, when an UPDATE or SELECT FOR UPDATE finds a row another transaction is changing, it waits for that transaction to finish, and "the search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches." For the guarded counter, the 11th request re-checks seats_used < seat_limit against 10 and updates nothing. For FOR UPDATE, the count has to be a separate statement after the lock, so it takes a fresh snapshot that includes the seats the previous holder committed.
Which to pick:
FOR UPDATEon the tenant row needs no extra column and works for any limit you can count (projects, seats, API keys).- A guarded counter is one statement and cheap to read for dashboards, but every delete has to decrement it in the same transaction, or it drifts.
Median time per 50-request burst was 4.0 to 34.0 ms for the racy strategies and 30.8 to 138.5 ms for the locked ones across the three runs. The ranges overlapped in run 2, where the guarded counter (30.8 ms) beat count-then-insert (34.0 ms), and laptop timings are noisy, so we don't rank the strategies by speed. The lock is per tenant, so one tenant's invite burst doesn't queue another tenant's. We didn't test SERIALIZABLE with retries or advisory locks; both can work, and neither was measured here.
Limits on API requests per minute or per month are a different problem (counters in Redis, 429 responses), covered in SaaS API rate limiting. Billing for usage, as opposed to capping it, is in usage-based billing for SaaS. If your tenants share tables under row-level security, the seat and tenant rows here sit under the same policies as in multi-tenant SaaS architecture.
Syncing from Stripe Entitlements
Stripe Entitlements tells you which features a customer has, based on their subscriptions; it doesn't hold limits, and Stripe recommends you copy the result into your own database. So the sync is: Stripe sends a webhook, you fetch the full list, you store it, and your check reads from your store.
What Stripe's Entitlements guide and API reference say, read on 2026-11-18:
- A Feature has a
name, a uniquelookup_keyof up to 80 characters andmetadata. There is no quantity or limit field, and the examples are on or off: API access, AI assistant, premium support, advanced reporting, extended data retention. Seats and project counts stay in your catalog, keyed by the same lookup keys. - You attach features to products; one feature can go on several products. But "existing subscriptions will create active entitlements for any product feature changes at the start of the next billing period." Adding a feature to a product doesn't give it to current subscribers mid-cycle. If you promise it today, grant it yourself.
- The webhook
entitlements.active_entitlement_summary.updated"occurs each time a customer's active entitlements change, for example when a subscription is created, updated, or canceled," including when a subscription "is canceled automatically due to failed payments." - The summary's
entitlements.data"contains a maximum of 10 entitlements"; beyond that, page throughentitlements.url. - List Active Entitlements requires a
customer, pages by cursor, and returns 10 per page by default, up to 100. Stripe suggests it "on application startup, for authorization checks, or to reconcile state after a webhook delivery failure." - "We recommend you persist these entitlements internally for faster resolution."
Stripe's pages don't say what entitlements do while a subscription is trialing, past due, unpaid or paused, and we didn't test it in a sandbox, so don't assume. That's one reason the grace rule lives in our own effectivePlan, driven by the subscription status you already store.
Because the summary caps at 10 and webhooks can arrive late or out of order, we treat the event as a "something changed" signal and re-fetch the list. A sketch of the handler (not run against Stripe for this post):
// POST /webhooks/stripe, after verifying the signature
if (event.type === "entitlements.active_entitlement_summary.updated") {
const customer = event.data.object.customer;
const keys: string[] = [];
for await (const ent of stripe.entitlements.activeEntitlements.list({ customer, limit: 100 })) {
keys.push(ent.lookup_key);
}
const features = featuresFromStripe(keys, knownFeatureKeys); // drops keys you no longer know
await db.replaceStripeFeatures(tenantIdFor(customer), [...features]); // one transaction
}
Re-fetching makes the handler safe to run twice and in any order, because it always writes current state. Still record event IDs and verify signatures; the reasons and the tests behind them are in webhook idempotency and retries. Then add a nightly reconcile job that runs the same fetch for every paying customer, so a missed webhook costs a day at most, not a quarter.
featuresFromStripe keeps only lookup keys your catalog knows. A feature someone added in the Stripe Dashboard grants nothing until code knows what it means; the test for it passes old_beta_flag and gets back only sso.
Downgrades, failed payments and grace periods
A downgrade should change what a customer can do next, never delete what they already have. In the module, a tenant with 12 seats that drops from Business (25 seats) to Pro (5) keeps all 12; checkLimit(e, "seats", 12) returns { allowed: false, limit: 5, remaining: 0 }, so new invites are refused until they're under the limit. The same goes for projects and stored data.
| Subscription status | Plan the module applies | Reason logged |
|---|---|---|
active, trialing | The subscribed plan | active or trialing |
past_due, under 7 days | The subscribed plan | past_due, inside grace period |
past_due, 7 days or more | Free | status past_due |
canceled, unpaid, paused, incomplete, incomplete_expired | Free | status <name> |
| Plan not in the catalog | Free | unknown plan <id> |
Three decisions to make on purpose:
- Length of grace. Seven days is ours. Align it with how long your billing provider keeps retrying the card, so the plan doesn't drop while a retry is still pending.
- What over-limit means in the UI. Show the limit and the count ("12 of 5 seats, remove 7 to invite more"), not a generic error.
- Whether grants survive non-payment. In this module they don't: grants only apply while the paid plan does, so a customer 8 days past due drops to free with 1 seat, not 50. That's right for a paid add-on or an enterprise override. If you also hand out support credits that should outlast a lapse, give them their own
sourceand exempt it explicitly.
Module or entitlement service
Entitlement checks should start as a module inside your app, not a separate service. The check is pure and runs on data each request already loads, so a network hop only adds latency and a new failure mode. In our monolith vs microservices benchmark, the same kind of entitlement check took about 0.1 microseconds in-process and 72 microseconds at the median over a reused local HTTP connection, before timeouts and retries. Called on every request and every job, you pay that difference each time, and when the service is down every caller has to choose between failing and guessing.
A separate entitlement service is worth it when several separately deployed apps (a web app, a public API, a desktop client) need the same answer and you'd otherwise copy the rules. Even then, cache the resolved set close to the caller and invalidate it from the same webhook that updates the store. If the cache is unavailable, read the tenant row directly; never default to "allow". Keep enforcement of numeric limits next to the data, as in the race test, wherever the rules live. Pulling scattered if statements into one layer like this is often the first job after product-market fit, as we cover in re-architecting a SaaS after product-market fit.
Build or buy entitlements
Build it when your plans fit in a catalog like the one above and Stripe already runs your subscriptions: the module and its tests come to under 200 lines, and you own the rules. Buy when pricing changes often and product or sales people need to edit plans, trials and overrides without a deploy. What each option says it does, from its own pages:
| Option | What it covers, per its own docs | What you still own |
|---|---|---|
| Stripe Entitlements | Feature access per customer from Stripe subscriptions, a summary webhook and a list API | Limits, grants, grace rules, enforcement, a local copy |
| Stigg | "A developer-first entitlements and metering platform" (Stigg), including metered limits | Check calls in your code, concurrency on your own writes |
| Schematic | "An entitlements layer on top of Stripe," configuring plans, limits, trials, add-ons and overrides (Schematic, June 10, 2026) | Check calls in your code, concurrency on your own writes |
| LaunchDarkly | Entitlements as long-lived flag targeting rules on segments (LaunchDarkly) | Limits, billing sync, grace rules |
| Your own module | Whatever you write and test | All of it |
We haven't run Stigg or Schematic in a project for this post, we didn't compare prices, and the order of the table means nothing. Billing platforms such as Orb also write about entitlements; we didn't review their entitlement features. Whichever you pick, two parts stay in your code: the call sites that check before doing work, and limit enforcement that holds under concurrent writes. For the general version of this trade-off, see build vs buy software.
Full code and output
Three files plus package.json, run on 2026-11-18. entitlements.ts and its tests need Node 22.18 or later (we used 24.20.0) and nothing else: node --test entitlements.test.ts. seat-race.mjs needs Docker and one dependency, pg 8.23.1 (npm install pg@8.23.1, with "type": "module" in package.json). Start Postgres with the command in the script's header and run node seat-race.mjs. Your timings will differ; the over and under counts are the result.
entitlements.ts
// entitlements.ts: resolve what one account may use right now, from its plan, its subscription
// status and any time-boxed grants. Pure functions, no I/O, so every rule is unit-testable.
// Runs on Node 22.18+ / 24 with built-in type stripping: node --test entitlements.test.ts
export type Limit = number | null; // null = unlimited
export interface Plan {
id: string;
features: string[]; // boolean entitlements, e.g. "sso", "audit_log"
limits: Record<string, Limit>; // numeric entitlements, e.g. { seats: 5, projects: 10 }
}
export type Catalog = Record<string, Plan>;
// A grant changes one account's entitlements without changing its plan:
// an add-on pack, a sales override, a trial of a higher tier's feature.
export interface Grant {
source: "addon" | "override" | "trial";
feature?: string;
limit?: { key: string; value: Limit; mode: "add" | "set" };
expiresAt?: Date;
}
// Stripe-style subscription statuses.
export type SubStatus =
| "trialing" | "active" | "past_due" | "unpaid"
| "canceled" | "incomplete" | "incomplete_expired" | "paused";
export interface Account {
planId: string;
status: SubStatus;
pastDueSince?: Date;
grants: Grant[];
}
export interface Entitlements {
plan: string; // the plan actually applied (may be the fallback)
features: ReadonlySet<string>;
limits: Readonly<Record<string, Limit>>;
reason: string; // why this plan applies; log it on every denial
}
export const FALLBACK_PLAN = "free";
export const GRACE_DAYS = 7;
const DAY = 86_400_000;
// Which plan applies, given billing state. Paying (or trialing) gets the plan; a failed payment
// keeps the plan for a grace period; everything else falls back to the free plan.
export function effectivePlan(a: Account, catalog: Catalog, now: Date): { plan: string; reason: string } {
if (!catalog[a.planId]) return { plan: FALLBACK_PLAN, reason: `unknown plan ${a.planId}` };
if (a.status === "active" || a.status === "trialing") return { plan: a.planId, reason: a.status };
if (a.status === "past_due" && a.pastDueSince &&
now.getTime() - a.pastDueSince.getTime() < GRACE_DAYS * DAY) {
return { plan: a.planId, reason: "past_due, inside grace period" };
}
return { plan: FALLBACK_PLAN, reason: `status ${a.status}` };
}
export function resolve(a: Account, catalog: Catalog, now: Date): Entitlements {
const { plan, reason } = effectivePlan(a, catalog, now);
const base = catalog[plan] ?? { id: plan, features: [], limits: {} };
const features = new Set(base.features);
const limits: Record<string, Limit> = { ...base.limits };
// Grants ride on the paid plan: when billing drops the account to the fallback, they stop too.
// "set" grants first (a negotiated limit replaces the plan's), then "add" grants stack on top.
const live = plan !== a.planId ? [] :
a.grants.filter(g => !g.expiresAt || g.expiresAt.getTime() > now.getTime());
for (const g of live) {
if (g.feature) features.add(g.feature);
if (g.limit?.mode === "set") limits[g.limit.key] = g.limit.value;
}
for (const g of live) {
if (g.limit?.mode !== "add") continue;
const cur = limits[g.limit.key] ?? 0;
limits[g.limit.key] = cur === null || g.limit.value === null ? null : cur + g.limit.value;
}
return { plan, features, limits, reason };
}
// Unknown feature = denied. Fail closed.
export function hasFeature(e: Entitlements, feature: string): boolean {
return e.features.has(feature);
}
// Unknown limit key = 0 allowed. `used` must come from the source of truth, not a cache.
export function checkLimit(e: Entitlements, key: string, used: number, requested = 1):
{ allowed: boolean; limit: Limit; remaining: number | null } {
const limit = key in e.limits ? e.limits[key] : 0;
if (limit === null) return { allowed: true, limit, remaining: null };
const remaining = Math.max(0, limit - used);
return { allowed: requested <= remaining, limit, remaining };
}
// Stripe Entitlements returns active features per customer as lookup keys, with no quantities.
// Map them onto feature names; numeric limits stay in your own catalog.
export function featuresFromStripe(activeLookupKeys: string[], known: ReadonlySet<string>): Set<string> {
return new Set(activeLookupKeys.filter(k => known.has(k)));
}
entitlements.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { resolve, hasFeature, checkLimit, featuresFromStripe, type Catalog, type Account } from "./entitlements.ts";
const catalog: Catalog = {
free: { id: "free", features: [], limits: { seats: 1, projects: 3 } },
pro: { id: "pro", features: ["api_access", "export_csv"], limits: { seats: 5, projects: 50, api_calls_month: 100_000 } },
business: { id: "business", features: ["api_access", "export_csv", "sso", "audit_log"], limits: { seats: 25, projects: null, api_calls_month: 1_000_000 } },
};
const now = new Date("2026-11-18T12:00:00Z");
const daysAgo = (d: number) => new Date(now.getTime() - d * 86_400_000);
const acct = (p: Partial<Account>): Account => ({ planId: "pro", status: "active", grants: [], ...p });
test("active plan gets its features and limits", () => {
const e = resolve(acct({}), catalog, now);
assert.equal(e.plan, "pro");
assert.ok(hasFeature(e, "api_access"));
assert.ok(!hasFeature(e, "sso"));
assert.equal(e.limits.seats, 5);
});
test("unknown feature and unknown limit fail closed", () => {
const e = resolve(acct({}), catalog, now);
assert.ok(!hasFeature(e, "does_not_exist"));
assert.deepEqual(checkLimit(e, "does_not_exist", 0), { allowed: false, limit: 0, remaining: 0 });
});
test("trialing counts as paying", () => {
assert.equal(resolve(acct({ status: "trialing", planId: "business" }), catalog, now).plan, "business");
});
test("past_due keeps the plan for 7 days, then falls back to free", () => {
assert.equal(resolve(acct({ status: "past_due", pastDueSince: daysAgo(3) }), catalog, now).plan, "pro");
const late = resolve(acct({ status: "past_due", pastDueSince: daysAgo(8) }), catalog, now);
assert.equal(late.plan, "free");
assert.match(late.reason, /past_due/);
});
test("canceled, unpaid, paused and unknown plans fall back to free", () => {
for (const status of ["canceled", "unpaid", "paused", "incomplete_expired"] as const) {
assert.equal(resolve(acct({ status }), catalog, now).plan, "free", status);
}
assert.equal(resolve(acct({ planId: "legacy_2019" }), catalog, now).plan, "free");
});
test("seat limit: at the limit, one more is denied", () => {
const e = resolve(acct({}), catalog, now);
assert.equal(checkLimit(e, "seats", 4).allowed, true);
assert.equal(checkLimit(e, "seats", 5).allowed, false);
assert.equal(checkLimit(e, "seats", 3, 3).allowed, false); // bulk invite of 3 with 2 left
});
test("null limit means unlimited", () => {
const e = resolve(acct({ planId: "business" }), catalog, now);
assert.deepEqual(checkLimit(e, "projects", 10_000), { allowed: true, limit: null, remaining: null });
});
test("add-on pack stacks on the plan limit", () => {
const e = resolve(acct({ grants: [{ source: "addon", limit: { key: "seats", value: 10, mode: "add" } }] }), catalog, now);
assert.equal(e.limits.seats, 15);
});
test("sales override replaces the limit, and add-ons stack on the override", () => {
const e = resolve(acct({ grants: [
{ source: "addon", limit: { key: "seats", value: 10, mode: "add" } },
{ source: "override", limit: { key: "seats", value: 40, mode: "set" } },
] }), catalog, now);
assert.equal(e.limits.seats, 50);
});
test("feature trial grant expires on time", () => {
const g = { source: "trial" as const, feature: "sso", expiresAt: new Date("2026-11-20T00:00:00Z") };
assert.ok(hasFeature(resolve(acct({ grants: [g] }), catalog, now), "sso"));
assert.ok(!hasFeature(resolve(acct({ grants: [g] }), catalog, new Date("2026-11-20T00:00:01Z")), "sso"));
});
test("grants stop when billing drops the account to free", () => {
const grants = [
{ source: "override" as const, limit: { key: "seats", value: 40, mode: "set" as const } },
{ source: "addon" as const, limit: { key: "seats", value: 10, mode: "add" as const } },
];
assert.equal(resolve(acct({ status: "past_due", pastDueSince: daysAgo(3), grants }), catalog, now).limits.seats, 50);
const late = resolve(acct({ status: "past_due", pastDueSince: daysAgo(8), grants }), catalog, now);
assert.equal(late.plan, "free");
assert.equal(late.limits.seats, 1);
});
test("downgrade keeps data but blocks new usage over the new limit", () => {
// 12 seats in use, plan drops business -> pro (5 seats): nothing is deleted, new invites are refused.
const e = resolve(acct({ planId: "pro" }), catalog, now);
assert.deepEqual(checkLimit(e, "seats", 12), { allowed: false, limit: 5, remaining: 0 });
});
test("Stripe lookup keys map to known features only", () => {
const known = new Set(["sso", "audit_log", "api_access"]);
assert.deepEqual([...featuresFromStripe(["sso", "old_beta_flag"], known)], ["sso"]);
});
seat-race.mjs
// seat-race.mjs: does a seat limit hold when many invites arrive at once?
// 50 concurrent "add seat" requests against a tenant with a 10-seat limit, 20 trials per strategy,
// PostgreSQL default isolation (READ COMMITTED), one pooled connection per request.
// docker run -d --name ent-pg -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:18
// node seat-race.mjs
import pg from "pg";
const LIMIT = 10, CONCURRENCY = 50, TRIALS = 20;
const pool = new pg.Pool({ connectionString: process.env.PGURL ?? "postgres://postgres:pg@localhost:55432/postgres", max: CONCURRENCY });
const strategies = {
// 1. Read the count in the app, then insert. The classic check-then-act.
"count, then insert": async (c, t, u) => {
const { rows } = await c.query("SELECT count(*)::int AS n FROM seats WHERE tenant_id = $1", [t]);
const { rows: [l] } = await c.query("SELECT seat_limit FROM tenants WHERE id = $1", [t]);
if (rows[0].n >= l.seat_limit) return false;
await c.query("INSERT INTO seats (tenant_id, user_id) VALUES ($1, $2)", [t, u]);
return true;
},
// 2. One statement: INSERT ... SELECT ... WHERE count < limit. Looks atomic, is not under READ COMMITTED.
"single INSERT ... WHERE count < limit": async (c, t, u) => {
const r = await c.query(
`INSERT INTO seats (tenant_id, user_id)
SELECT $1, $2 WHERE (SELECT count(*) FROM seats WHERE tenant_id = $1) < (SELECT seat_limit FROM tenants WHERE id = $1)`, [t, u]);
return r.rowCount === 1;
},
// 3. Lock the tenant row, then count and insert in the same transaction.
"SELECT ... FOR UPDATE on the tenant, then count and insert": async (c, t, u) => {
await c.query("BEGIN");
try {
const { rows: [l] } = await c.query("SELECT seat_limit FROM tenants WHERE id = $1 FOR UPDATE", [t]);
const { rows } = await c.query("SELECT count(*)::int AS n FROM seats WHERE tenant_id = $1", [t]);
if (rows[0].n >= l.seat_limit) { await c.query("ROLLBACK"); return false; }
await c.query("INSERT INTO seats (tenant_id, user_id) VALUES ($1, $2)", [t, u]);
await c.query("COMMIT");
return true;
} catch (e) { await c.query("ROLLBACK"); throw e; }
},
// 4. A counter column with a guarded UPDATE: the row lock serialises writers, the WHERE re-checks.
"guarded UPDATE on a seats_used counter": async (c, t, u) => {
await c.query("BEGIN");
try {
const r = await c.query("UPDATE tenants SET seats_used = seats_used + 1 WHERE id = $1 AND seats_used < seat_limit", [t]);
if (r.rowCount === 0) { await c.query("ROLLBACK"); return false; }
await c.query("INSERT INTO seats (tenant_id, user_id) VALUES ($1, $2)", [t, u]);
await c.query("COMMIT");
return true;
} catch (e) { await c.query("ROLLBACK"); throw e; }
},
};
async function setup() {
await pool.query(`DROP TABLE IF EXISTS seats; DROP TABLE IF EXISTS tenants;
CREATE TABLE tenants (id int PRIMARY KEY, seat_limit int NOT NULL, seats_used int NOT NULL DEFAULT 0);
CREATE TABLE seats (tenant_id int NOT NULL REFERENCES tenants(id), user_id int NOT NULL, PRIMARY KEY (tenant_id, user_id));`);
}
async function trial(fn, t) {
await pool.query("INSERT INTO tenants (id, seat_limit) VALUES ($1, $2)", [t, LIMIT]);
const clients = await Promise.all(Array.from({ length: CONCURRENCY }, () => pool.connect()));
const t0 = performance.now();
const ok = await Promise.all(clients.map((c, i) => fn(c, t, i)));
const ms = performance.now() - t0;
clients.forEach(c => c.release());
const { rows: [r] } = await pool.query("SELECT count(*)::int AS n FROM seats WHERE tenant_id = $1", [t]);
return { seats: r.n, accepted: ok.filter(Boolean).length, ms };
}
const v = (await pool.query("SHOW server_version")).rows[0].server_version;
const iso = (await pool.query("SHOW default_transaction_isolation")).rows[0].default_transaction_isolation;
console.log(`PostgreSQL ${v}, isolation ${iso}, Node ${process.version}, pg ${(await import("pg/package.json", { with: { type: "json" } })).default.version}`);
console.log(`seat limit ${LIMIT}, ${CONCURRENCY} concurrent add-seat requests per trial, ${TRIALS} trials per strategy\n`);
console.log("strategy | trials over the limit | worst case seats | mean seats | median ms per trial");
await setup();
let tenant = 0;
for (const [name, fn] of Object.entries(strategies)) {
const res = [];
for (let i = 0; i < TRIALS; i++) res.push(await trial(fn, ++tenant));
const over = res.filter(r => r.seats > LIMIT).length;
const worst = Math.max(...res.map(r => r.seats));
const mean = res.reduce((s, r) => s + r.seats, 0) / TRIALS;
const ms = res.map(r => r.ms).sort((a, b) => a - b)[TRIALS / 2];
if (res.some(r => r.accepted !== r.seats)) console.log(" (accepted count differs from rows written)");
console.log(`${name} | ${over} of ${TRIALS} | ${worst} | ${mean.toFixed(1)} | ${ms.toFixed(1)}`);
}
await pool.end();
package.json for the race test
{
"name": "entitlements-bench",
"private": true,
"type": "module",
"dependencies": {
"pg": "8.23.1"
}
}
Race test output, runs 2 and 3
Run 1 is shown in full in the concurrency section. Runs 2 and 3, unedited:
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+2), isolation read committed, Node v24.20.0, pg 8.23.1
seat limit 10, 50 concurrent add-seat requests per trial, 20 trials per strategy
strategy | trials over the limit | worst case seats | mean seats | median ms per trial
count, then insert | 20 of 20 | 50 | 49.5 | 34.0
single INSERT ... WHERE count < limit | 20 of 20 | 50 | 50.0 | 16.9
SELECT ... FOR UPDATE on the tenant, then count and insert | 0 of 20 | 10 | 10.0 | 138.5
guarded UPDATE on a seats_used counter | 0 of 20 | 10 | 10.0 | 30.8
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+2), isolation read committed, Node v24.20.0, pg 8.23.1
seat limit 10, 50 concurrent add-seat requests per trial, 20 trials per strategy
strategy | trials over the limit | worst case seats | mean seats | median ms per trial
count, then insert | 20 of 20 | 50 | 49.8 | 11.0
single INSERT ... WHERE count < limit | 20 of 20 | 50 | 49.2 | 4.9
SELECT ... FOR UPDATE on the tenant, then count and insert | 0 of 20 | 10 | 10.0 | 53.2
guarded UPDATE on a seats_used counter | 0 of 20 | 10 | 10.0 | 70.4
Frequently asked questions
What are entitlements in SaaS?
An entitlement is what a customer's plan allows them to use right now. There are three common kinds: a boolean feature (SSO on or off), a numeric limit (5 seats, 50 projects) and a configuration value (90 days of data retention). Your app resolves them from the plan, the subscription status and any per-account grants such as add-ons or sales overrides, and checks them on the server before it does the work. Feature gating is the enforcement side: allowing or blocking a feature at the point of use based on those entitlements. In identity and access management, entitlement means a user's access rights, which is a different subject.
How do you implement entitlements in a SaaS app?
Store plans, features and limits as data in a catalog. Resolve each account's entitlements from its plan, subscription status and grants (add-ons, overrides, trials) with one pure function that fails closed on anything unknown. Call that check on the server before every write and in background jobs, and enforce numeric limits in the database by locking the tenant row or using a guarded counter in the same transaction as the insert. If you use Stripe Entitlements, sync its feature list into your own table and keep limits in your catalog.
What is the difference between entitlements and feature flags?
A feature flag controls a rollout: who sees code that is still being released, and it is meant to be removed once the release is done. An entitlement controls paid access and lives as long as the plan does. Billing changes it, not engineers. You can store entitlements in a flag tool, and LaunchDarkly documents that pattern as a long-lived targeting rule, but limits, grace periods and billing sync still need code of your own. Many products check both: the flag says the feature is released, the entitlement says this customer paid for it.
What is the difference between entitlements and permissions?
Entitlements are per account and come from billing: does this company's plan include the audit log? Permissions are per user inside the account and come from roles: is this person an admin who may open it? A request to a paid admin feature should pass both checks. Keep them in separate code so a plan change never edits roles and a role change never grants a paid feature.
Do Stripe Entitlements handle usage limits or seat counts?
Not as documented. A Stripe Feature has a name, a unique lookup_key of up to 80 characters and metadata, with no quantity or limit field, and Stripe's examples are on or off features such as API access or premium support. Stripe tells you which features a customer has; numeric limits like seats or projects stay in your own catalog, keyed by the same lookup keys. Stripe also recommends persisting entitlements internally for faster resolution.
How do you enforce a seat limit when invites arrive at the same time?
Serialize writers per tenant in the database. In our test on PostgreSQL 18.7 at READ COMMITTED, 50 concurrent add-seat requests against a 10-seat limit went over the limit in every trial of all 3 runs when the app counted and then inserted, and also when it used a single INSERT ... SELECT ... WHERE count is below the limit (worst case 50 seats, mean 49.2 to 50.0 across runs). Locking the tenant row with SELECT ... FOR UPDATE before counting, or a guarded UPDATE on a seats_used counter in the same transaction, kept every trial at exactly 10.
Should entitlements be a separate service?
Usually not at first. The check is a pure function over data you already load per request, and in our earlier benchmark the same kind of check cost about 0.1 microseconds in-process against 72 microseconds over a local HTTP hop, before any timeout or retry handling. Keep it as a module with one interface inside your app, and extract it when several separately deployed apps need the same answer.
Get in touch.
Whether you have questions or just want to explore what's possible, we're here to help.
