The user wants to build a multi-tenant analytics backend.
The specific requirements are:
Multi-tenancy: Data isolation or logical separation for different customers (tenants).
Row-level filters: Ensuring tenants can only access their own data.
Quotas: Limiting resource usage (API calls, data volume, query complexity) per tenant.
Caches: Improving performance by caching query results, specific to the multi-tenant context.
I need to design a system architecture or provide a code example (likely Python/SQL + a framework like FastAPI or Django) that demonstrates these concepts.
Key Components:
Database Layer (The "Source of Truth"):
Needs a tenant_id column in every relevant table.
PostgreSQL is a good choice for this due to RLS (Row Level Security) or just standard query filtering.
Application Layer (The API):
Authentication/Authorization: Identifying the tenant.
Row-Level Security implementation (Middleware or ORM level).
Quota Management: Rate limiting or storage caps.
Caching: Redis or in-memory, namespaced by tenant.
Middleware to extract tenant_id from a JWT or API Key.
Store tenant context in a context variable (Python's contextvars) so the ORM can access it without passing it around everywhere.
Phase 3: Quotas (Rate Limiting)
Use a sliding window algorithm in Redis.
Check against a limit defined per tenant.
Phase 4: Caching
Cache query results.
Crucial: The cache key must include the tenant_id to prevent data leakage (Tenant A seeing Tenant B's cached data).
Refining the Row-Level Security (RLS) approach:
Option A: Database RLS (Postgres). This is the most secure but harder to demo in a single code snippet without complex setup.
Option B: ORM Filtering (SQLAlchemy global filter). This is standard for app-level multi-tenancy. I'll implement a mixin that automatically injects tenant_id filters on reads and injects tenant_id on writes.
Refining the Quota approach:
Fixed window vs. Sliding window. Sliding window is better for analytics.
Need to define "resources". Let's say "API Requests per minute".
Security risk: Cache poisoning. If I cache get_stats(), and the key is just get_stats, tenant A creates data, caches it. Tenant B requests stats, gets Tenant A's data.
Fix: Ensure the cache key factory always pulls the current tenant context.
Final Output Structure:
Architecture Overview: High-level design.
Database Strategy: How to structure data.
Code Implementation: A robust Python/FastAPI example covering:
Query Hook: Listen to before_flush to inject tenant_id on write. Override query_class to filter on read? Actually, SQLAlchemy 1.3/1.4/2.0 handling of global filters varies. The simplest robust way for a demo is a custom Session mixin or helper functions, but let's try to make it look elegant.
Approach: Use a custom Session class that overrides execute to inject filters? That's complex.
Simpler Approach for demo: A dependency get_tenant_scoped_db that returns a query object already filtered? Or just manual filtering in the demo endpoint for clarity?
Better Approach: Define a TenantQuery extension or just clearly show where the filter happens. I will use a TenantMixin on models and a helper method to emphasize the logic.
Let's stick to:
Context: Store tenant_id.
Quota: Redis INCR with expiry.
Cache: Redis GET/SET.
DB: Standard SQLAlchemy with explicit filtering (to ensure code clarity, or maybe a global filter mixin if concise enough). I'll use a scoped query helper to keep it clean.
Wait, "Row-Level Security" usually implies Postgres RLS.
While the user asked for "row-level filters", they might mean app-level. I will mention Postgres RLS as the "Gold Standard" but implement App-Level filtering for the backend code as it's more portable for a general backend example.
Let's assemble the Python example.
I will use fastapi, sqlalchemy, redis, and uvicorn (standard stack).
Middleware: Extract X-Tenant-ID header. Set ContextVar.
Dependency: get_current_tenant reads ContextVar.
Quota: Check Redis tenant:{id}:req_count. If > limit, raise 429.
This looks solid. I will provide a complete, runnable single-file example (conceptually) or modularized code blocks.
Structure of the answer:
Architecture Design: Explaining the "Shared Database, Shared Schema" model.
Key Concepts:
Context Propagation: How the tenant ID travels through the request.
Implicit Filtering: Avoiding developer errors (forgetting the WHERE clause).
Cache Isolation: Namespace collision prevention.
Implementation (Python/FastAPI/Postgres/Redis):
Setup (Context, DB).
Middleware (Auth/Context).
Quota System.
Caching Layer.
API Endpoint.
Let's refine the "Implicit Filtering". A common pattern in SQLAlchemy is to use a Mixin that overrides __init__ to set tenant_id, and a global query filter (available in newer SQLAlchemy versions or via event listeners).
For this guide, I will use SQLAlchemy Global Filters (with_loader_criteria) or a custom Query class to show "How to build it so you don't forget the filter". This is critical for multi-tenant backends. If a developer forgets filter(tenant_id=x), it's a data breach.
Quotas:
Need to distinguish between Request Quotas (Rate limiting) and Data Quotas (Storage limits). I'll focus on Request Quotas (API calls) as they are more relevant to an analytics backend context usually, but mention storage quotas.
Cache:
Using a decorator @tenant_cached is a nice pattern.
Let's go.
Building a multi-tenant analytics backend requires strict isolation at the database layer, intelligent resource management to prevent "noisy neighbors," and cache isolation to ensure security and performance.
Below is a comprehensive design and implementation guide using Python (FastAPI), PostgreSQL, and Redis.
1. Architecture Overview
We will use the Shared Database, Shared Schema approach. This is the most common pattern for SaaS analytics:
Isolation: Every table has a tenant_id column.
Security: Row-Level Security (RLS) is enforced at the database level (not just the app level) to prevent accidental data leaks.
Performance: Redis caches aggregated results per tenant.
2. Database Layer: Row-Level Filters & Security
The most critical part of multi-tenancy is ensuring Tenant A never sees Tenant B's data. We do this by enforcing context at the database connection level.
The SQL Setup (PostgreSQL)
Instead of manually adding WHERE tenant_id = X to every query, we set a session variable in Postgres and use Row-Level Security (RLS) policies.
sql
-- 1. Enable RLS on your analytics table
CREATE TABLE page_views (
id BIGSERIAL PRIMARY KEY,
tenant_id VARCHAR(50) NOT NULL,
url TEXT,
timestamp TIMESTAMPTZ DEFAULT NOW(),
duration_ms INT
);
-- 2. Create a policy function
-- This checks a session variable set by the backend app
CREATE POLICY tenant_isolation_policy ON page_views
USING (tenant_id = current_setting('app.current_tenant_id'));
-- 3. Enable RLS
ALTER TABLE page_views ENABLE ROW LEVEL SECURITY;
The Python Middleware
We need a middleware that intercepts every request, identifies the tenant (e.g., via API Key or JWT), and sets that Postgres session variable.
python
# database.py
import os
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
3. Quotas: Preventing Noisy Neighbors
We need to limit how much data a tenant can query or ingest. We will implement two types of quotas:
Ingestion Quota: Max rows per day.
Query Cost Quota: Max execution time (preventing heavy analytics queries from slowing down the DB).
We'll use Redis for this to ensure atomic increments.
python
# quotas.py
import redis
from fastapi import HTTPException
r = redis.Redis(host='localhost', port=6379, db=0)
class QuotaManager:
def __init__(self, tenant_id: str):
self.tenant_id = tenant_id
def check_ingestion_quota(self, rows_to_add: int = 1):
# Key: tenant_id:ingestion:YYYY-MM-DD
key = f"{self.tenant_id}:ingest:{date.today()}"
current = r.incrby(key, rows_to_add)
# Set expiry on new keys (24 hours)
if current == rows_to_add:
r.expire(key, 86400)
if current > 10000: # Limit: 10k rows/day
raise HTTPException(status_code=429, detail="Daily ingestion quota exceeded")
def check_query_quota(self):
# Key: tenant_id:query_cost:current_minute (Sliding window)
key = f"{self.tenant_id}:cost:{int(time.time() / 60)}"
current_cost = int(r.get(key) or 0)
if current_cost > 5000: # Limit: 5000 "query credits" per minute
raise HTTPException(status_code=429, detail="Rate limit exceeded: Query too complex")
4. The Caching Layer
In analytics, users often refresh dashboards repeatedly. We cache the results.
Crucial: The cache key must include the tenant_id to prevent data leakage where Tenant A's cached result is served to Tenant B.
python
# cache.py
import json
import redis
import hashlib
r = redis.Redis(host='localhost', port=6379, db=1) # Separate DB for cache
def get_cache_key(tenant_id: str, query_params: dict):
# Create a unique hash for the query parameters + tenant
params_str = json.dumps(query_params, sort_keys=True)
query_hash = hashlib.md5(params_str.encode()).hexdigest()
return f"analytics:{tenant_id}:{query_hash}"
def get_cached_result(key):
data = r.get(key)
return json.loads(data) if data else None
def set_cache(key, data, ttl=60):
r.setex(key, ttl, json.dumps(data))
5. Putting it all together (FastAPI Application)
Here is the complete backend logic. It uses a Middleware to set the Database Session Variable (RLS) and dependencies for Quotas.
python
# main.py
from fastapi import FastAPI, Depends, HTTPException, Request
from sqlalchemy import text
from datetime import date
import time
app = FastAPI()
# --- Mock Auth ---
def get_current_tenant(request: Request):
# In reality, decode a JWT or look up an API Key
tenant_id = request.headers.get("X-Tenant-ID")
if not tenant_id:
raise HTTPException(status_code=401, detail="Tenant ID missing")
return tenant_id
# --- DB Dependency with RLS Setup ---
def get_tenant_db(tenant_id: str = Depends(get_current_tenant)):
db = SessionLocal()
try:
# CRITICAL: Set the session variable for Postgres RLS
# This ensures all subsequent SQL in this request is filtered automatically
db.execute(text(f"SET app.current_tenant_id = '{tenant_id}'"))
yield db
finally:
# Clean up session var just in case connection is pooled
db.execute(text("RESET app.current_tenant_id"))
db.close()
# --- Ingestion Endpoint ---
@app.post("/events")
def ingest_event(
payload: dict,
tenant_id: str = Depends(get_current_tenant),
db = Depends(get_tenant_db)
):
# 1. Check Quota
q = QuotaManager(tenant_id)
q.check_ingestion_quota()
# 2. Insert Data
# Note: We don't need to manually specify tenant_id in the INSERT
# if we use a Postgres Trigger or default value, but here we do it explicitly for safety.
sql = text("""
INSERT INTO page_views (tenant_id, url, duration_ms)
VALUES (:tid, :url, :dur)
""")
db.execute(sql, {
"tid": tenant_id,
"url": payload['url'],
"dur": payload['duration']
})
db.commit()
# Invalidate relevant cache keys if necessary (omitted for brevity)
return {"status": "ok"}
# --- Analytics Endpoint ---
@app.get("/analytics/avg-load-time")
def get_stats(
url_filter: str,
tenant_id: str = Depends(get_current_tenant),
db = Depends(get_tenant_db)
):
params = {"url": url_filter}
# 1. Check Cache
cache_key = get_cache_key(tenant_id, params)
cached = get_cached_result(cache_key)
if cached:
return {"source": "cache", "data": cached}
# 2. Check Query Quota
q = QuotaManager(tenant_id)
q.check_query_quota()
# 3. Execute Query
# Because of `SET app.current_tenant_id` in the dependency,
# this query ONLY returns rows for the current tenant.
start_time = time.time()
result = db.execute(text("SELECT AVG(duration_ms) FROM page_views WHERE url = :url"), params)
avg_time = result.scalar()
duration_ms = (time.time() - start_time) * 1000
# 4. Update Query Cost (Simple heuristic: 1 cost per 10ms)
# Prevents users from spamming expensive queries
cost_key = f"{tenant_id}:cost:{int(time.time() / 60)}"
r.incrby(cost_key, int(duration_ms / 10))
r.expire(cost_key, 120)
# 5. Update Cache
set_cache(cache_key, {"avg_load_time": avg_time}, ttl=300)
return {"source": "database", "data": {"avg_load_time": avg_time}}
Key Implementation Details
Implicit Filtering: In get_stats, notice I did not add AND tenant_id = :tid to the SQL. The database enforces this via the SET app.current_tenant_id command run in the middleware. This is safer; if a developer forgets the WHERE clause, RLS returns an empty result set rather than leaking data.
Quota Strategy: We used a simple time-window counter in Redis. For the query quota, we measured the actual execution time and deducted "credits" from the tenant's allowance.
Cache Isolation: The get_cache_key function hashes the parameters and the tenant ID. This guarantees that Tenant A cannot retrieve Tenant B's cached dashboard data.