Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Enforce Free Plan Limits: Database Decision Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Putting the free-plan limit decision in the database means your application reads a limit value from a database table instead of having it hard-coded in the source code. This lets you change limits without redeploying, run experiments on different user cohorts, and keep a full audit trail of who hit which limit and when. Before you start, you need an existing database (PostgreSQL, MySQL, or similar), a backend service that talks to it, and a basic understanding of SQL and your application's user model.

What You'll Need

  • A database you can write to (PostgreSQL, MySQL, SQLite, etc.)
  • Your application's user table, or a way to identify the current user (user ID, workspace ID, tenant ID)
  • Access to the backend code that handles API requests or background jobs
  • A migration tool or SQL client to run schema changes
  • Your existing plan definitions (free, pro, enterprise, etc.)

Step-by-Step

  1. Design the limits table schema. Create a table that stores the plan name, the resource you're limiting (e.g., projects, seats, storage bytes), and the maximum allowed value. Include a primary key on (plan_name, resource_key) so each plan has exactly one limit per resource. Add a created_at and updated_at timestamp for auditing.
  2. Write the migration. Use your migration tool (e.g., Alembic for Python, Flyway for Java, or a raw SQL script) to create the table. A minimal PostgreSQL migration looks like this: CREATE TABLE plan_limits (plan_name VARCHAR(50) NOT NULL, resource_key VARCHAR(50) NOT NULL, max_value BIGINT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), PRIMARY KEY (plan_name, resource_key));
  3. Populate the table with your current free-plan limits. Insert a row for each resource you currently hard-code. For example, if your free plan allows 3 projects and 1 GB of storage, insert ('free', 'projects', 3) and ('free', 'storage_bytes', 1073741824). Also insert rows for paid plans so the lookup always returns something.
  4. Create a database access function. Write a function in your backend that takes a plan name and a resource key, queries the table, and returns the max value. Cache the result in memory for a short TTL (e.g., 60 seconds) to avoid hammering the database on every request. If the row doesn't exist, decide on a fallback: either return a very high number (effectively unlimited) or a sensible default like 0.
  5. Replace hard-coded checks with the database lookup. Find every place in your code where you compare a user's usage against a literal number (e.g., if user.projects.count >= 3). Replace the literal with a call to your new function: limit = get_plan_limit(user.plan, 'projects') then if user.projects.count >= limit.
  6. Handle the decision atomically where needed. For operations that create a new resource (e.g., creating a project), wrap the check-and-create in a transaction or use a conditional INSERT. For example, in PostgreSQL you can use INSERT INTO projects ... SELECT ... WHERE (SELECT COUNT(*) FROM projects WHERE user_id = $1) < (SELECT max_value FROM plan_limits WHERE plan_name = $2 AND resource_key = 'projects'). This prevents two simultaneous requests from both passing the check.
  7. Add a usage counter table (if you don't have one). If your app doesn't already track how many resources a user has, create a usage table with user_id, resource_key, and current_value. Update it on every create/delete. This gives you a single source of truth for both the limit and the current usage.
  8. Expose the limits via an API endpoint. Create a read-only endpoint like GET /api/v1/limits that returns the current user's plan limits and their current usage. This lets your frontend show a progress bar or disable buttons before the user hits the limit.
  9. Write a test for the decision logic. Add a unit test that inserts a user with a plan, sets a low limit in the database, and verifies that the app blocks the action once the limit is reached. Also test that changing the limit in the database takes effect without a code deploy.
  10. Deploy and monitor. Ship the code change, then watch your logs for any errors from the new database lookups. Add a metric for how often the limit is hit, and verify that no user is blocked who shouldn't be.

Common Mistakes

  • Hard-coding the fallback. If you write if limit is None: return 3, you've just moved the hard-coded value into a different file. Always put a real row in the database for every plan.
  • Not handling cache invalidation. If you cache the limit for 60 seconds, a plan change won't take effect for up to a minute. That's usually fine, but make sure your cache key includes the plan name and resource, and consider a shorter TTL for admin-triggered changes.
  • Race conditions. Checking the count and then inserting in two separate queries will let users exceed the limit under concurrent requests. Use a transaction or a conditional insert.
  • Using the wrong type for max_value. If you store the limit as an integer but your usage is a float (e.g., storage in GB), you'll get rounding errors. Store storage in bytes as a big integer, or use a numeric type.
  • Forgetting to update the usage counter on deletes. If a user deletes a project but the usage table still counts it, they'll be blocked from creating new ones. Make sure deletes decrement the counter.

Tips

  • Use a separate table per resource type if your limits have different shapes (e.g., a boolean for "can export" vs. a number for "max projects").
  • Store limits as strings if you need to support values like "unlimited" — use a sentinel like -1 and interpret it in code.
  • Add a grace_period_ends_at column if you want to allow temporary overages.
  • Log every time a limit is enforced, including the user ID, resource, and the limit value, so you can answer support tickets.
  • For multi-tenant apps, include the tenant ID in the limits table if different tenants can have custom limits.
  • Consider a separate plan_override table for individual users who get a custom limit without changing their plan.

Troubleshooting

  • Limits not taking effect after a database change. Check your cache TTL. If you cached the value for 60 seconds, wait or restart the service. If you use a shared cache like Redis, make sure you're not caching across environments.
  • Users are blocked even though they're under the limit. Verify the usage counter is accurate. Run a manual count query and compare it to the usage table. Also check that you're using the correct plan name — a user might be on a legacy plan that doesn't have a row in the table.
  • Database errors on the lookup. If the plan_limits table doesn't exist in a test or staging environment, the query will fail. Make sure migrations run on all environments before the code that depends on them.
  • Performance issues. If the lookup is on every request, add an index on plan_name (already covered by the primary key) and cache aggressively. If you're doing a COUNT on a large table, add an index on the user_id column in the resource table.
  • Race condition still happening. If you're using an ORM, make sure you're using a database-level lock or a serializable transaction. In PostgreSQL, use SELECT ... FOR UPDATE on the user row before checking the count.

Frequently Asked Questions

Q: Should I store the limit in the same table as the user?
A: No. Keep limits in a separate table keyed by plan name. This way you can change limits for all users on a plan at once, and you don't duplicate data.

Q: What if a user upgrades mid-billing-cycle?
A: The lookup should use the user's current plan. When they upgrade, update the plan name on the user record, and the new limits apply immediately. If you want prorated limits, add a plan_started_at column and calculate the allowance based on time elapsed.

Q: Can I use this for rate limiting (requests per second)?
A: Yes, but for high-frequency limits you'll want an in-memory or Redis-based counter, not a database COUNT on every request. Use the database for the limit value, but keep the current count in a fast store.

Q: How do I handle a user who needs a one-time limit increase?
A: Add an overrides table with user_id, resource_key, and max_value. In your lookup function, check the override first, then fall back to the plan limit.

Q: What if my app has no concept of "plans"?
A: You can still use this pattern. Replace plan_name with a user tier or even a global default row. The key is that the limit lives in the database, not in code.

Q: Is it safe to let non-admins see the limit values?
A: Yes, showing a user their own limits is standard practice. Just make sure the API endpoint only returns limits for the authenticated user's plan, not all plans.