Usage-Based API Pricing with Moesif and Recurly

Back in the day, it was normal to buy or rent servers and pay for them in a lump sum, independent of utilization. With the rise of serverless computing, infrastructure to build APIs has become cheaper, and on-demand pricing is the norm. Now that you only pay for what you use, why not include usage-based pricing as a feature in your own SaaS offering.

With usage-based pricing your customers don’t get intimidated by high upfront costs, instead their costs grow as their business grows. Recurly is a subscription management service that allows you to charge your customers based on their API usage.

This article explains how to set up usage-based pricing using Recurly in a Node.js Express install, with the API usage figures coming from Moesif.

Prerequisites

You’ll need a Moesif account and a Recurly account. You also need to have Node.js installed.

Setting up Moesif

The first step is linking API requests with your customers’ IDs. This is a basic step in Moesif’s setup and is needed later to tell Recurly what a customer has to pay for.

const express = require("express");
const moesif = require("moesif-nodejs");

const moesifMiddleware = moesif({
  applicationId: "<APP_ID>",
  identifyCompany: ({ body }) => (body.companyId ? body.companyId : undefined),
});

const app = express();

app.use(express.json());
app.use(moesifMiddleware);
...
app.listen(process.env.PORT || 5000);

You should replace APP_ID with your Moesif Application ID, so that Moesif knows what API to track.

You also have to replace identifyCompany with a function that extracts the customer ID from a request. In this example, the ID is in the request body, but it could be entirely different depending on your implementation.

You can define your API endpoints after you’ve added the moesifMiddleware to the Express app.

With this setup all your API requests will be logged by Moesif API Analytics. The next step is to set up Recurly.

Setting up Recurly

Recurly has plans and customer accounts, where customers can subscribe to more than one plan. In this example, we’ll create a simple plan for our usage-based pricing and the customer can only be subscribed to the single plan.

To create a usage-based plan in Recurly, create the plan and then choose a usage-based add-on. You can set a base price and then increase it, on-demand, when customer use dictates. We will create a free plan and only charge per use in this example, to keep things simple.

Figure 1 shows where to find the configuration of the Recurly plans.

Figure 1: Recurly plans


Click on “New Plan” in the top right and then create a new plan called “Usage-Based” with a plan code of “001”. The price per billing period will stay zero.

Under Plan Add-Ons, create a new add-on. This add-on needs a name and a code. It should be billed at the end of a billing cycle, because we don’t know what a customer will use in advance. Next, create a new “measure unit” called “requests” and set it to a fixed price of $0.01. That way, every request costs a cent. The add-on should not be optional.

Your plan creation form should look like the following:

Figure 2: Recurly plan creation form

Linking Moesif and Recurly

Now that we have a usage-based plan in Recurly, customers can subscribe to it. We need to link the subscription ID in Recurly to the customer ID in Moesif.

Recurly explicitly states in their docs that you shouldn’t use webhooks for account creation, but use instead the return values from their API client. This means Recurly subscription creation and Moesif company and user creation have to be done in one go.

Let’s start with the Recurly part. Inside an Express API endpoint for a signup, you have to use the following two Recurly API calls.

  let account;
  try {
    account = await recurlyClient.createAccount({
      code: getNewCustomerId(),
      firstName: request.body.firstName,
      lastName: request.body.lastName,
      address: request.body.address,
    });
  } catch (error) {
    console.log(error);
    return response.end();
  }

  let subscription;
  try {
    subscription = await recurlyClient.createSubscription({
      account,
      addOns: [{ code: "001" }],
      currency: "USD",
      planCode: "001",
    });
  } catch (error) {
    console.log(error);
    return response.end();
  }

The first one will create a Recruly account for your user, and the second one will start a subscription. You need to create a unique account code on your own. The easiest way to do this is to sign up a customer to your own authentication system first and use the ID you generated.

The second Recurly API call will subscribe the Recurly account to the plan. The plan’s code and its add-on code are the ones we used when we created the plan before.

If everything went well, you should end up with two objects, account and subscription. We will use these in the next step to link them with a company and user inside Moesif.

const moesifCompany = {
  company_id: subscription.uuid,
  metadata: subscription,
};

moesifapi.ApiController.updateCompany(
  moesifCompany, 
  (error) => {
  if (error) {
    console.log(error);
    return response.end();
  }

  const moesifUser = {
    user_id: account.account_code,
    company_id: moesifCompany.company_id,
    email: account.email,
    first_name: account.first_name,
    last_name: account.last_name,
    metadata: { ...account },
  };

  moesifapi.ApiController.updateUser(moesifUser, (error) => {
    if (error) console.log(error);
    return response.end();
  };
};

To create a Moesif company from a Recurly subscription, we have to create a new object with a company_id; we will use the uuid of our freshly created subscription for this and put the rest of the subscription data into the metadata of our moesifCompany object.

Next, we use the moesifapi library, which will be installed alongside moesif-nodejs. The updateCompany function will create a new company record in the Moesif service. Since we used the subscription’s uuid, these two are now linked.

The final stage is to create a Moesif user. While it isn’t required for billing, which works on a company level, it will help later on within Moesif if we want to find out who issued which request for the company.

Log All Your Events With Moesif

Learn More

Logging Usage

Now that we can log usage in Moesif -for a company and a user- and we made sure that the company has the same ID as its Recurly subscription, we have to inform Recurly of usage.

function usageMiddleware(request, response, next) {
  recurlyClient.createUsage(
    request.company_id,
    "001",
    { amount: 1 }
  );
  next();
}
app.use(usageMiddleware);

To create a usage in Recurly, you need a subscription ID; since we used the subscription ID as our company ID, we’ll use the company ID here. We just have to make sure it’s present in the request.

Every Express endpoint you create after the usageMiddleware is added will be counted. This is just a basic example, you could batch up the amounts for every company and then send them all at once, or you could write a CRON job that fetches all usage from Moesif API analytics and delivers it directly to Recurly, without your API server being involved.

Embed Usage Reports

Now that your usage-based invoicing is fully set up with Moesif and Recurly, you’ll also want to look into ways to keep your customers informed of their usage. The best way we recommend you to do this is to use embedded dashboards, which elegantly shows usage metrics.

Embedded usage reports enable you to provide self-serve metrics to your customers, so that they can understand what they’re paying for. These reports create additional transparency and trust with your customers, since they can easily track the value they get relative to cost. To get started, view embedded template docs and the example GitHub project.

Set up Quota Alerts and Emails

You can also leverage Moesif Behavioral Emails to automatically inform customers when they are close to, or exceeding, their quota for the billing period. This can be a static threshold, specific to a plan, or even specific to groups of customers.

To get started, follow our guide to set up automatic notifications of quota and billing issues.

Summary

Moesif and Recurly are an excellent combination for usage-based billing. The telemetry is stored in Moesif, so you can leverage its additional widgets like behavioral emails and embedded dashboards to keep your customers informed of their subscription.

You can also set up alerts with Moesif, so your own customer success team can proactively reach out if usage/billing wildly fluctuates during a billing cycle.

Make Your API Platform Successful With Moesif

Learn More
Usage-Based Billing with Moesif and Recurly

Usage-Based Billing with Moesif and Recurly

Learn More