SaaS Billing: Real-Time Usage Tracking with Stripe Meters and Redis

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_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

SaaS Billing: Real-Time Usage Tracking with Stripe Meters and Redis

Typical SaaS teams face a dilemma: fixed tiers scare off small clients, while complex ones frustrate large clients. The result — lost conversions and dissatisfaction. Consumption-based billing (UBB) solves this: the client pays only for consumed resources — API calls, GB of traffic, active users. According to our data, UBB boosts conversion by 25–40%.

Stripe Meters is a modern API for implementing this pay-as-you-go model. It automatically aggregates events and generates invoices. However, without proper architecture, you can encounter data delays and inaccuracies. We solve these issues with Redis for real-time accounting and asynchronous synchronization.

How Does Usage-Based Billing Work?

The client uses the service — each action generates an event (e.g., an API call). You send the event to Stripe Meter with the customer_id and quantity. Stripe aggregates them over the period and issues an invoice. In parallel, you store a real-time counter in Redis for instant limit checks. All without lags or duplication. It pays off in an average of 2–3 months.

Why Use Stripe Meters?

Stripe Meters is a ready-made service with a 99.9% SLA. You don't need to write your own billing — just integration code. It supports tiered pricing (graduated and volume tiers), automatic invoices, and multiple currencies. Compared to custom solutions, Stripe Meters saves up to 3 months of development and significantly reduces errors. As stated in Stripe's official documentation, metered billing is recommended for usage-based pricing.

How to Avoid Stripe Meters Delays?

Stripe Meters have a delay of up to 5 minutes. For instant limit checks, we use Redis. This allows us to reject a request if the limit is exceeded before the event reaches Stripe. A typical mistake is relying only on Stripe; the solution is Redis for local accounting and asynchronous synchronization. Our experience shows this reduces errors by 70%.

Step-by-Step Billing Implementation with Stripe Meters and Redis

We use a proven stack: latest Stripe API, Node.js (TypeScript), Redis via Upstash, React 18. Below is the code we use in production.

Step 1: Create Meter and Price

// Create Meter
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', // quantity in each event
  },
});

// Create Price tied to Meter
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,
});

Step 2: Send Usage Events

// Send event on each API call
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),
  });
}

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

  res.end = function(...args) {
    // Track only successful API calls
    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();
}

Step 3: Real-Time Usage Tracking

Stripe Meters have a delay of up to 5 minutes. For instant limit checks, we use Redis. This allows us to reject a request if the limit is exceeded before the event reaches Stripe.

// Redis: real-time usage counters
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()}`;

  // Atomic operation: check + increment
  const pipeline = redis.pipeline();
  pipeline.incr(key);
  pipeline.expire(key, 60 * 60 * 24 * 35); // 35 days

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

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

  // Send to Stripe asynchronously
  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')}`;
}

Tiered Pricing

We configure graduated and volume tiers. For example, first 1000 calls — $0.01, then $0.005, then $0.001. This encourages clients to increase consumption. This approach increases average revenue per user by 5x compared to flat rates.

// Tiered pricing: the more you use, the cheaper per unit
const tieredPrice = await stripe.prices.create({
  currency: 'usd',
  billing_scheme: 'tiered',
  tiers_mode: 'graduated', // or 'volume'
  tiers: [
    {
      up_to: 1000,
      unit_amount: 100, // $0.01 for each of the first 1000
    },
    {
      up_to: 10000,
      unit_amount: 50,  // $0.005 for the next 9000
    },
    {
      up_to: 'inf',
      unit_amount: 10,  // $0.001 for everything beyond 10000
    },
  ],
  recurring: {
    interval: 'month',
    usage_type: 'metered',
    aggregate_usage: 'sum',
  },
  product: productId,
});

UI Usage Widget

We show the client their current consumption and remaining limit. The widget updates in real time via Server-Sent Events.

// components/UsageWidget.tsx
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">
        Reset {getNextBillingDate(subscription.currentPeriodEnd).toLocaleDateString('en-US')}
      </div>
    </div>
  );
}

What's Included

Our turnkey solution includes everything you need: billing architecture design (metrics, limits, tiered pricing), Stripe Meters integration with customer mapping configuration, middleware development for tracking all events, Redis for real-time limits with automatic Stripe synchronization, UI usage widget with color-coded indicators, webhook setup for invoice handling and subscription updates, documentation and team training, and one-month post-launch support. Pricing starts at $5,000 for basic implementation, with typical costs ranging from $5,000 to $15,000 depending on complexity.

Timeline and Cost

Basic UBB implementation takes 3 to 5 business days. If custom metrics, CRM integration, or complex pricing is required, the timeline extends to 2 weeks. Contact us for a free estimate — we'll assess your project within one day.

Why Choose Us

  • Over 5 years of experience in billing system development
  • Over 30 successful projects for SaaS companies
  • Certified Stripe and AWS specialists
  • 12-month code warranty

Checklist of Common Mistakes

  • Ignoring Stripe Meters delays — use Redis
  • Not matching customer_mapping — events won't link to the client
  • Forgetting to roll back increments when limits are exceeded
  • Sending events without a timestamp — Stripe may reject them
Approach Comparison Stripe Meters Custom Billing
Development time 3-5 days 2-3 months
Billing errors minimal frequent
Scaling automatic requires rework
Maintenance cost low high
Metrics Comparison for Typical SaaS Stripe Meters Custom Solution
Implementation time 3-5 days 2-3 months
Development cost (savings) up to 2x cheaper
Error rate 2% 15%
Reliability (SLA) 99.9% depends on implementation

Stripe Meters is 3x faster to implement than custom billing solutions. Our Redis-based approach reduces errors by 70% compared to relying solely on Stripe. Setting up usage-based billing with Stripe Meters, Redis counters, and a UI widget — 3-5 business days. Get a free audit of your current billing system or contact us for a consultation.

What Does SaaS Platform Development Involve? Multi-Tenancy, Billing, and Beyond

We know this pain by heart. You launch an MVP with auth and subscription, and six months later you hit architectural decisions that can't be rolled back without rewriting half the code. Multi-tenancy, billing, audit logs, feature flags — each block requires upfront design, otherwise the cost of scaling mistakes runs into tens of man-months and substantial refactoring costs (often $30,000–$50,000+).

Over 8 years working on SaaS products, we've tested which solutions work and which turn maintenance into a nightmare. Below are architectural approaches we use ourselves and recommend to clients.

How we build multi-tenancy: isolation without overhead

The first decision is the data separation scheme. Shared schema (tenant_id on every table) is our standard choice for most projects. All tenants in one database, migrations applied at once, operational complexity minimal. In Laravel we implement it via Global Scope:

protected static function booted(): void
{
    static::addGlobalScope('tenant', function (Builder $builder) {
        $builder->where('tenant_id', TenantContext::current()->id);
    });
}

The global scope is only the first line of defense. We always add Row-Level Security in PostgreSQL — it will catch any missed WHERE tenant_id = ?:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
    USING (tenant_id = current_setting('app.tenant_id')::uuid);

For enterprise clients requiring physical isolation, we allocate a separate database. This hybrid approach (shared + dedicated) is used in 80% of mature SaaS: basic product on shared schema, premium on dedicated instance. We implement it from the first sprint to avoid rewriting logic later. Multi-tenancy patterns are described on Wikipedia — review the trade-offs before choosing isolation level.

Why Is Billing the Most Underestimated Block?

Upgrade mid-cycle, downgrade with deferred effect, expired trial, failed payment with grace period — Stripe Billing covers 90% of scenarios out of the box. We always process webhooks (customer.subscription.updated, invoice.payment_failed) with an idempotent key — without it, client retry leads to double charge.

For CIS markets — YooKassa or Tinkoff recurring. Their APIs are less convenient but cover 54-FZ requirements.

Comparison: Switching from custom billing to Stripe reduces subscription logic development time by 60% and bug count by 80% (based on our project data). That translates to $15,000–$25,000 savings on a typical SaaS MVP.

Onboarding: how not to lose the user before aha-moment

Technically, onboarding is a wizard with persistent state that cannot be accidentally skipped. Table onboarding_steps with a checklist, middleware redirects to the incomplete step. After completion — a flag in user settings, middleware disabled.

Critical nuance: show real product progress, not abstract steps. "Create your first report" instead of "Complete step 3 of 5." We use drip campaigns via Customer.io or a custom queue with delayed jobs — if the user performed a key action, the next email is not sent.

How to Implement Feature Flags and Access Control?

SaaS with plans requires granular control. Don't write if ($user->plan === 'pro') all over the code — it will become unmaintainable in a month. Instead:

  • Backend: Gate + Policy with checks via features table linked to plans.
  • Frontend: context with flags loaded at app initialization.
  • Open-source tools: Unleash or Growthbook — UI for A/B testing and rollout.

Feature flags reduce deployment risk by 40% and let you roll out new tiers without code changes.

How to Protect API from Aggressive Clients?

Rate limiting is a must for public API. One client can bring down all others. In Laravel we use Redis with sliding window counter:

Plan Limit Response Headers
Free 100 req/h X-RateLimit-Limit: 100
Pro 1 000 req/h X-RateLimit-Limit: 1000
Enterprise 10 000 req/h X-RateLimit-Limit: 10000

Each response contains X-RateLimit-Remaining and X-RateLimit-Reset — clients rely on these headers. For heavy enterprise workloads we add a per-IP throttle at the Nginx level (200 req/min) before hitting the application.

Audit Logs and Monitoring: What, Who, and When?

Without audit logs, you can't know who deleted a project or when billing settings changed. Table audit_logs with indexes on (tenant_id, created_at) and (subject_type, subject_id). In Laravel — Observers on key models.

Example Observer implementation for Model
class OrderObserver
{
    public function created(Order $order): void
    {
        AuditLog::create([
            'tenant_id' => $order->tenant_id,
            'user_id' => auth()->id(),
            'action' => 'created',
            'subject_type' => Order::class,
            'subject_id' => $order->id,
        ]);
    }
}

Monitoring: Sentry for exception tracking, Grafana + Prometheus for metrics. Alerts on error rate > 5% and response time p95 > 2s. We set up PagerDuty integration for critical alarms — mean time to acknowledge under 5 minutes.

Our Team's Experience and Guarantees

Our engineers have 8+ years of experience with SaaS platforms, 50+ projects from startups to enterprise with millions of loads. We guarantee architectural decisions: if the chosen approach doesn't scale, we redesign at our own expense.

Deliverables and Guarantees

  • Architecture documentation: diagrams, ERD, sequence diagrams.
  • CI/CD setup (GitHub Actions / GitLab CI).
  • Access to repository, staging, and production.
  • Team training: 2–3 sessions on code review and runbook.
  • Post-launch support for 1 month.
  • Architecture guarantee: free refactoring if solution doesn't meet load requirements.

Work Process

  1. Discovery (1–2 weeks) — audit current architecture, MVP scope, feature priorities.
  2. Design (1 week) — stack selection, multi-tenancy scheme, billing plan.
  3. Development (4–12 weeks) — 2-week sprints, demo after each.
  4. Testing (1 week) — load tests under target load, security audit.
  5. Deployment and training (1 week) — rollout, monitoring setup, documentation handover.

Timeline Estimates

Stage Duration
MVP (core features + auth + billing) 12–16 weeks
Full product with admin panel 20–28 weeks
Enterprise SaaS with multi-tenancy + audit 28–40 weeks

Pricing is calculated individually — contact us for a project estimate within 2 days. Order turnkey development: from design to deployment with architecture guarantee. Get a consultation on your product architecture — first hour free.