# Home

{% hint style="warning" %}
Now you can ask AI how to use Paigo! Click the search icon at the top right corner and type your question!
{% endhint %}

{% hint style="info" %}
**Hint:** Paigo platform is implemented to be self-explanatory without documentation and friendly to both technical and non-technical users. Signing up and try the product is much easier than reading docs.&#x20;
{% endhint %}

### Overview

Paigo is a modern billing platform to 100% automate SaaS billing for any pricing model, any business stage and any GTM strategy. From quote to cash cycle, Paigo has made every single step in billing operations intelligent and automated without human intervention.:

* **Pricing**: Manage pricing plans for self-serve SaaS or Enterprise SaaS. Test and launch pricings with iterations managed by Paigo.
* **Billing**: Bill customers from onboarding to offboarding with deep integrations with products.
* **Metering**: Usage metering that is scalable, real-time, and reliable from every layer of your stack.
* **Invoicing**: Fully tax-compliant invoice with detailed itemized breakdowns provide 100% visibility to your customers.
* **Payment**: Seamless payment integrations covers multiple currencies. Revenue recovery already built-in with payment process.
* **Analytics**: Explore analytics on revenue and product metrics with visualization and analytics code.

Paigo streamlines the process across engineering, product, finance, operations, sales and growth, and provide insights for revenue growth.

### Feature Overview

#### Pricing - Customizable billing OS for any pricing model

Paigo implements building blocks for modeling pricing, so that SaaS business can define, test, and iterate on friction-free pricing strategies. Paigo supports an enormously large amount of pricing models, thanks to the underlying architecture design for flexibility. Below are just a few sample pricing models:

* Pricing plans with product metric limits
* Feature flags and gates
* Free trial, free credits or free usage amount
* Prepaid credits
* Usage-based pricing
* Recurring subscription
* Custom currency unit
* Tiered prices
* Overage
* Minimum charge
* Commitment
* Customized sales contract

#### Metering - Scalable usage metering from every layer of your stack

Ready to scale up to 1000x your product usage with Paigo's usage metering infrastructure for real-time, performant and accurate tracking.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FAfSEteMODPs0D8kIzX6I%2Fmetering.png?alt=media&amp;token=b7213155-72e8-423b-a893-3b5610c7b90c" alt=""><figcaption></figcaption></figure>

#### Billing stack - Spin up SaaS monetization in 3 minutes with no-code billing stack

Set up an entire end-to-end billing stack in exactly 3 minutes (we tested!) without writing a single line of code. Customize with your logo, brand color and preference.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Fk9rJAP94eJycifuDO4f8%2FUntitled%20design.png?alt=media&amp;token=1dac8860-7ccf-4ac8-9e42-64dcc1c23706" alt="" width="563"><figcaption></figcaption></figure>

#### Analytics - Extract insights from billing & usage analytics without data team

* **Query billing & usage data:** Query data in revenue, billing, pricing or usage with intuitive query builder or SQL query directly.
* **Stream usage data in realtime:** Stream usage data metered into dashboard in real-time.
* **Run analytics lambda code:** Run interactive code or upload JavaScript code snippets to perform analytics on queried data.
* **Visualize and report:** Visualize data with interactive diagrams or exported reports.

### Quick Links

If you want to deep dive into the product and navigate in this documentation site, start with [Getting Started with Paigo](/overview/getting-started-with-paigo) guide.

If you are looking for guide to measure and collect usage data, start with [Usage Metering](/usage-metering/meter-usage-data-at-scale)

### **API Reference**

To use Paigo API, visit [API Docs](https://paigo-public-information.s3.us-east-2.amazonaws.com/public_api.html).


# Getting Started with Paigo

This chapter describes a hands-on guide for getting started with Paigo platform. The chapter will guide through a typical case of SaaS billing setup and get ready to bill customers with a simple SaaS pricing structure. Guidance on further exploring additional features are also provided at the end of the chapter. Going through the entire onboarding process takes roughly 5 minutes 24 seconds.

### Overview

Onboarding checklist can be found under **Home** page and navigate to **Onboarding** at the top right corner.

There are five major steps to get started with Paigo.

* Set up a pricing plan
* Add product metrics to the pricing plan (optional)
* Create a customer and enroll in the plan
* Meter product usage (optional)
* Invoice the customer

Now let's dive in! If you haven't already, sign up for Paigo [here](https://api.prod.paigo.tech/users/login). Remember, everyone starts with Free Forever plan :smile:. Once signed up, navigate to [Paigo dashboard](https://api.prod.paigo.tech/users/login) and login.

### Set up a pricing plan

Follow the steps in this video to quickly create a pricing plan.

{% embed url="<https://www.loom.com/share/ef259bc3ffac4160846bf096eab1cd9e?sid=2a03b732-1d7b-43bd-b6bc-c00550b89faa>" %}

### Add product metrics to the pricing plan (optional)

Follow the steps in this video to quickly add product metrics into pricing plan:

{% embed url="<https://www.loom.com/share/9050a7d2d67a42389b9bb5e22d9cb012?sid=663ca22f-9c45-42be-8482-1e2b058d9390>" %}

### Create a customer and enroll in the plan

Follow the steps in this video to quickly create a customer and enroll in the plan we just created:

{% embed url="<https://www.loom.com/share/cc0140fef02848e18304298e39a6a8d0?sid=3b8ef44f-5653-4b41-ab33-885fc4a0962c>" %}

### Meter product usage (optional)

Paigo implements a wide range of ways to meter SaaS customer's usage of software in real-time. In this guide, we are going to use Paigo dashboard to create usage record and then use a sample script for sending mocked usage data to Paigo. In this step, we are going to send the usage of metric `VM Compute Time`  that we created in a previous step continuously with some interval to mock the behavior of a hypothetical SaaS application.

#### Using Dashboard

From Paigo Dashboard, usage data can be recorded without writing code. Navigate to **Customer** tab and select the customer that you just created from the table. In the customer view, select the **Usage Monitoring** tab near the top navigation bar. Next, from the **Select Dimension** dropdown, choose the dimension `VM Compute Time` and click on the **Report Usage** button. In the **Report Usage** form, the fields of **Customer ID** and **Dimension ID**, are all prefilled. Set value for the following fields with suggested value:

| Field                   | Value                           |
| ----------------------- | ------------------------------- |
| Record Value            | 0.8                             |
| Timestamp               | Leave as default (current time) |
| Record Metadata (Key)   | Foo                             |
| Record Metadata (Value) | Bar                             |

Click on **Add Metadata** to add the key-value pair to metadata. See screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FzFFk5qbg74tA0fRZjlWp%2FCursor_and_Paigo_Customer_Portal.png?alt=media&amp;token=ba614304-9044-42ca-8c63-deb1ab0c0fd6" alt=""><figcaption></figcaption></figure>

In the **Preview Record Code Snippet** section down below, the code to create the same usage record is provided. Click on the **Copy** button on the top right corner of **Preview Record Code Snippet** to copy the code. Click **Submit** button to submit the usage record.

At this point, we have already posted exactly one usage record for the service specified. Now let's explore more automated way to continuously collect usage data.

#### Using Script

Paigo API can be used to measure and collect usage data for SaaS application. In this guide, we are using a sample script to demonstrate how it works with Paigo's [API-based Method](/usage-metering/api-based-method). There are more intelligent methods of usage measurement documented in [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale) chapter. Download the below script to a local machine as `ingestToPaigo.js` and modify the **4** lines marked with **TODO** as the instruction below.

{% tabs %}
{% tab title="Javascript (Node JS)" %}
{% code lineNumbers="true" %}

```javascript
// npm i cross-fetch --save
const fetch = require("cross-fetch");

const sleep = time => new Promise(res => setTimeout(res, time, "done sleeping"));

const ingestToPaigo = async () => {
    const authResponse = await fetch('https://auth.paigo.tech/oauth/token', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            "audience": "https://qnonyh1pc7.execute-api.us-east-1.amazonaws.com",
            "grant_type": "client_credentials",
            "client_id": "client_id", // TODO
            "client_secret": "client_secret" // TODO
        })
    })
    const bearerToken = JSON.parse(await authResponse.text()).access_token;
    for (let i = 0; i < 120; i++) {
        await postUsageRecord(bearerToken);
        await sleep(1000);
    }
    console.log(bearerToken);
};

const postUsageRecord = async (bearerToken) => {
    const response = await fetch('https://api.prod.paigo.tech/usage', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + bearerToken,
        },
        body: JSON.stringify({
            "timestamp": new Date().toISOString(),
            "customerId": "customerId", // TODO
            "dimensionId": "dimensionId", // TODO
            "recordValue": "0.8",
            "metadata": { "Foo": "Bar" }
        })
    })
    console.log(await response.text());
};

ingestToPaigo();
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
# python3 -m pip install requests
import requests
import json
from time import sleep
from datetime import datetime
   
def post_usage_record(bearer_token):
    current_time = datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
    response = requests.post('https://api.prod.paigo.tech/usage', 
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + bearer_token,
        },
        data=json.dumps({
            "timestamp": current_time,
            "customerId": "customerId", // TODO
            "dimensionId": "dimensionId" // TODO,
            "recordValue": "0.8",
            "metadata": { "Foo": "Bar" }
        })
    )
    print(response.text)

def ingest_to_paigo():
    auth_response = requests.post('https://auth.paigo.tech/oauth/token', 
        headers={
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        data=json.dumps({
            "audience": "https://qnonyh1pc7.execute-api.us-east-1.amazonaws.com",
            "grant_type": "client_credentials",
            "client_id": "client_id", // TODO
            "client_secret": "client_secret" // TODO
        })
    )
    bearer_token = json.loads(auth_response.text)['access_token']
    for _ in range(120):
        post_usage_record(bearer_token)
        sleep(1)

ingest_to_paigo()
```

{% endcode %}
{% endtab %}
{% endtabs %}

* **Client ID**: the client id used for auth. Can be provided on request via the **Settings > API**&#x20;
* **Client Secret**: the client secret used for auth. Can be provided on request via the **Settings > API**&#x20;
* **Customer ID**: navigate to **Customer** tab in Paigo dashboard and click in the table the customer profile just created in the step above. In the customer view, copy the **Customer ID** in the customer information widget and paste it on the line marked with `customerId`. It should be in the form of UUID.
* **Dimension ID**: navigate to **Product Metrics** tab in Paigo dashboard and click in the table the dimension just created in the above step, such as `VM Compute Time`. In the dimension view, copy the **Dimension ID** and paste it on the line marked with `dimensionId`. It should be in the form of UUID.

Save the script and run locally with the following command:

```javascript
node ingestToPaigo.js
```

This script first authenticates with Paigo API, then sends a number that mimics the amount of data processed every 1 second to Paigo server. The script will stop by itself after 120 seconds.&#x20;

Now we have some usage data collected, we are going to see how Paigo can leverage them for billing.

### Invoice the customer

Follow the steps in this video to invoice the customer:

{% embed url="<https://www.loom.com/share/5637121239a0442f962edc6229076340?sid=5276bb55-e1fe-42c0-ad92-c5942a84ae29>" %}

Congratulations! When you finish this list, you have finished the basic steps to get started with Paigo. There are a lot more exciting features available on the platform. Again, Paigo is free to use. Just go ahead to explore how they can help your daily work. The last section in this chapter provides some pointer for next reading material.

### Next Steps

* To explore Paigo's different ways of metering usage of SaaS applications, read [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale) chapter for full documentation.
* To explore more ways of modeling pricing in Paigo, read [Product Plans](/saas-pricing/pricing-basics/product-plans) chapter for full documentation.
* To understand the key concepts in Paigo and how they work together, read [Key Concepts](/overview/key-concepts)page for more details.
* To dive deep into how invoicing and payment works, read [Issue Invoice](/invoicing-and-payment/issue-invoice)for full documentation.


# Key Concepts

This chapter introduces the most important concepts in Paigo and uses examples to help understand how those concepts can be used for real-world cases.

### Terminology

**Offering:** Offering represents a pricing plan of the product, or how the product is charged. *As an example, an offering called "Enterprise Plan" is priced $49 per month for subscribed SaaS customers.*

**Dimension:** Dimension represents a valuable product metric that SaaS customers can consume and be charged on. *As an example, a dimension for an API SaaS would be API requests and a dimension for a machine learning platform would be the minutes of GPU used.*

**Customer:** Customer represents a SaaS customer of the SaaS business who uses products and make payments for their usage.

**Measurement:** measurement represents the implementation of how dimension usage is measured, collected and tracked.  *As an example, a dimension called Processing Time (Minutes) for a machine learning SaaS application needs a measurement to define how Paigo calculates the running time in the SaaS infrastructure (such as GPU running in a Kubernetes Pod) and the frequency for Paigo to sample the running time (such as every 30 seconds).*

### Use a typical CRM SaaS as an example

A CRM SaaS business manages an offering called "Basic Plan" that charges $1.30/email sent and $10/Seat. A customer called John Doe subscribes to this plan. These relationship is illustrated in the diagram below.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Frqgd6cSFz0A7ZsUc93MH%2Fimage.png?alt=media&amp;token=a5c01181-fa8e-4b65-98e8-b81443d47eea" alt=""><figcaption></figcaption></figure>

Each of the dimension in the above diagram may have a measurement assigned so that the usage can be measured, collected and tracked. The full picture is illustrated in the diagram below.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Fx9dK7rLohhkbLOfN1IsE%2Fimage.png?alt=media&amp;token=d07d8fe6-eade-4e63-a7f1-5b2d403aeaf5" alt=""><figcaption></figcaption></figure>


# Pricing Basics

Read the below pages to understand the basic concepts and configurations of pricing in Paigo.

* [Product Plans](/saas-pricing/pricing-basics/product-plans)
* [Product Items](/saas-pricing/pricing-basics/product-items)

For modeling specific pricing structures, you can go directly to the following pages:

* [Model Pricing Structure](/saas-pricing/model-pricing-structure)


# Product Items

### Overview

Product items represent some value metric of business that customers can pay for. Product items are atomic units that describe some aspect of the business or software products they are selling. Example of product items are API calls, data storage, number of users, support plan, feature flag, transaction volume, or support plan. Product item represents how product usage occurs, can be measured, tracked, and charged.

### Product Item Configuration

Product Item is a resource used with Product Plans. See [Product Plans](/saas-pricing/pricing-basics/product-plans) for using product items on offerings. A product item can be associated with multiple Offerings.&#x20;

By associating a product items with multiple product plans, the same product item can be reused without redundant information. For example, a SaaS business has a product item of $1 per 1,000 API requests. The same product item can be associated with a public offering called `Enterprise Plan` as well as a private offering similar to Enterprise Plan but with additional discount terms, since the private offering is created for a specific customer's sales deal.

These properties are configurable for a product item.

* **Name** Display name of a product item. It shows up in dashboard, is returned by API, and appear on SaaS customer invoice. Required.
* **Usage Measurement** Measurement specifies how a product item is measured and collected by Paigo. Measurement is an optional property of product item. See [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale) for more details.
* **Consumption Unit** Unit of tracking usage of the product item. Required.
  * **Count-based** The usage doesn't have a unit. Such as API requests are tracked as the number of API requests without a unit.
  * **Time-based** The usage is tracked in the matter of time. Paigo supports second, minute and hour and day.
  * **Data-based** The usage is tracked in the matter of data size. Paigo supports gigabyte, megabyte, kilobyte, and byte.
* **Usage Increment** The chunk of consumption units that is calculated for billing. The final billable usage must be multiple of usage increment. Examples of usage increment can be 1 million API calls, 1 hour of compute time (rather than 1 minute of compute time). As an example to use usage increment, if 1 hour consumption is specified as the billing usage increment, then 1 Hour and 5 Minutes consumption may be treated as 1 Hour of Consumption or 2 Hour of Consumption, depending on the rounding algorithm. Another example is 1,000 API calls. 1,001 API calls may be treated as 1,000 API calls, or 2,000 API calls, depending on the rounding algorithm. Default `1`.
* **Rounding** The algorithm used to calculate the total number of usage increment.
  * **Ceiling:** Ceiling algorithm rounds up. As an example, if 1 hour is specified as the usage increment, then 1 hour and 5 minutes consumption is calculated as 2 hours of consumption with ceiling algorithm.
  * **Floor:** Floor algorithm rounds down. As an example, if 1 hour is specified as the usage increment, then 1 hour and 5 minutes consumption is calculated as 1 hour of consumption with floor algorithm.&#x20;
  * **Rounding:** Rounding algorithm rounds data point to the closest integer. As an example, if 1 hour is specified as the usage increment, then 1 hour and 5 minutes consumption is calculated as 1 hour of consumption, and 1 hour 55 minutes consumption is calculated as 2 hour of consumption.
* **Usage Entitlement** Numerical value represents the amount limit customers can use on a plan. Used with `Fixed Subscription` Offering type. SaaS customers who enrolled in a `Fixed Subscription`  are entitled to use the amount of product in the current product item up to the value specified in this property. For example, a subscription may entitle customers to make up to 1,000,000 API requests. Entitlement can be used jointly with **Allow Overage** for overage usage, and **Consumption Price** for overage charge beyond entitlement.
* **Overage Allowed** The property to determine whether overage usage is allowed and taken into account in billing.
* **Consumption Price** The price to calculate the bill for per usage increment. Such as price for per 1,000,000 API call.
  * For usage-based offering, this property specifies the unit price of usage.&#x20;
  * For fixed subscription offering, this property specifies the unit price of overage usage beyond **Usage Entitlement**. A usage entitlement must be specified in order to have **Consumption Price** take effect.
* **Aggregation Interval** The time period that multiple raw usage data points will be aggregated together using **Aggregation Method** to 1 data point that is used to calculate the bill. For example, an aggregation interval may be 1 hour so that all of the usage amount in an hour is aggregated together into one data point.
* **Aggregation Method** The algorithm to aggregate multiple raw usage data points into one aggregated data point.
  * Sum
  * Average
  * Maximum
  * Minimum
  * Count

### Understand How Billing Aggregation Works

There are two kinds of usage data exist in Paigo: raw usage data and aggregated usage data. Raw usage data are typically more, granular, frequent, real-time or near real-time, whereas aggregated usage data are typically less, high-level, infrequent, and batch processed so that they are not real-time.

As an example, the raw usage data of a product item for GPU usage might be 187 milliseconds, 658 milliseconds, 981 milliseconds in a time sequence within an hour. An aggregated usage data point would be 1826 milliseconds for this hour, which is the sum of three values. In this case, the way to aggregate three data points into one is pretty straightforward, which is to sum up all the data. However, in real-world pricing scenarios, there could be a lot of complicated ways to aggregate usage data. The aggregation can be determined by various input. The following properties on product items are used to determine how aggregations are done for billing.

* Usage Increment
* Rounding
* Aggregate Interval
* Aggregate Method

To best illustrate how the aggregation works, we are using the following example of a product item called API call. The configuration of this product item is shown below.

* Usage Increment: `1,000,000` API Calls
* Rounding: `Ceiling`
* Aggregate Interval: `Hour`
* Aggregate Method: `Count`
* Consumption Price: $`0.01` / 1,000,000 API calls

The SaaS business would send usage data `1` to Paigo API every time one API call is made by a customer. Those 1s are treated as raw usage data with their timestamp and other metadata. In order to calculate a customer's total usage and bill for a month, the following step is performed by Paigo:

1. For each **Hour, Count** the total number of usage records. (As defined in **Aggregate Interval -> Hour, and Aggregate Method -> Count)**. Such as 1,000,001 API calls from 00:00 to 01:00, and 1,999,999 API calls from 01:00 to 02:00.
2. Divide the usage per hour by usage increment to calculate the multiplier of usage increment, such as 1,000,001 / 1,000,000 = 1.000001 for 00:00 to 01:00, and 1,999,999 / 1,000,000 = 1.999999 for 01:00 to 02:00. (As defined in **Usage Increment -> 1,000,000**)
3. Round the multiplier of usage increment with **Ceiling** algorithm. (As defined in **Rounding -> Ceiling**). Such as ceiling(1.000001) = 2 for 00:00 to 01:00 and ceiling(1.999999) = 2 for 01:00 to 02:00.
4. Multiply the multiplier with the usage increment. Such as 2 \* 1,000,000 = 2 Million API calls from 00:00 to 01:00, and 2 \* 1,000,000 = 2 Million API calls from 01:00 to 02:00.
5. Multiply the aggregated usage data with consumption price **$0.01**. (As defined in **Consumption Price -> $0.01**) to get the amount due in fiat currency for each hour. Such as 2,000,000 \* ($0.01 / 1,000,000 API calls) = $0.02 for both hours 00:00 to 01:00 and 01:00 to 02:00.
6. Add the amount due together for each hour for the billing month to calculate the total final bill. In this example, the total amount due from 00:00 to 02:00 is $0.02 + $0.02 = $0.04.

For a more practical view of using different configurations of product items, read the [Model Pricing Structure](/saas-pricing/model-pricing-structure) chapter to see how popular real world pricing strategies are implemented in Paigo.


# Product Plans

### Overview

Product plan represents pricing plans, packages, or SKUs that customers can enroll in and be billed on. Examples of product plan are free trial plan, startup plan, enterprise plan, etc. Product plan defines how bills will be calculated such as fixed amount or variable amount, the schedule of payments such as beginning of billing cycle or end of billing cycle, and adjustments to payment such as free trial period or free credits. All businesses are different, so are their pricing strategies. Product plan in Paigo is built with flexibility so that product plans can be customized and fit various business needs.

### Product Plan Configuration

A product plan can be enrolled by multiple customers or single customer. These properties are configurable for a product plan.

* **Name:** Each product plan has a name that will be used to display on invoice or show up in payment. The product plan name should be human-friendly and intuitive (thinking of `Growth Plan` rather than `growth-plan-public` )
* **Type:**
  * **Usage-based**: The amount customers are billed depends on the exact customer's usage. The billing occurs after the billing cycle concludes, such as the first day of the next month. When the product plan type is `Usage-based`, the **Usage Dimension** property is required to have at least one dimension.
  * **Subscription-based:** The amount customers are billed are determined upfront. Therefore, the billing occurs before the billing cycle starts, such as the first day of the month.
  * **Fixed Fee**: The amount customers are billed is the same for every billing cycle. The billing occurs at the beginning of the billing cycle, such as the first day of current month. When the product plan type is `Fixed Subscription`, the **Usage Dimension** property is optional. If there are dimensions attached to product plan, then the charges for the usage occurs at the end of the billing cycles as invoices.
* **Subscription Price:** Required for `Fixed Subscription`. The fixed amount to be billed to customers every billing cycle.
* **Free Trial**: Whether to enable free trial on the pricing product plan. The configuration of free trials (free trial period, free trial credit, or free trial usage) is determined the other properties.
* **Free Trial Period (Days)**: The number of days for free trial period.
* **Billing Cycle**: The time period for billing to be processed.
  * **Calendar Month**: Billing will be processed with billing cycle aligned with calendar month, such as beginning of the month or end of the month.
* **Usage Dimension**: The product metrics tied to the pricing strategy, such as API call, compute capacity, or storage volume. Usage dimension can be one or more metrics combined as a business package. See [Product Items](/saas-pricing/pricing-basics/product-items) on documentation to define dimensions.

### Model Free Trial

Paigo offers three models of free trial: free trial period, free trial credit, and free trial usage.

Free trial period is defined in terms of days. During the period, all fees and charges are waived for the customers, such as bills based on usage or fixed subscription fees. Invoices are still generated for customers with line items shown, but the amount due during free trial periods is 0. If the free trial period spans more than one billing cycle, Paigo calculates the prorated amount due after deducting the charges from free trial periods. The customer's free trial period status is shown in Paigo dashboard with days remaining or expired dates in the past. The customer's free trial period can also be retried by API. See [Get Customer API](http://www.api.docs.paigo.tech/#tag/Customers/operation/Get%20a%20customer%20by%20ID).

Free trial usage is defined at dimensions level. Customers can use up to a certain limit of product usage free of charge. A classic example of free trial usage is AWS Lambda function: the first 1M Lambda runs are free every month. Free trial usage is implemented in Paigo using dimension entitlement. To define free trial usage, follow the steps below:

1. Turn on the **Usage Entitlement** toggle of a dimension
2. Enter the free trial usage amount in the **Entitlement Limit**, such as 1,000,000 API requests.
3. Turn on **Allow Overage** toggle.
4. Enter the price in the **Consumption Price**
5. Specify other properties as appropriate. See [Product Items](/saas-pricing/pricing-basics/product-items) .

Once dimensions are set up, the initial usage metered is free of charge for every billing cycle. Usage above the entitlement limit will be billed accordingly.

Free trial credit is coming soon.

### Defining Product Plan Best Practices

**Define B2B sales deals as separate product plans**

Each B2B sales deals may contain different software packages, pricing structure, or payment schedule. The best approach to charge customers the right price is to define dedicated product plan for a particular customer, with the following benefits:

* Customized identifier (product plan name) for a particular customer, therefore it's easier to manage
* Allow different pricing structures such as different payment schedule or discount terms
* Update to product plan won't affect other customers. The contract may be renewed or revised. Therefore, the product plan maybe updated. Create dedicated product plan for a customer will minimize the potential impact to other customers bill.

**Leverage usage dimensions to fully customize product plans**

Usage dimension is the key to the flexibility of product plans as usage dimension can be used to represent a product usage metric (such as consumed data), usage entitlement (such as limit 50GB storage), feature flag (such as Enterprise Support Plan, or SLA level 99.95%), or customer value metric (such as number of users). The beauty of product plan is that it allows combinations of usage dimensions of different kinds. For example, a usage-based product plan can consist of the following dimensions at the same time:

* $0.0001 per 1,000 API call, as a product usage metric
* $50 GB Data Storage Limit, as a usage entitlement
* Developer Support Plan for $99/Month, as a feature flag

Different ways of usage dimension combinations can be used to test software packing, or tailored for different segment customers such as SMB, free trials, etc. See [Product Items](/saas-pricing/pricing-basics/product-items) for more documentation and best practices on using dimensions.


# Model Pricing Structure

### Overview

This chapter provides guidance on the implementation to model popular pricing in the industry in Paigo. For each of the popular pricing model, the documentation uses a famous pricing plan of an established business to demonstrate the case. The following pricing models are covered:

* [Pay-as-you-go (Like EC2)](/saas-pricing/model-pricing-structure/pay-as-you-go-like-ec2) (with AWS EC2 On-Demand Pricing example)
* [Subscription Tier](/saas-pricing/model-pricing-structure/subscription-tier) (with Replit Personal Plan example)
* [Custom Unit (Like Snowflake)](/saas-pricing/model-pricing-structure/custom-unit-like-snowflake) (with Confluent ksqlDB Pricing Example)
* [Top-Up Pricing (like OpenAI)](/saas-pricing/model-pricing-structure/top-up-pricing-like-openai)
* [Seat-based Pricing](/saas-pricing/model-pricing-structure/seat-based-pricing)


# Pay-as-you-go (Like EC2)

### Overview

AWS EC2 on-demand pricing can be found on [this page](https://aws.amazon.com/ec2/pricing/on-demand/). The core of EC2 on-demand pricing is a pay-as-you-go plan with a single dimension on running time. The basic structure is billing the running time by hourly price. The critical implementation behind EC2 pricing is that hour is the minimum usage increment, any usage beyond a hour will be rounded up to the entire hour.

### Implement AWS EC2 On-Demand Pricing

EC2 on-demand price can be implemented in Paigo with an offering called `EC2 On-Demand` with one usage dimension attached to the offering. The dimension has following configurations.

* Consumption Unit: Minute
* Consumption Price: $0.096
* Usage Increment: 60
* Rounding: Ceiling
* Aggregate Interval: Hour
* Aggregate Method: Sum

The idea of this configuration is that with a short time interval such as every five minutes, the usage of EC2 instance is sampled, and stored in Paigo as raw usage data. For example, the instance ran for 3 minutes in the past 5 minutes. Therefore, a usage record of `3` is saved to Paigo as the raw usage data. After an hour, Paigo billing aggregation system will kick in and calculate the **sum** (as specified by **Aggregate Method**) of all raw usage data, such as 47 minutes, divide it by **60** minutes chunk (as specified by **Usage Increment**), and round it **up** (as specified by **Rounding**), so that the final billable amount is 1 hour, and the amount due for this hour is $0.096. This algorithm is exactly the algorithm behind Paigo's [Infrastructure-based Method](/usage-metering/infrastructure-based-method) to calculate customer's usage and bill automatically.

Note that there is not only one way of implementing EC2 on-demand pricing. Depending on the usage measurement technique, other alternatives including using **Count** as the **Aggregate Method** when the raw usage data measurement is from the CPU Utilization from CloudWatch per minute data. So the aggregation algorithm would count the number of minutes in an hour that the instance CPU is up and running, and finally aggregates to the billable amount, which is still 1 hour and $0.096.

For more information on the algorithm behind billing aggregation of Paigo, read [Product Items](/saas-pricing/pricing-basics/product-items#understand-how-billing-aggregation-works) chapter.


# Subscription Tier

### Overview

Subscription tiers are very common among SaaS businesses. It's usually the go-to pricing strategy for new businesses. It's easier for both businesses and customers to understand, reasonable and predictable for paying customers. Commonly there are three tiers represent low/medium/high willingness to pay. Replit personal plan is a well-known example of implementing a fixed subscription tier. Its pricing can be found on [this page](https://replit.com/pricing). The core of this pricing plan is a fixed payment every month, and users are set for the usage limit on various things such as storage, transfer or the number of Repl instances. The billing schema behind is a fixed subscription payment with usage entitlement.

### Implement Replit Personal Plan

Replit personal plan can be implemented in Paigo with an offering called `Replit Personal Plan` with subscription price **$20**. This offering will be attached with 4 usage dimensions with configurations below.

<table><thead><tr><th width="246.33333333333331">Dimension Name</th><th width="188">Consumption Unit</th><th>Usage Entitlement</th></tr></thead><tbody><tr><td>Account Storage</td><td>Gigabyte</td><td>10</td></tr><tr><td>Outbound Data Transfer</td><td>Gigabyte</td><td>100</td></tr><tr><td>Always On Repl</td><td>Count-based</td><td>1</td></tr><tr><td>Boosted Repl</td><td>Count-based</td><td>1</td></tr></tbody></table>

###


# Custom Unit (Like Snowflake)

### Overview

The custom currency unit is a popular way of pricing strategy. It abstracts away the complex product metrics and makes the billing protocol between businesses and customers much easier to communicate. Additionally, it also allows the business to tweak the internal implementation without necessarily impacting the customer experience. Confluent ksqlDB is a popular product that adopts a custom currency unit called Confluent Streaming Unit (CSU). Its pricing can be found on [this page](https://www.confluent.io/confluent-cloud/pricing/#ksqldb). The core of this pricing plan is a custom currency in the product that allows customers to consume. The billing schema behind this pricing strategy is a custom product dimension, in the form of currency, that can be mapped from how products are used and link the customer payment to the product dimension on a pricing plan.

### Implement Confluent ksqlDB Confluent Streaming Unit (CSU)

The first step to implementing such a pricing schema is to define the currency. Paigo's dimension system is the best fit for this purpose as it combines flexibility with all built-in billing infrastructure. See below for an example of defining currency as a dimension.

| Configuration Property | Value                          |
| ---------------------- | ------------------------------ |
| Dimension Name         | Confluent Streaming Unit (CSU) |
| Usage Measurement      | API-based Measurement          |
| Consumption Unit       | Count-based / Custom Unit      |
| Consumption Price      | $0.23                          |
| Usage Increment        | 1                              |
| Rounding               | Ceiling                        |
| Aggregate Interval     | Hour                           |
| Aggregate Method       | Maximum                        |

A few notes about the above configuration:

* **Dimension Name** is the billing unit that appeared on customer invoices or charges.
* **Usage Increment, Rounding, Aggregate Interval,** and **Aggregate Method** may be different values based on the application logic of custom currency. For all ways to leverage these configurations, see [Product Items](/saas-pricing/pricing-basics/product-items#understand-how-billing-aggregation-works) for more details.

See the screenshot below for a dashboard view.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2F6gQh5RVLKjc76R329Z0A%2FCursor_and_Paigo_Dashboard___Editor___Retool.png?alt=media&amp;token=297967be-74d7-4500-b9b6-7f9b931cd59f" alt=""><figcaption></figcaption></figure>

With the currency defined, the next step is to wrap it with an offering that customers can enroll in. See below for an example offering configuration.

| Configuration Property | Value                          |
| ---------------------- | ------------------------------ |
| Offering Name          | ksqlDB Pricing                 |
| Offering Type          | Usage-based                    |
| Usage Dimension        | Confluent Streaming Unit (CSU) |

See the screenshot below for a dashboard view.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FzBJVgne6VSiEkxLGEbEg%2FCursor_and_Paigo_Dashboard.png?alt=media&amp;token=0143fc6a-e8c1-4e21-9133-0bea63f3946b" alt=""><figcaption></figcaption></figure>

The very last step is to enroll a customer in this offering.

### Implement Automatic Refill of Custom Credit Unit

Another way to set up currency is that customers' accounts will be refilled with a certain amount of currency units per billing cycle, and they pay a fixed amount on a subscription. The billing schema behind this pricing strategy is a fixed subscription with usage entitlement implemented by Paigo dimension. See below for an example of setting up usage entitlement on a dimension to implement currency refill.

| Configuration Property | Value                     |
| ---------------------- | ------------------------- |
| Dimension Name         | Application Token         |
| Usage Measurement      | API-based                 |
| Consumption Unit       | Count-based / Custom Unit |
| Usage Entitlement      | True                      |
| Entitlement Limit      | 1000                      |
| Consumption Price      | $0.05                     |
| Usage Increment        | 1                         |
| Rounding               | Ceiling                   |
| Aggregate Interval     | Hour                      |
| Aggregate Method       | Maximum                   |

A few notes about the above configuration:

* **Dimension Name** is the billing unit that appeared on customer invoices or charges.
* **Entitlement Limit** is the automatic refill amount at the beginning of every billing cycle
* **Allow Overage** is optional. When turned on, customers are allowed to use more than refilled currency and pay for the additional.
* **Consumption Price** is optional. When **Allow Overage** is turned on, this value is used to calculate bills for the overage currency used.
* **Usage Increment, Rounding, Aggregate Interval,** and **Aggregate Method** may be different values based on the application logic of custom currency. For all ways to leverage these configurations, see [Product Items](/saas-pricing/pricing-basics/product-items#understand-how-billing-aggregation-works) for more details.

See the screenshot below for a dashboard view.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FEr3dSkNV0YOK9s97FJ2V%2FCursor_and_Paigo_Dashboard___Editor___Retool.png?alt=media&amp;token=fbfd502d-88eb-45d9-9476-54393d3c8736" alt=""><figcaption></figcaption></figure>

This dimension defined as custom currency unit can be used in an offering as described in the above example.

### Update Balance

Given that the custom credit currency is defined as a usage dimension, any usage data collection method can be used to report consumption or update balances. See [Usage Metering](/usage-metering/meter-usage-data-at-scale) for more details.

The easiest way to do so is by API-based usage reporting method. See [API-based Method](/usage-metering/api-based-method) for full document.&#x20;

The currency balance can also be manually updated in dashboard. See [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale#ingest-usage-record-with-dashboard) for an example.


# Seat-based Pricing

### Overview

Seat-based SaaS pricing is arguably still the most common ways of pricing structure. It is straightforward to both buyers and sellers. Seat-based pricing usually charges upfront for the amount of seats purchased. Some examples of popular SaaS products with seat-based pricing are HubSpot, Apollo, Rippling, etc. Seat-based pricing sometimes is also called license-based, or subscription-based.

### Enable Seat-based Pricing

Seat-based pricing works in the following ways:

* Billing occurs upfront for the amount of seat purchased.
* Customers can add seats during the billing cycle. An immediate charge will be made for the net new amount added. In the next billing cycle, the total new amount will be billed automatically.
* Depends on the business preference, reducing the number of seats may or may not allowed mid billing cycle.

To enable seat-based pricing, first create a product item called `Seat` of type `Upfront Subscription` ,  which essentially means the product items are determined and charged upfront. Then create a product plan of type `Subscription-based` that contains the product item `Seat`. All other properties of the product plan can be configured as wish, such as monthly recurring fee on top of the fees for `Seat`.

When a customer is enrolled in the product plan, they will be asked to provide the amount of `Seat` purchased. An invoice will be generated and a charge maybe attempted automatically for the total amount due.

For example, if the product item `Seat` is defined as $25/seat, and product plan has a $30 recurring monthly fee. When a customer is enrolled in the plan with `1` seat purchased, the customer will be invoiced and charged $55 upon enrollment. See a screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Ff5qL4UifvoFjPRZTvAmi%2FCursor_and_Paigo_Customer_Portal.png?alt=media&amp;token=c45132e2-3575-4934-9a15-a560ff8a0486" alt=""><figcaption></figcaption></figure>

### Add Seats (Mid Billing Cycle)

During billing cycles, customers may choose to add more seats to what they are already purchased. Paigo has built-in features to automatically handle subscription updates such as adding seats. The business can add seats from Paigo billing dashboard, using Paigo API, or allow customers to self-serve inside Customer Billing Portal. See below for a screenshot of adding seats from Paigo billing dashboard.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FGLWzGQhZ7V0qKmlrW5bt%2FCursor_and_Paigo_Customer_Portal.png?alt=media&amp;token=07972df3-fa42-423e-92e4-d72524eabcf6" alt=""><figcaption></figcaption></figure>


# Top-Up Pricing (like OpenAI)

### Overview

Top-up pricing is a variation of usage-based pricing. Customers must make payments to purchase credits upfront. As the product usage occurs, credits will be deducted accordingly. When certain percentage of the top-up amount is reached, such as 20%, customers will be charged again up to top-up amount. This pricing model is especially popular among AI companies due to the model set-forth by OpenAI's API pricing.

### Enable Top-up Pricing

To enable top-up pricing, a product plan should be created with **Billing Cycle** be `Top Up`. In contrast to billing cycles being monthly or annually, the billing cycle is not driven by time, but by credit balance. The property **Recurring Fee Amount** on the product plan is the total top-up amount. Therefore, it is required to have a non-zero value of **Recurring Fee Amount** in order to use top-up pricing. Optionally, you can specify a property **Top Up Threshold** that triggers recharge of customers to the full top-up amount. By default, the threshold is 20% of full top-up amount. The customers' customer wallets inside Paigo are used to store credits recharged and keep track of the credit balance.

For example, if **Recurring Fee Amount** is $100 and **Top Up Threshold** is 20%, then a customer will be recharged if they started using product with $100 balance in credit and used the product until $20 remaining in balance. The recharging amount would be $80, which is the difference of full top-up amount and the current balance.

Below are some of the implementation mechanism of top-up pricing:

* Top-up product plan can be used only on `Usage-based` plan type. It does not support `Subscription-based` or `Fixed Price` plan types. Top-up product plan also does not support pricing features such as free trial and minimum payments.
* The credit consumption is calculated frequently as customers are using the product, and deducted from credit balance in customer wallet. Invoices will be generated for recharges of top-up product plan.
* Top-up pricing plan can be used only with `Metered Usage` product items. There is no limitation of how pricings of product items are defined, they will be calculated as part of credit consumption.


# Manage Customer Profile

### Overview

Customer information is the billing target in Paigo. Customers should represent the paying entity for bills. Customers can be defined with basic information such as name and email, payment information, billing addresses, tax information, and their enrollment in pricing plans. For different teams or departments with different budgets or paying channels within the same company, different customers should be created and maintained inside Paigo.

### Customer Configuration

These properties are configurable for a customer.

#### Basic Information

* **Customer Name**: A friendly display name of the customer. This name is shown on invoices. Required.
* **Customer Email**: The contact of customers. This email is used to contact customer for billing-related communication such as invoice delivery or payment issues. Please make sure this is a valid email address to ensure the communication of critical billing matters. Required.
* **Offering**: The offering plan customers are enrolled in.&#x20;

#### Payment

* **Payment Channel**: How customers will be charged.
  * **Stripe**: Use Stripe Connect to have Paigo orchestrate the payment. See [Process Payment with Stripe](/invoicing-and-payment/process-payment-with-stripe) chapter for full documentation on payment. Requires Payment enabled and Stripe Connect enabled under Setting > App.
  * **Manual**: Payment will be handled outside Paigo by the business. Paigo will skip payment for the billing.
* **Customer in Stripe**: How to bind a customer entity in Stripe with customer entity in Paigo.
  * **Existing**: Provide an existing customer entity in Stripe by customer ID in Stripe.
  * **Create New**: Paigo will create a new customer in Stripe on behalf the SaaS business.
* **Customer Stripe Account ID**: The unique identifier of customer information in Stripe in the form of `cus_xxxxxxxxxxxxxx`. It can be found in Stripe dashboard when viewing customer's information. See screenshot below for an example.

  <figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FX5xEl8Dl8dYjB4mFXKiA%2FCursor_and_Customers_%E2%80%93_paigo_tech_%E2%80%93_Stripe.png?alt=media&amp;token=a214e3cd-14c7-4998-88e7-a7f8e8f146c0" alt=""><figcaption></figcaption></figure>
* **Preferred Currency**: The currency customer preferred. See the section [#customer-preferred-currency](#customer-preferred-currency "mention") below for more details.

To understand the customer information binding in Paigo and in Stripe, read [Process Payment with Stripe](/invoicing-and-payment/process-payment-with-stripe#binding-customer-entity-in-paigo-with-customer-stripe-accounts) chapter for more details.

#### Billing Address

The properties of the billing address are required to calculate global sales tax and is recommended for invoices to be fully compliant.

* **Address Line 1**
* **Address Line 2**
* **City**
* **State**
* **Postale Code**
* **Country**

#### Tax

* **Customer VAT ID**: To be displayed on invoice if either SaaS business or SaaS customer has a European Union address.
* **Tax Exempt**: Whether the customer is exempt from global sales tax.
  * **None**: the customer is not exempt from global sales tax
  * **Exempt**: the customer is exempt from global sales tax

### Customer Preferred Currency

Customers can choose their preferred currencies for billing. Paigo currently supports the following currencies:

* US Dollar
* Euro

The preferred currency is a customer-specific configuration. Every customer has their own preference. The preferred currency might be the same as or different from the default currency on the offering. If it's the same currency as the offering's, Paigo will not make any currency conversions. If the preferred currency is different from the currency on the currency on the offering, Paigo will dynamically calculate the value to bill based on realtime exchange rate provided by [Open Exchange Rates API](https://openexchangerates.org/).

For example, assume the offering's default currency is US Dollar, and a customer's preferred currency is Euro. If the customer has used $100 equivalent of product usage based on the offering, then the customer will be invoiced and charged €91.80 based on the realtime currency exchange rate. The currency exchange calculation only happens when invoices are generated and when payment is charged. Therefore, the exchange rate is used for those points in time.

Please note that if customer's preferred currency is different from the offering's default currency, the customer is bearing the foreign currency exchange rate risk, because the SaaS business will always receive a fixed amount of revenue for the default currency specified on the offering, but the customer will likely pay variable amount every billing cycle due to the fluctuation of exchange rate.

For SaaS business account balance with regard to difference currencies charged to SaaS customers, see [Process Payment with Stripe](/invoicing-and-payment/process-payment-with-stripe#multi-currency-support) for details.


# Meter Usage Data at Scale

### Overview

The most critical and fundamental steps to get started with usage-based billing and pricing are to measure accurate usage data and collect them for billing/pricing. Paigo does deep integration with SaaS application at every layer to extract usage out in real-time and keep track of the usage amount for the SaaS business.

The architecture diagram below shows how Paigo meteres product usage data from every layer of SaaS application stack:

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FAfSEteMODPs0D8kIzX6I%2Fmetering.png?alt=media&amp;token=b7213155-72e8-423b-a893-3b5610c7b90c" alt=""><figcaption></figcaption></figure>

The table below summarizes usage meter architecture:

<table><thead><tr><th width="306.3333333333333">Layer</th><th>Integration Method</th></tr></thead><tbody><tr><td><strong>Application</strong></td><td>REST API, Amplitude, Mixpanel</td></tr><tr><td><strong>Platform (Storage-based)</strong></td><td>AWS S3</td></tr><tr><td><strong>Platform (Streaming-based)</strong></td><td>Confluent Kafka, AWS Kinesis</td></tr><tr><td><strong>Platform (Query-based)</strong></td><td>PostgreSQL, Bring-your-own-DB</td></tr><tr><td><strong>Platform (Agent-based)</strong></td><td>Prometheus, Grafana, Vector, Logstash</td></tr><tr><td><strong>Infrastructure</strong></td><td>AWS, Azure, Docker, Kubernetes</td></tr></tbody></table>

### Ingest Usage Record with Dashboard

From Paigo Dashboard, usage data can be recorded without writing code. It is great for trying usage data ingestion and getting started with more programmatic way of usage data collection automation. To try creating usage record with dashboard, it is required to have a dimension and a customer profile created. See [Getting Started with Paigo](/overview/getting-started-with-paigo) chapter for an example setup.

To ingest usage record, navigate to **Customer** tab and select a customer profile from the customer table. In the customer profile view, scroll down to **Usage Monitoring** widget. In the dropdown on the top right corner of the widget, select the dimension to record usage with, and click on the **Record Usage** button. In the **Record Usage** form, the fields of **Customer ID**, and **Dimension ID**, are all prefilled. Set value for the following fields with proper values:

* **Record Value**: a numerical value represent the amount of usage
* **Timestamp**: the time of when the usage record is measured. Usually it marks the end of the period when usage amount occurs.
* **Record Metadata (Key - Value Pair)**: additional metadata to be stored on the usage record, such as environment, purpose, owner, developer, contract number, or any arbitrary data to be associated with this usage record. Metadata can be used for analytics purpose in the future. Click on **Add Metadata** to add the key-value pair to metadata. Double click previewed Metadata table cells to edit added metadata, and press **Enter** to save the edits.

See the screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FzFFk5qbg74tA0fRZjlWp%2FCursor_and_Paigo_Customer_Portal.png?alt=media&amp;token=ba614304-9044-42ca-8c63-deb1ab0c0fd6" alt=""><figcaption></figcaption></figure>

In the **Preview Record Code Snippet** section down below, the code to create the same usage record is provided. Click on the **Copy** button on the top right corner of **Preview Record Code Snippet** to copy the code. Click **Submit** button to submit the usage record.


# Usage Measurement Template

{% hint style="success" %}
**New Feature Announcement**

Paigo has introduced native Azure Usage Measurement support! See detailed documentation from [Infrastructure-based Method](/usage-metering/infrastructure-based-method#virtual-machine-compute-time-on-azure-measurement-template)and [Infrastructure-based Method](/usage-metering/infrastructure-based-method#managed-disk-on-azure-measurement-template)
{% endhint %}

### Overview

Usage measurement templates are predefined sets of configurations of measurements and dimensions for commonly used SaaS product usage. For example, compute time is a commonly defined product metric by many infrastructure SaaS business. Paigo has several templates for compute time measurement and dimension configurations. See below table for the supported usage measurement templates.

<table><thead><tr><th width="172">Template Name</th><th width="85">Status<select><option value="9610b3079a734d10af8fe3f613a9673d" label="GA" color="blue"></option><option value="683e537f7e6f4c3eb7cae6952943cb96" label="Preview" color="blue"></option></select></th><th width="109">Platform<select><option value="0b15c76f84134e5091e3fb56aacea774" label="Kubernetes" color="blue"></option><option value="49f1331540624cf1b7ff5bc4f7d45e7a" label="AWS" color="blue"></option><option value="ac1d667d093644a69760ce2635ff57bf" label="Azure" color="blue"></option><option value="4e0f0e0fd34742e7a5e789a7e9d29481" label="S3" color="blue"></option></select></th><th width="143">Method<select><option value="f3ffeefe098f40a2a0484c99325c6df4" label="Agent" color="blue"></option><option value="dbd3c9c7b0d9422a9d1bc03e15934cd6" label="Infrastructure" color="blue"></option><option value="123f2212fbab469e82e35b88c8df2131" label="Datastore" color="blue"></option><option value="658de6e1a0264c5c9af2f6a457d450e5" label="SQL" color="blue"></option></select></th><th>Description</th></tr></thead><tbody><tr><td><a href="/usage-metering/agent-based-method#kubernetes-pod-compute-time-measurement-template">Kubernetes Pod Compute Time</a></td><td><span data-option="9610b3079a734d10af8fe3f613a9673d">GA</span></td><td><span data-option="0b15c76f84134e5091e3fb56aacea774">Kubernetes</span></td><td><span data-option="f3ffeefe098f40a2a0484c99325c6df4">Agent</span></td><td>Measure pod running time in Kubernetes with minute-level precision</td></tr><tr><td><a href="/usage-metering/infrastructure-based-method#ec2-instance-compute-time-measurement-template">EC2 Compute Time</a></td><td><span data-option="9610b3079a734d10af8fe3f613a9673d">GA</span></td><td><span data-option="49f1331540624cf1b7ff5bc4f7d45e7a">AWS</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure EC2 instance running time with minute-level precision</td></tr><tr><td><a href="/usage-metering/infrastructure-based-method#ec2-egress-measurement-template">EC2 Egress</a></td><td><span data-option="9610b3079a734d10af8fe3f613a9673d">GA</span></td><td><span data-option="49f1331540624cf1b7ff5bc4f7d45e7a">AWS</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure network egress from EC2 instance with byte-level precision</td></tr><tr><td><a href="/usage-metering/infrastructure-based-method#ebs-volume-and-snapshot-measurement-template">EBS Volume</a></td><td><span data-option="9610b3079a734d10af8fe3f613a9673d">GA</span></td><td><span data-option="49f1331540624cf1b7ff5bc4f7d45e7a">AWS</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure EBS volume size with gigabyte-level precision</td></tr><tr><td><a href="/usage-metering/infrastructure-based-method#ebs-volume-and-snapshot-measurement-template">EBS Snapshot</a></td><td><span data-option="9610b3079a734d10af8fe3f613a9673d">GA</span></td><td><span data-option="49f1331540624cf1b7ff5bc4f7d45e7a">AWS</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure EBS snapshot size with gigabyte-level precision</td></tr><tr><td><mark style="color:red;">(NEW)</mark><br><a href="/usage-metering/infrastructure-based-method#virtual-machine-compute-time-on-azure-measurement-template">Virtual Machine Compute Time</a></td><td><span data-option="683e537f7e6f4c3eb7cae6952943cb96">Preview</span></td><td><span data-option="ac1d667d093644a69760ce2635ff57bf">Azure</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure Azure VM running time with minute-level precision</td></tr><tr><td><mark style="color:red;">(NEW)</mark><br><a href="/usage-metering/infrastructure-based-method#managed-disk-on-azure-measurement-template">Managed Disk</a></td><td><span data-option="683e537f7e6f4c3eb7cae6952943cb96">Preview</span></td><td><span data-option="ac1d667d093644a69760ce2635ff57bf">Azure</span></td><td><span data-option="dbd3c9c7b0d9422a9d1bc03e15934cd6">Infrastructure</span></td><td>Measure the size of Azure managed disk, with gigabyte-level precision</td></tr><tr><td><mark style="color:red;">(NEW)</mark><br><a href="/usage-metering/datastore-based-method#usage-data-in-s3-measurement-template">Usage Data in S3</a></td><td><span data-option="683e537f7e6f4c3eb7cae6952943cb96">Preview</span></td><td><span data-option="4e0f0e0fd34742e7a5e789a7e9d29481">S3</span></td><td><span data-option="123f2212fbab469e82e35b88c8df2131">Datastore</span></td><td>Collect usage based on data in S3 objects</td></tr></tbody></table>

### Measurement Properties and Predefined Values

Following properties are measurement properties and their values predefined for the templates:

* **Measurement Frequency** The frequency that Paigo measures the usage as the atomic usage data.
* **Precision** The precision of atomic usage data Paigo measures.

Once a measurement is used to populate usage data for a dimension, the dimension configuration is automatically decided based on the configuration of measurement. For example, if the measurement is measuring the compute time, then the dimension unit can only be time-based unit such as Hour. Any other value such as gigabyte will be rejected as invalid.

The Following properties are dimension properties and their values predefined for the templates.

* Unit
* Aggregation Method
* Aggregation Interval
* Usage Increment
* Rounding

See [Product Plans](/saas-pricing/pricing-basics/product-plans) for information on these properties.


# Manage Measurement

### Overview

Measurement is a resource that implements Paigo's unique feature of **Usage Measurement and Collection** engine. Measurement can be created and managed in Paigo dashboard or by API. This chapter introduces Measurement at a high level. For complete guide on a specific kind of measurement that implements one of the support usage measurement and collection methods, see other pages in this chapter.

By official definition, measurement defines where, what and how to calculate usage data and collect back to Paigo backend. For example, a measurement could instruct Paigo to calculate the number of API calls by **subscribing to a production event bus in us-east-1** (where), polls for **the message in an API call topic named** `apiEmit` (what) **every 30 seconds** (how) with a limited **read-only access role** `billing-reader` (how). All of these things can be defined in a measurement so that Paigo can be on autopilot mode to calculate the usage.

### Manage Measurement

The easiest way to manage measurement is from Paigo dashboard. Navigate to **Measurement** tab to see a list of **Measurement** already created. Click **New Measurement** to create new measurement. Click on existing **Measurement** in the table to view the details on the measurement, then update or delete existing measurements. Measurements can be reused by different **Dimensions.**

Paigo supports the following methods for usage measurement and collection. See below pages on detailed information of setting up **Measurement** for those methods.

* [Infrastructure-based Method](/usage-metering/infrastructure-based-method)
* [Agent-based Method](/usage-metering/agent-based-method)
* [API-based Method](/usage-metering/api-based-method)
* [Datastore-based Method](/usage-metering/datastore-based-method)
* SQL-based Measurement (Coming soon).


# Infrastructure-based Method

### Overview

Paigo can measure SaaS customer's usage by inspecting the underlying shared resource usage and map data to each individual tenants to derive accurate usage of customers' in real-time. Among other usage measurement and collection methods, infrastructure-based method requires least setup and maintenance. For comparison with other usage measurement and collection methods, see [Usage Metering](/usage-metering/meter-usage-data-at-scale) chapter for full documentation.

### How it Works

Within Paigo's **Usage Measurement and Collection** engine, there is a component called **Infrastructure Connector.** At a regular interval, infrastructure connector will use Cloud API to gather necessary information for calculate precise resource usage at tenant level. Then it uses metadata and algorithms to slice and dice resource usage into per tenant usage and store data in the usage journal.&#x20;

As an example, consider a common design pattern in SaaS industry that saves customer data in a shared blob storage system such as S3 buckets with different file paths, so that customer A's archive are saved under `s3://all-customer-archive/customer-a-2022-01-01.json` and customer B's archive are saved under \``s3://all-customer-archive/customer-b-2022-01-01.json`  Assume both customers are high usage customers so that there will be gigabytes of data moved into and out of their S3 folder every hour. Unfortunately, AWS S3 AWS has neither the data size available to query at prefix level, nor the total bucket size at hourly frequency. Paigo automatically measures the data usage of customer A and customer B with **Infrastructure-based Measurement.** Below are the high-level steps of how Paigo **Usage Measurement and Collection** measures the usage in this example:

1. At a frequent interval, calls AWS API to get all the objects in S3
2. Walks the virtual directory (prefix) recursively to construct the hierarchy structure and filter the target object patterns / folders / prefix
3. Group all of the objects by metadata key-value pairs
4. Calculate the total size a particular customer has used for the short period of time (such as 5 minutes).
5. This usage record value is timestamped and indexed in the backend journal for future aggregation.
6. As the data size consumed by customer A and B go up and down, Paigo samples the usage size frequently and keeps the usage journal in the backend.
7. On top of the hour, aggregation process kicks in to calculate the total usage of customer A and B respectively in the past hour based on the raw data collected every 5 minutes.&#x20;

### Use Case

For infrastructure-focused SaaS business, the product metrics can typically closely related to the usage of the resources. Those resources usually fall into the categories of compute, storage and network. This measurement method is the best way to automatically calculate the usage amount in realtime and bill customers on. Below is an example list possible product metrics that are good fit for **Infrastructure-based Measurement.** Note that it is not an exhaustive list.

* **Compute Time / GPU Milliseconds / Query Time / Execution Time / Job Running Time** This metric is commonly seen in data platform, AI/ML platform and CI/CD platform. The underlying resources are typically some computing system such as containers, VMs or Kubernetes.
* **Data Storage / Archive / Snapshot / Backup / Log file** The data at rest and data in transit product metrics are more commonly seen within big data industries.
* **Network Egress / Peering / PrivateLink / Load Balancer Network** The network usage is usually common for infrastructure SaaS where the infrastructure cost represents the majority of the business COGS.

### Set up Measurement

Navigate to **Measurement** tab and click **New Measurement** button to see the **Measurement Template Table**. Choose from the table one of the agent-based measurement templates to open the measurement creation form. In the **Creation Form,** some fields are pre-filled based on the template. Provide values to other required or optional fields. Instructions for some of the fields in the form:

* **Measurement Frequency:** This field dictates how frequent will Paigo calculates the raw usage data per tenant. The only supported mode is `Automatic`. Under this mode, Paigo decides the best frequency to sample usage based on many factors, such as type of infrastructure, platform, region, success rate, API throttling, etc.
* **IAM Role ARN** and **External ID:** The read-only access role for Paigo to interact with Cloud API. See [Configure IAM Role](/usage-metering/configure-iam-role) page for details on setting up the role.

The next step is to link measurement to dimensions. Dimension represents the abstraction concept of a product metric, whereas measurement represents the implementation of usage measurement and collection. When a measurement ID is attached to the **Measurement ID** field of a Dimension, the measured usage data will be treated as the data points for that particular Dimension.

As an example, a dimension is defined as `Job Running time in Minutes`, and a measurement is defined as the `Elapsed Time of Serverless Container`. Attaching the Measurement ID will instruct Paigo to treat every single usage value measured from severless container as the running time of a job in minutes.

Note that the actual trigger of measurement is the attachment to a dimension. So when measurement is created initially, Paigo doesn't schedule any process to start measurement. Once a measurement is attached to a dimension, processes are scheduled to start measurement frequently.

### Required Tagging Schema

Paigo uses metadata to qualify measurement data and differentiate tenants. For the underlying infrastructure resources to be identified as being used by a particular tenant, Paigo requires these tagging schema.

* `paigoDimensionId`: REQUIRED. Comma delimited unique identifiers of the dimension this usage record is associated with, assigned by Paigo during dimension creation. Example: `e6a4a1ab-7fd6-43cf-b44f-73a2539fdf85,7946113e-b1b4-11ed-afa1-0242ac120002`
* `paigoCustomerId`: REQUIRED. The **Customer ID** of a customer this usage record attributes to, assigned by Paigo during customer creation. Example: `e8366954-6f36-47e9-8431-ac95f88b5cc7`.

The above tagging schema can be used on any infrastructure resources measured by Paigo.

### EC2 Instance Compute Time (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |
| Precision             | Minute    |
| Unit                  | Hour      |
| Aggregation Method    | Sum       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

Compute time of EC2 instance is the length of collective period of time that AWS EC2 instances runs in good state. Paigo measures the running time of AWS EC2 Instance. With predefined frequency, Paigo will collect the running status of qualified instances, and attribute usage to the right customer automatically. For an instance to be qualified for usage calculation, the following conditions must be met:

* Instances must be in the right region, as specified in measurement configuration.
* Instances must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Instances must be in **RUNNING** state. All hibernated/stopped/terminated instances are not measured as usaged.
* Instances must be tagged with correct tagging schema, as specified in [Infrastructure-based Method](/usage-metering/infrastructure-based-method#required-tagging-schema)
* Instances of type on-demand, reserved or spot instances can all be qualified for usage calculation.

For multiple qualified instances, Paigo will calculate the usage of a sample period as the sum of all running time. For example, if Paigo samples usage every 5 minute and there are 3 qualified instances, the total usage measured by Paigo will be 15 minutes.

The metadata collected on each usage record will be all the property on instances, such as instance ID, vpc, tags, network interfaces, etc.

### EC2 Egress (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |
| Precision             | Byte      |
| Unit                  | Byte      |
| Aggregation Method    | Sum       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

EC2 Egress is the outbound network generated from AWS EC2 instances to internet or other part of the network on AWS. With predefined frequency, Paigo measures the egress traffic originated from AWS EC2 Instances, and attribute usage to the right customer automatically. For an instance to be qualified for egress usage calculation, the following conditions must be met:

* Instances must be in the right region, as specified in measurement configuration.
* Instances must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Instances' CloudWatch metrics must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Instances must be tagged with correct tagging schema, as specified in [Infrastructure-based Method](/usage-metering/infrastructure-based-method#required-tagging-schema)

For egress traffic from multiple qualified instances, Paigo will calculate the usage of a sample period as the sum of all egress traffic from all instances. For example, if Paigo samples usage every 5 minute and there are 3 qualified instances with egress usage of 1,000 bytes, 2,000 bytes and 3,000 bytes, the total usage measured by Paigo will be 6,000 bytes. Also note that the egress data measured has a 10 minute lag. For example, the egress traffic occurred during 00:00 AM - 00:05 AM will be measured by Paigo at around 00:10 AM.

The frequency of egress measurement can increase up to once per minute. However, there are additional cost associated with increased frequency charged by AWS CloudWatch.&#x20;

The metadata collected on each usage record will be all the property on instances where egress traffic originates from, such as instance ID, vpc, tags, network interfaces, etc.

### EBS Volume and Snapshot (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |
| Precision             | Gigabyte  |
| Unit                  | Gigabyte  |
| Aggregation Method    | Max       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

EBS volume size and snapshot are two different dimension Paigo can automatically measure with measurement template. The technology behind is the same. With predefined frequency, Paigo will collect the information of qualified EBS volumes or snapshots, and attribute usage to the right customer automatically. For a volume or a snapshot to be qualified for usage calculation, the following conditions must be met:

* The volume or the snapshot must be in the right region, as specified in measurement configuration.
* The volume or the snapshot must be viewable by the role Paigo assumes, as specified in measurement configuration.
* The volume or the snapshot must be tagged with correct tagging schema, as specified in [Infrastructure-based Method](/usage-metering/infrastructure-based-method#required-tagging-schema)

For multiple qualified volumes or snapshots, Paigo will calculate the usage of a sample period as the sum of all volumes or the sum of all snapshots. For example, if in a particular sample period, there are three qualified volumes of size 10 GB, 30 GB and 40 GB, the total usage measured by Paigo will be 80 GB.

The metadata collected on each usage record will be all the property on the volumes such as IOPS, provisioned throughput, volume ID, etc..

### Virtual Machine Compute Time on Azure (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |
| Precision             | Minute    |
| Unit                  | Hour      |
| Aggregation Method    | Sum       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

Compute time of virtual machines on Azure is the length of collective period of time that virtual machines run in good state. Paigo measures the running time of Azure virtual machine. With predefined frequency, Paigo will collect the running status of qualified virtual machines, and attribute usage to the right customer automatically. For a virtual machine to be qualified for usage calculation, the following conditions must be met:

* Virtual machines must be in the right region, as specified in measurement configuration.
* Virtual machines must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Virtual machines must be in **RUNNING** state. All deallocated/stopped virtual machines are not measured as usaged.
* Virtual machines must be tagged with correct tagging schema, as specified in [Infrastructure-based Method](/usage-metering/infrastructure-based-method#required-tagging-schema)

For multiple qualified virtual machines, Paigo will calculate the usage of a sample period as the sum of all running time. For example, if Paigo samples usage every 1 minute and there are three qualified Virtual Machines, the total usage measured by Paigo will be 3 minutes.

The metadata collected on each usage record will be all the property on the virtual machines, such as virtual machine name, ID, location, etc.

### Managed Disk on Azure (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |
| Precision             | Gigabyte  |
| Unit                  | Gigabyte  |
| Aggregation Method    | Max       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

Paigo measures the size of Azure managed disk. With predefined frequency, Paigo will collect the running status of qualified managed disks, and attribute usage to the right customer automatically. For a managed disk to be qualified for usage calculation, the following conditions must be met:

* Managed disks must be in the right region, as specified in measurement configuration.
* Managed disks must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Managed disks must be tagged with correct tagging schema, as specified in [Infrastructure-based Method](/usage-metering/infrastructure-based-method#required-tagging-schema)

For multiple qualified managed disks, Paigo will calculate the usage of a sample period as the sum of all disks combined. For example, if in a particular sample period, there are three qualified managed disks of size 10 GB, 30 GB and 40 GB, the total usage measured by Paigo will be 80 GB.

The metadata collected on each usage record will be all the property on the managed disks, such as disk name, ID, location, configurations, etc.&#x20;


# Agent-based Method

### Overview

Usage records can be collected by leveraging Prometheus agent and Prometheus Exporter protocol. Among other usage measurement and collection methods, agent-measurement method combines both flexibility and easy maintenance. It's easy enough to launch, and can be configured and extended to do power lifting. For comparison with other usage measurement and collection methods, see [Usage Metering](/usage-metering/meter-usage-data-at-scale) chapter for full documentation.

### How It Works

Prometheus is one of the most popular monitoring and observability products. Paigo leverages Prometheus for agent-based integration method. There are two steps in agent-based integration method: usage measurement and usage collection.

* **Usage Measurement**: The usage data can be measured from any program compatible with Prometheus Exporter protocol, including Prometheus official exporters, Community-supported exporters, 3rd-party exporters or any custom exporters. See a sample list of available exporter [here](https://prometheus.io/docs/instrumenting/exporters/).
* **Usage Collection:** The usage data can be collected to Paigo backend with Prometheus agent, which takes data from exporters. Paigo API has a Prometheus protocol compatible endpoint that listens for usage data.&#x20;

The Prometheus agent can be deployed alongside where SaaS application runs (such as Virtual machine, Container, or Kubernetes) across different platforms (such as AWS, Azure, GCP, Bare Metal, Data Center, or even local laptop). Paigo applies server-side transformation to clean, join, filter or transform the raw data sent from Prometheus to maintain the usage record for billing and pricing purpose.&#x20;

### Deploy Agent and Exporter

The code samples of configuring and deploying agents and exporters can be found in this repository.

{% embed url="<https://github.com/paigo-tech/paigo-prometheus-sample>" %}

To follow the sample deployment, the following components are required in the environment.

* [Helm](https://helm.sh/docs/intro/install/)
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)

This repository contains a sample deployment to leverage Prometheus to gather the usage of Elastic Kubernetes Service on AWS, and collect them to Paigo API. However, Paigo API can receive a wide range of usage data that are in Prometheus protocol. In the sample deployment, there are two components installed:

* Usage Measurement is done by deploying [Kube State Metrics](https://github.com/kubernetes/kube-state-metrics)
* Usage Collection is done by deploying [Prometheus Agent](https://prometheus.io/docs/introduction/overview/).

#### Steps to Deploy

1\. Clone the repository locally.

```sh
git clone git@github.com:paigo-tech/paigo-prometheus-sample.git
```

2\. Replace `<Fill_ME_IN>` with client ID and secret ID for the Paigo API in the `chart/values.yaml` file

3\. (OPTIONAL) Authenticate with a Kubernetes cluster with the following command so that the deployment of next step will be authenticated. This step is required for Kubernetes cluster on AWS EKS.

```sh
aws eks update-kubeconfig --name your-cluster-name-here
```

5\. Install and start Paigo agent with the following command.

```sh
helm upgrade paigo-agent ./chart --install
```

6\. Verify the agent is running successfully with the following command.

```
kubectl get pods -n paigo-billing
```

There should be a pod running with name string starting with `paigo-agent-` and the status should be **RUNNING**.

### Required Tagging Schema

Exporters and agents collect a large volume of data and send over to Paigo API. However, not all data is counted as usage record for billing or pricing. In order for the data collected by exporter to be linked to a dimension in Paigo and attribute the usage to customers correctly, additional metadata is required. Label the pods running in Kubernetes cluster with the following schema in order for the agent and Paigo **Usage Measurement and Collection** engine to treat the data as usage record.

* `paigoDimensionId`: REQUIRED. The **Dimension ID** of the dimension this usage record is associated with, assigned by Paigo during dimension creation. Example: `e8366954-6f36-47e9-8431-ac95f88b5cc7`.
* `paigoCustomerId`: REQUIRED. The **Customer ID** of a customer this usage record attributes to, assigned by Paigo during customer creation. Example: `e8366954-6f36-47e9-8431-ac95f88b5cc7`.

Using the following sample command to assign tags to pods of Kubernetes cluster:

{% code overflow="wrap" lineNumbers="true" %}

```bash
kubectl label pods $REPLACE_WITH_POD_NAME \
  paigoDimensionId=$REPLACE_WITH_DIMENSION_ID \
  paigoCustomerId=$REPLACE_WITH_CUSTOMER_ID
```

{% endcode %}

### Undeploy Agent and Exporter

Use the following sample command to stop and undeploy the package of agent and exporter:

```bash
helm uninstall paigo-agent
```

### Set up Measurement

A measurement is required only for usage-based cost. For billing purpose, this step can be skipped.

Navigate to **Measurement** tab and click **New Measurement** button to see the **Measurement Template Table**. Choose from the table one of the agent-based measurement templates to open the measurement creation form. In the creation for&#x6D;**,** some fields are pre-filled based on the template. Provide values to other required or optional fields. Instructions for some of the fields in the form:

* **Measurement Frequency:** This field dictates how frequent will Paigo calculates the raw usage data per tenant. The only supported mode is `Automatic`. Under this mode, Paigo decides the best frequency to sample usage based on many factors, such as type of infrastructure, platform, region, success rate, API throttling, etc.
* **IAM Role ARN** and **External ID:** The read-only access role for Paigo to interact with Cloud API. See [Configure IAM Role](/usage-metering/configure-iam-role) page for details on setting up the role.

The next step is to link measurement to dimensions. Dimension represents the abstraction concept of a product metric, whereas measurement represents the implementation of usage measurement and collection. When a measurement ID is used in the **Measurement ID** field of a Dimension, the measured usage data will be treated as the data points for that particular Dimension.

### Kubernetes Pod Compute Time (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | Automatic |
| Precision             | Minute    |
| Unit                  | Hour      |
| Aggregation Method    | Sum       |
| Aggregation Interval  | Hour      |
| Usage Increment       | 1         |
| Rounding              | Ceiling   |

Compute time of Kubernetes Pods is the length of collective period of time that Pods run in good state. Paigo measures the running time of Kubernetes Pods with agent-based method. With automatically-decided frequency, Paigo will collect the usage amount of all qualified pods, and attribute usage to the right customer automatically. The measurement frequency is automatic as Paigo collects various set information from the agent at different times, and perform transformation on the data such as join to record atomic usage data.

For a Kubernetes Pod to be qualified for usage calculation, the following conditions must be met:

* The Kubernetes cluster must be viewable by the role Paigo assumes, as specified in measurement configuration.
* Kubernetes Pods must be in **READY** state. All other states of Pods are not counted towards usage calculation.
* Kubernetes Pods must be tagged with correct tagging schema, as specified in [Agent-based Method](/usage-metering/agent-based-method#required-tagging-schema)

For multiple qualified Pods, Paigo will calculate the usage of a sample period as the sum of all running time. For example, if Paigo samples usage every 1 minute and there are three qualified Pods, the total usage measured by Paigo will be 3 minutes.

The metadata collected on each usage record will be all the property on the pods, such as cluster information and other metadata.


# API-based Method

### Overview

Usage record can be collected to Paigo by Paigo's public REST API. Among other usage measurement and collection methods, API-based measurement is the most flexible method while requires most maintenance work and taking longest time to deliver value. For comparison with other usage measurement and collection methods, see [Usage Metering](/usage-metering/meter-usage-data-at-scale) chapter for full documentation.

### Data Record Schema

Paigo's usage record ingestion API `/usage` is designed with simplicity while allowing extensibility for product of various scale. Each individual usage record must be in JSON format that is compliant with the following schema and requirement:

```json
{
  "timestamp": "string",
  "customerId": "string",
  "dimensionId": "string",
  "recordValue": "0.0",
  "metadata": {}
}
```

Requirement for each field:

* `timestamp`  : REQUIRED. The timestamp of usage record in [RFC3339](https://www.rfc-editor.org/rfc/rfc3339) format with a 4-digit year. This is the time the usage occurred, or the end of the usage period. Example: `2021-01-23T01:23:45Z`
* `customerId`: REQUIRED. The **Customer ID** of a customer this usage record attributes to, assigned by Paigo during customer creation. Example: `e8366954-6f36-47e9-8431-ac95f88b5cc7`.
* `dimensionId`: REQUIRED. The unique identifier of the dimension this usage record is associated with.
* `recordValue` : REQUIRED. The amount of the usage on this record. Numerical values are represented as strings to avoid precision loss.
* `metadata` : Key-value pairs used for analytical purpose. Example `{"environment": "staging", "purpose": "proof-of-concept", "owner": "John Doe"}`

For detailed information on response, payload, and other API spec, see [API Docs](http://www.api.docs.paigo.tech/). To construct a usage record payload for API-based method, use Paigo dashboard to try creating a usage record, and copy code from the **Preview** section at the end of the page to get started. See [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale#ingest-usage-record-with-dashboard) for more information.

### Leveraging Metadata

Additional metadata to be stored on the usage record, such as environment, purpose, owner, developer, contract number, or any arbitrary data to be associated with this usage record. Metadata can be used for analytics purpose in the future.&#x20;


# Datastore-based Method

### Overview

Usage records can be collected by Paigo's deep integration with data storage systems. Paigo supports many popular systems such as cloud object/blob store (AWS S3, Azure Blob Storage), queue-based datastore (Kafka, AWS Kinesis), file-based datastore (Log File, Archive), etc. Paigo can connect directly to a wide range of data stores to subscribe to real-time events of SaaS applications, extract usage records by doing server-side transformations, and save usage data for billing and analytical purposes. Among all usage measurement and collection methods, the datastore-based method has several advantages:

* **Change-nothing architecture:** SaaS business does not need to allocate additional infrastructure to store data or to send data, but leverage any existing architecture of the SaaS application.&#x20;
* **Native support:** Datastore-based integration is more suitable for batch usage ingestion as datastores can be used to sink data dumps.&#x20;
* **Performance and scalability:** The ingestion of usage records can harness the power and features of the underlying datastore, such as async processing and high throughput of the queue-based systems

For comparison with other usage measurement and collection methods, see [Meter Usage Data at Scale](/usage-metering/meter-usage-data-at-scale) chapter for the complete documentation.

### How It Works

Within Paigo's **Usage Measurement and Collection** engine, there is a component called **Datastore Connector**. Datastore connector subscribes to a wide range of storage system for updates, and extract usage based on predefined data schema.

As an example, consider a typical architecture pattern in SaaS applications: event-driven architecture. In the backend of SaaS applications, there is usually a central event bus hosted by popular event streaming platforms such as Kafka. Assume this is an API SaaS application, and their customers are billed based on millions of API calls.

1. As part of the datastore-based measurement, Paigo subscribes to topics in Kafka with read-only permissions.
2. &#x20;Whenever a customer makes an API call, an event is emitted on the central event bus for the API call containing metadata such as the API caller and timestamp.
3. As a subscriber to the Kafka topic, Paigo listens to the event as it is emitted, parses the event body, extracts usage data, updates the counter of API calls (usage count), and persists usage record in the backend journal.

Millions of events can be emitted to the central event bus and taken in by Paigo without concerning throughputs or performance.

Different data stores work slightly differently with Paigo, but this control flow demonstrates the high-level idea of the datastore-based method.

### Data Record Schema and Metadata

The data record schema is the standard format that Paigo consumes for usage data measurement and collection. See [API-based Method](/usage-metering/api-based-method#data-record-schema) and [API-based Method](/usage-metering/api-based-method#leveraging-metadata) for details on the schema.

### Usage Data in S3 (Measurement Template)

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 1 Minutes |

AWS S3 is an object store for data persistence. Paigo collects usage data in S3 with the following flow.

1. At a predefined interval, Paigo **Usage Measurement and Collection Engine** discovers all new objects saved in S3 buckets hosted by Paigo and downloads those objects and their metadata (such as prefix, path, etc.)
2. Paigo takes in objects as raw byte streams and decodes them as plain text in [newline delimited JSON (NDJSON)](http://ndjson.org/).
3. Paigo parses each JSON object in NDJSON and validates with the data record schema as defined in [#data-record-schema-and-metadata](#data-record-schema-and-metadata "mention").
4. For validated usage records, Paigo ingests the record into the backend usage journal. For invalid or unprocessed usage records, Paigo will drop a message to the Dead Letter Queue (DLQ) bucket hosted by Paigo.

#### Setup Measurement

Navigate to the **Metering** tab and click **New Measurement** to view the **Measurement Template Table**. Select **Usage Data in S3** to create a new measurement. In the **New Measurement** form, some fields are prefilled for the template. Provide a value for **Measurement Name**. Lastly, in the **Account ID** field, provide an AWS account number that will be able to assume an AWS IAM role with access to the S3 bucket for data ingestion. For context on assuming an IAM role, see AWS Document on [Creating a role to delegate permissions to an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html). Click **Submit** to create a measurement.

Once the measurement is successfully created, click on the measurement from the **Measurement Table**. The below information is provided for ingesting usage data using S3.

* **IAM Role Arn**: The IAM role that can be assumed by the AWS account as specified in the measurement configuration.
* **External ID**: The additional field required when assuming the IAM role provided above. Code examples to assume the IAM roles are provided below. For best security purposes, Paigo will always generate an external ID every time a measurement is created.
* **Region**: The AWS region to initialize the S3 client with.
* **Ingestion**: The S3 bucket path to ingest usage data.
* **DLQ**: The S3 bucket path to read messages in Dead Letter Queue.

The S3 bucket for data ingestion is hosted and fully managed by Paigo. The SaaS business will be granted access to ingest data into the S3 bucket.

The same set of operations to set up and get measurements can also be performed by Paigo API.

#### Ingest Data into S3

Paigo decodes object content saved in S3 as plain text in newline delimited JSON ([NDJSON](http://ndjson.org/)). Below are examples of valid formats of usage data ingested. For the JSON schema of usage records, see [API-based Method](/usage-metering/api-based-method#data-record-schema) chapter.

{% tabs %}
{% tab title="Batch Usage Data" %}
{% code lineNumbers="true" %}

```jsonp
{"timestamp":"string","customerId":"string","dimensionId":"string","recordValue":"0","metadata":{}}
{"timestamp":"string","customerId":"string","dimensionId":"string","recordValue":"0","metadata":{}}
{"timestamp":"string","customerId":"string","dimensionId":"string","recordValue":"0","metadata":{}}
```

{% endcode %}
{% endtab %}

{% tab title="Single Usage Data" %}
{% code lineNumbers="true" %}

```jsonp
{"timestamp":"string","customerId":"string","dimensionId":"string","recordValue":"0","metadata":{}}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Note that pretty-formatted, multiple-line JSON is not a valid NDJSON format.

Below are examples of using the roles and access information provided by Paigo to write data into S3 buckets. For more information on the topic, see AWS Documentation [Uploading objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html).

{% tabs %}
{% tab title="Java" %}
Below is a code example of assuming a role:

{% code overflow="wrap" lineNumbers="true" %}

```java
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
     .roleArn(iamRoleArn) // Provided in measurement
     .withExternalId(externalId) // provided in measurement
     .roleSessionName(roleSessionName) // Any string, such as "mySession"
     .build();
 
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
```

{% endcode %}

See [AWS Official Documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/example_iam_Scenario_CreateUserAssumeRole_section.html) for full code examples of the above snippet.<br>

Below is a code example of uploading an file object to S3 bucket:

{% code lineNumbers="true" %}

```java
public static String putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) {
    try {
        Map<String, String> metadata = new HashMap<>();
        metadata.put("x-amz-meta-myVal", "test");
        PutObjectRequest putOb = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(objectKey)
            .metadata(metadata)
            .build();
   
        PutObjectResponse response = s3.putObject(putOb, RequestBody.fromBytes(getObjectFile(objectPath)));
        return response.eTag();

    } catch (S3Exception e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
   
    return "";
}
```

{% endcode %}

See [AWS Official GitHub Repository](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java) for a full code example of the above snippet.
{% endtab %}
{% endtabs %}

SaaS business has full control over the structure within the S3 bucket with granted access. Paigo **Datastore Connector** is unaware of the hierarchy of folders/prefixes. SaaS business also has full control to read/write/manage the objects within the given S3 bucket.

Please note that the same object is never read or parsed twice by Paigo **Datastore Connector**. The objects that appeared in the S3 bucket are treated as an event emitted.&#x20;

Here is an example of prefix schema that can be used to organize objects in buckets:

```
/customerId/yyyy/mm/dd/hh/MM/ss/uniqueId
```

#### Manage Measurement

Measurements for S3 usage data ingestion can be updated with different account ID. The permission (IAM Role Policy) will be updated accordingly.

Measurements for S3 usage data ingestion can be deleted. The access to S3 buckets will be revoked with the deletion.

#### Error Handling and Dead Letter Queue

For unprocessed or invalid usage records, Paigo will put a message in a Dead Letter Queue (DLQ) S3 bucket hosted and fully managed by Paigo. The DLQ bucket information is also returned as part of the measurement information. The same set of IAM Role Arn and External ID can be used to gain access and read from DLQ bucket.

Paigo puts an object decodable as plain text into DLQ bucket for every S3 file failed to be processed entirely. Note that Paigo ingests as many usage records as possible on a best-effort basis. So if the original S3 NDJSON file contains more than one usage records, and only one of them is malformatted, Paigo ingests all the other ones and discards the malformatted one. But there will be a DLQ message for this malformatted usage record.

As an example, if there is an input file with path `/customerA/2023/01/01/13/41/56/8fh923f.txt` that contains three JSON line as NDJSON, and one of them is malformated. Paigo ingests two usage records into backend usage journal, and puts a new message file in DLQ bucket with prefix `/customerA/2023/01/01/13/41/56/8fh923f.txt`**`.9a1eaab.message.txt`** . The message contains the following information:

* Timestamp of processing usage record, in UTC time
* Which usage record is invalid
* Reason of failed processing
* Process result: ingested, transformed discard, or some other actions taken

Below are examples of using the roles and access information provided by Paigo to read message  from DLQ buckets. For more information on the topic, see AWS Documentation [Downloading an object](broken://pages/NM0Fo4LLmnzGxOlNvFM2).

{% tabs %}
{% tab title="Java" %}
Below is a code example of assuming a role:

{% code overflow="wrap" lineNumbers="true" %}

```java
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
     .roleArn(iamRoleArn) // Provided in measurement
     .withExternalId(externalId) // provided in measurement
     .roleSessionName(roleSessionName) // Any string, such as "mySession"
     .build();
 
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
```

{% endcode %}

See [AWS Official Documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/example_iam_Scenario_CreateUserAssumeRole_section.html) for full code examples of the above snippet.\
\
Below is a code example of reading from S3 bucket.

{% code lineNumbers="true" %}

```java
public static void getObjectBytes (S3Client s3, String bucketName, String keyName, String path) {
    try {
        GetObjectRequest objectRequest = GetObjectRequest
            .builder()
            .key(keyName)
            .bucket(bucketName)
            .build();
 
        ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
        byte[] data = objectBytes.asByteArray();
 
        // Write the data to a local file.
        File myFile = new File(path );
        OutputStream os = new FileOutputStream(myFile);
        os.write(data);
        System.out.println("Successfully obtained bytes from an S3 object");
        os.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (S3Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
```

{% endcode %}

See [AWS Official GitHub Repository](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java#L67) for a full code example of the above snippet.
{% endtab %}
{% endtabs %}

### Usage Data in Kafka&#x20;

| Measurement Property  | Value     |
| --------------------- | --------- |
| Measurement Frequency | 5 Minutes |

Kafka is a popular solution for event based architectures, it enables an extremely scalable high throughput system. Paigo can be given access to a Kafka topic and pull measurement data to be used for billing and usage tracking with the following flow.&#x20;

1. Paigo Consumer registers with host via SASL SSL Username and Password granted through the measurement on paigo backend (See [#setup-measurement-1](#setup-measurement-1 "mention")). The `consumerId` will take the format of `paigo-${measurementId}`
2. Paigo begins to pull usage data from its assigned topic and process it. Paigo takes in each event as a byte stream and expects each to be a valid JSON object.&#x20;
3. Usage data is loaded into the backend journal and queryable via the API or in the UI data explorer.&#x20;

#### Setup Measurement

Navigate to **Metering** tab and click **New Measurement** to view the **Measurement Template Table**. Select **Usage Data in Kafka** to create a new measurement. In the **New Measurement** form, some fields are prefilled for the template. Provide a value for **Measurement Name**. Provide a **Username** and **Password** for your specific topic. In confluent the Username is the API key and the Password is the secret for a given cluster. Fill in the **Bootstrap Server** and **Topic / DLQ Topic** names respectively. All of these should be created ahead of time otherwise the measurement will fail to initialize. In the Confluent UI you can find your Bootstrap server under the **Cluster Settings** tab. Topics are also separated on the left side of the UI. \
See [confluent documentation](https://docs.confluent.io/platform/current/clients/consumer.html) for more information.&#x20;

#### Initial Testing&#x20;

After successfully creating a measurement in Paigo, please wait 15 minutes for Paigo to initialize the consumer, you should see a new consumer register with your cluster afterwards. Once initialized, load JSON data onto the topic with the following format

{% tabs %}
{% tab title="Usage Data event" %}
{% code lineNumbers="true" %}

```jsonp
{"timestamp":"string","customerId":"string","dimensionId":"string","recordValue":"0","metadata":{}}
```

{% endcode %}
{% endtab %}
{% endtabs %}

If successful you should see the usage data populate for your customer in the Paigo UI or via an API call to `GET` `/customers/:customerId/usage`

#### Manage Kafka Measurement

To deregister the consumer, simply delete the measurement. By navigating back to the **Metering** tab selecting the measurement consumer and **Deleting** \
\
**Note**

Deleting will not happen instantaneously, the consumer will deregister over the course of the next fifteen minutes. You can verify the completion of the dregistration in your Kafka Cluster by noting the Paigo consumer no longer appearing.  It is recommended that you halt adding records to your topic before deregistering in order to be sure that the last record was successfully processed.&#x20;

#### Error Handling and Topic DLQ

As apart of the measurement creation, you must expose a DLQ topic for Paigo to handle cases where a record failed to be processed. Paigo requires that the DLQ topic and ingestion Topic are apart of the same Cluster, meaning they share the same bootstrap host. For the API credentials Paigo will need read and write permissions. Specifically read for the ingestion and write for the DLQ topic.  \
\
Errors written to the DLQ topic contain the following information and are a valid JSON object.&#x20;

* Which usage record is invalid
* Timestamp of processing usage record, in UTC time
* Reason of failed processing
* Process result: ingested, transformed discard, or some other actions taken

Downstream of the DLQ it is recommended to have an automated consumer responsible for parsing and taking the correct action, such as storing the event, notifying relevant team members, or reprocessing the event with any corrections required. Such as putting in a missing `customerId` into the usage record.&#x20;


# Configure IAM Role

### Overview

This page describes how to create a IAM role and enable access for **Usage Measurement and Collection**. There are two alternative ways described below to create the IAM role and enable access for Paigo to query your account in order to determine usage.&#x20;

### Requirements

The CLI method requires you have the latest [AWS CLI](https://aws.amazon.com/cli/) installed. Both ways require you have access to create and manage IAM policies within the AWS account that Paigo will interact with.

### Create IAM role with AWS CLI

#### Prepare for the Configurations

Below are two JSON files that you need in order to enable Paigo to measurement usage. Save the below file on the file system, and name it `trust-relationships.json`. This JSON document defines an AWS IAM policy that allows Paigo to assume a role with access to the AWS account owned by SaaS business. Line 8 is the AWS account owned by Paigo. There is an optional field called external ID for assuming role. Change the line 12 to some other External ID for enhanced security. It is a strongly recommended practice to use External ID. However, if you want to opt out using External ID, use the JSON document of the **Without External ID** tab.

{% tabs %}
{% tab title="With External ID (Change Line 12)" %}
{% code title="trust-relationships.json" lineNumbers="true" %}

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {
                "AWS": "647662420899"
            },
            "Condition": {
                "StringEquals": {
                    "sts:ExternalId": "TODO"
                }
            }
        }
    ]
}
```

{% endcode %}
{% endtab %}

{% tab title="Without External ID" %}
{% code title="trust-relationships.json" lineNumbers="true" %}

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {
                "AWS": "647662420899"
            }
        }
    ]
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Save the below file in the same directory as above, and name this file `permissions.json`. This file defines the minimal list of permission granted to Paigo for measurement, billing and analytics functionalities.

{% code title="permissions.json" lineNumbers="true" %}

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "eks:DescribeFargateProfile",
                "eks:ListTagsForResource",
                "cloudtrail:ListServiceLinkedChannels",
                "cloudtrail:GetTrailStatus",
                "cloudtrail:DescribeQuery",
                "eks:ListAddons",
                "cloudtrail:GetEventSelectors",
                "aws-portal:ViewUsage",
                "cloudwatch:Describe*",
                "cloudtrail:CancelQuery",
                "ebs:ListChangedBlocks",
                "eks:DescribeAddon",
                "billing:ListBillingViews",
                "eks:DescribeNodegroup",
                "aws-portal:ViewPaymentMethods",
                "eks:ListUpdates",
                "cloudtrail:GetServiceLinkedChannel",
                "cloudtrail:ListTags",
                "aws-portal:ViewBilling",
                "eks:DescribeAddonVersions",
                "cloudwatch:Get*",
                "cloudtrail:ListQueries",
                "cloudtrail:GetInsightSelectors",
                "eks:ListIdentityProviderConfigs",
                "ebs:GetSnapshotBlock",
                "ec2:Get*",
                "cloudtrail:LookupEvents",
                "cloudtrail:GetTrail",
                "eks:ListNodegroups",
                "cloudtrail:ListTrails",
                "cloudtrail:GetEventDataStore",
                "aws-portal:ViewAccount",
                "ebs:ListSnapshotBlocks",
                "cloudwatch:List*",
                "cloudtrail:GetQueryResults",
                "cloudtrail:DescribeTrails",
                "cloudtrail:ListEventDataStores",
                "eks:ListFargateProfiles",
                "ec2:Describe*",
                "eks:DescribeIdentityProviderConfig",
                "cloudtrail:ListPublicKeys",
                "eks:DescribeUpdate",
                "eks:AccessKubernetesApi",
                "eks:DescribeCluster",
                "cloudtrail:StartQuery",
                "eks:ListClusters"
            ],
            "Resource": "*"
        }
    ]
}
```

{% endcode %}

#### Create a role with the configurations

Run the following command to grant Paigo read-only access from the directory where the configuration files prepared above are saved.

{% code overflow="wrap" lineNumbers="true" %}

```bash
aws iam create-role --role-name paigo-assumed-role \
--assume-role-policy-document file://trust-relationships.json && \
aws iam put-role-policy --role-name paigo-assumed-role \
--policy-name read-cw-read-ec2 --policy-document file://permissions.json
```

{% endcode %}

In the above script, a role named `paigo-assumed-role` will created with the policy specified above.

### Create IAM role with AWS Console

Alternatively, an IAM role can be created from AWS Console.

1. Navigate to the [IAM Role Policy](https://us-east-1.console.aws.amazon.com/iamv2/home#/policies) after logging in to AWS Console&#x20;
2. On the next page for permissions choose the **Create a Policy** option and then chose the **JSON** tab. You should be presented with a page that looks like the following:

   <figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FD8TD2ZV95DFpAoLajqmC%2FScreenshot%20from%202022-06-21%2019-40-18.png?alt=media&amp;token=0282fe1c-24ba-4571-abe1-4c1af3c83591" alt=""><figcaption></figcaption></figure>
3. Paste the following JSON document into the JSON editor. This file defines the minimal list of permission granted to Paigo for measurement, billing and analytics functionalities.

{% code title="" overflow="wrap" lineNumbers="true" %}

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "eks:DescribeFargateProfile",
                "eks:ListTagsForResource",
                "cloudtrail:ListServiceLinkedChannels",
                "cloudtrail:GetTrailStatus",
                "cloudtrail:DescribeQuery",
                "eks:ListAddons",
                "cloudtrail:GetEventSelectors",
                "aws-portal:ViewUsage",
                "cloudwatch:Describe*",
                "cloudtrail:CancelQuery",
                "ebs:ListChangedBlocks",
                "eks:DescribeAddon",
                "billing:ListBillingViews",
                "eks:DescribeNodegroup",
                "aws-portal:ViewPaymentMethods",
                "eks:ListUpdates",
                "cloudtrail:GetServiceLinkedChannel",
                "cloudtrail:ListTags",
                "aws-portal:ViewBilling",
                "eks:DescribeAddonVersions",
                "cloudwatch:Get*",
                "cloudtrail:ListQueries",
                "cloudtrail:GetInsightSelectors",
                "eks:ListIdentityProviderConfigs",
                "ebs:GetSnapshotBlock",
                "ec2:Get*",
                "cloudtrail:LookupEvents",
                "cloudtrail:GetTrail",
                "eks:ListNodegroups",
                "cloudtrail:ListTrails",
                "cloudtrail:GetEventDataStore",
                "aws-portal:ViewAccount",
                "ebs:ListSnapshotBlocks",
                "cloudwatch:List*",
                "cloudtrail:GetQueryResults",
                "cloudtrail:DescribeTrails",
                "cloudtrail:ListEventDataStores",
                "eks:ListFargateProfiles",
                "ec2:Describe*",
                "eks:DescribeIdentityProviderConfig",
                "cloudtrail:ListPublicKeys",
                "eks:DescribeUpdate",
                "eks:AccessKubernetesApi",
                "eks:DescribeCluster",
                "cloudtrail:StartQuery",
                "eks:ListClusters"
            ],
            "Resource": "*"
        }
    ]
}
```

{% endcode %}

4\. Click **Next Tags** , no fields are required on this page.

5\. Click through to the finalize page, and enter a name you can remember, such as `paigo-policy`.

6\. Navigate to [IAM Role Page](<https://us-east-1.console.aws.amazon.com/iamv2/home#/roles/create?step=selectEntities >). You should see the following layout:&#x20;

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FCtZgzEA7ffrOmSEtMXkg%2FScreenshot%20from%202022-06-21%2019-37-17.png?alt=media&amp;token=cf2db2fd-e20a-4cc7-8238-4aee2d3c8cf4" alt=""><figcaption></figcaption></figure>

To configure the External ID select the **Require external ID (Best practice when a third party will assume this role)** near the bottom and fill in an custom string. Take note of this for entering into Paigo later.

7\. Select the **AWS Account** option and choose the **External Account** choice on the next page:

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FBBwTpJf313ZScdKoc45g%2FScreenshot%20from%202022-06-21%2019-37-17.png?alt=media&amp;token=6b03f908-450f-409b-84d2-63d8567f6a37" alt=""><figcaption></figcaption></figure>

8\. Enter the Paigo AWS account ID: `647662420899`

9\. Click **Next** and on the following page select the `paigo-policy`  you just created:&#x20;

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FdQi811ONK5EUeOm5CaNB%2FScreenshot%20from%202022-06-21%2019-46-54.png?alt=media&amp;token=f1325386-a696-4521-a756-5ff8f3981af3" alt=""><figcaption></figcaption></figure>

10\. Click **Next**, then give it a role name you want to call it on the following page:&#x20;

11\. Click **Create Role** to save the role just created.

12\. Copy the role ARN by search for the role name in the list, and click on the **Copy** icon below **ARN.** See below screenshot for an example. The role ARN and externalID will be needed by Paigo.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Fssf2uTylTgfNQVZwstJi%2FCursor_and_IAM_Management_Console.png?alt=media&amp;token=3e25f67d-ca1b-49f7-bb0a-16583b8e806d" alt=""><figcaption></figcaption></figure>


# Issue Invoice

### Overview

Paigo supports fully tax-compliant invoice as part of billing infrastructure. Invoice can be automatically generated by Paigo or created manually for any one-off transactions. Invoices are grouped and viewed by customer profile. To find invoices that is related to a particular customer, navigate to **Customer** tab and scroll down to view all the invoices related.

### Invoice Life Cycle

The table below illustrates the invoice life cycle.

<table><thead><tr><th width="101.33333333333331" align="center">Stage</th><th>Meaning</th></tr></thead><tbody><tr><td align="center">Draft</td><td>Invoices are generated automatically or manually. Draft invoices can be reviewed, edited, approved or voided. Draft invoices are not sent to customers.</td></tr><tr><td align="center">Active</td><td>Invoices are approved by business and sent to customers. Payments have not been made for this invoice.</td></tr><tr><td align="center">Paid</td><td>Invoices that are paid. </td></tr><tr><td align="center">Void</td><td>Invoices that are voided or not in good standing. Voided invoice do not count for revenue analytics. Voided invoices can be marked as other good standing state.</td></tr></tbody></table>

### Automatic and Manual Invoice

At the end of each billing cycle, an automatic invoice will be generated for each customer for their total usage occured in the past billing cycle. The automatic invoice will aggregate all the usage by a particular customer across different services, offerings and dimensions. See [#configure-invoices](#configure-invoices "mention") to understand how automatic invoices are generated.

Business can choose to create manual invoice. Navigate to **Customers** tab and select a customer from the customer table. At the top of the page, click **Off-Cycle Invoice** to generate one-off invoices manually. There are two ways to generate off-cycle invoices, by **Manually Enter Line Items** on the invoice, or by **Selecting Billing Period** and bill customers based on their real usage as line items on the invoice.

Both automatic and manual invoices can be edited when they are in draft status.

### Configure Invoices

Below is an invoice example marked with important fields that can be configured by SaaS business.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FH4EZzr79qvkvgWX4Yfx3%2FScreenshot%20from%202023-12-03%2009-39-00.png?alt=media&amp;token=d4147b71-b6d2-44a6-bfb1-2dbb9153a401" alt=""><figcaption></figcaption></figure>

1. **Logo**: The business logo can be configured in **Setting** > **Invoice** > **Logo Image**. The best size of a logo image would be 60 pixels x 60 pixels ( or 0.2 inch x 0.2 inch). If logo image is not set, the logo section will be empty on invoices.
2. **Customer Information:** Customer business information can be configured in **Customer** profile. It customer business information is not set, this section will be empty on invoices. It is highly recommended to properly set those information for the invoice to be fully tax compliant. See [Manage Customer Profile](/saas-pricing/manage-customer-profile) chapter for full documentation on configuring customer information.
3. **Line Items**: For automatic invoices, the line items are the **Dimensions** of the offering that the customer has subscribe to. Each dimension will be a line item on the invoice, with the dimension name, aggregated usage quantity, unit price and subtotal dollar amount of the dimension usage. For manual invoices, all the line items can be manually entered.
4. **Invoice Date**: For automatic invoices, the invoice date is the end of billing cycle. For manual invoices, the date can be set explicitly.
5. **Due Date**: When the invoice payment is due. It is decided by the payment term of invoices. Payment term can be configured in **Setting** > **Invoice** > **Invoice Payment Terms**. With the payment terms set, the due date on the invoice will be automatically calculated, as the days after the invoice date.
6. **Business Name and Addresses:** Basic business information can be configured in **Setting** > **Company**. If business information is not set, this section will be empty on invoices. It is highly recommended to properly set those information for the invoice to be fully tax compliant.
7. **Tax**: See [Handle Tax and Compliance](/invoicing-and-payment/handle-tax-and-compliance) chapter for more information on automatically include sales tax or VAT on the invoice.

### Issue Payment

Customer profiles in Paigo are required to have payment information entered when they are created. When an invoice is approved and sent to customers, Paigo automatically processes payment as a direct charge with the payment information available on the customer profile. For instance, with Stripe, Paigo issues a direct charge from SaaS business to customers via Stripe Direct Charge. For more information on payment, see [Process Payment with Stripe](/invoicing-and-payment/process-payment-with-stripe) chapter.


# Automatic Line Item Formatting

### Overview

Line items on invoices follow a predetermined format when generated by the Paigo. In this chapter, we take a deep dive into how line items are constructed in invoices. The line items automatic formatting also applies to the automatic invoices generated by Paigo. Off-cycle invoices with line items manually entered will be not formatted by Paigo.&#x20;

### Line Item Format

Format for line items are determined by properties of dimensions and offerings:&#x20;

* Offering Name
* Dimension Name
* Consumption Unit
* Usage Increment&#x20;

A standard line item follows the following structure:&#x20;

```
${Dimension Name} - ${Converted Unit} - ${Offering Name}
```

The element `${Converted Unit}` is automatically determined by Paigo. It is based on the consumption unit and usage increment. For definitions of these two properties, see [Product Items](/saas-pricing/pricing-basics/product-items). As a quick example, when the consumption unit is `Byte` and usage increment is `1024`, the converted unit becomes `Kilobyte`. So the invoice will show `Kilobyte` for ease of understand and better user experience.

### More Examples

We are providing a more detailed example regarding line item formatting.

Assume a SaaS business that wants to bill customers on two dimensions `Queries` and `CPU Hours` for an offering called **Professional Plan**. The dimensions are defined as below.

* **Seats** Usage Increment: 1000 and Consumption Unit: Count
* **Process Time** Usage Increment: 1 and Consumption Unit: Hour

An invoice is generated for the following usage amount:

* **Seats** 400,000 Seats
* **Process Time** 72 Hours

The sample invoice is shown below.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2F8po30bmGEXWdQCsXM035%2Fimage.png?alt=media&amp;token=c9e83d5a-a69f-4b5c-9ab0-22f8ac5a4c68" alt=""><figcaption></figcaption></figure>

The explanation of line items:

* Line item `Seats` is shown in thousands because the usage increment is 1,000. Therefore, the quantity is showing 400, and the line item name is showing as `Seats - Thousand - Professional Plan`.
* Line item `CPU Hours` is shown in its original terms `Hour` because the usage increment is 1.

### Unit Conversion Reference

Below is a table reference for the different automated conversion units.&#x20;

#### Time Units

<table><thead><tr><th width="230" align="center">Unit</th><th width="298.3333333333333" align="center">Usage Increment to Next Level</th></tr></thead><tbody><tr><td align="center">Second</td><td align="center">60</td></tr><tr><td align="center">Minute </td><td align="center">60</td></tr><tr><td align="center">Hour</td><td align="center">24</td></tr><tr><td align="center">Day</td><td align="center"></td></tr></tbody></table>

#### Data Units

<table><thead><tr><th width="226" align="center">Unit</th><th width="302" align="center">Usage Increment to Next Level</th></tr></thead><tbody><tr><td align="center">Byte</td><td align="center">1024</td></tr><tr><td align="center">Kilobyte</td><td align="center">1024</td></tr><tr><td align="center">Megabyte</td><td align="center">1024</td></tr><tr><td align="center">Gigabyte</td><td align="center"></td></tr></tbody></table>

#### Count-based Units / Custom Units

<table><thead><tr><th width="294">Unit</th><th width="269">Usage Increment to Next Level</th></tr></thead><tbody><tr><td>The original consumption unit</td><td>1000</td></tr><tr><td>Thousand</td><td>1000</td></tr><tr><td>Million</td><td>1000</td></tr><tr><td>Billion</td><td></td></tr></tbody></table>

&#x20;


# Process Payment with Stripe

Paigo supports Stripe integration as the payment transaction processor. Paigo uses [Standard Stripe Connect](https://stripe.com/connect) to orchestrate the direct charge between software buyer and software seller.

### Enable Stripe Integration

Navigate to **Settings > App > Stripe Connect** in Paigo dashboard. Click **Enable** button. The browser will open in a new tab the onboarding site for Stripe authentication. See the screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2F8LtzJg2BiEw2X1vB6c3j%2FCursor_and_Identity_Verification_by_Stripe.png?alt=media&amp;token=17fe3da7-3e51-49eb-b418-6c023078434f" alt=""><figcaption></figcaption></figure>

Fill in all the necessary business information, address, and payment so that Paigo will be able to process billing payments successfully. By authenticating and submitting all the required information, this Stripe account becomes a connected Standard Account on Standard Stripe Connect managed by Paigo. See more information from [Stripe Documentation](https://stripe.com/docs/connect/standard-accounts).

Note that it's critical to provide all the necessary business or payment informtion to Stripe to ensure no disruption to revenue collection. Failure to provide sufficient information to Stripe may cause the Stripe account to be in not ready status so as to block the receiving of customer payment.

If there are issues with Stripe Integration or Stripe Authentication failed for some reason, follow the step to [#disable-stripe-integration](#disable-stripe-integration "mention") and re-enable as documented here.

### Binding Customer Entity in Paigo with Customer Stripe Accounts

Paigo requires SaaS customers' Stripe account information to issue payment request to. In order to correctly charge customers, the customer ID in the form of `cus_xxxxxxxxxxxxxx` is stored in the customer entity of Paigo as the binding with a particular customer Stripe Account which is responsible for making payment for bills incurred. During the creation of Paigo customer entity, there are two options to set the binding: use an existing Stripe customer IDs (`cus_xxxxxxxxxxxxxx`) or create new Stripe customer IDs.

The customer data in Paigo and customer data in Stripe are not in sync automatically because they are used for different purpose. The customer data in Paigo is used for billing, invoicing and tax purposes. SaaS business is responsible for maintaining different records of customer data in Stripe if needed.

To use either of the options to bind customer entities, you must first follow [these steps](https://stripe.com/docs/customer-management/activate-no-code-customer-portal) from Stripe Document to activate the no-code customer portal. Activating the customer portal inside Stripe dashboard [here](https://dashboard.stripe.com/test/settings/billing/portal). The branding and UI customization can also be done in the same place.&#x20;

{% hint style="info" %}
Note that it's important to prompt customers to provide correct payment methods such as credit card information when their Stripe Account is onboarded in the customer portal in order to avoid failed charges or other errors in subsequent billing flows.
{% endhint %}

#### Option 1: Use Existing Stripe Customer IDs

Existing Stripe customer IDs must pre-exist in SaaS business' Stripe account, and the customer ID `cus_xxxxxxxxxxxxxx` then be provided during the creation of customer entity in Paigo. Below information is a high-level overview of onboarding customer's Stripe account, which involved two steps.

Step 1: Collect customer Stripe Account Information

A customer profile must exist under the Stripe account of SaaS business in order for Paigo to orchestrate the payment. Following [these steps](https://stripe.com/docs/billing/customer) from Stripe Document to create a customer profile in Stripe.

1. Verify that the customer doesn’t already exist.
2. Click **Add Customer**, or press **N**, on the **Customers** page.
3. At a minimum, enter your customer’s **Name** and **Account email**.
4. Click **Add Customer** in the dialog.

After the creation of a customer profile, it's recommended to use Stripe's no-code customer portal to ask customers to complete their profile information such as payment methods.

Step 2: Enter customer information in Paigo

Navigate to **Customer > New Customer** for the new customer creation form in Paigo dashboard. Pay special attention to the following fields:

* **Payment Channel** Select `Stripe`
* **Customer in Stripe** Select `Existing`
* **Customer Stripe Account ID** Set the customer ID as assigned by Stripe when this customer profile was created. Customer ID should be in the form of `cus_xxxxxxxxxxxxxx`. Customer ID can be found the customer profile of Stripe. See below screenshot for an example.&#x20;

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FkiHEN3hqdoIsEZbpgovH%2FCursor_and_Customers_%E2%80%93_paigo_tech_%E2%80%93_Stripe.png?alt=media&amp;token=eea26877-e4f9-4325-ba93-ec9b002c119d" alt=""><figcaption></figcaption></figure>

#### Option 2: Create New Stripe Customer IDs

If the creation of a new Stripe customer ID is selected, during customer entity creation, Paigo will automatically call Stripe API to create a new customer entity in Stripe on behalf of the SaaS business's Stripe account and store the new customer ID. Upon successful creation of customers in Paigo and Stripe, Paigo API will return a URL to a short-lived, pre-authenticated Stripe Hosted Page, which SaaS business can redirect SaaS customers to, in order for SaaS customers to fill in the right payment information and other relevant business data. See [Broken mention](broken://pages/NM0Fo4LLmnzGxOlNvFM2) Doc for details on the returned data schema and URL. If a customer is created in Paigo dashboard manually, the portal URL will be copied to the clipboard automatically.

This option is only available for creating new customers in Paigo. Updating existing customers must use [#option-1-use-existing-stripe-customer-ids](#option-1-use-existing-stripe-customer-ids "mention").

***Note:** You must have enabled the customer billing portal inside of stripe in order for Paigo to create a link on your behalf. See the* [*stripe documentation*](https://stripe.com/docs/customer-management/activate-no-code-customer-portal#activate-link) *for more information.*&#x20;

### Issue Billing Payment

Paigo uses Stripe Standard Connect to orchestrate the payment between SaaS business and SaaS customers. The payment will be issues as a Direct Charge on the SaaS customer's account. Below steps describe how Direct Charge works. See [Stripe Document](https://stripe.com/docs/connect/direct-charges) for more information about Direct Charge.

* Paigo uses Stripe API to create a charge on SaaS customers Stripe account so the payment appears as a charge on the SaaS business Stripe account directly (not in Paigo's account balance).
* SaaS business' account balance increases with every charge.
* SaaS business' account balance will be debited for the cost of Stripe fees, refunds, and chargebacks.

Paigo will issue a Direct Charge when an automatic or manual invoice is reviewed and approved. See [Stripe Doc](https://stripe.com/docs/declines) for more information on the potential reasons for payment issuing. When there is correct payment information collected from customer Stripe account, the payment will automatically be used.

Paigo runs async process to monitor the payment transactions. If the payment is successful, Paigo will automatically update the invoice as paid.

### Multi-Currency Support

Paigo supports multiple currencies for payment settlement using Stripe. Paigo processes currencies based on SaaS customer's preference as defined in [Manage Customer Profile](/saas-pricing/manage-customer-profile#customer-preferred-currency). The balance received in SaaS business Stripe account is by default automatically converted to the settlement currency of the SaaS business account, such as US Dollar for US businesses. To view your payout setup in Stripe, go to payouts settings in Stripe Dashboard [here](https://dashboard.stripe.com/settings/payouts). SaaS business can opt to enable alternative currency payouts or opt out of automatic currency conversion. See [Stripe Docs](https://stripe.com/docs/payouts/alternative-currencies) for more details.

### Failed Payment Handling

In one or multiple of following scenarios, issued payment Direct Charge may fail.

* Incorrect payment information on customer Stripe account
* Incorrect customer Stripe account ID set in Paigo
* Credit card declined the transaction

Paigo runs async process to monitor the payment transactions. Errors or disruptions to payment processing will appear in your system inbox within 12 hours of the payment processes. Paigo will provide detailed failure information to SaaS business for further action on retrying or other processing methods.

### Disable Stripe Integration

{% hint style="info" %}
Disabling Stripe Connect will remove Stripe account record from Paigo so that Paigo won't be able to process payment for your customers. Additional actions may need to be performed to deauthorize your Stripe Account from Stripe Connect. Contact <team@paigo.tech> for support.
{% endhint %}

Navigate to **Settings > App > Stripe Connect** in Paigo dashboard. Click **Disable** button. Finally click the OK button to confirm disabling Stripe Integration. Once disabled, the **Stripe Connect Reference ID** will be cleared in the text field of Stripe Connect integration.


# Cloud Marketplace Invoicing

### Overview

For Cloud Marketplaces (AWS, Azure and GCP), SaaS product offering requires SaaS customer usage report continuously and precisely on a fixed schedule in order to invoice SaaS customer correctly. Paigo has the cloud marketplace integration fully automated so that SaaS business just needs to enable it with one click. Paigo platform automatically measures SaaS customer usage, collects into database for persistence, and aggregates according to the policy of marketplace, report usage to marketplace API by a scheduler, and finally consolidates revenue data from marketplaces.

Different cloud marketplaces have different levels of support for usage-based billing, their terminologies and limitations are different as well. Paigo works as a consolidated billing layer on top of all cloud marketplaces to enhance their billing support while leveraging their payment option as a revenue channel.

The diagram below illustrates how Paigo being the proxy of cloud marketplaces and enhances the billing functionality on top of marketplaces.

<img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FT65SiRVXoCKpYr64fvlK%2Ffile.drawing.svg?alt=media&amp;token=7ed442e1-c961-41d9-9359-e08e776ef229" alt="" class="gitbook-drawing">

### Usage Reporting

In order to bill customers based on usage, marketplaces requires reporting of customers usage on a regular basis in order to invoice customers correctly at the end of the month. Paigo automatically takes care of the usage reporting requirement for usage-based billing. The high-level workflow works as such:

1. Usage measurement and collection: Paigo does deep integration with SaaS application to measure and collect each SaaS customers' usage in real-time.
2. Data aggregation: aggregate raw usage data into the level of granularity required by different marketplaces. Such as on AWS, the usage data has to be aggregated to an hour level.
3. Data reporting: use scheduler infrastructure to deliver the aggregated data to different APIs of marketplaces.

The entire usage reporting works as a blackbox to SaaS application. So there is no additional work needed on the SaaS application side to accommodate marketplace invoicing.&#x20;

### Payment

Paigo uses cloud marketplace as a payment channel. On the basis of automatic [#usage-reporting](#usage-reporting "mention"), cloud marketplace will generate invoices sent to SaaS customers. The revenue collected from SaaS customers will be subsequently sent to SaaS business account.

{% hint style="info" %}
Cloud marketplaces also charge transaction fee as a percentage of revenue invoiced. For specific fee structure, consult the specific cloud platform teams.
{% endhint %}

### Offering

There are a few critical challenges in terms of managing pricing plans on Cloud marketplace.

1. Different cloud platforms have different models for pricing plans. Examples are public offering, private contracts, SaaS, subscriptions, etc. Those models come with various strength and limitations.
2. Apart from many kinds of models to deal with, another challenge with multiple cloud marketplaces is maintaining the consistency between the pricing structures, or pricing parity.&#x20;
3. Multiple platforms also comes with the challenge of various APIs and technologies to integration.

Paigo allows SaaS business to bypass all of these challenges by providing a uniform Offering system that can be applied across platforms. Paigo incorporates different Offering structures, and deals with platform specific terminology and APIs underneath. SaaS business only needs to use Paigo dashboard or Paigo API to manage Offerings across the board.

### Enhanced Billing

Cloud marketplaces provide limited billing function. Paigo as a billing layer on top of cloud marketplaces, enhanced the billing solution with great flexibility and powerfulness. With Paigo, Cloud marketplace invoicing can be enhanced with free trial, prepaid credits, usage entitlement, flexible B2B deal structure, itemized invoice or revenue recovery.

### Consolidated Analytics

In Paigo's analytical dashboard, SaaS business can see consolidated analytics such as revenue recognition metrics (monthly recurring revenue or annual recurring revenue) taking into account both cloud marketplace revenue as well as other revenue sources such as Stripe.

{% hint style="info" %}
Cloud Marketplace invoicing is currently in closed preview. Contact <team@paigo.tech> to get access.
{% endhint %}


# Handle Tax and Compliance

Paigo supports taxation on billing payments. Paigo supports automatic tax mode and manual tax mode. For automatic tax mode, the sales tax calculation and keeping track of tax information is achieved by integrating with tax software provider. Paigo currently supports [TaxJar](https://www.taxjar.com/) as the integrated tax software. SaaS business can provide the API key of the TaxJar account they own in order to enable automatic sales tax calculations and tracking. For manual tax mode, SaaS business can set arbitrary tax rates with Paigo, and SaaS business is fully responsible of the tax compliance.

### Enable TaxJar Integration

#### **Account Setup**

A TaxJar account is required to enable integration on Paigo. A Starter Plan is required to use sales tax API. A Professional Plan is required if VAT Calculation for the EU, UK, Australia and Canada is needed for SaaS business. See [this page](https://support.taxjar.com/article/139-how-much-does-taxjar-cost) for TaxJar pricing.

Navigate to **Account** at the top right corner, and select **Business Profile**. Fill in the necessary business information in order for the tax rate calculation to be accurate.

Navigate to **Account** at the top right corner, and select **State Setting**. On this page, provide proper information of state with nexus in order for the tax rate calculation to be accurate. Consult local tax expert for more information on tax nexus. There are also [many knowledge base articles](https://www.taxjar.com/?s=nexus) about economic nexus.&#x20;

#### Retrieve API Key

Paigo uses an API key to work with TaxJar API. Follow these steps to retrieve the API key of your account.

1. Log into TaxJar account console.
2. Click on **Account** button at the top right corner and select **Taxjar API.**
3. On the page **TaxJar API Token**, copy the string under **Live Token.**

<div align="left"><figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FpypOLXbNPPLS0cQCeQSG%2FCursor_and_Account_Info_-_TaxJar.png?alt=media&amp;token=40d5186c-db0c-4b07-8a6a-521f4ec577a2" alt=""><figcaption></figcaption></figure></div>

#### Enable Integration

Navigate to **Setting > Integration > TaxJar,** fill in the **TaxJar API Key** copied from above, and click **Enable**. Paigo will try to authenticate with TaxJar API with the key provided.

### Sales Tax Calculation

Paigo can automatically calculate the sales tax amount on each transaction in the billing system with the integration with TaxJar. Navigate to **Setting > Tax > Sales Tax Calculation** and select **Paigo Calculated** to enable automatic sales tax calculation. Save the setting to take effect. Note that TaxJar integration has to be enabled as well as described in [#enable-taxjar-integration](#enable-taxjar-integration "mention").

There are certain conditions to be met in order for the sales tax calculation to be accurate.

* **SaaS Business Address and SaaS Customer Address** Complete and correct business addresses are necessary for Paigo to determine the appropriate tax rates on the transaction. Complete address information should include information such as address lines, city, state, country and postal code. Navigate to **Setting > Business** to set the business information. Make sure to verify the address correctness with local postal office or government system. For example, in United States, [this tool](https://www.ups.com/address_validator/search?loc=en_US) might be used for address validation.
* **Product Tax Category** SaaS business is responsible for setting the correct product tax category. Navigate to **Setting > Tax > Product Tax Category** and select from dropdown the proper category that defines the product. Some of the common product tax categories are listed below. Please consult with local tax experts for the proper product category for taxation purpose.
  * Cloud-based software as a service (SaaS) - Business Use
  * Cloud-based software as a service (SaaS) - Personal Use
  * Software as a Service
  * Cloud-based platform as a service (PaaS) - Business Use
  * Cloud-based platform as a service (PaaS) - Personal Use
  * Cloud-based infrastructure as a service (IaaS) - Business Use
  * Cloud-based infrastructure as a service (IaaS) - Personal Use

In the event of one or more conditions above not met, such as address unable to be validated by TaxJar API, Paigo will treat the sales tax as non-taxable since there is no applicable tax law.

TaxJar supports sales tax calculate of more than 30 countries/regions across North America, European Union and Oceania. For the full list, please see [Country List](https://developers.taxjar.com/api/reference/#countries). For other taxation information such as sales tax nexus or threshold, please visit [TaxJar Documentation](https://developers.taxjar.com/api/reference/).

### Tax Compliance

TaxJar offers automated tax filing and remittance. Paigo records all transactions with sales amount and tax amount using TaxJar API. All the transactions can be retrieved from SaaS business' TaxJar account. See [this page](https://www.taxjar.com/product/autofile) for more information on tax filing and compliance.

### Tax Exemption

Some SaaS customers may be exempted from sales tax, such as non-profit organization or government organizations. The tax exemption information can be specified in customer profile in Paigo. Navigate to **Customer** and select a customer profile from the table to see the **Tax Exempt** field. **Tax Exempt** is either `None` or `Exempt`. When it's set to `None`, this customer is not exempted from sales tax. All sales tax calculation will be applied. When it's set to `Exempt`, then all tax calculation will be bypassed and set the tax rate to be 0%.

All tax exempt customer profile will have a customer record in TaxJar system as well, with exempt type being `other`.

### Disable TaxJar Integration

Navigate to **Setting > Integration > TaxJar,** and click **Disable** to remove the integration with TaxJar. The API key will be cleared from Paigo.

### Manual Tax Mode

SaaS business can choose to take full ownership of the taxation of billing by selecting manual tax mode. To enable manual tax mode, navigate to **Settings > Tax > Sales Tax Calculation** and select **Manually Set**. In the **Default Tax Rate** field, set the tax rate for all billing transactions. Finally, save the **Settings** to make sure it takes effect.

In the manual tax mode, all invoices will automatically calculate the tax based on the set rate. The SaaS business is responsible for keeping track of the amount of tax collected for the entire organization for tax compliance purpose.


# Business Analytics Overview

There are four categories of business analytics in Paigo: revenue recognition, profit margin analytics, usage-based cost insights and unit costs.

<table><thead><tr><th>Metric Name</th><th>Category<select multiple><option value="8651b141a8ea4f0ea8ba0f4ad7970ee4" label="Revenue Recognition" color="blue"></option><option value="681a5440a0954aed91e96e67a62e1014" label="Usage-based Cost" color="blue"></option><option value="4a1b4755dd094994ad84c3d9720a420c" label="Unit Cost" color="blue"></option><option value="cf29360ebc854211aa4c59990b99be65" label="Profit Margin" color="blue"></option></select></th></tr></thead><tbody><tr><td>Monthly Recurring Revenue</td><td><span data-option="8651b141a8ea4f0ea8ba0f4ad7970ee4">Revenue Recognition</span></td></tr><tr><td>Annual Recurring Revenue</td><td><span data-option="8651b141a8ea4f0ea8ba0f4ad7970ee4">Revenue Recognition</span></td></tr><tr><td>Monthly Growth Rate</td><td><span data-option="8651b141a8ea4f0ea8ba0f4ad7970ee4">Revenue Recognition</span></td></tr><tr><td>Net Revenue Retention</td><td><span data-option="8651b141a8ea4f0ea8ba0f4ad7970ee4">Revenue Recognition</span></td></tr><tr><td>Monthly Revenue</td><td><span data-option="8651b141a8ea4f0ea8ba0f4ad7970ee4">Revenue Recognition</span></td></tr><tr><td>Monthly Gross Margin</td><td><span data-option="cf29360ebc854211aa4c59990b99be65">Profit Margin</span></td></tr><tr><td>Monthly Contribution Margin</td><td><span data-option="cf29360ebc854211aa4c59990b99be65">Profit Margin</span></td></tr><tr><td>Monthly Contribution Margin (by Customer)</td><td><span data-option="cf29360ebc854211aa4c59990b99be65">Profit Margin</span></td></tr><tr><td>Monthly Contribution Margin (By Offering)</td><td><span data-option="cf29360ebc854211aa4c59990b99be65">Profit Margin</span></td></tr><tr><td>Monthly Total Cost</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost</span></td></tr><tr><td>Monthly Fixed Cost</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost</span></td></tr><tr><td>Monthly Variable Cost</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost</span></td></tr><tr><td>Compute Cost (EKS)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Compute Cost (EC2)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Storage Cost (EBS)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Storage Cost (S3)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Archive Cost (EBS)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Archive Cost (S3)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr><tr><td>Network Cost (VPC)</td><td><span data-option="681a5440a0954aed91e96e67a62e1014">Usage-based Cost, </span><span data-option="4a1b4755dd094994ad84c3d9720a420c">Unit Cost</span></td></tr></tbody></table>

See the chapters on each analytics category:

* [Usage-based Cost Insights](/business-analytics/usage-based-cost-insights)
* [Profit Margin Analytics](/business-analytics/profit-margin-analytics)
* [Product Unit Cost](/business-analytics/product-unit-cost)


# Usage-based Cost Insights

### Understand Usage-based Cost

Paigo calculates cost breakdown including fixed costs and variable costs. Variable costs are calculated based on designated infrastructure resources usage. For example, if a SaaS business provisions Kubernetes pods for each customer separately, and uses a shared load balancer for all customers, then Paigo identifies Kubernetes as variable costs, and load balancer usage as fixed costs. SaaS customers can select different variable cost categories such as compute, storage, archive or network. The explanation of each cost insight item is listed below.

<table><thead><tr><th width="151.33333333333331">Item</th><th width="432">Explanation</th><th>Source of Data</th></tr></thead><tbody><tr><td>Total Cost</td><td>Total Cloud Bill</td><td>Cloud Billing Data</td></tr><tr><td>Variable Cost</td><td>Costs that increase as every new customer is onboarded. Also known as marginal costs. Typical examples of variable costs are compute, storage, network, archive depending on the nature of business.</td><td>Paigo Calculated Variable Costs, Cloud Billing Data</td></tr><tr><td>Fixed Cost</td><td>Costs that do not increase as every new customer is onboarded. Also known as shared overhead. Typical examples of fixed costs are load balancer, shared storage, monitoring infrastructure, etc.</td><td>Total Cost - Variable Cost</td></tr></tbody></table>

Note that the variable cost calculated by Paigo typically is not the same as the AWS bill on some particular resources, as those information is readily available from AWS. The costs calculated by Paigo represents a more precise view of cost attribution tied to revenue stream. Therefore, it's usage-based cost.

For example, SaaS business may provision Kubernetes pods for each new customer onboarded. So AWS Elastic Kubernetes Services (EKS) can be selected as a variable cost category in Paigo. While AWS bill contains the total dollar amount of using EKS, Paigo calculates the cost of serving customers by the following sample algorithm:

1. Frequently sample the usage Kubernetes, such as in seconds.
2. Filter out non-customer usage, such as monitoring pods.
3. Calculate precise atomic cost at more granular level, such as by multiple of $0.00000001 and by minutes.
4. Aggregate the collective costs.


# Profit Margin Analytics

### Understand Profit Margin Analytics

Paigo calculates profit margin metrics based on revenue and costs. The explanation of each profit margin item is listed below.

<table><thead><tr><th width="198.33333333333331">Item</th><th width="322">Explanation</th><th>Source of Data</th></tr></thead><tbody><tr><td>Gross Margin</td><td>Total Revenue - Total Cost. Reflects the net profit SaaS business retains.</td><td>Various Payment Channels, Cloud Billing Data</td></tr><tr><td>Contribution Margin</td><td>Total Revenue - Variable Cost. Reflects marginal profit.</td><td>Paigo Calculated Costs, Various Payment Channels, Cloud Billing Data</td></tr><tr><td>Contribution Margin by Customer</td><td>Revenue from a customer - Variable Cost attributed to a customer. Reflects the profitability on particular customers or contracts.</td><td>Paigo Calculated Costs, Various Payment Channels, Cloud Billing Data</td></tr><tr><td>Contribution Margin by Offering<br>(Coming Soon)</td><td>Revenue from a product offering - Variable Cost attributed to a product offering. Reflects the profitability of product lines or packages.</td><td>Paigo Calculated Costs, Various Payment Channels, Cloud Billing Data</td></tr></tbody></table>

The costs used in profit margin analytics are those defined in [#understand-usage-based-cost](#understand-usage-based-cost "mention").


# Product Unit Cost

### Overview

Usage-based business model is entirely built around unit economics. As a critical part of unit economics, unit cost greatly impacts the sustainability of the business model, such as deriving pricing strategy or sales motions. For some segments of SaaS industries, the benchmark for product pricing and sales contracts involve careful unit cost estimations. Examples of such segments are data & analytics, machine learning products, developer tools or software infrastructure.

Paigo provides real-time, granular and automatic unit cost measurement for SaaS business. On Paigo platform, SaaS business can understand the unit cost of serving customers and leverage aggregated usage-based cost analytics to drive business decisions.

### Terminology

**Cost / Unit Cost** refers to the cost of SaaS business.

**Pricing / Usage-based Pricing** refers to the price SaaS business charges SaaS customers.

**Cloud Pricing** refers to the price cloud platform (such as AWS, Azure and GCP) curages SaaS businesses for using their infrastructure.

**Fixed Cost** refers to the cost that typically doesn't change as every new SaaS customer is onboarded to the SaaS product. For example, if a monitoring component is running 24x7 to monitor the status of SaaS backend, onboarding another new customer to the platform typically does not change the cost of running monitoring component. Fixed cost is sometimes called shared overhead.

**Variable Cost** refers to the cost that changes (usually increases) as every new SaaS customer is onboarded to the SaaS product. For example, if a new virtual machine is allocated to each new SaaS customer, the cost of running virtual machine is considered a kind of variable cost.

Unit cost is a kind of variable cost, because as a new customers onboarded, their incurred usage will increase the cost of SaaS business.&#x20;

### Defining Unit Economics

To understand the cost structure, it is useful to define an atomic usage unit for a particular dimension that SaaS business wants to charge customers for, then find the unit cost structure for the usage unit. For instance:

* For customers' data storage, the usage unit can be GB-Hour, meaning storing 1GB of data volume for a SaaS customer for 1 hour.
* For customers' compute time, the usage unit can be Minute, meaning running 1 Minute of CPU and compute machine for a SaaS customer.

There might be more than one way of defining unit usage for a particular Dimension or SaaS business, such as GB-Hour vs GB-Month for data storage. If possible, it is preferable to define more granular units because they can be aggregated to coarse units. And as pricing evolves, different units might be used to improve on pricing.

Note that unit cost includes the software cost incurred to run SaaS application, it doesn't include other operations cost such as engineer salary, office rental, develop tools etc.

{% hint style="info" %}
Paigo offers a courtesy consulting service to define the unit economics of SaaS product and unit cost. Contact <team@paigo.tech> to find out more.
{% endhint %}

### Methodology for Cost Calculation

There are several critical challenges to derive unit for SaaS.

* **Multi-tenant environments:** It typically requires careful attribution of cost to customers in order to derive a meaningful unit cost. For example, at the infrastructure level, a Kubernetes cluster is serving multiple customers at the same time. The cost attribution to each customer, or even each tenant, has to be calculated correctly.
* **Differentiating variable cost vs fixed cost:** The complexity of the underlying infrastructure of SaaS applications has made the boundary of variable cost and fixed cost hard to define. For example, a load balancer serving all customers might be considered variable costs or fixed costs depends on the nature of business, the pricing model and the infrastructure topology.
* **Complex cloud pricing and cost structure:** the cloud pricing could involve various cost all combined and not in a linear way. For example, when serving SaaS customers with data snapshots on AWS, the cost depends on various input such as the data block that has changed from last the snapshot, the amount of time to keep the snapshot (such as 0.8 months), etc. All of these parameters could affect the unit cost.

In order to calculate unit costs that takes into account all of aforementioned challenges, Paigo samples unit cost at different times and apply aggregation algorithms (such as AVERAGE) to derive the unit cost in the context of a particular business model.&#x20;

As an example, a business uses AWS EC2 instance to run their applications for SaaS customers. They use fleets of on-demand instances, reserved instances and spot instances as the working node for their backend. The provisioning and orchestration of different instance types is done by a third-party software, and is subject to the availability of instant families they desired and going market rate of spot instances. In order to derive the unit cost for serving EC2 instances to customers, Paigo would measure unit cost continuously at a high frequency, and calculated average unit cost of serving one instance for one hour to customers based on their infrastructure topology and customer usage pattern.&#x20;

See the use cases of usage-based costs in the following chapters for more details.

### Difference with Cloud Cost Optimization

There are many cloud cost optimization software in the market. They would scan and monitor the cloud cost together to recommend or even execute cost saving tactics. Examples would be releasing idle resources, purging inactive data or arbitraging with cheapter resources. Paigo's usage-based cost analytics differs from them in several ways:

* Paigo takes into account the usage-based business model and SaaS customers' usage topology. Therefore, Paigo would identify variable cost / fixed cost, multi-tenant / single-tenant in the context of the SaaS business to calculate cost.
* Paigo focuses on increase revenue by calculating usage-based cost. Cost optimization software focuses on reduce the cost.
* Paigo takes into account cost optimization done by other software when calculating usage-based cost. For example, a cost optimization software may actively manage the EC2 fleets by buying/selling reserved instances in the secondary markets or spinning up spot instances to save SaaS business on the instance cost. When Paigo calculates usage-based cost, it takes into account all the activities performed by the cost optimization software for the granular unit cost calculation.


# Unit Cost for Data Storage

### Overview

Many data and analytics services store data in AWS Elastic Block Storage (EBS) and bill customers by provisioned EBS volume. The cloud pricing of EBS volume includes various usage metrics such as storage size (GB-Month), IOPS (Provisioned IOPS-Month), Throughput (Provisioned MB/S-Month) and API Requests. It's a common practice for SaaS business to abstract away the lower level details of EBS Volume configuration but allowing SaaS customers to choose the storage size, or dynamically scale the volume size based on SaaS customers' usage.&#x20;

### Defining Unit Economy

Based on the business model described above, a useful usage unit could be defined as GB-Hour, meaning serving 1 GB of data volume to SaaS customer for 1 Hour. There potentially could also be different ways of defining unit economy such as GB-Month or MB-Hour. However, they should essentially represent the same idea and can be transformed from GB-Hour back and forth.

Also note the unit economy is different for different configurations of EBS volumes. In other words, the GB-Hour unit cost should be considered differently for a volume of 6,000 IOPS and a volume of 3,000 IOPS. &#x20;

### Measurement of Usage-based Cost

Given that different configurations of EBS volumes are all abstracted away by the data size, Paigo treats different configuration combinations of EBS volumes differently. At a regular interval, Paigo samples all of the actively used data volumes by SaaS customers, calculate the unit costs of those volumes in terms of GB-Hour, and save those data points in the backend journal as the raw data. Finally, Paigo runs batch analytics on the giant raw data set to group them by volume configurations and calculate of the average of each group. See below table for a sample result.

<table><thead><tr><th width="187" align="center">Storage Size (GB)</th><th width="189" align="center">IOPS (IOPS-Month)</th><th width="239" align="center">Throughput (MB/s-Month)</th><th align="center">Unit Cost ($)</th></tr></thead><tbody><tr><td align="center">50</td><td align="center">3000</td><td align="center">25</td><td align="center">$0.01</td></tr><tr><td align="center">50</td><td align="center">6000</td><td align="center">50</td><td align="center">$0.02</td></tr><tr><td align="center">100</td><td align="center">3000</td><td align="center">100</td><td align="center">$0.03</td></tr></tbody></table>

To enable the usage-based cost for EBS volume, it is recommended to enable [Infrastructure-based Method](/usage-metering/infrastructure-based-method) usage measurement and collection.

### How to Use The Data

The usage-based cost can be leveraged to benchmark the pricing strategy. For example, one of the common ways is to define a pay-as-you-go pricing [Product Items](/saas-pricing/pricing-basics/product-items) that allows customers to pay for the amount of data they consumed. Knowing the unit cost of serving GB-Hour can help to define a meaningful price of the pay-as-you-go plan. Another example would be combining storage into a subscription tier [Product Plans](/saas-pricing/pricing-basics/product-plans) with other usage such as compute time. A startup subscription may include 50 GB of data storage per month. With the usage-based cost of calculated by Paigo, the Offering price could be set correctly ensuring there is sufficient margin baked into the subscription price.


# Unit Cost for Kubernetes

### Overview

Kubernetes is undoubtedly one of the most popular choices for modern SaaS architecture. Therefore, finding out the usage-based cost for running Kubernetes for SaaS customers is a commonly requested task by many SaaS business. There are different ways to run SaaS applications in Kubernetes. In this use case, we are exploring a multi-tenant deployment in Kubernetes while each tenant occupies one or more pods in a node. The diagram below illustrates the example topology for such a Kubernetes cluster.

<img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FwK57ytV1nLRbixdFHqQx%2Ffile.drawing.svg?alt=media&amp;token=999a0215-efec-442b-a5c1-84654b63c0a5" alt="" class="gitbook-drawing">

Kubernetes can be hosted in different environments as well. In this use case study, we are exemplifying with AWS Elastic Kubernetes Service (EKS) hosted on AWS EC2 Instances. The usage-based cost calculation differs as the hosting environment differs. Paigo supports usage-based cost for various hosting environments.

The cost of running EKS on EC2 has several components. There are platform fees of EKS based on usage (see [EKS Pricing](https://aws.amazon.com/eks/pricing/)), and there are EC2 costs (see [EC2 Pricing](https://aws.amazon.com/ec2/pricing/)). And there is potentially some other factors in the mix influencing the usage-based cost such as different types of EC2 instances including on-demand instances and reserved instances.

### Defining Unit Economy

A good unit economy framework for the topology described above would be pod running time based given the single occupancy in Kubernetes pods. The running time example we are using here is Hour, meaning serving 1 hour of running time to a SaaS customer. There potentially could also be different ways of defining unit economy such as Minute or even Million Seconds. However, they should essentially represent the same idea and can be transformed from Hour back and forth.

Also note the unit economy is different for different configurations of Kubernetes pods. In other words, the hourly unit cost should be considered differently for a pod of 4 cores and a pod of 2 cores.

### Measurement of Usage-based Cost

Paigo treats different configurations of Kubernetes pods differently, take into account the number of cores and the amount of memory. At a regular interval, Paigo samples all of the actively running pods by SaaS customers in Kubernetes clusters. Then Paigo calculates the hourly costs of those pods and save those data points in the backend journal as the raw data. Finally, Paigo runs batch analytics on the giant raw data set to group them by different configurations and calculate the average of each group. See below table for a sample result.

<table><thead><tr><th width="187" align="center">CPU Cores</th><th width="189" align="center">Memory (GB)</th><th align="center">Unit Cost ($)</th></tr></thead><tbody><tr><td align="center">2</td><td align="center">8</td><td align="center">$0.01</td></tr><tr><td align="center">4</td><td align="center">16</td><td align="center">$0.02</td></tr><tr><td align="center">8</td><td align="center">32</td><td align="center">$0.03</td></tr></tbody></table>

When calculating the hourly cost of running pods, Paigo also takes into account the real cost of running underlying EC2 resources such as on-demand instances or reserved instances.

To enable the usage-based cost for EKS on EC2, it is recommended to enable [Agent-based Method](/usage-metering/agent-based-method) usage measurement and collection.

### How to Use The Data

The usage-based cost can be leveraged to benchmark the pricing strategy. For example, one of the common ways is to define a pay-as-you-go pricing [Product Items](/saas-pricing/pricing-basics/product-items) that allows customers to pay for the exact time of their usage, such as in CI/CD SaaS platforms. Knowing the unit cost of serving  an hour of running time can help to define a price with a desired margin. Another example would be combining running time into a subscription tier [Product Plans](/saas-pricing/pricing-basics/product-plans) with other usage Dimension such as Storage. An Enterprise subscription tier may include 100 hours of running time per month.

Similar use cases can be applied to derive the usage-based cost of running GPUs in Kubernetes for machine learning platforms.


# Enable Business Analytics

### **Configure Cost Categories**

Required configuration for:

* Usage-based Cost
* Unit Cost
* Profit Margin Analytics

Navigate to **Setting** > **Analytics** and set values for the following fields.

* **Compute Cost Source**: Select from the dropdown the resource of compute cost. Default: none.
* **Storage Cost Source**: Select from the dropdown the resource of data storage cost. Default: none.
* **Archive Cost Source**: Select from the dropdown the resource of data archive cost. Default: none.
* **Network Cost Source**: Select from the dropdown the resource of network cost. Default: none.

Click **Save** to save the settings. Selection of these cost categories will be used in usage-based costs, margin analytics as well as unit costs.&#x20;

For additional configuration specific to a cost source, such as AWS EKS for Compute, follow steps in [#enable-data-sources-for-cost](#enable-data-sources-for-cost "mention").

### Configure Permissions

Required Configuration for:

* Profit Margin Analytics
* Usage-based Cost of Storage, Archive and Network
* Unit Cost of Storage, Archive and Network

Paigo requires additional cloud platform permissions to calculate various kinds of revenue and cost analytics. Those permissions are all within AWS Cost Explorer. The steps to create an IAM role is documented in [Configure IAM Role](/usage-metering/configure-iam-role). Follow the same steps described in that page, but use the `permissions.json` file below.

{% code title="permissions.json" %}

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ce:*"
            ],
            "Resource": "*"
        }
    ]
}
```

{% endcode %}

Once the role is created, take note of the IAM role ARN.

Navigate to **Setting** tab and select **Analytics** subtab from the top. Fill in the **IAM Role ARN** and **External ID** just created and click **Save** to save the new settin&#x67;**.**

### Enable AWS Cost Allocation Tags

Required Configuration for:

* Profit Margin Analytics
* Usage-based Cost of Storage, Archive and Network
* Unit Cost of Storage, Archive and Network

For several cost and margin analytics, Paigo leverages AWS Cost Allocation Tags to attribute usage to customers. Following these steps to enable AWS cost allocation tags.

1. Sign in to the AWS Management Console and open the AWS Billing console at <https://console.aws.amazon.com/billing/>.
2. In the navigation pane, choose **Cost allocation tags**.
3. Select the following tags from the list: `paigoCustomerId` and `paigoDimensionId`.
4. Choose Activate.

See screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2Fee0bU2M4nR8yjRqQwqvj%2FBilling_Management_Console_and_WeChat__Chats_.png?alt=media&amp;token=29e66934-4675-4be0-9478-b830187f34f5" alt=""><figcaption></figcaption></figure>

After you create and apply user-defined tags to your resources, it can take up to 72 hours for the tags to appear on your cost allocation tags page for activation. After you select your tags for activation, it can take up to 24 hours for tags to activate.

If those tags don't appear in the list, then they have never been used by any AWS resources before. First apply those tags on some AWS resources such as EC2 instances or EBS volumes. It may take AWS up to 24 hours to pick up newly created tags on resources.&#x20;

For detailed documentation of enabling AWS Cost Allocation Tags, see the official documentation [User-defined cost allocation tags](broken://pages/YETI04ZCs6HN4YEh09FN).

### Enable Hourly Cost Data

Required Configuration for:

* Unit Cost of Storage, Archive and Network

For several unit cost categories, Paigo leverages hourly usage and cost data available in AWS Cost Explorer to calculate. Following these steps to enable **Hourly and Resource Level Data.**

1. Sign in to the AWS Management Console and open the AWS Cost Explorer at <https://us-east-1.console.aws.amazon.com/cost-management/home#/settings>.
2. In the navigation pane, choose **Preference**.
3. Check the box **Hourly and Resource Level Data** in the Cost Explorer preference.
4. Click **Save preferences** at the bottom of the page.

See screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FeMljrWAr3zgEvWR0HSzD%2FCursor_and_Cost_Management.png?alt=media&amp;token=90a439c4-b31b-41da-a7bc-a393b0ce4ade" alt=""><figcaption></figcaption></figure>

Note that Hourly and Resource Level Data has additional cost charged by AWS. Here is the quote from AWS:

> a cost of $0.01 per 1,000 UsageRecords-month will be incurred as a result of storing and accessing your hourly- and resource-level information. A UsageRecord is defined as one line of usage. For example, one EC2 instance running for 24 hours will generate 24 distinct UsageRecords at the hourly granularity.

For detailed information on pricing of AWS Cost Explorer, see official documentation [AWS Cost Explorer Pricing](https://aws.amazon.com/aws-cost-management/aws-cost-explorer/pricing/).

### Enable Data Sources for Cost

After choosing the cost source, there are additional steps to perform for each category in order for Paigo to calculate the cost correctly.

#### Compute Cost on AWS EKS

An agent-based measurement is required for Paigo to collect usage and calculate compute costs. Follow the instructions to deploy agent, label Kubernetes cluster and create agent-based measurement as documented here [Agent-based Method](/usage-metering/agent-based-method) .


# Sandbox

### Overview

Sandbox is a safe and isolated environment to explore the platform, develop integrations or run tests. This chapter describes how to use Paigo sandbox.

### Sandbox vs Production

Sandbox is different from production environment in the following ways:

* Everything in sandbox is completely isolated from production environment, including business data and settings. Therefore, enabling external integrations in sandbox doesn't automatically enable integrations in your production environment.
* The sandbox environment is shared for the same organization, but enabling sandbox mode is a per-user setting. For example, user A in the company turns on sandbox mode (by API or in dashboard) won't impact user B, who uses production environment in Paigo dashboard or programming against Paigo API. However, user A and user B share the same sandbox environment when both of them turn it on.
* The API credentials to access sandbox environment are different from API credentials to access production environment.
* In sandbox mode, the payment is in sandbox. All payments are simulated using Stripe Test Mode. No real banking or credit card transactions will happen.
* In sandbox mode, the tax integration is in sandbox. All sales tax calculations are simulated using TaxJar sandbox mode. Sales tax nexus or compliance is not maintained in sandbox mode.
* In sandbox mode, any invoice, processed revenue, or charges against SaaS customers are not counted toward Paigo's metered usage.
* Sandbox environment runs in a multi-tenant architecture. It is used for development purpose only.

### Enabling Sandbox Mode

Sandbox mode can be enabled in Paigo dashboard by toggling the **Sandbox Mode** button in the left navigation pane. Sandbox mode is turned off by default whenever a User refreshes or logs in. See the screenshot below for an example.

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2F5O9CKUb6EJTMMv7Wnq0i%2FScreenshot%20from%202023-12-03%2010-33-11.png?alt=media&amp;token=57924970-1b66-4d9c-b258-dd9f6c70cfa5" alt=""><figcaption></figcaption></figure>

Sandbox mode can also be used with Paigo API. Each set of API key is uniquely bound with an environment, and keys are not shared across environment. Therefore, use the API keys to the sandbox environment to develop against sandbox mode.


# Customer Wallet and Credits

Usage based billing requires you wait until the end of the billing cycle to capture revenue from customers. Paigo's Customer wallet and credit feature enables you to have customer's prepay for credits in order to capture revenue. Additionally the flexibility of Paigo's credit system enables you to use it for a variety of use cases beyond just prepaid credits, in cases of customer refunds you can additionally issue the credit as a note to be used for payment on later charges. <br>

## Creating Credits&#x20;

Credits can be created and managed via the UI or API in Paigo.&#x20;

### UI/Dashboard

1. Navigate to app.paigo.tech&#x20;
2. Go to the customer you want to issue credit for
3. Select **Actions > Update Customer Credit**

<div data-full-width="true"><figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FuwjPOxw9icoYuWGiWTAL%2FScreenshot%20from%202023-07-26%2011-01-56.png?alt=media&amp;token=b1cc6c26-af98-4988-b55f-db1a1896ad90" alt=""><figcaption><p>The Update Credit Screen</p></figcaption></figure></div>

4. Choose to either issue new credit or reduce their current existing credits.&#x20;

   See [#considerations-for-credits](#considerations-for-credits "mention") for implications with negative credits.&#x20;
5. Hit submit.&#x20;

On the main customer page you should see their credit transaction in the Customer Wallet section.&#x20;

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FWH6kIJsqKAFY2ga7lpCN%2FScreenshot%20from%202023-07-26%2011-07-17.png?alt=media&amp;token=7fcc2cae-55eb-4e61-a7ca-a9cf6089e091" alt=""><figcaption><p>A customer's credit ledger</p></figcaption></figure>

### API

To make the call to API directly please use or [API documentation](http://www.api.docs.paigo.tech/#tag/Customers/operation/Create%20a%20wallet%20transaction)

### Removing Credits

The process for removing credits is almost exactly the same as issuing credits. When choosing the amount of credits to issue in the UI simply select "Reduce Existing Credits" and reduce the amount of credits a customer has in their wallet. You additionally can provide a `Reason` which is great for tracking why a deduction occurred. \ <br>

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FsOcBJmiGl3FN5HxisMkR%2FScreenshot%20from%202023-07-26%2011-26-08.png?alt=media&amp;token=6e451be1-b18a-45d0-8611-30cbda919617" alt=""><figcaption><p>Reduce existing creedits option selected</p></figcaption></figure>

## Offerings and Credit

Paigo additionally can automatically add credits to your customer's wallet when they sign up. By selecting a `Free Trial Credit` amount on an offering, when a customer is attached to that offering their credit amount will be added to their wallet to be used at the end of the billing cycle.&#x20;

To add prepaid credits to an offering please select the Credit tab under the create offering. <br>

<figure><img src="https://3896284822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F6A4R1rYAI87V2R47cxIl%2Fuploads%2FO5kNsdEdAeSVVcY30wVW%2FScreenshot%20from%202023-07-26%2011-30-00.png?alt=media&amp;token=9263698b-3b14-4dfa-81aa-a30b64bf71d7" alt=""><figcaption><p>An offering partially filled out with 1337.00 of free credit. </p></figcaption></figure>

additionally, the same action is available under the `POST /offering` endpoint in the API. See the [docs](http://www.api.docs.paigo.tech/#tag/Offerings/operation/Create%20an%20offering) for more information

### Payments with Credits&#x20;

If a customer has a balance of credits above zero the credits will be used *first* when a payment occurs through Paigo, such as transitioning an Invoice to `Open` status for a `Stripe` Customer. Partial payments for credits will be applied as well. As an example see the following case:&#x20;

#### Partial Credit Payment Example

Suppose your Stripe customer SuperSaaS has $100.00 of credits in Paigo, and at the end of the billing cycle they owe $133.70. Paigo will first subtract the 100.00$ of credits from their account, committing a transaction to the credit ledger with `invoiceId` metadata for traceability. The remaining $33.70 will be charged directly to their associated stripe account with the `invoiceId` as metadata on the payment intent.&#x20;

#### Full Credit Payment Example

In the case where credits exceed the charge required for a customer Paigo will simply substract the credits from their account and not charge their payment channel. For example suppose your customer LinkedOut has $50.00 of credit, and at the end of the billing cycle they have used $42.00 of credit. Paigo will deduct the $42.00 of credit from their wallet and commit the transaction with an `invoiceId` metadata field. No charge will occur on the supported payment channel.&#x20;

### Considerations for Credits

Below are some important considerations when issuing credits for a customer.

* Credits are always issued in the selected currency of a customer, defaulted to `USD` if none is selected on a customer.&#x20;
* Customer's cannot change preferred currency unless their wallet is empty.&#x20;
* Customer's cannot have a negative balance of credits. So if a customer's balance is `5.00` and you want to issue `-6.00 credits` an error will be returned and the ledger will not be updated.&#x20;
* Credits currently have no expire date, but can be negated at anytime by committing a deduction to a customer's wallet.&#x20;


