← Back to all products
$19
Usage Metering
Usage tracking for SaaS with API calls, storage, compute minutes, and custom metrics.
PythonMarkdown
📄 Product Preview
Try the interactive reader and demo tools below, or get the full product with all content unlocked.
📖 Interactive Reader (Free Preview) ⚙ Try Demo Tools 📦 Download Free Sample📁 File Structure 9 files
usage-metering/
├── LICENSE
├── README.md
├── examples/
│ └── basic_example.py
├── free-sample.zip
├── guide/
│ ├── 01_features.md
│ ├── 02_quick-start.md
│ └── 03_project-structure.md
├── index.html
└── src/
└── main.py
📖 Documentation Preview README excerpt
Usage Metering
A Python usage tracking system for SaaS applications. Tracks API calls, storage, compute minutes, and custom metrics with quota enforcement, billing period aggregation, idempotency protection, and billing integration hooks — all built on Python's standard library.
Features
- Event recording — Track any metric (API calls, storage, compute, custom)
- Quota enforcement — Per-plan limits with configurable overage policies
- Idempotency — Dedup protection prevents double-counting on retries
- Usage summaries — Aggregate by tenant, metric, and billing period
- Billing reports — Generate billing-ready reports with overage calculations
- Top users — Identify heaviest users within a tenant
- Batch recording — Record multiple events in one call
- Plan management — Define usage plans with per-metric quotas
Requirements
- Python 3.10+
- No external dependencies (stdlib only)
Quick Start
python src/main.py --init-demo
# Record usage
curl -X POST http://localhost:8005/api/events \
-H "Content-Type: application/json" \
-d '{"tenant_id": "tenant_acme", "metric": "api_calls", "quantity": 1, "user_id": "user_1"}'
# Check usage
curl http://localhost:8005/api/usage/tenant_acme/api_calls
# Check quota
curl http://localhost:8005/api/quota/tenant_acme/api_calls
# Generate billing report
curl -X POST http://localhost:8005/api/billing-report \
-H "Content-Type: application/json" \
-d '{"tenant_id": "tenant_acme"}'
API Endpoints
| Method | Path | Description |
|---|---|---|
| POST | /api/events | Record a usage event |
| GET | /api/usage/:tenant/:metric | Get usage summary |
| GET | /api/quota/:tenant/:metric | Check quota status |
| POST | /api/billing-report | Generate billing report |
Project Structure
usage-metering/
├── README.md
├── LICENSE
├── src/
*... continues with setup instructions, usage examples, and more.*
📄 Code Sample .py preview
src/main.py
#!/usr/bin/env python3
"""
Usage Metering — API & Resource Usage Tracking
================================================
A complete usage metering system for SaaS applications. Tracks API calls,
storage consumption, compute minutes, and custom metrics. Provides real-time
counters, billing period aggregation, quota enforcement, and integration
hooks for billing systems.
Zero dependencies. Just run: python3 main.py
Part of the SaaS Starter collection by DataNest.
License: MIT
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import time
import uuid
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone, timedelta
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any, Optional
from urllib.parse import parse_qs, urlparse
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULT_HOST = "0.0.0.0"
DEFAULT_PORT = 8005
DATA_DIR = Path("./metering-data")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("usage-metering")
# ---------------------------------------------------------------------------
# Data Models
# ... 426 more lines ...