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
| Field | Type | Description |
|---|---|---|
id | Long | Plan identifier |
name | String | Display name (e.g., "Professional") |
tier | TenantTier | FREE, PROFESSIONAL, or ENTERPRISE |
monthlyPrice | BigDecimal | Base monthly price in USD |
annualPrice | BigDecimal | Base annual price in USD |
maxUsers | Integer | Maximum user seats |
maxQueries | Integer | Monthly query limit |
maxStorageGb | Integer | Storage limit in GB |
features | List of PlanFeature | Feature flags and limits |
active | Boolean | Whether the plan is available for new subscriptions |
Default Plans
| Plan | Tier | Monthly | Annual | Users | Queries/mo | Storage |
|---|---|---|---|---|---|---|
| Starter | FREE | $0 | $0 | 3 | 1,000 | 5 GB |
| Professional | PROFESSIONAL | $299 | $2,990 | 25 | 50,000 | 100 GB |
| Enterprise | ENTERPRISE | Custom | Custom | Unlimited | Unlimited | Unlimited |
Plan Features
Each plan includes a set of feature flags that gate access to platform capabilities:
| Feature | Free | Professional | Enterprise |
|---|---|---|---|
| Text-to-SQL | Yes | Yes | Yes |
| Dashboards | 5 max | Unlimited | Unlimited |
| Data connectors | 2 max | 10 max | Unlimited |
| ML workbench | No | Yes | Yes |
| Custom domains | No | No | Yes |
| SSO (SAML/OIDC) | No | Yes | Yes |
| SLA | None | 99.5% | 99.9% |
| Support | Community | Dedicated |
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
| Field | Type | Description |
|---|---|---|
id | Long | Subscription identifier |
tenantId | UUID | Associated tenant |
planId | Long | Subscribed plan |
status | SubscriptionStatus | ACTIVE, PAST_DUE, CANCELLED, TRIAL |
billingCycle | BillingCycle | MONTHLY or ANNUAL |
startDate | LocalDate | Subscription start |
endDate | LocalDate | Current period end |
trialEndDate | LocalDate | Trial period end (if applicable) |
cancelledAt | Instant | Cancellation 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 subscriptionUsage Metering
The UsageMeteringService tracks resource consumption per tenant for usage-based billing components.
Metered Resources
| Resource | Unit | Collection Method |
|---|---|---|
| SQL queries executed | Count | Event from query engine |
| AI conversations | Count | Event from AI service |
| Data storage | GB | Periodic measurement |
| API calls | Count | API gateway logs |
| Data pipeline runs | Count | Event from pipeline service |
| Compute time | CPU-hours | Kubernetes resource metrics |
Usage Record Entity
| Field | Type | Description |
|---|---|---|
id | Long | Record identifier |
tenantId | UUID | Tenant |
metricName | String | Resource type |
value | BigDecimal | Usage quantity |
unit | String | Measurement unit |
recordedAt | Instant | Measurement timestamp |
billingPeriod | String | YYYY-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
| Field | Type | Description |
|---|---|---|
id | Long | Invoice number |
tenantId | UUID | Billed tenant |
subscriptionId | Long | Associated subscription |
billingPeriod | String | YYYY-MM format |
subtotal | BigDecimal | Pre-tax amount |
taxAmount | BigDecimal | Tax amount |
total | BigDecimal | Total amount due |
status | InvoiceStatus | DRAFT, ISSUED, PAID, OVERDUE, VOID |
issuedAt | Instant | Issue date |
dueAt | Instant | Payment due date |
paidAt | Instant | Payment received date |
lineItems | List | Itemized charges |
Invoice Line Items
| Field | Type | Description |
|---|---|---|
description | String | Charge description |
quantity | BigDecimal | Usage quantity |
unitPrice | BigDecimal | Price per unit |
amount | BigDecimal | Line 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 PDFPayment Processing
The PaymentWebhookService handles payment processor callbacks:
Payment Transaction Entity
| Field | Type | Description |
|---|---|---|
id | Long | Transaction identifier |
invoiceId | Long | Associated invoice |
amount | BigDecimal | Payment amount |
currency | String | Currency code (USD) |
status | PaymentStatus | PENDING, COMPLETED, FAILED, REFUNDED |
processorTransactionId | String | External payment processor reference |
processedAt | Instant | Processing timestamp |
Payment Webhook Endpoint
POST /api/v1/billing/webhooks/paymentThe 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:
| Resource | Attribution Method |
|---|---|
| CPU | Proportional to CPU usage |
| Memory | Proportional to memory usage |
| Storage | Proportional to PVC usage |
| Network | Proportional to ingress/egress bytes |
| Load Balancer | Fixed 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:
| Property | Value |
|---|---|
| Trial duration | 14 days |
| Trial features | Professional tier features |
| Trial limits | 5 users, 5,000 queries |
| Expiration behavior | Downgrade to Free tier (data preserved) |
| Extension | Admin can extend trial by 14 additional days |
Next Steps
- Connector Management -- data source connectors and usage tracking
- API Reference -- billing API endpoints
- Platform Services: Billing Service -- platform-wide billing operations