svc-infra

Service Infrastructure

Production-ready backend infrastructure with auth, database, caching, and jobs.

svc-infra

Production-ready FastAPI infrastructure in one import

PyPI Python 3.11+ License: MIT Downloads

Stop rebuilding auth, billing, webhooks, and background jobs for every project.

Documentation ยท Examples ยท PyPI


Why svc-infra?

Every FastAPI project needs the same things: authentication, database setup, background jobs, caching, webhooks, billing... You've written this code before. Multiple times.

svc-infra packages battle-tested infrastructure used in production, so you can focus on your actual product:

python
from svc_infra.api.fastapi.ease import easy_service_app

app = easy_service_app(name="MyAPI", release="1.0.0")
# โœ… Health checks, CORS, security headers, structured logging
# โœ… Prometheus metrics, OpenTelemetry tracing
# โœ… Request IDs, idempotency middleware
# That's it. Ship it.

โšก Quick Install

bash
pip install svc-infra

๐ŸŽฏ What's Included

FeatureWhat You GetOne-liner
๐Ÿ” AuthJWT, sessions, OAuth/OIDC, MFA, API keysadd_auth_users(app)
๐Ÿ’ณ BillingUsage tracking, subscriptions, invoices, Stripe syncadd_billing(app)
๐Ÿ“ฆ DatabasePostgreSQL + MongoDB, migrations, inbox/outboxadd_sql_db(app)
โšก JobsBackground tasks, scheduling, retries, DLQeasy_jobs()
๐Ÿ”— WebhooksSubscriptions, HMAC signing, delivery retriesadd_webhooks(app)
๐Ÿ’พ CacheRedis/memory, decorators, namespacinginit_cache()
๐Ÿ“Š ObservabilityPrometheus, Grafana dashboards, OTELBuilt-in
๐Ÿ“ StorageS3, local, memory backendsadd_storage(app)
๐Ÿข Multi-tenancyTenant isolation, scoped queriesBuilt-in
๐Ÿšฆ Rate LimitingPer-user, per-endpoint, headersBuilt-in

๐Ÿš€ 30-Second Example

Build a complete SaaS backend:

python
from fastapi import Depends
from svc_infra.api.fastapi.ease import easy_service_app
from svc_infra.api.fastapi.db.sql.add import add_sql_db
from svc_infra.api.fastapi.auth import add_auth_users, current_active_user
from svc_infra.jobs.easy import easy_jobs
from svc_infra.webhooks.fastapi import require_signature

# Create app with batteries included
app = easy_service_app(name="MySaaS", release="1.0.0")

# Add infrastructure
add_sql_db(app)                    # PostgreSQL with migrations
add_auth_users(app)                # Full auth system
queue, scheduler = easy_jobs()     # Background jobs

# Your actual business logic
@app.post("/api/process")
async def process_data(user=Depends(current_active_user)):
    job = queue.enqueue("heavy_task", {"user_id": user.id})
    return {"job_id": job.id, "status": "queued"}

# Webhook endpoint with signature verification
@app.post("/webhooks/stripe")
async def stripe_webhook(payload=Depends(require_signature(lambda: ["whsec_..."]))):
    queue.enqueue("process_payment", payload)
    return {"received": True}

That's a production-ready API with auth, database, background jobs, and webhook handling.

๐Ÿ“š Feature Highlights

๐Ÿ” Authentication & Security

Full auth system with zero boilerplate:

python
from svc_infra.api.fastapi.auth import add_auth_users, current_active_user

add_auth_users(app)  # Registers /auth/* routes automatically

@app.get("/me")
async def get_profile(user=Depends(current_active_user)):
    return {"email": user.email, "mfa_enabled": user.mfa_enabled}

Includes: JWT tokens, session cookies, OAuth/OIDC (Google, GitHub, etc.), MFA/TOTP, password policies, account lockout, key rotation.

๐Ÿ’ณ Usage-Based Billing

Track usage and generate invoices:

python
from svc_infra.billing import BillingService

billing = BillingService(session=db, tenant_id="tenant_123")

# Record API usage (idempotent)
billing.record_usage(metric="api_calls", amount=1, idempotency_key="req_abc")

# Generate monthly invoice
invoice = billing.generate_monthly_invoice(
    period_start=datetime(2025, 1, 1),
    period_end=datetime(2025, 2, 1),
)

Includes: Usage events, aggregation, plans & entitlements, subscriptions, invoices, Stripe sync hooks.

โšก Background Jobs

Redis-backed job queue with retries:

python
from svc_infra.jobs.easy import easy_jobs

queue, scheduler = easy_jobs()  # Auto-detects Redis or uses memory

# Enqueue work
queue.enqueue("send_email", {"to": "user@example.com", "template": "welcome"})

# Schedule recurring tasks
scheduler.add("cleanup", interval_seconds=3600, target="myapp.tasks:cleanup")
bash
# Run the worker
svc-infra jobs run

Includes: Visibility timeout, exponential backoff, dead letter queue, interval scheduler, CLI worker.

๐Ÿ”— Webhooks

Send and receive webhooks with proper security:

python
from svc_infra.webhooks import add_webhooks, WebhookService

add_webhooks(app)  # Adds subscription management routes

# Publish events
webhook_service.publish("invoice.paid", {"invoice_id": "inv_123"})

# Verify incoming webhooks
@app.post("/webhooks/external")
async def receive(payload=Depends(require_signature(lambda: ["secret1", "secret2"]))):
    return {"ok": True}

Includes: Subscription store, HMAC-SHA256 signing, delivery retries, idempotent processing.

๐Ÿ“Š Observability

Production monitoring out of the box:

python
app = easy_service_app(name="MyAPI", release="1.0.0")
# Prometheus metrics at /metrics
# Health checks at /healthz, /readyz, /startupz
# Request tracing with OpenTelemetry
bash
# Generate Grafana dashboards
svc-infra obs dashboard --service myapi --output ./dashboards/

Includes: Prometheus metrics, Grafana dashboard generator, OTEL integration, SLO helpers.

โš™๏ธ Configuration

Everything is configurable via environment variables:

bash
# Database
SQL_URL=postgresql://user:pass@localhost/mydb
MONGO_URL=mongodb://localhost:27017

# Auth
AUTH_JWT__SECRET=your-secret-key
AUTH_SMTP_HOST=smtp.sendgrid.net

# Jobs
JOBS_DRIVER=redis
REDIS_URL=redis://localhost:6379

# Storage
STORAGE_BACKEND=s3
STORAGE_S3_BUCKET=my-uploads

# Observability
ENABLE_OBS=true
METRICS_PATH=/metrics

See the Environment Reference for all options.

๐Ÿ“– Documentation

ModuleDescriptionGuide
APIFastAPI bootstrap, middleware, versioningdocs/api.md
AuthSessions, OAuth/OIDC, MFA, API keysdocs/auth.md
BillingUsage tracking, subscriptions, invoicesdocs/billing.md
DatabaseSQL + MongoDB, migrations, patternsdocs/database.md
JobsBackground tasks, schedulingdocs/jobs.md
WebhooksPublishing, signing, verificationdocs/webhooks.md
CacheRedis/memory caching, TTL helpersdocs/cache.md
StorageS3, local, memory file storagedocs/storage.md
ObservabilityMetrics, tracing, dashboardsdocs/observability.md
SecurityPassword policy, headers, MFAdocs/security.md
TenancyMulti-tenant isolationdocs/tenancy.md
CLICommand-line toolsdocs/cli.md

๐Ÿƒ Running the Example

See all features working together:

bash
git clone https://github.com/nfraxio/svc-infra.git
cd svc-infra

# Setup and run
make setup-template    # Creates DB, runs migrations
make run-template      # Starts at http://localhost:8001

Visit http://localhost:8001/docs to explore the API.

svc-infra is part of the nfrax infrastructure suite:

PackagePurpose
svc-infraBackend infrastructure (auth, billing, jobs, webhooks)
ai-infraAI/LLM infrastructure (agents, tools, RAG, MCP)
fin-infraFinancial infrastructure (banking, portfolio, insights)

๐Ÿ“„ License

MIT License - use it for anything.


Built with โค๏ธ by nfraxio

โญ Star us on GitHub ยท ๐Ÿ“ฆ View on PyPI