# High-Level Architecture Overview
# Multi-tenant SaaS app with dynamic theming via design tokens (CSS custom properties).
# Tokens stored per-tenant in DB, injected at runtime via SSR/CSR hydration.
# Instrumentation: OpenTelemetry (OTel) for traces/metrics/logs, with tenant context propagation.
# Anomalies: Runtime validation + ML-lite rules (e.g., z-score outliers on token values).
# Stack: Node.js/Express (backend), React/Next.js (frontend), Postgres (DB), Prometheus+Grafana (observability).
components:
- Tenant Resolver Middleware
- Theme Service (fetch/validate/merge tokens)
- Token Injector (SSR/CSS-in-JS)
- Instrumentation Agent (OTel spans/metrics)
- Anomaly Detector (background job + real-time hooks)
1. Data Model (Postgres Schema)
-- Tenants table (customer instances)
CREATE TABLE tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
subdomain VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Themes table: JSONB for tokens { "primary-color": "#ff0000", "font-size-base": "16px" }
CREATE TABLE tenant_themes (
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE PRIMARY KEY,
default_tokens JSONB NOT NULL DEFAULT '{}'::JSONB, -- App defaults
overrides JSONB NOT NULL DEFAULT '{}'::JSONB, -- Tenant-specific overrides
updated_at TIMESTAMP DEFAULT NOW()
);
-- Instrumentation logs (partitioned by tenant_id for scale)
CREATE TABLE theme_events (
id BIGSERIAL,
tenant_id UUID NOT NULL,
event_type VARCHAR(50) NOT NULL, -- 'override_applied', 'anomaly_detected', 'token_fetched'
token_key VARCHAR(255),
old_value TEXT,
new_value TEXT,
anomaly_score FLOAT, -- 0-1 severity
metadata JSONB,
timestamp TIMESTAMP DEFAULT NOW(),
PARTITION BY RANGE (timestamp)
) PARTITION BY RANGE (timestamp);
2. Backend: Tenant Resolver & Theme Service
// middleware/tenantResolver.ts (Express middleware)
import { Request, Response, NextFunction } from 'express';
import { trace } from '@opentelemetry/api'; // OTel for spans
export function tenantResolver(req: Request, res: Response, next: NextFunction) {
const span = trace.getTracer('app').startSpan('tenant-resolve');
const tenantId = req.headers['x-tenant-id'] as string || req.subdomains[0]; // Subdomain/header
if (!tenantId) return res.status(400).json({ error: 'Tenant ID required' });
req.tenantId = tenantId; // Attach to req
span.setAttribute('tenant.id', tenantId);
span.end();
next();
}
// services/themeService.ts
import { Pool } from 'pg';
const db = new Pool({ /* config */ });
interface Tokens { [key: string]: string; }
export class ThemeService {
async getMergedTokens(tenantId: string): Promise<Tokens> {
const span = trace.getTracer('app').startSpan('theme-merge');
span.setAttribute('tenant.id', tenantId);
const client = await db.connect();
try {
const res = await client.query(`
SELECT default_tokens, overrides FROM tenant_themes WHERE tenant_id = $1
`, [tenantId]);
if (!res.rows[0]) {
this.logEvent(tenantId, 'theme_missing', null, null, 0.8); // Anomaly: high score
return {}; // Fallback to globals
}
const { default_tokens, overrides } = res.rows[0];
const merged = { ...default_tokens, ...overrides } as Tokens;
// Log overrides
Object.entries(overrides).forEach(([key, value]) => {
this.logEvent(tenantId, 'override_applied', null, value, 0);
span.addEvent(`override.${key}`, { value });
});
// Real-time anomaly check
await this.detectAnomalies(tenantId, merged);
span.setAttribute('tokens.count', Object.keys(merged).length);
return merged;
} finally {
client.release();
span.end();
}
}
private async logEvent(tenantId: string, type: string, oldVal: string | null, newVal: string | null, score: number) {
await db.query(
`INSERT INTO theme_events (tenant_id, event_type, old_value, new_value, anomaly_score)
VALUES ($1, $2, $3, $4, $5)`,
[tenantId, type, oldVal, newVal, score]
);
// Export to OTel logs/metrics
}
private async detectAnomalies(tenantId: string, tokens: Tokens) {
// Rules-based + simple stats (extend with ML via pgml or Kafka stream)
const anomalies: string[] = [];
for (const [key, value] of Object.entries(tokens)) {
if (key.includes('color') && !this.isValidHex(value)) {
anomalies.push(key);
this.logEvent(tenantId, 'anomaly_detected', null, value, 0.9);
}
if (key.includes('size') && parseFloat(value) > 100) { // e.g., font-size > 100px outlier
this.logEvent(tenantId, 'anomaly_detected', null, value, 0.7);
}
}
if (anomalies.length > 0) {
// Alert via webhook/Slack
console.warn(`Anomalies for ${tenantId}: ${anomalies.join(', ')}`);
}
}
private isValidHex(color: string): boolean {
return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color);
}
}
3. SSR/Frontend Integration (Next.js Example)
// pages/_app.tsx or middleware.ts (Next.js 13+)
import { headers } from 'next/headers';
import ThemeService from '../services/themeService';
export async function generateStaticParams() { /* ... */ }
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const tenantId = headers().get('x-tenant-id') || 'default';
const tokens = await new ThemeService().getMergedTokens(tenantId);
// Inject CSS vars into <html>
const style = Object.entries(tokens).map(([k, v]) => `--${k}: ${v};`).join(' ');
return (
<html style={{ '--global-tokens': style } as any}>
<head>
<style dangerouslySetInnerHTML={{
__html: `:root { ${style} }`
}} />
</head>
<body>{children}</body>
</html>
);
}
// Client-side hydration check (useEffect in _app.tsx)
useEffect(() => {
const computed = getComputedStyle(document.documentElement);
Object.entries(tokens).forEach(([key, expected]) => {
if (computed.getPropertyValue(`--${key}`).trim() !== expected) {
// Log client-side drift (anomaly)
window.gtag?.('event', 'theme_drift', { tenant: tenantId, key, expected, actual: computed.getPropertyValue(`--${key}`) });
}
});
}, []);
4. Instrumentation & Observability
-
OTel Setup: Instrument Express/Next.js with @opentelemetry/instrumentation-http, propagate tenant.id via baggage.
npm i @opentelemetry/sdk-node @opentelemetry/exporter-prometheus
Metrics: theme_overrides_total{tenant_id}, anomaly_rate{tenant_id}, token_load_latency.
-
Dashboards:
| Metric | Query | Alert Threshold |
|---|
| Overrides/min | sum(rate(theme_events{event_type="override_applied"}[5m])) by (tenant_id) | >50 (spammy overrides) |
| Anomaly Score Avg | avg(theme_events{event_type="anomaly_detected"}.anomaly_score) by (tenant_id) | >0.5 → PagerDuty |
| Token Size | histogram_quantile(0.95, sum(rate(theme_tokens_size_bucket[5m])) by (le, tenant_id)) | >10KB |
-
Background Jobs: Cron job scans theme_events for trends (e.g., Node.js BullMQ).
// jobs/anomalyTrends.ts
async function detectTrends() {
const trends = await db.query(`
SELECT tenant_id, AVG(anomaly_score) as avg_score
FROM theme_events WHERE timestamp > NOW() - INTERVAL '1 day'
GROUP BY tenant_id HAVING AVG(anomaly_score) > 0.6
`);
trends.rows.forEach(row => notifyAdmins(row.tenant_id, row.avg_score));
}
5. Deployment & Scaling
- Multi-tenant Isolation: Use
pg_trgm for tenant-indexed queries, row-level security (RLS):
ALTER TABLE theme_events ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON theme_events USING (tenant_id = current_setting('app.current_tenant')::uuid);
- Caching: Redis per-tenant:
await redis.get(theme:${tenantId}) with TTL 5m, invalidate on override webhook.
- API for Overrides: POST
/api/themes/override → Update DB, purge cache, log event.
- Testing:
# Load test: Artillery
scenarios:
- flow:
- post:
url: "/api/theme-apply"
headers: { "x-tenant-id": "customer1" }
json: { "primary-color": "invalid!!!" } # Triggers anomaly
- Edge Cases: Fallback to defaults on DB outage, rate-limit overrides (10/min/tenant).
This system captures every override (logged + traced), detects anomalies in real-time (rules/ML-ready), and scales to 10k+ tenants with O(1) lookups. Extend with Vector DB for semantic anomaly search on logs. Questions?