Building a Python-based Tenant Routing Service involves creating a system that can route incoming HTTP requests to the appropriate tenant-specific service or database. This is commonly used in multi-tenant applications where each tenant (customer) has isolated data and potentially different configurations.
We’ll use Flask for simplicity, but this concept applies equally well to other frameworks like FastAPI, Django, etc.
✅ Goals of the Tenant Routing Service
- Identify the tenant from an incoming request (e.g., via subdomain, header, or query parameter).
- Route the request to the appropriate backend based on tenant configuration.
- Optionally support fallback logic (e.g., default tenant or error page).
🧱 Architecture Overview
[Client] → [Routing Service] → [Tenant-Specific Backend]
The routing service will:
- Parse tenant info (e.g.,
X-Tenant-ID header)
- Look up the corresponding backend URL
- Proxy the request to the correct backend
🛠️ Tech Stack
- Python 3.8+
- Flask (for routing and proxying)
- Requests (to forward requests)
📁 Project Structure
tenant-routing-service/
├── app.py
├── config.py
└── tenants.json
🔧 Step-by-Step Implementation
1. Define Tenants Configuration (tenants.json)
{
"tenant1": {
"name": "Tenant One",
"backend_url": "http://localhost:5001"
},
"tenant2": {
"name": "Tenant Two",
"backend_url": "http://localhost:5002"
}
}
Each tenant maps to a backend service.
2. Create the App (app.py)
import json
import logging
from functools import wraps
import requests
from flask import Flask, request, Response
# Load tenant configuration
with open("tenants.json") as f:
TENANTS = json.load(f)
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
def get_tenant_from_request(req):
"""Extract tenant identifier from request headers."""
return req.headers.get("X-Tenant-ID")
def route_tenant(func):
"""Middleware to route request to correct backend."""
@wraps(func)
def wrapper(*args, **kwargs):
tenant_id = get_tenant_from_request(request)
if not tenant_id or tenant_id not in TENANTS:
return {"error": "Unknown tenant"}, 400
backend_url = TENANTS[tenant_id]["backend_url"]
app.logger.info(f"Routing to {tenant_id} at {backend_url}")
# Proxy the request
try:
resp = requests.request(
method=request.method,
url=f"{backend_url}{request.path}",
headers={key: value for (key, value) in request.headers if key.lower() != "host"},
data=request.get_data(),
cookies=request.cookies,
allow_redirects=False
)
headers = [(name, value) for (name, value) in resp.raw.headers.items()]
return Response(resp.content, status=resp.status_code, headers=headers)
except requests.exceptions.RequestException as e:
app.logger.error(f"Error proxying request: {str(e)}")
return {"error": "Service unavailable"}, 503
return wrapper
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
@route_tenant
def proxy(path):
pass # Handled by middleware
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
🧪 Testing with Dummy Backends
You can simulate two dummy tenant services using simple Flask apps:
Tenant 1 (tenant1.py)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Tenant 1"
if __name__ == "__main__":
app.run(port=5001)
Tenant 2 (tenant2.py)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Tenant 2"
if __name__ == "__main__":
app.run(port=5002)
🚀 Run the System
- Start tenant services:
python tenant1.py
python tenant2.py
- Start routing service:
python app.py
- Send test request:
curl -H "X-Tenant-ID: tenant1" http://localhost:5000
# Output: Hello from Tenant 1
curl -H "X-Tenant-ID: tenant2" http://localhost:5000
# Output: Hello from Tenant 2
🧩 Optional Enhancements
- Use subdomains instead of headers for tenant identification (e.g.,
tenant1.example.com)
- Add JWT validation per tenant
- Cache tenant mappings
- Add rate limiting per tenant
- Store tenant configs in a DB (e.g., PostgreSQL or Redis)
✅ Summary
You now have a basic multi-tenant routing service in Python using Flask that:
- Identifies tenants via header
- Routes traffic to tenant-specific backends
- Proxies requests transparently
This can be extended into a full API Gateway pattern depending on your architecture needs.
Let me know if you'd like it implemented with FastAPI, async support, or Kubernetes Ingress integration!