Usage-Based Billing for SaaS Application

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

SaaS Billing Based on Usage (Usage-Based Billing)

Pay-per-use or metric billing: client pays for actual consumption — API calls, GB traffic, active users, generated images. Stripe Meters is the modern way.

Stripe Meters (New API)

const meter = await stripe.billing.meters.create({
  display_name: 'API Calls',
  event_name: 'api_call',
  default_aggregation: {
    formula: 'sum',
  },
  customer_mapping: {
    event_payload_key: 'stripe_customer_id',
    type: 'by_id',
  },
  value_settings: {
    event_payload_key: 'value',
  },
});

const price = await stripe.prices.create({
  currency: 'usd',
  unit_amount: 100, // $0.01 per unit
  recurring: {
    interval: 'month',
    usage_type: 'metered',
    aggregate_usage: 'sum',
  },
  billing_scheme: 'per_unit',
  product: productId,
});

Sending Usage Events

export async function trackApiUsage(
  customerId: string,
  quantity: number = 1,
  metadata?: Record<string, string>
) {
  await stripe.billing.meterEvents.create({
    event_name: 'api_call',
    payload: {
      stripe_customer_id: customerId,
      value: quantity.toString(),
      ...metadata,
    },
    timestamp: Math.floor(Date.now() / 1000),
  });
}

export function trackUsageMiddleware(req: Request, res: Response, next: NextFunction) {
  const originalEnd = res.end;

  res.end = function(...args) {
    if (res.statusCode < 400 && req.user?.stripeCustomerId) {
      trackApiUsage(req.user.stripeCustomerId, 1, {
        endpoint: req.path,
        method: req.method,
      }).catch(console.error);
    }

    return originalEnd.apply(this, args);
  };

  next();
}

Tiered Pricing

const tieredPrice = await stripe.prices.create({
  currency: 'usd',
  billing_scheme: 'tiered',
  tiers_mode: 'graduated',
  tiers: [
    {
      up_to: 1000,
      unit_amount: 100, // $0.01 each for first 1000
    },
    {
      up_to: 10000,
      unit_amount: 50,  // $0.005 for next 9000
    },
    {
      up_to: 'inf',
      unit_amount: 10,  // $0.001 for everything above 10000
    },
  ],
  recurring: {
    interval: 'month',
    usage_type: 'metered',
    aggregate_usage: 'sum',
  },
  product: productId,
});

Local Usage Tracking

Stripe Meters have latency. For real-time limits — local counter:

import { Redis } from '@upstash/redis';

const redis = new Redis({
  url: process.env.UPSTASH_REDIS_URL!,
  token: process.env.UPSTASH_REDIS_TOKEN!,
});

export async function checkAndIncrementUsage(
  tenantId: string,
  resource: string,
  limit: number
): Promise<{ allowed: boolean; current: number; limit: number }> {
  const key = `usage:${tenantId}:${resource}:${getCurrentMonthKey()}`;

  const pipeline = redis.pipeline();
  pipeline.incr(key);
  pipeline.expire(key, 60 * 60 * 24 * 35);

  const [current] = await pipeline.exec() as [number, number];

  if (current > limit) {
    await redis.decr(key);
    return { allowed: false, current: current - 1, limit };
  }

  syncUsageToStripe(tenantId, resource, 1).catch(console.error);

  return { allowed: true, current, limit };
}

function getCurrentMonthKey(): string {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
}

UI: Usage Widget

export async function UsageWidget({ tenantId }: { tenantId: string }) {
  const usage = await getMonthlyUsage(tenantId);
  const subscription = await getSubscription(tenantId);
  const limits = PLAN_LIMITS[subscription.plan];

  return (
    <div className="space-y-4">
      {Object.entries(usage).map(([resource, current]) => {
        const limit = limits[resource as keyof typeof limits];
        const percentage = limit === Infinity
          ? 0
          : Math.min((current / limit) * 100, 100);

        return (
          <div key={resource}>
            <div className="flex justify-between text-sm mb-1">
              <span className="capitalize">{resource.replace(/_/g, ' ')}</span>
              <span>
                {current.toLocaleString()}
                {limit !== Infinity && ` / ${limit.toLocaleString()}`}
              </span>
            </div>
            {limit !== Infinity && (
              <div className="h-2 bg-gray-200 rounded">
                <div
                  className={`h-2 rounded transition-all ${
                    percentage > 90 ? 'bg-red-500' :
                    percentage > 70 ? 'bg-yellow-500' : 'bg-blue-500'
                  }`}
                  style={{ width: `${percentage}%` }}
                />
              </div>
            )}
          </div>
        );
      })}

      <div className="text-xs text-gray-500">
        Resets {getNextBillingDate(subscription.currentPeriodEnd).toLocaleDateString('en-US')}
      </div>
    </div>
  );
}

Usage-based billing setup with Stripe Meters and Redis counters — 3–5 working days.