Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created May 6, 2019 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/ff293e23576e6df9efe42dffeba65977 to your computer and use it in GitHub Desktop.
Save alfonmga/ff293e23576e6df9efe42dffeba65977 to your computer and use it in GitHub Desktop.
SaaS plan based volume limits example

Plan based volume limits

Checking plan features is pretty neatly handled by a fairly generic way of asserting if a thing is either "on" or "off".

Checking volumes is a bit different. Why is it different? It is different because we need to include the state of specific resources we are offering our customers, not just flags on the account record.

This means you have to actively poll your database and count stuff on each request. Yes, you can cache a bit and being off by one might not be the end of the world.

In the pricing page example above you can see Checkly offers 5 API checks for one plan and 15 for the other. This is how we assert this volume limit in our backend API

function getVolumeLimits (accountId, delta) {
  const checksCountQuery = Checks.query().where({ accountId }).count()
  const accountLimitsQuery = Account.query().findOne({ accountId })

  return Promise.all([checksCountQuery, accountLimitsQuery])
    .then(res => {
      const count = res[0].count
      const { maxChecks } = res[1]
      const newTotal = parseInt(count) + delta
      return newTotal <= maxChecks
    })
}

This function is executed after basic authorization, but before any actual work is done. We fetch the current amount checks and the plan limit of checks for the current account concurrently. This is a very Javascript Promise.all statement. We compare the current amount to the new total amount. In our specific case, a user can create multiple checks at once, hence the delta argument. In this example it is 1 but in real life it can be any number above 0. We need to check if the total amount of new "things to be created" fits into the plan. In the end, we return if the newTotal is less or equal to the maxChecks, our plan limit. Asserting users are within their plan limits on the backend is really important for all kinds of reasons, but how are we going to do "be nice about it" on the frontend, specifically in an SPA type setup? We don't want to have the situation where a user is happily creating a new thing, hits submit and is then presented with a "you are over your plan limits"-message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment