MATIH Platform is in active MVP development. Documentation reflects current implementation status.
7. Tenant Lifecycle
Billing

Billing Integration

The MATIH platform includes a comprehensive billing system that handles subscription plans, usage metering, invoice generation, and payment processing. The billing functionality is split between the tenant service (which owns the billing domain within the tenant context) and the billing service (which handles platform-wide billing operations).


Billing Architecture

Tenant Service                      Billing Service (8087)
+---------------------------+       +---------------------------+
| billing/                  |       |                           |
|   plans/                  |       |  Usage aggregation        |
|     BillingPlan           |       |  Invoice generation       |
|     BillingPlanService    |       |  Payment gateway          |
|     TenantSubscription    |       |  Cost attribution         |
|   invoice/                |       |  Revenue reporting        |
|     Invoice               |       |                           |
|     InvoiceService        |       +---------------------------+
|     PaymentWebhookService |
|   usage/                  |
|     UsageMeteringService  |
|     UsageRecord           |
+---------------------------+

Subscription Plans

Plan Entity

FieldTypeDescription
idLongPlan identifier
nameStringDisplay name (e.g., "Professional")
tierTenantTierFREE, PROFESSIONAL, or ENTERPRISE
monthlyPriceBigDecimalBase monthly price in USD
annualPriceBigDecimalBase annual price in USD
maxUsersIntegerMaximum user seats
maxQueriesIntegerMonthly query limit
maxStorageGbIntegerStorage limit in GB
featuresList of PlanFeatureFeature flags and limits
activeBooleanWhether the plan is available for new subscriptions

Default Plans

PlanTierMonthlyAnnualUsersQueries/moStorage
StarterFREE$0$031,0005 GB
ProfessionalPROFESSIONAL$299$2,9902550,000100 GB
EnterpriseENTERPRISECustomCustomUnlimitedUnlimitedUnlimited

Plan Features

Each plan includes a set of feature flags that gate access to platform capabilities:

FeatureFreeProfessionalEnterprise
Text-to-SQLYesYesYes
Dashboards5 maxUnlimitedUnlimited
Data connectors2 max10 maxUnlimited
ML workbenchNoYesYes
Custom domainsNoNoYes
SSO (SAML/OIDC)NoYesYes
SLANone99.5%99.9%
SupportCommunityEmailDedicated

Plan Management API

GET  /api/v1/billing/plans              # List available plans
GET  /api/v1/billing/plans/{id}         # Get plan details
POST /api/v1/billing/plans              # Create plan (admin)
PUT  /api/v1/billing/plans/{id}         # Update plan (admin)

Tenant Subscriptions

Subscription Entity

FieldTypeDescription
idLongSubscription identifier
tenantIdUUIDAssociated tenant
planIdLongSubscribed plan
statusSubscriptionStatusACTIVE, PAST_DUE, CANCELLED, TRIAL
billingCycleBillingCycleMONTHLY or ANNUAL
startDateLocalDateSubscription start
endDateLocalDateCurrent period end
trialEndDateLocalDateTrial period end (if applicable)
cancelledAtInstantCancellation timestamp

Subscription Lifecycle

TRIAL (14 days)
    |
    +--- Convert to paid ---> ACTIVE
    |
    +--- Trial expires -----> CANCELLED (data retained 30 days)

ACTIVE
    |
    +--- Payment succeeds --> ACTIVE (new period)
    |
    +--- Payment fails -----> PAST_DUE (3 retry attempts)
    |                              |
    |                              +--- Payment succeeds --> ACTIVE
    |                              +--- All retries fail --> CANCELLED
    |
    +--- User cancels ------> CANCELLED (active until period end)
    |
    +--- Upgrade ------------> ACTIVE (new plan, prorated)
    |
    +--- Downgrade ----------> ACTIVE (new plan, effective next period)

Subscription Management API

GET  /api/v1/tenants/{id}/subscription        # Get current subscription
POST /api/v1/tenants/{id}/subscription         # Create subscription
PUT  /api/v1/tenants/{id}/subscription/upgrade # Upgrade plan
PUT  /api/v1/tenants/{id}/subscription/downgrade # Downgrade plan
POST /api/v1/tenants/{id}/subscription/cancel  # Cancel subscription

Usage Metering

The UsageMeteringService tracks resource consumption per tenant for usage-based billing components.

Metered Resources

ResourceUnitCollection Method
SQL queries executedCountEvent from query engine
AI conversationsCountEvent from AI service
Data storageGBPeriodic measurement
API callsCountAPI gateway logs
Data pipeline runsCountEvent from pipeline service
Compute timeCPU-hoursKubernetes resource metrics

Usage Record Entity

FieldTypeDescription
idLongRecord identifier
tenantIdUUIDTenant
metricNameStringResource type
valueBigDecimalUsage quantity
unitStringMeasurement unit
recordedAtInstantMeasurement timestamp
billingPeriodStringYYYY-MM format

Usage Aggregation

Usage records are aggregated by the UsageAggregateRepository for billing period summaries:

GET /api/v1/tenants/{id}/usage?period=2026-02
{
  "tenantId": "550e8400-...",
  "period": "2026-02",
  "metrics": [
    {
      "name": "sql_queries",
      "total": 12450,
      "limit": 50000,
      "percentUsed": 24.9
    },
    {
      "name": "storage_gb",
      "total": 45.2,
      "limit": 100,
      "percentUsed": 45.2
    },
    {
      "name": "ai_conversations",
      "total": 320,
      "limit": 5000,
      "percentUsed": 6.4
    }
  ]
}

Invoice Generation

The InvoiceService generates invoices at the end of each billing period.

Invoice Entity

FieldTypeDescription
idLongInvoice number
tenantIdUUIDBilled tenant
subscriptionIdLongAssociated subscription
billingPeriodStringYYYY-MM format
subtotalBigDecimalPre-tax amount
taxAmountBigDecimalTax amount
totalBigDecimalTotal amount due
statusInvoiceStatusDRAFT, ISSUED, PAID, OVERDUE, VOID
issuedAtInstantIssue date
dueAtInstantPayment due date
paidAtInstantPayment received date
lineItemsListItemized charges

Invoice Line Items

FieldTypeDescription
descriptionStringCharge description
quantityBigDecimalUsage quantity
unitPriceBigDecimalPrice per unit
amountBigDecimalLine total

Invoice API

GET  /api/v1/tenants/{id}/invoices              # List invoices
GET  /api/v1/tenants/{id}/invoices/{invoiceId}  # Get invoice details
GET  /api/v1/tenants/{id}/invoices/{invoiceId}/pdf # Download PDF

Payment Processing

The PaymentWebhookService handles payment processor callbacks:

Payment Transaction Entity

FieldTypeDescription
idLongTransaction identifier
invoiceIdLongAssociated invoice
amountBigDecimalPayment amount
currencyStringCurrency code (USD)
statusPaymentStatusPENDING, COMPLETED, FAILED, REFUNDED
processorTransactionIdStringExternal payment processor reference
processedAtInstantProcessing timestamp

Payment Webhook Endpoint

POST /api/v1/billing/webhooks/payment

The webhook endpoint validates the payment processor's signature, updates the invoice status, and triggers appropriate actions (activate subscription, send receipt, etc.).


Cost Attribution

The CostAggregationService and SharedClusterCostAttributionService provide cost attribution for shared infrastructure.

Cost Attribution Model

For tenants on shared clusters, infrastructure costs are attributed based on resource consumption:

ResourceAttribution Method
CPUProportional to CPU usage
MemoryProportional to memory usage
StorageProportional to PVC usage
NetworkProportional to ingress/egress bytes
Load BalancerFixed allocation per tenant

Cost Dashboard API

GET /api/v1/tenants/{id}/costs?period=2026-02
{
  "period": "2026-02",
  "totalCost": 245.50,
  "breakdown": {
    "compute": 120.00,
    "storage": 45.50,
    "network": 30.00,
    "loadBalancer": 50.00
  }
}

Trial Management

The TrialManagementService handles free trial periods:

PropertyValue
Trial duration14 days
Trial featuresProfessional tier features
Trial limits5 users, 5,000 queries
Expiration behaviorDowngrade to Free tier (data preserved)
ExtensionAdmin can extend trial by 14 additional days

Next Steps