Skip to main content

Infrastructure for building and deploying prod-ready services

Project description

svc-infra

v1.0.0 CI PyPI Python License Downloads codecov

Production-ready FastAPI infrastructure in one import

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

Documentation · Examples · PyPI · Changelog


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:

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

pip install svc-infra

🎯 What's Included

Feature What You Get One-liner
🔐 Auth JWT, sessions, OAuth/OIDC, MFA, API keys add_auth_users(app)
💳 Billing Usage tracking, subscriptions, invoices, Stripe sync add_billing(app)
📦 Database PostgreSQL + MongoDB, migrations, inbox/outbox add_sql_db(app)
⚡ Jobs Background tasks, scheduling, retries, DLQ easy_jobs()
🔗 Webhooks Subscriptions, HMAC signing, delivery retries add_webhooks(app)
💾 Cache Redis/memory, decorators, namespacing init_cache()
📊 Observability Prometheus, Grafana dashboards, OTEL Built-in
📁 Storage S3, local, memory backends add_storage(app)
🏢 Multi-tenancy Tenant isolation, scoped queries Built-in
🚦 Rate Limiting Per-user, per-endpoint, headers Built-in

🚀 30-Second Example

Build a complete SaaS backend:

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:

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:

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:

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")
# 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:

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:

app = easy_service_app(name="MyAPI", release="1.0.0")
# Prometheus metrics at /metrics
# Health checks at /healthz, /readyz, /startupz
# Request tracing with OpenTelemetry
# 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:

# 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

Module Description Guide
API FastAPI bootstrap, middleware, versioning docs/api.md
Auth Sessions, OAuth/OIDC, MFA, API keys docs/auth.md
Billing Usage tracking, subscriptions, invoices docs/billing.md
Database SQL + MongoDB, migrations, patterns docs/database.md
Jobs Background tasks, scheduling docs/jobs.md
Webhooks Publishing, signing, verification docs/webhooks.md
Cache Redis/memory caching, TTL helpers docs/cache.md
Storage S3, local, memory file storage docs/storage.md
Observability Metrics, tracing, dashboards docs/observability.md
Security Password policy, headers, MFA docs/security.md
Tenancy Multi-tenant isolation docs/tenancy.md
CLI Command-line tools docs/cli.md

🏃 Running the Example

See all features working together:

git clone https://github.com/nfraxlab/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.

🤝 Related Packages

svc-infra is part of the nfrax infrastructure suite:

Package Purpose
svc-infra Backend infrastructure (auth, billing, jobs, webhooks)
ai-infra AI/LLM infrastructure (agents, tools, RAG, MCP)
fin-infra Financial infrastructure (banking, portfolio, insights)

📄 License

MIT License - use it for anything.


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

svc_infra-1.0.5.tar.gz (352.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

svc_infra-1.0.5-py3-none-any.whl (496.6 kB view details)

Uploaded Python 3

File details

Details for the file svc_infra-1.0.5.tar.gz.

File metadata

  • Download URL: svc_infra-1.0.5.tar.gz
  • Upload date:
  • Size: 352.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for svc_infra-1.0.5.tar.gz
Algorithm Hash digest
SHA256 40ab8cd41a9a5e1005f0c8fea6d9fa163ff1862a7644c7be48fc4ca525b4afa2
MD5 573d073c9a4f8ef9a07d4d7e4536a1fb
BLAKE2b-256 33300c4c5967c22b655b997f313fc8f3cd48faf2bb7e4bc66d4ed3fcfef81f1a

See more details on using hashes here.

Provenance

The following attestation bundles were made for svc_infra-1.0.5.tar.gz:

Publisher: publish-pypi.yml on nfraxlab/svc-infra

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file svc_infra-1.0.5-py3-none-any.whl.

File metadata

  • Download URL: svc_infra-1.0.5-py3-none-any.whl
  • Upload date:
  • Size: 496.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for svc_infra-1.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 64178425f0b4b8040e69f45422869a4ddf0dfd729c87f741e035bd1511aecdc2
MD5 65b1c615a8843b8751aa0223fa9f06d9
BLAKE2b-256 3b6f60ab77ce9821d34c252a90c419eb24b8542c5ee7ac38936a21e9c13b0944

See more details on using hashes here.

Provenance

The following attestation bundles were made for svc_infra-1.0.5-py3-none-any.whl:

Publisher: publish-pypi.yml on nfraxlab/svc-infra

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page