Imagine a SaaS app whose Free plan allows three projects. The API checks the count before creating a project, and the tests pass. Then a customer double-clicks "New project," or a script fires two requests at once, and the workspace ends up with four. Nobody bypassed anything. Both requests checked the count, both saw two, and both created a project.
Plan limits look like a simple if statement. In a concurrent system, they need the same care as a bank balance.
Limits that hold come down to a few decisions:
- Check and reserve capacity in one atomic database step, not a check followed by an insert.
- Keep limits in your own database, synced from your billing provider.
- Return a clear, machine-readable error when a limit is reached.
- Decide in advance what soft limits, overages, and downgrades mean.
- Show usage honestly in the UI, while the server makes the final call.
Why check-then-insert fails
PostgreSQL's default isolation level is Read Committed. Its transaction isolation documentation explains that each query sees a snapshot of the database as of the moment it starts. Two transactions can each count two projects, each decide there's room for one more, and each insert. Nothing is wrong with either transaction on its own; the problem is that the check and the write aren't one step.
Four ways to make it atomic
1. A conditional counter update. Keep a usage counter on the tenant, and reserve capacity with one statement: increase projects_used by one, but only where it's still below the limit, and return the new value. The same documentation explains why this works under Read Committed: when an UPDATE finds a row that another transaction has just changed, it waits, then re-evaluates its WHERE clause against the new version of the row. The second request sees the updated count and its condition fails. PostgreSQL's UPDATE supports RETURNING, so you know immediately whether a row was updated. If none was, the limit is reached.
2. Lock the tenant row. Inside a transaction, select the tenant's row FOR UPDATE, count, then insert. PostgreSQL's explicit locking documentation says rows locked this way can't be locked, modified, or deleted by other transactions until the current transaction ends, so concurrent requests for the same tenant queue up. This keeps the real count as the source of truth, at the cost of serializing writes per tenant.
3. Serializable isolation with retries. At the Serializable level, PostgreSQL detects conflicting concurrent transactions and fails one of them. The documentation is clear that applications using this level must be prepared to retry transactions that fail with a serialization error (SQLSTATE 40001). It's the most general option, but every code path needs retry logic.
4. A transaction-level advisory lock. PostgreSQL's advisory lock functions include pg_advisory_xact_lock, which holds an application-defined lock until the transaction ends. Locking on a key derived from the tenant serializes limit checks without touching the tenant row. Use the transaction-level variant; session-level locks don't mix well with connection poolers in transaction mode.
For most apps, the conditional counter or the tenant row lock is the simplest choice. Both are easy to read and test, and both handle the double-click case.
Counters need care
If you choose a counter:
- Decrement it on delete, in the same transaction as the delete.
- Scope it to the tenant, and include the tenant in every update, like any other tenant data.
- Reconcile it periodically against the real count, because counters drift when a code path forgets to update them.
A CHECK constraint can back this up. PostgreSQL doesn't allow CHECK constraints that look at other rows, but a constraint comparing a counter with a limit stored in the same row is fine. Watch for one trap: if the limit can go down on a downgrade while usage stays above it, that constraint will reject the downgrade update itself. Decide how downgrades work before adding it.
Seats are a limit too
Per-seat plans have the same race, plus a twist: invitations. If pending invites don't count toward seats, a workspace can send ten invites on a five-seat plan, and the problem appears only when people accept. Counting pending invites as reserved seats, and freeing them when invites expire or are revoked, keeps seat counts honest and stops the surprise at acceptance time.
Where limits come from
Your billing provider knows what the customer paid for. Your database needs to know it too, quickly and reliably:
- Subscription status matters. Stripe's subscriptions overview describes statuses such as active, past_due, and unpaid, and recommends revoking access when a subscription becomes unpaid. Stripe only moves a subscription to unpaid if your subscription settings choose that outcome, so check which statuses your account actually produces.
- Entitlements are features, limits are numbers. Stripe Entitlements maps products to features and sends an
entitlements.active_entitlement_summary.updatedwebhook when they change, and Stripe recommends persisting them internally. Entitlements tell you whether a feature is on. Numeric limits, such as three projects or 10,000 API calls, usually live in your own plan table, keyed by plan. - Seats come from the subscription quantity. Stripe's quantities guide uses the quantity for per-seat pricing, and its proration documentation explains how changes mid-period are charged.
Sync through webhooks, and handle them carefully. Stripe's webhook guide recommends guarding against duplicate events by logging event IDs, notes that Stripe doesn't guarantee events arrive in the order they were generated, and says it retries failed deliveries for up to three days. Store the plan with a timestamp, ignore older updates, and run a periodic reconciliation against the billing API in case a webhook was missed.
Caching limits
Reading the plan from your own database on every write is usually fast enough. If you cache it, decide how stale it's allowed to be, and clear the cache when a plan webhook arrives. An upgrade that takes minutes to apply is a support ticket; a downgrade that takes minutes is usually harmless.
Which error to return
When a limit is reached, the response should tell the client exactly what happened. The HTTP specification, RFC 9110, offers a few candidates:
- 403 Forbidden: the server understood the request but refuses to fulfill it.
- 409 Conflict: the request conflicts with the current state of the resource.
- 402 Payment Required: defined but reserved for future use, so clients may not handle it consistently. Some APIs use it anyway; Shopify's response codes use 402 when a shop is frozen.
Avoid 429 Too Many Requests for plan limits. RFC 6585 defines it for too many requests in a given amount of time, which is rate limiting, and clients often retry it automatically. Stripe's rate limit documentation and GitHub's REST rate limits use it that way.
Whichever status you choose, return a body clients can act on. RFC 9457, Problem Details for HTTP APIs, defines type, title, detail, and extension members, served as application/problem+json. Its own example of an account without enough credit uses 403. A response with a stable problem type such as "plan-limit-reached," plus the limit, current usage, and an upgrade link, lets React show a precise message.
Soft limits and warnings
Not every limit should be a wall:
- Warn before the limit. Vercel's spend management sends notifications at 50, 75, and 100 percent of a budget. GitHub's budgets and alerts alert at 75, 90, and 100 percent, and for metered products a budget can stop usage once it's reached.
- Choose between blocking and overage. Some limits should stop at 100 percent; others can allow usage beyond the plan and bill for it. Make that a product decision, documented per limit.
- Expect some lag in metered limits. Vercel notes that pausing projects after a limit can take several minutes.
Metered usage is different from counts
Counting projects or seats needs strong consistency, because the count is right there in your database. Metered usage, such as API calls or storage, is usually aggregated. Stripe's meters aggregate meter events over a billing period, and its usage recording API processes events asynchronously. Use them for billing, not as a real-time cap. If a metered limit must stop usage immediately, keep your own counter and treat the billing meter as the invoice record.
Downgrades
A customer on a ten-project plan downgrades to three. What happens to the other seven? Real products tend to avoid deleting data:
- Slack: per its plans and pricing information, Free workspaces get 90 days of message and file history, and content more than a year old is permanently deleted.
- Atlassian: its billing guidance asks customers to reduce the number of users before changing to a plan with a lower user limit.
- GitHub: its downgrade documentation says an organization loses features not in the new plan, effective from the next billing date.
A practical default: keep existing data, block creating new items until usage is back under the limit, and show which items are over. Decide whether over-limit items become read-only. Stripe's entitlements documentation notes that subscription pricing, plan, and entitlement changes might be subject to legal requirements, so check consumer rules where you sell.
Showing usage in React
The UI should make limits visible before they surprise anyone:
- Show usage as a meter. MDN describes the meter element as representing a value within a known range, which fits "2 of 3 projects." Use the progress element for task completion instead, and give either one an accessible label.
- Explain instead of hiding. When the limit is reached, keep the "New project" button visible but explain why it's disabled, with an upgrade link.
- Let the server decide. The UI can be wrong, stale, or racing another tab. Handle the problem-details response gracefully even when the button looked enabled.
Checklist
- Enforce limits atomically, with a conditional counter update, a tenant row lock, Serializable with retries, or a transaction-level advisory lock.
- Scope counters to the tenant, decrement on delete, and reconcile them.
- Watch CHECK constraints that would block a downgrade.
- Count pending invites as reserved seats.
- Keep numeric limits in your plan table, synced from billing.
- Handle webhooks idempotently, tolerate out-of-order delivery, and reconcile periodically.
- Bound cache staleness, and clear caches on plan changes.
- Return 403 or 409 with problem details, not 429.
- Warn at thresholds, and decide blocking versus overage per limit.
- Don't use billing meters as real-time caps.
- Keep data on downgrade, block new creation, and show what's over.
- Show usage with an accessible meter, and let the server have the final say.



