Billing service library for API usage tracking and Stripe integration.
Project description
Augint Billing Library
Production-ready billing service library for API usage tracking, tiered pricing calculations, and Stripe integration.
📊 Live Dashboards
| 📖 Documentation | 🧪 Unit Tests | 🔬 Integration Tests | 📊 Coverage | ⚡ Benchmarks | 🔒 Security | ⚖️ Compliance |
|---|
Overview
This library provides production-ready core business logic for:
- Usage Tracking - Track API usage per customer with high-performance caching
- Tiered Pricing - Calculate charges with flexible pricing models
- Stripe Integration - Manage customers, invoices, and payments with full idempotency
- Webhook Processing - Process Stripe webhook events reliably
- Event Publishing - Publish billing events to AWS EventBridge for integration
- Audit Logging - Comprehensive audit trails for all billing operations
- Report Generation - Generate detailed usage and billing reports
- Retry & Circuit Breaking - Production-grade reliability patterns
🚀 Production Ready Features
⚡ High-Performance Caching Layer
- In-memory cache optimized for AWS Lambda environments
- Decorator-based integration with
@cachedand@cache_invalidate - Wildcard pattern invalidation for efficient cache management
- Thread-safe operations with comprehensive metrics collection
- 94% test coverage with production-grade error handling
🔒 Enterprise Security & Reliability
- Retry mechanisms with exponential backoff and circuit breakers
- Idempotency keys for all financial operations
- Comprehensive audit logging with PII redaction
- Input validation with Pydantic models
- Error isolation - cache failures don't impact core operations
📊 Observability & Monitoring
- Built-in metrics collection for cache performance and business operations
- EventBridge integration for real-time event publishing
- Structured logging with contextual information
- Health check endpoints and operational dashboards
Quick Start
Installation
pip install augint-billing-lib
Basic Usage
from augint_billing_lib import BillingService
# Initialize the service
service = BillingService(
table_name="billing-data-prod",
eventbridge_bus_name="billing-events"
)
# Track usage with automatic caching
service.track_usage(
customer_id="customer_123",
endpoint="/api/search",
usage_count=1
)
# Get customer (cached for performance)
customer = service.get_customer("customer_123")
# Calculate charges with tiered pricing
charges = service.calculate_charges("customer_123", "2024-01")
# Create and send invoice via Stripe
invoice = service.create_invoice("customer_123", charges)
Architecture
Core Components
BillingService- Main orchestrator for all billing operationsUsageCollector- High-performance usage tracking with cachingPricingCalculator- Flexible tiered pricing calculation engineStripeManager- Production Stripe integration with idempotencyWebhookProcessor- Reliable webhook event processingReportGenerator- Comprehensive reporting and analyticsEventPublisher- EventBridge event publishing with retry logicCacheLayer- High-performance Lambda memory cache
Data Storage
Single DynamoDB Table Design with optimized access patterns:
- Customer Data:
CUSTOMER#{id}- Customer information and configuration - Usage Records:
USAGE#{customer_id}#{date}- API usage tracking - Billing Periods:
BILLING#{customer_id}#{period}- Monthly billing cycles - Pricing Tiers:
PRICING#{plan_type}#{tier}- Pricing configuration - Invoices:
INVOICE#{id}- Invoice records and status
EventBridge Integration
The library publishes events for real-time monitoring and integration:
# Events published automatically
{
"source": "augint.billing",
"detail-type": "billing.usage.tracked",
"detail": {
"customer_id": "customer_123",
"endpoint": "/api/search",
"usage_count": 1,
"timestamp": "2024-01-15T10:30:00Z"
}
}
Event Types:
billing.usage.tracked- API usage recordedbilling.customer.created- New customer onboardedbilling.invoice.created- Invoice generatedbilling.payment.processed- Payment status updatesbilling.webhook.processed- Webhook events handled
Event publishing can be disabled via BILLING_ENABLE_EVENT_PUBLISHING=false.
Development Setup
# Clone the repository
git clone https://github.com/svange/augint-billing-lib.git
cd augint-billing-lib
# Install dependencies
make install
# Run tests with coverage
make test
# Run specific test categories
make test-unit # Unit tests only
make test-integration # Integration tests only
make test-all # All tests including slow ones
# Code quality checks
make lint # Fix linting issues
make format # Format code
make type-check # Type checking with mypy
make security # Security scanning
# Generate documentation
make docs # Generate API documentation
Testing Strategy
The library follows a "Mock at the Boundaries, Not the Seams" testing philosophy:
- 94% test coverage across all modules
- Real internal components used in tests for authentic behavior
- External services mocked (AWS, Stripe) at API boundaries
- State verification over behavior verification
- Comprehensive integration tests with LocalStack and Stripe test mode
See Testing Strategy Guide for detailed information.
Configuration
Environment Variables
# Required
DYNAMODB_TABLE=billing-data-prod
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
# Optional
AWS_REGION=us-east-1
EVENTBRIDGE_BUS=billing-events-prod
BILLING_ENABLE_EVENT_PUBLISHING=true
BILLING_ENABLE_AUDIT=true
# Cache Configuration
CACHE_TTL_SECONDS=300
CACHE_MAX_ITEMS=1000
DynamoDB Setup
The library expects a single DynamoDB table with these key attributes:
- Partition Key:
pk(String) - Sort Key:
sk(String) - Global Secondary Index:
gsi1pk/gsi1sk
See Architecture Guide for detailed table design.
Production Deployment
1. Infrastructure Requirements
- DynamoDB Table with on-demand or provisioned billing
- EventBridge Custom Bus for event publishing
- IAM Roles with appropriate permissions
- Secrets Manager (recommended) for API keys
2. Performance Characteristics
- Cache Hit Rate: 85-95% typical for production workloads
- Response Time: <50ms for cached operations, <200ms for uncached
- Throughput: Handles 1000+ requests/second per Lambda instance
- Memory Usage: ~50MB baseline, ~100MB with full cache
3. Monitoring & Alerting
Monitor these key metrics in production:
- Cache hit rate and eviction rate
- DynamoDB read/write capacity utilization
- EventBridge publish success rate
- Stripe API error rates and latency
Documentation
- Architecture Guide - System design and component architecture
- Troubleshooting Guide - Common issues and solutions
- Stripe Testing Guide - End-to-end Stripe integration testing
- Testing Strategy - Testing philosophy and patterns
- API Documentation - Full API reference (generated)
Contributing
Branch Naming Conventions
Use descriptive branch names with these prefixes:
-
feat/description- New features and enhancementsfeat/issue-43-caching-layerfeat/stripe-webhook-validation
-
fix/description- Bug fixesfix/issue-25-currency-formattingfix/dynamo-connection-timeout
-
docs/description- Documentation updatesdocs/api-reference-updatedocs/troubleshooting-guide
-
refactor/description- Code refactoringrefactor/pricing-calculator-cleanuprefactor/extract-common-utilities
-
test/description- Test additions or improvementstest/integration-coverage-improvementtest/unit-test-refactoring
-
chore/description- Maintenance taskschore/update-dependencieschore/ci-pipeline-optimization
Contribution Workflow
- Fork the repository
- Create a feature branch following naming conventions above
- Make your changes with comprehensive tests
- Ensure all tests pass (
make test-all) - Run quality checks (
make lint type-check security) - Commit using conventional commits format
- Push to your fork and create a Pull Request
- Link related issues in your PR description using
Closes #123orRefs #123
Pull Request Guidelines
- Use the provided PR template
- Reference related issues with
Closes #123(for issues resolved by the PR) orRefs #123(for related but not resolved issues) - Ensure CI passes and address any feedback
- Maintain backward compatibility unless explicitly agreed otherwise
License
This project is licensed under the AGPL v3 License - see the LICENSE file for details.
Built for Production • Battle-tested • Fully Observable • Enterprise-ready
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file augint_billing_lib-1.7.0.tar.gz.
File metadata
- Download URL: augint_billing_lib-1.7.0.tar.gz
- Upload date:
- Size: 117.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef7e62824f5155c7513c4896179d0091e9cf1c9d2467d8e3ff2033ea45658468
|
|
| MD5 |
775df85dd5b4fc2f3b2af11f2dd7a70c
|
|
| BLAKE2b-256 |
0b86e85863d8f3a2fa672c7e6713c754d28102c85311ed1059b7b0d3ae9ef1fa
|
Provenance
The following attestation bundles were made for augint_billing_lib-1.7.0.tar.gz:
Publisher:
pipeline.yaml on svange/augint-billing-lib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
augint_billing_lib-1.7.0.tar.gz -
Subject digest:
ef7e62824f5155c7513c4896179d0091e9cf1c9d2467d8e3ff2033ea45658468 - Sigstore transparency entry: 397227277
- Sigstore integration time:
-
Permalink:
svange/augint-billing-lib@e70b064e5f8688543fcbfe636682b904b7be869d -
Branch / Tag:
refs/heads/main - Owner: https://github.com/svange
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pipeline.yaml@e70b064e5f8688543fcbfe636682b904b7be869d -
Trigger Event:
push
-
Statement type:
File details
Details for the file augint_billing_lib-1.7.0-py3-none-any.whl.
File metadata
- Download URL: augint_billing_lib-1.7.0-py3-none-any.whl
- Upload date:
- Size: 130.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7b40350eebc3c63058abb7367cdec713a37846b6691aab53b7b7e6637b7a4e91
|
|
| MD5 |
46be33d7236c55f52854dc4fb3ff309a
|
|
| BLAKE2b-256 |
b3917f71cf0ae3d9aa8f5a97dba2c89c2a7f844cc150ea05dd97c498bc772d41
|
Provenance
The following attestation bundles were made for augint_billing_lib-1.7.0-py3-none-any.whl:
Publisher:
pipeline.yaml on svange/augint-billing-lib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
augint_billing_lib-1.7.0-py3-none-any.whl -
Subject digest:
7b40350eebc3c63058abb7367cdec713a37846b6691aab53b7b7e6637b7a4e91 - Sigstore transparency entry: 397227296
- Sigstore integration time:
-
Permalink:
svange/augint-billing-lib@e70b064e5f8688543fcbfe636682b904b7be869d -
Branch / Tag:
refs/heads/main - Owner: https://github.com/svange
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pipeline.yaml@e70b064e5f8688543fcbfe636682b904b7be869d -
Trigger Event:
push
-
Statement type: