How to Easily Deploy Usage-Based Billing with Moesif and SBT-AWS for SaaS

Introduction

Are you building a SaaS application on AWS and wrestling with the complexities of implementing usage-based billing? Moesif and Amazon Web Services (AWS) are working together to make it easy for SaaS architects and developers to implement usage-based billing with the SaaS Builder Toolkit for AWS (SBT-AWS). Moesif is a cloud-based solution for usage-based metering and billing. SBT-AWS is an open-source developer toolkit provided by AWS to implement SaaS best practices. With the recently released Moesif Module for SBT-AWS, billing infrastructure can quickly be incorporated in SBT-AWS projects making it easier than ever to monetize your SaaS application and driving usage-based revenue.

Why Usage Based Billing?

Usage-based billing models (also called consumption-based billing) are quickly becoming the preferred way to monetize APIs and SaaS applications to accelerate adoption time, increase expansion revenue, while improving overall customer experience. For applications with high infrastructure cost like data APIs and AI-based applications, usage-based billing allows SaaS providers to maximize revenue by aligning the costs with actual usage. Consumers benefit from cost control and transparency, paying only for what they use, while gaining the flexibility to scale usage as needed. This model also fosters innovation by reducing the financial risk associated with adopting a new API or SaaS application

Challenge with Usage-Based Billing

Usage-based pricing requires a flexible reliable analytics system to accurately meter customer usage in real-time. This requires significant time and engineering resources to build the needed data infrastructure to meter usage at scale delaying the time to start generating revenue. Tracking granular usage metrics, accurately invoicing customers with the right amounts, and ensuring ASC 606 compliant revenue recognition can introduce significant complexity. The development to create this billing infrastructure is time taken away from core development which can prolong monetization plans.

Another challenge is accurately predicting and managing costs for SaaS providers and customers. Usage patterns can be unpredictable, leading to fluctuating bills that are difficult to budget for and create unexpected cost from overage. Additionally, setting the right price points is a balancing act, as overly high prices deter users while overly low prices lead to revenue loss for providers.

Challenge building SaaS Applications

Besides investment in billing, building a successful SaaS involves a significant engineering investment in many “boring” systems that goes unnoticed by the end-user. A substantial amount of effort is dedicated to creating essential infrastructure. This includes building robust billing systems, secure authentication flows, reliable provisioning processes, and intuitive onboarding experiences. These underlying components are critical for the smooth operation of the SaaS platform but can divert valuable engineering resources away from developing innovative features that directly enhance the product’s value proposition.

The Moesif Solution

Moesif is a turnkey usage-based billing solution for APIs and AI-based applications. With powerful metering and analytics capabilities, you can quickly create complex metering rules on just about any attribute around your event data such as billing on API transactions, compute resources, or unique users. You can set up prepaid credits, tiered discounts, quotas and entitlements, and more. As an open platform, Moesif can automatically invoice through your preferred invoicing solutions like Stripe, Zuora, or a custom invoicing solution.

With Moesif, you can meter usage in real-time so you can take action such as revoke access when credits run out or payment failed. Moesif also unifies usage reporting from disparate sources such as Amazon API Gateway, Amazon Data Firehose, internal applications, and more, simplifying metering and rating. This ensures product owners and customer facing teams have a good understanding of customer usage ensuring customer spend is aligned to value. 

The SaaS Builder Toolkit

Like Moesif, the AWS SaaS Builder Toolkit for AWS (SBT) is an open-source developer toolkit to quickly build SaaS applications without worrying about the “boring” stuff. SBT is a boilerplate to handle the common functions most SaaS applications require including billing, authentication, provisioning, onboarding, and more. SBT is built on top of the AWS Cloud Development Kit (CDK) which makes it easy to treat your SaaS infrastructure as Code (IaaC) to easily encapsulate SaaS and devops best practices in your application.

Moesif Plugin for SBT-AWS

With the Moesif plugin for SBT-AWS, you can add native usage-based billing capabilities to your SBT-AWS based applications without worrying about the boilerplate logic. The plugin is specifically tailored for SaaS applications built with the SaaS Builder Toolkit for AWS and provides the following capabilities into your SaaS architecture:

  • Accurate Event Ingestion: The plugin leverages Moesif’s AWS Firehose integration to collect your raw usage events. These events, which can encompass API calls or custom actions within your application, are sent to Moesif’s Collection API for accurate metering and aggregation.
  • Unified User and Tenant Management: A dedicated AWS Lambda function ensures that core SaaS entities (tenants, subscriptions, and users) remain synchronized across your SBT-AWS deployment, Moesif, and your selected payment gateway (e.g., Stripe, Zuora).
  • Automated Usage-Based Invoicing: Moesif’s comprehensive API monetization features allow you to define billable metrics, streamline the invoicing process, and integrate with your preferred payment provider (e.g., Stripe, Zuora).

Key Use Cases

Moesif and the Moesif SBT-AWS plugin empowers you to:

  • Monetization of APIs: Charge customers based on the volume of API requests, sum of payload size, and more.
  • Monetization AI Applications: Create PAYG pricing models for GenAI-based applications to charge on input tokens, context size, and more.
  • Monetization of Infrastructure: Create billing models that account for resources such as CPU time, memory usage, or storage consumption.

Key Pricing Models

With Moesif and the Moesif SBT-AWS plugin, a variety of different pricing models are supported including:

  • Prepaid Credits: Customers purchase credits upfront which are then burned down over time as Pay-As-You-Go (PAYG). A customer’s access can be revoked when credits run out.
  • In Arrears: At the end of a billing period (such as a month), a customer is invoiced for the previous period’s consumption. This can be paid through credit card, bank transfer, and other payment methods.
  • Commitment Plans A customer can prepay to commit to a usage tier or quota before service is consumed. Volume discounts can be provided for enabling a customer to pay upfront.

How Does it work

The plugin will deploy a set of resources as part of your SBT-AWS project to support usage-based billing including:

  1. An Amazon Firehose to ingest your raw usage events.
  2. An Amazon Lambda to handle provisioning and deprovisioning subscriptions.

The plugin will map Moesif entities to SBT-AWS entities as follows:

SBT Entity Moesif Entity Description Parent
Tenant Company Your customer that you provisioned resources for. None
Tenant Subscription A single subscription for a company/tenant. Company
User User End users of your customer who login to your SaaS. Company

Getting Started

Getting started with the plugin is straightforward. Follow these steps to integrate the Moesif SBT-AWS plugin (assumes an existing SBT-AWS project and Moesif account). The setup takes less than an hour.

Prerequisites

If you don’t already have a SBT-AWS project deployed, follow SBT-AWS’s tutorial to deploy the sample hello-cdk project with a ControlPlane and CoreApplicationPlane.
After your sample project is deployed, follow the steps below.

Installation

Within your SBT-AWS project directory, install SBT-aws-moesif via the following command:

npm install --save SBT-aws-moesif

Add Moesif Module

Instantiate the MoesifBilling construct like below. You will need to set some properties like the moesifApplicationId and moesifManagementAPIKey to authenticate with Moesif.

export class ControlPlaneStack extends Stack {
  public readonly regApiGatewayUrl: string;
  public readonly eventBusArn: string;

  constructor(scope: Construct, id: string, props: any) {
    super(scope, id, props);
    const cognitoAuth = new CognitoAuth(this, 'CognitoAuth', {
      idpName: 'COGNITO',
      systemAdminRoleName: 'SystemAdmin',
      systemAdminEmail: '<<Your Admin Email>>',
    });

    const moesifBilling = new MoesifBilling(stack, 'MoesifBilling', {
      moesifApplicationId: '<<Your Moesif Application Id>>',
      moesifManagementAPIKey: '<<Your Moesif Management API Key>>',
      billingProviderSlug: BillingProviderSlug.STRIPE,
      billingProviderSecretKey: '<<Your Billing Provider\'s Secret Such as for Stripe>>'
    }
   );

    const controlPlane = new ControlPlane(this, 'ControlPlane', {
      auth: cognitoAuth,
      billing: moesifBilling,
    });
    this.eventBusArn = controlPlane.eventBusArn;
    this.regApiGatewayUrl = controlPlane.controlPlaneAPIGatewayUrl;
  }
}

Ingest Events

Now that you created a tenant, you should ingest some actions in your newly created firehose. Actions have an action name (like “Signed Up”, “API Request”, or “Finished Job”) which represents the usage event. You can also include arbitrary metadata with an action, which enables you to create billable metrics, usage reporting, and more. For more info, see docs on actions

You’ll want to set a few fields like below:

action_name is a string and should include name of the event such as “Processed Payment Transaction”
company_id is your tenant identifier. See companies
transaction_id should be a random UUID for this event which Moesif uses for deduplication. Docs on Moesif idempotency.
request.time represents the transaction time as an ISO formatted string.
metadata is an object which includes any custom properties for this event. By setting metadata, you can bill on arbitrary metrics, create metrics on them, etc. For example, if the action name is “Processed Payment Transaction”, you can include an amount and the currency to bill on the total amount.

For full schema and available fields, see Actions API Reference

An example action is below:

{
  "action_name": "Processed Payment Transaction",
  "request": {
    "time": "2024-04-01T04:45:42.914"
  },
  "company_id": "12345",
  "transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257",
  "metadata": {
    "amount": 24.6,
    "currency": "USD",
    "time_seconds": 66.3
  }
}

In the above example, the action is created whenever a payment is processed. There are also two metrics we are tracking as part of the action (the amount of the payment and how long the job took). You can create billable metrics and usage reports from these attributes.

If your events are API calls, we recommend changing the MoesifEventSchema to API_CALL which provides a different schema than the above actions. See API Calls

Let Us Help

The Moesif SBT-AWS plugin is in preview, with active development underway. For more information, you can find the plugin and detailed documentation on GitHub: https://github.com/Moesif/SBT-aws-moesif.

If you’d like a personalized demonstration of how the Moesif SBT-AWS plugin can power your SaaS billing strategy, don’t hesitate to contact us!

API Monetization for AWS API Gateway API Monetization for AWS API Gateway

API Monetization for AWS API Gateway

Learn More