graph TD
A[Client Request<br/>(User ID via cookies/headers)] --> B[Edge Function<br/>(e.g., Cloudflare Worker / Vercel Edge)]
B --> C{User Identified?}
C -->|No| D[Fallback: Serve Default Config<br/>(Static JSON/Embedded)]
C -->|Yes| E[Fetch Personalization Payload<br/>(Cache HIT → Serve)<br/>Cache MISS → Call Personalization API]
E --> F[Personalization Engine<br/>(Serverless API, e.g., AWS Lambda / Supabase Edge)]
F --> G[A/B Assignment w/ Guardrails]
G --> H{Guardrails Pass?}
H -->|No| I[Fallback: Control Variant<br/>+ Log Incident]
H -->|Yes| J[Compute Variant Payload<br/>(ML Scores, Segments, Rules)]
J --> K[Store Assignment<br/>(Redis / DB for Consistency)]
K --> L[Return JSON Payload<br/>(e.g., {layout: 'A', banner: 'promo1'})]
L --> M[Edge: Cache (TTL 5-60min)<br/>Inject into Response<br/>(SSR/SSG Rewrite)]
M --> N[Personalized Response to Client]
B -.-> O[Metrics Logging<br/>(Guardrail Alarms, Latency)]
O --> P[Observability<br/>(e.g., Datadog / Sentry)]
style D fill:#ffcccc
style I fill:#ffcccc
Architecture Overview
This server-driven personalization architecture dynamically tailors user experiences (e.g., UI layouts, content recommendations, feature flags) at the edge for sub-50ms latency. Personalization logic lives server-side, ensuring consistency, security, and easy updates without client redeploys. Key principles:
- Server-Driven: Clients request generic endpoints; servers respond with personalized payloads.
- Edge-Optimized: Computation at the network edge minimizes TTFB.
- A/B Guardrails: Safe experimentation with enrollment caps, risk checks, and auto-fallbacks.
- Fallback Defaults: Graceful degradation to static defaults on errors.
Core Components
1. Edge Layer (Execution: Cloudflare Workers, Vercel Edge Runtime, Fastly Compute)
- Responsibilities:
- Authenticate/identify user (JWT,
x-user-id header, or sticky cookies).
- Check local cache (KV store like Cloudflare KV or Upstash Redis) for recent payload.
- Proxy to Personalization Engine on miss (timeout: 100ms).
- Inject payload into HTML/JSON response (e.g., via
Response.rewrite or middleware).
- Fallback: Serve embedded static JSON
{ "layout": "default", "features": {} }.
- Pseudocode (Cloudflare Worker):
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const userId = getUserId(request); // Parse cookies/headers
const cacheKey = `personalization:${userId}`;
let payload = await KV.get(cacheKey, { cacheTtl: 300 }); // 5min TTL
if (!payload) {
try {
payload = await fetchPersonalization(userId); // POST to Engine
await KV.put(cacheKey, payload, { expirationTtl: 300 });
} catch (e) {
payload = DEFAULT_PAYLOAD; // Static fallback
logError('Personalization fetch failed', { userId, error: e });
}
}
const response = await fetch(request); // Fetch base page
return new Response(response.body, {
...response,
headers: { 'x-personalization': payload } // Or rewrite HTML
});
}
2. Personalization Engine (Serverless: AWS Lambda@Edge, Supabase Functions, or PlanetScale EdgeDB)
- Responsibilities:
- Aggregate user data: Profile (DB), behavior (analytics), segments (e.g., "high-value").
- Run ML/rules for recommendations (e.g., Vercel AI SDK or simple heuristics).
- Delegate A/B assignment.
- Data Sources (low-latency reads):
| Store | Use Case | Latency Target |
|---|
| Redis | User profile, assignments | <10ms |
| Postgres (e.g., Neon) | Historical data | <50ms (indexed) |
| Analytics (e.g., PostHog) | Sessions/cohorts | Cached |
3. A/B Framework with Guardrails
- Assignment Logic (Deterministic, consistent across devices):
- Hash
userId + experimentId → bucket (0-99%).
- Guardrails (pre-assignment checks):
- Eligibility: User in segment? (e.g.,
user.ltv > 100).
- Traffic Caps: <5% total traffic? (Redis counter:
exp:${id}:enrolled < max).
- Risk Filters: Exclude VIPs, new users, or error-prone geographies.
- Runtime Safety: If
error_rate > 2% or conversion_drop > 10% (from metrics), pause → control.
- Consistency: Check prior assignment (sticky bucketing).
- On fail: Fallback to control + increment
guardrail_blocks metric.
- Pseudocode:
async function assignVariant(userId, expId, variants) {
const bucket = hash(userId + expId) % 100;
const config = await getExpConfig(expId); // Redis
// Guardrail 1: Eligibility
if (!isEligible(user, config.rules)) return 'control';
// Guardrail 2: Caps
const enrolled = await redis.incr(`exp:${expId}:enrolled`);
if (enrolled > config.maxEnroll) return 'control';
// Guardrail 3: Safety Pause
if (config.paused) return 'control';
// Assign
const variant = variants[bucket < 50 ? 0 : 1];
await redis.set(`assignment:${userId}:${expId}`, variant, 'EX', 86400);
return variant;
}
- Monitoring: Emit to Prometheus/Grafana. Alerts on guardrail hits → auto-pause via API.
4. Client Integration (Minimal)
- Receive payload via
x-personalization header or <script>window.__PERSONALIZATION = {}</script>.
- Hydrate app:
usePersonalization(payload) in React/Next.js.
- No client-side logic for A/B – pure render.
5. Fallback Defaults & Resilience
- Tiers:
- Cache Hit: Ideal (99% cases).
- Service Timeout: Static
DEFAULT_PAYLOAD.
- Guardrail Fail: Control variant.
- Global Outage: Edge serves fully static SSG pages.
- Circuit Breaker: If Engine error rate >5% (tracked in Redis), Edge bypasses for 1hr.
- Testing: Chaos engineering (e.g., Gremlin) to validate fallbacks.
Deployment & Scaling
- Costs: Edge: $0.0001/req. Engine: <1M req/day free tier.
- Rollout: Start 1% traffic, ramp with guardrails.
- Benefits:
- Latency: Edge + cache → <50ms personalization.
- Safety: Guardrails prevent bad deploys (e.g., saved 20% conversion loss).
- Flexibility: Update experiments server-side instantly.
- Privacy: No PII to edge; userId anonymized.
This composable design scales to millions of users. Extend with WebAssembly for ML at edge or federated configs. Questions?