Anti-vendor-lock-in framework
SwapLayer
Infrastructure sovereignty.
Keep your Django application independent of its service providers. SwapLayer gives billing, email, SMS, storage, identity and verification one interface each, and picks the provider from settings.
pip install SwapLayer
from swap_layer import ConfigurationError, SwapLayerSettings
# A publishable key pasted where the secret key belongs, and an SMS
# provider selected without its credentials block.
stripe = {"provider": "stripe", "stripe": {"secret_key": "pk_test_EXAMPLE0000"}}
mistakes = [
{"billing": stripe},
{"communications": {"sms": {"provider": "twilio"}}},
]
for config in mistakes:
try:
SwapLayerSettings(**config)
except ConfigurationError as e:
print(type(e).__name__)
print(" hint:", e.hint)python check_config.py
StripeKeyError hint: Stripe secret keys have a specific format. You provided a value starting with: 'pk_t...' (full value: pk_t***********0000) ProviderConfigMismatchError hint: When you set provider='twilio', you must also provide the twilio configuration.
import io
import tempfile
import django
from django.conf import settings
from swap_layer.settings import SwapLayerSettings
media = tempfile.mkdtemp()
settings.configure(
SWAPLAYER=SwapLayerSettings(
storage={"provider": "local", "media_root": media}
)
)
django.setup()
from swap_layer import get_provider
from swap_layer.storage.security import (
StorageSecurityContext,
storage_context,
)
def as_user(role):
return StorageSecurityContext(
user_id=f"{role}-1",
organization_id="org-456",
role=role,
scope_format="orgs/{organization_id}",
)
storage = get_provider("storage")
with storage_context(storage, as_user("admin")) as scoped:
upload = scoped.upload_file("docs/report.txt", io.BytesIO(b"hello"))
print(upload["file_path"])
with storage_context(storage, as_user("viewer")) as scoped:
print(scoped.download_file("docs/report.txt"))
try:
scoped.delete_file("docs/report.txt")
except PermissionError as e:
print("PermissionError:", e)python tenant_storage.py
orgs/org-456/docs/report.txt b'hello' PermissionError: Storage operation 'delete_file' requires delete permission. User 'viewer-1' with role 'viewer' does not have this permission.
Each window shows a snippet exactly as it was run and the output it printed, using the version published on PyPI.
01Before and after
The architectural shift
Move from fragile, tightly-coupled implementations to robust, provider-agnostic domain logic.
Vendor captivity
Direct SDK usage scatters vendor-specific logic across your entire codebase. Changing providers means rewriting your business.
import stripe
def checkout(user):
# Direct dependency on Stripe's API shape
customer = stripe.Customer.create(
email=user.email,
metadata={'uid': user.id}
)
# What if you need another provider later?
# How do you mock this easily?
Adapter pattern
Code against a stable, unified interface. The implementation details are abstracted away. Swap providers via configuration.
from swap_layer import get_provider
def checkout(user):
provider = get_provider('payments')
# Interface is consistent regardless of backend
customer = provider.create_customer(
email=user.email,
metadata={
'uid': str(user.id)
}
)
02Capabilities
Unified capabilities.
Explicit provider capability boundaries across billing, communication, identity, storage, and agent tooling.
Billing interface
The PyPI release (0.3.0) ships a Stripe adapter for customers, subscriptions, payment methods, payment intents, Checkout sessions, invoices and webhook verification. PayPal and Square adapters are on the GitHub main branch but not yet released to PyPI.
- Provider-neutral customer and subscription flows
- Product and price methods are defined in the interface but not yet implemented
- Explicit capability errors where providers differ
Communication hub
Direct SMTP and Django-anymail email paths, plus Twilio and AWS SNS SMS adapters.
- Consistent email and SMS send contracts
- Optional dependencies remain provider-scoped
- Normalized configuration and error handling
Identity & auth
Use Auth0 or WorkOS behind one identity-platform contract, with Stripe Identity verification as a separate capability.
- Authorization URL, code exchange, session, and logout flows
- Provider selection by application configuration
Storage agnosticism
One storage API over local disk, Google Cloud Storage and any django-storages backend (S3, Azure Blob).
- Signed upload and download URLs on Google Cloud Storage. Other backends return their storage's own file URL and do not issue presigned upload URLs.
- Scoped paths and role permissions via StorageSecurityContext
Also in the package
Framework adapters
Python core, thin integrations
Built for Django: configure a validated SwapLayerSettings object in settings.py, or load it from SWAPLAYER_* environment variables.
- Pydantic-validated configuration that rejects unknown keys
- Django settings, model, admin, and storage integration
- A swaplayer_check management command
Agent interface
Scoped MCP tooling
The optional swaplayer-mcp command gives AI assistants tools that list providers, describe setup, generate usage code and quickstarts, and send test emails and SMS through your configured provider.
- Install with
swaplayer[mcp] - Written for version 1 of the
mcpPython package: it does not start undermcp2.x yet, so install it withmcp<2 - No billing operations are exposed over MCP
- Transactional production operations remain outside the MCP surface
03Developer experience
Designed for developer sanity
Mock one interface per service instead of each vendor SDK.
-
Standardized exceptions
Customer and subscription-creation calls turn Stripe errors into PaymentDeclinedError, PaymentValidationError and other subclasses of PaymentError.
-
Testability first
Every service is an abstract base class, so tests can substitute a fake implementation.
-
Strict typing
Type-annotated interfaces with a py.typed marker for editor autocompletion.
from swap_layer import get_provider
from swap_layer.billing.adapter import PaymentError
def register_customer(user):
try:
return get_provider("payments").create_customer(email=user.email)
except PaymentError:
# Stripe errors on this call arrive as PaymentError subclasses
return notify_user("Billing is unavailable")
04Installation
Integration
Install from PyPI, then choose a provider for each service in settings.py.
-
01Install the package
pip install "swaplayer[all]" -
02Configure providers in settings.py
# settings.py: change a provider value to switch providers from swap_layer.settings import SwapLayerSettings SWAPLAYER = SwapLayerSettings( billing={"provider": "stripe", "stripe": {"secret_key": env("STRIPE_SECRET_KEY")}}, communications={"email": {"provider": "django"}}, storage={"provider": "django"}, # wraps your django-storages backend )
05Migration blueprint
How to remove lock-in without rewrites
Move vendor calls behind SwapLayer's interface first. A later provider change then becomes a settings change rather than a rewrite.
Phase 1 — normalize
Wrap the incumbent provider using SwapLayer adapters and map provider-specific errors into domain-level errors.
Phase 2 — parallelize
Add tests against the interface, so a second provider can be checked before it is switched on. This is a recommended practice, not a package feature.
Phase 3 — cut over
Change the provider value in your SWAPLAYER settings and redeploy.
Implemented boundaries teams can verify
- Pydantic-validated Django configuration with environment-variable loading.
- Provider-specific capability gaps fail explicitly instead of pretending parity.
- Secret-aware configuration errors and webhook verification helpers.
- A scoped MCP server for configuration checks, provider information, code generation and test sends.
SwapLayer
Read the design paper
The paper sets out the adapter model behind SwapLayer, the staged migration method, how failures should surface, and the trust that stays with each provider.