We are to design a server-driven personalization architecture that uses edge functions, A/B guardrails, and fallback defaults.
The goal is to have a system that can personalize content for users based on various signals (like user segment, behavior, etc.) but with safety nets (A/B guardrails to limit changes and fallback defaults when personalization fails).
Steps:
User makes a request to our edge (CDN) which is configured to run an edge function (e.g., on Cloudflare Workers, Fastly Compute, etc.).
The edge function will:
a. Determine the user's context (e.g., via cookies, headers, IP, etc.) to get user attributes (like segment, experiment group, etc.).
b. Check for any active A/B tests or personalization rules that apply to this user (from a configuration stored in a key-value store, e.g., Cloudflare KV, or a remote configuration service).
c. Apply the personalization rules to the request (e.g., modify the response, redirect, etc.) but within the guardrails of the A/B test (e.g., only a percentage of users get the treatment, or the change is limited to a certain feature set).
d. If the personalization fails (e.g., missing data, rule not found, etc.), then use a fallback default.
The edge function might need to fetch configuration from a central store. Since edge functions are stateless and we want low latency, we can cache the configuration in the edge KV (or similar) and update it periodically.
We also need to consider that the personalization might require additional data (like user profile) from an origin. We can either:
a. Have the edge function call the origin (but that might increase latency) or
b. Have the edge function cache user profile data (if it's not sensitive and we have consent) or
c. Have the personalization rules be based only on data available at the edge (like geolocation, device, etc.) and then pass the decision to the origin via headers/cookies.
Alternatively, the edge function could be used to set a cookie or header that the origin then uses to serve personalized content. This way, the heavy lifting of personalization (if complex) can be done at the origin, but the edge function sets the stage.
However, the requirement is for server-driven personalization, meaning the server (edge function) makes the decision and modifies the response.
Let's break down:
Option A: Edge function modifies the response directly (e.g., by fetching the origin and then modifying the body, or by using a template and replacing placeholders). This is more complex because we have to handle the response from the origin (which might be HTML, JSON, etc.) and then modify it.
Option B: Edge function sets a header or cookie that the origin uses to serve the personalized content. This is simpler and offloads the personalization to the origin, but the edge function still decides which variant the user should see.
Since the requirement says "compose a server-driven personalization architecture", I think we are to design the system where the edge function is the one that applies the personalization.
However, note: edge functions have limited CPU and memory, so we cannot do heavy computations. We can do:
Simple rule evaluation (if user in segment X, then set header Y)
Fetch a pre-rendered personalized page from a cache (keyed by user attributes) or from the origin with a special header.
Given the constraints, I propose:
Edge function receives request.
It looks up user attributes (from cookie, IP, etc.) and then looks up the active personalization rules from a configuration (stored in KV, updated periodically).
The rules are in the form:
if (condition on user attributes) then (action: set header, set cookie, redirect, fetch from a different cache key, etc.)
The edge function then either:
a. Modifies the request (e.g., change the URL to fetch a different cached object) or
b. Modifies the response (after fetching from origin) by injecting content (if the origin returns a placeholder) or
c. Sets a header that the origin uses to serve the right content (if the origin is dynamic and can handle the header).
We must have A/B guardrails: the configuration should specify that only a percentage of users in a segment get the treatment. So we need to randomize (using a hash of user identifier or IP) and check against the rollout percentage.
Fallback defaults: if no rule matches, or if the rule matches but the treatment fails (e.g., the cache key for the treatment is missing), then we use a default.
Implementation:
Let's assume we are using Cloudflare Workers with KV.
Steps in the edge function:
Parse the request, get user identifier (if any). We can use a cookie or generate one if not present (but for personalization we might need a consistent identifier, so we set a cookie if not present?).
Get the user attributes. We might have a user profile service that we can call, but that would be a network call and increase latency. Alternatively, we can store user attributes in a cookie (encrypted) if we have them from previous visits, or we can infer from the request (IP for geo, User-Agent for device, etc.). We can also have a mapping of IP to attributes (like geo) stored in KV (updated periodically).
Fetch the personalization configuration from KV (cached in the worker, so we don't fetch on every request? We can use a cache with TTL). The configuration might look like:
{
"rules": [
{
"id": "rule1",
"condition": {
"segment": "premium",
"country": ["US", "CA"]
},
"treatment": {
"type": "header",
"name": "X-Personalization",
"value": "variant_a"
},
"rollout": 0.5, // 50% of users in this segment get this
"fallback": {
"type": "header",
"name": "X-Personalization",
"value": "default"
}
}
]
}
For each rule (or the first matching rule? We might have multiple rules, but we need to decide priority. Let's assume we have an ordered list and we take the first that matches and also passes the rollout percentage).
For a given rule, check:
Does the user match the condition? (segment in user.attributes, country in user.attributes)
Does the user pass the rollout? We can compute a hash of (rule.id + user.id) mod 100 and check if it's less than rollout*100.
If yes, then apply the treatment. The treatment can be:
Set a header (to be used by the origin)
Set a cookie
Redirect to a different URL
Fetch a different resource (by modifying the request URL) from the cache/origin.
If the rule doesn't match, or the user doesn't pass the rollout, then we check the next rule? Or we have a default rule? We can have a fallback at the rule level (as in the example above) and also a global fallback.
If no rule applies, then we use the global fallback (which might be to do nothing, or set a default header).
Then we fetch the resource (from cache or origin) and if we set a header, we add it to the request so the origin can use it, or if we are modifying the response, we wait for the response and then modify.
But note: if the treatment is to fetch a different URL (like a personalized cache key), then we modify the request and then fetch. This is efficient because we don't have to modify the response.
If the treatment is to set a header and the origin uses that header to decide what to serve, then we don't need to modify the response. The origin does the work.
So, I think the best practice is to let the origin handle the personalization via a header (or cookie) that the edge function sets. Then the origin can use that to fetch the right content from its cache or database.
But the requirement says "server-driven", meaning the server (edge) is driving. So if the origin is not personalized, we have to do it at the edge.
Given the complexity, I think we should design for two modes:
Mode 1: Edge sets a header/cookie and origin uses it (preferred, because origin can do complex personalization and edge doesn't have to handle the response).
Mode 2: Edge modifies the response (only for simple text replacements, or if the origin returns a placeholder that we replace). This is risky because we might break the structure.
So, let's stick to Mode 1 for the main design, and if we need Mode 2, we can have a treatment type that does response modification (but we have to be cautious).
Proposed treatment types:
"request_header": set a header in the request that is passed to the origin.
"response_header": set a header in the response (after fetching from origin).
"cookie": set a cookie in the response.
"redirect": send a redirect response.
"url_rewrite": change the request URL (so we fetch a different resource).
We can have a rule that uses one of these.
Now, for the A/B guardrails, we already have the rollout percentage.
Fallback defaults:
At the rule level: if the rule matches but the rollout fails, we can either do nothing (and let the next rule try) or use the rule's fallback (which is an action).
If the rule matches and the rollout passes, but the action fails (e.g., the rewritten URL doesn't exist, or the header is not set because of an error), then we use the fallback for that rule? Or we have a global fallback?
We can have:
code
rule: {
condition: ...,
rollout: 0.5,
treatment: { type: "url_rewrite", ... },
fallback: { type: "url_rewrite", ... } // if the treatment fails, do this? But how do we know it fails?
}
Actually, the treatment might not fail in the edge function (we are just setting a header or rewriting a URL). The failure would happen at the origin (if the rewritten URL returns 404). We might not know until we fetch.
So, we can have:
code
If we rewrite the URL and the origin returns 404, then we try the fallback? But that would require a second request? That's expensive.
Alternatively, we can have a fallback cache key or URL that we try if the treatment URL fails? But that would require two fetches.
Given the edge function's limitation, we might not want to do two fetches. So we can do:
code
If the treatment is a URL rewrite, we try the treatment URL first. If it returns a 404 or 5xx, then we try the fallback URL (if defined). But note: the fallback might be the original URL? Then we are already trying the original if the treatment fails? Actually, the original URL is the one we started with.
So, we can:
code
Let originalURL = request.url
If rule matches and rollout passes, then try treatmentURL (which is a rewritten version of originalURL). If treatmentURL returns an error (404, 500, etc.), then we try the originalURL? But that might be the same as the fallback?
Alternatively, we can have:
code
treatment: { type: "url_rewrite", pattern: "...", replacement: "..." }
fallback: { type: "url_rewrite", pattern: "...", replacement: "..." } // but this is also a rewrite, so we are rewriting again?
This is getting complicated.
Maybe we should separate:
code
The rule condition and rollout decide whether to apply the treatment or not. If we apply the treatment and it fails (at the origin), then we don't have a built-in way to fallback. We can have a global fallback that is the original request (which is what we would have done anyway). So we don't need a fallback for the treatment? Because if the treatment fails, we are already making a request to the treatment URL. If that fails, we can retry the original URL? But that would be two network calls.
Given the edge function's goal of low latency, we don't want two network calls. So we must be confident that the treatment URL exists. We can have a configuration that maps the treatment URL to a cache key that we know exists? Or we can pre-warm the cache.
Alternatively, we can design the treatment to be safe: the treatment URL is a variant that we know exists (because we deployed it). So we don't expect 404s.
So, let's assume that the treatment is safe and we don't need to handle 404s for the treatment. If we get a 404, it's an error and we return the 404.
But what about the rollout? If the user doesn't pass the rollout, we don't apply the treatment and we use the original URL (which is the default). So that's the fallback for the rollout.
So, we can have:
code
For each rule in order:
if user matches condition and rollout passes, then apply treatment and break.
else, continue to next rule.
If no rule applied, then use the global default (which is to do nothing, i.e., use the original request).
But what if we want a default treatment (like for users that don't match any condition)? We can have a default rule that matches everyone (condition: true) and then set a default treatment. And then we can have a rollout of 100% for that rule? But then everyone gets the default? That might not be what we want.
Alternatively, we can have a global default that is applied if no rule matches. That global default can be a treatment (like set a header to "default_variant").
So, we can have:
code
rules: [ ... ],
default: { ... } // default treatment if no rule matches.
And then, if a rule matches but the rollout fails, we don't apply that rule and we continue to the next rule? Or we break and use the default?
Let's decide:
code
We want to apply the first rule that matches AND the rollout passes. If a rule matches but rollout fails, we treat it as if it didn't match and continue to the next rule.
So:
for rule in rules:
if condition matches and rollout passes:
apply treatment and break
if no rule applied:
apply global default
But what if we want a rule to have a fallback when the rollout fails? That is, if the user is in the condition but doesn't pass the rollout, we want to give them the control (not the treatment) but also not the default? Then we need to have a rule for the control group? Actually, the rollout is the percentage that gets the treatment. The rest get the control (which is the original). So we don't need a fallback for the rollout because the control is the original request.
However, if the rule's condition is very specific (e.g., only for premium users in US) and the user is premium in US but doesn't pass the rollout, then we want to give them the control (original) and not the default (which might be for non-premium). So by continuing to the next rule, we might match a rule that is for all premium users? But we don't have such a rule?
Actually, the control for a specific rule is the original request. But if we have multiple rules, we might have a rule that matches more generally and sets a different default?
Example:
code
Rule1: condition: premium and US, rollout: 50%, treatment: variantA.
Rule2: condition: premium, rollout: 100%, treatment: variantB.
A premium user from US:
50% chance: Rule1 matches and rollout passes -> variantA.
50% chance: Rule1 matches but rollout fails -> then we try Rule2? Rule2 matches (premium) and rollout 100% -> variantB.
But that might not be what we want. We might want the control for Rule1 to be the original, and then Rule2 would apply to all premium (including those in US that are in the control of Rule1). That would mean 50% of US premium get variantA, 50% get variantB (from Rule2) and 0% get the original? That's not the control for Rule1.
So, we need to be careful about rule ordering and conditions.
Alternatively, we can have:
code
We want to apply the first rule that matches, regardless of rollout? And then within that rule, if the rollout fails, we use the rule's fallback? But then the rule's fallback could be the control (original) or something else.
Let me re-think:
code
We have a set of rules. Each rule has:
condition: a predicate on user attributes.
rollout: a number between 0 and 1.
treatment: what to do if condition matches and rollout passes.
fallback: what to do if condition matches but rollout fails. (optional, if not present, then we don't apply the rule and continue? or we use the global default?)
And then we have a global default that is applied if no rule matches (or if a rule matches but we decide to continue?).
We want to apply the first rule that matches, and then within that rule, we decide between treatment and fallback (based on rollout). Then we break.
So:
for rule in rules:
if condition matches:
if rollout passes (by hash):
apply treatment
else:
apply fallback (if present) or continue?
break
If we break without applying anything (because condition matched but we didn't have a fallback and we didn't apply treatment? Or we applied nothing because condition matched but we didn't have a fallback and we decided to continue? That's messy.
Alternatively, we can say: if condition matches, then we must either apply treatment or fallback. So the rule must have a fallback if we want to do something when the rollout fails.
Example:
Rule1: condition: premium and US, rollout: 0.5, treatment: variantA, fallback: control (which is the original request).
Then for a premium US user, 50% get variantA, 50% get control.
And then we break. We don't look at other rules.
But what if we have:
Rule1: condition: premium and US, rollout: 0.5, treatment: variantA, fallback: control.
Rule2: condition: premium, rollout: 1, treatment: variantB.
Then a premium US user:
50%: Rule1 applies (condition matches) and rollout passes -> variantA.
50%: Rule1 applies but rollout fails -> fallback: control (original). Then we break, so Rule2 never applies.
So the premium US user never gets variantB.
This is because we break after the first matching condition.
So we need to design the rules carefully. Maybe we want Rule2 to be applied to all premium, including US, but then we have to put Rule2 first? But then Rule1 would never apply.
This is a classic problem with rule ordering.
We can solve by having rule priorities. But that complicates.
Alternatively, we can have a different design: we have a set of experiments (A/B tests) that are independent. Each experiment has a condition and a rollout. And then we have a set of treatments (one for the variant, one for the control). And then we have a way to combine them? That's more complex.
Given the complexity, let's stick to:
code
We have a list of rules. We apply the first rule that matches. And that rule must specify both treatment and fallback (or we use a global fallback for the rule's fallback?).
And we design the rules in order of specificity. So more specific rules first.
Example:
Rule1: condition: premium and US, treatment: variantA, fallback: control.
Rule2: condition: premium, treatment: variantB, fallback: control.
Then for a premium US user, Rule1 matches and we apply variantA or control (depending on rollout). Rule2 never applies.
For a premium non-US user, Rule1 doesn't match, Rule2 matches and we apply variantB or control.
For a non-premium user, no rule matches, so we use the global default (which might be control).
This seems workable.
So, we need:
code
So, we design:
code
rules: [
{ condition: {...}, treatment: ..., fallback: ... },
...
]
And we break on the first condition that matches.
Now, for the rollout:
code
We compute a hash of (rule.id + user.id) and then take modulo 100. If the result is less than rollout*100, then rollout passes.
But what if the user doesn't have an id? We can use the IP? But that's not stable. We can set a cookie with a random user id if not present.
We can generate a UUID and set it as a cookie (with a long expiration) if not present. Then use that.
Steps for user identification:
code
Check for a cookie named "user_id". If not present, generate a UUID and set it in the response (so the next request will have it). But for the current request, we don't have it? So we cannot do rollout based on user_id for the first request? We can use the IP for the first request? But then if the user gets a cookie, the next request will have a different hash? That might break the rollout.
Alternatively, we can do:
If the user has a cookie, use that. Otherwise, use the IP (and maybe User-Agent) to generate a stable hash? But IP might change.
We can do:
Let identifier = cookie_user_id if present, else hash(IP + User-Agent) and then set a cookie with that hash? But then we are setting a cookie that is the hash, which is not a UUID? We want a random UUID for the user.
Actually, we want a stable identifier for the user across sessions. So we must set a cookie. But for the first request, we don't have it. So we can:
Step 1: Check for cookie. If present, use it.
Step 2: If not, generate a UUID and set it in a response cookie (so the next request will have it). But for the current request, we don't have a stable id? We can use the IP and User-Agent to generate a hash for the current request, and then set the cookie. But then the next request will have a different identifier (the UUID) and the rollout might change.
This is a problem. We want the rollout to be consistent for the same user. So we need a consistent identifier.
Solution: We generate a UUID and set it in a cookie, and then we use that UUID for the current request? But we don't have it until the next request.
We can do:
If the cookie is not present, we generate a UUID and set it in the request (as a property) and also set it in the response cookie. Then we use that UUID for the current request.
But note: the edge function is running on the request, and we can set a property on the request? Actually, we can set a variable in the function and use it for the current request. Then we set the cookie in the response so the next request will have it.
So:
let userId = request.cookies.get('user_id');
if (!userId) {
userId = generateUUID();
// set a cookie in the response
response.headers.append('Set-Cookie', `user_id=${userId}; Path=/; HttpOnly; Secure; SameSite=Lax`);
}
Then we use this userId for the rollout.
But note: if the user clears cookies, then they get a new id and might get a different variant.
That's acceptable.
Now, for the condition evaluation:
code
We have user attributes. We can store them in a cookie (encrypted) or we can infer from the request (like country from IP, device from User-Agent). We can also have a mapping of IP to country (updated periodically) in KV.
We can have:
userAttributes = {
country: getCountryFromIP(request.ip),
device: getDeviceFromUA(request.headers.get('User-Agent')),
... and maybe from a cookie: if we have a cookie with encrypted user profile, we can decrypt and use that.
}
But note: we don't want to store too much in the cookie because of size. We can store a user segment in the cookie? But then we have to update the cookie when the user changes segment? That's complex.
Alternatively, we can have a separate service that, given the user_id, returns the user attributes. But that would be a network call and increase latency.
Given the edge function's latency requirement, we might have to rely on request data (IP, UA, cookie with minimal data) and then cache the user profile in KV? But then we have to update the cache when the user profile changes.
This is getting complex.
Let's simplify:
We only use attributes that are available in the request (IP, UA, cookie with a segment identifier). We don't do a network call for user profile.
So the condition is on:
- country (from IP)
- device type (from UA)
- segment (from a cookie, which we set when the user logs in or does something that changes segment)
We can have a mapping of IP to country in KV (updated daily). And a mapping of UA to device type (updated monthly). And a cookie that says "segment=premium".
Then the condition can be:
condition: {
segment: "premium",
country: ["US", "CA"]
}
We check if userAttributes.segment is "premium" and userAttributes.country is in ["US", "CA"].
How do we get the segment from the cookie? We can have a cookie named "segment" and set it when the user logs in. But then we have to trust that the cookie is set by our system? We can sign it? Or we can have the edge function set the cookie when the user logs in? But that's a different flow.
For the personalization edge function, we just read the cookie.
So, the plan:
code
Summary:
code
We have:
user identification: cookie with user_id (UUID), generated if not present.
user attributes:
country: from IP (using Cloudflare's built-in GeoIP: request.cf.country)
device: from User-Agent (we can use a simple mapping, e.g., if User-Agent contains "Mobile" then "mobile", else "desktop")
segment: from cookie (set by another system)
config: stored in KV, with structure:
{
"rules": [
{
"id": "rule1",
"condition": {
"segment": "premium",
"country": ["US", "CA"]
},
"rollout": 0.5,
"treatment": {
"type": "request_header",
"name": "X-Personalization",
"value": "premium_us_variant"
},
"fallback": {
"type": "request_header",
"name": "X-Personalization",
"value": "premium_control"
}
},
...
],
"default": {
"type": "request_header",
"name": "X-Personalization",
"value": "default"
}
}
Evaluation:
For each rule (in order):
if condition matches (for every key in condition, userAttributes has the same value, or if condition value is array, userAttributes value is in the array) then:
compute hash(rule.id + userId) % 100 < rollout*100 ?
if yes: use treatment
else: if fallback exists, use fallback; else, continue
else: continue
If no action selected, use default.
Then apply the action (redirect, request_header, response_header, cookie).
Then fetch and set cookie if needed, set response header if needed.
function matches(condition, attributes) {
for (let key in condition) {
if (!attributes.hasOwnProperty(key)) return false;
let condValue = condition[key];
let attrValue = attributes[key];
if (Array.isArray(condValue)) {
if (!condValue.includes(attrValue)) return false;
} else {
if (condValue !== attrValue) return false;
}
}
return true;
}
But note: what if the condition has a key that the attributes doesn't have? Then false.
Also, what if the attributes has more keys? That's okay.
Now, we have to consider that the userAttributes might have segment as null or undefined? We should treat undefined as not matching? Yes.
We can also have condition that checks for existence? Like condition: { segment: null } meaning segment must be null? That might be useful.
But let's keep it simple.
Now, for the hash function:
code
We can use a simple hash (like SHA-256) and then take the first few bytes? But we don't need cryptographically secure. We can use a hash that is consistent across workers? We can use the built-in crypto.subtle.digest? But that returns a promise and is async.
Alternatively, we can use a simple string hash function (like djb2) but we want consistency across workers and over time? We can use a non-crypto hash that is consistent.
We can do:
function hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash);
}
Then we do hash % 100.
But note: this hash might not be consistent across different JavaScript engines? It should be, because it's just arithmetic.
However, we want the same hash on every worker for the same string. This function should be deterministic.
But we are using the same code on every worker, so it should be the same.
Alternatively, we can use a more robust hash like murmur? But for our purpose (rollout) we don't need perfect distribution, just consistency.
So, we can use the above.
Now, caching the config:
code
We can store the config in KV. We can read it on every request, but that would be a KV read on every request, which is slow and costs.
We can cache the config in the worker's global scope (so it's shared between requests) and update it every 5 minutes.
Example:
let configCache = {
data: null,
expires: 0
};
async function getConfig() {
const now = Date.now();
if (now < configCache.expires && configCache.data) {
return configCache.data;
}
// read from KV
let config = await CONFIG_KV.get('personalization_config', 'json');
configCache.data = config;
configCache.expires = now + 5*60*1000; // 5 minutes
return config;
}
But note: the edge function might have multiple instances? In Cloudflare Workers, the global scope is shared between requests on the same instance, but we might have multiple instances. So we cannot rely on a single global cache? Actually, we can, because each instance will have its own cache, but they will all read from the same KV. So it's okay.
However, if we update the config, it might take up to 5 minutes to propagate? But that's acceptable for personalization config.
Now, what about the user segment cookie? We are reading it from the request. But how is it set? That's by another system (like when the user logs in and we set a cookie). We don't handle that in this edge function.
But we can set the segment cookie in this edge function if we have a rule that sets a cookie? Yes, we can have a rule that sets a cookie. For example, if we want to assign a segment based on conditions? But then we are setting the segment cookie and then using it in the same request? That's too late.
So, we assume the segment cookie is set by a different process (like the origin when the user logs in).
This design is for personalization based on existing attributes.
Now, let's write the code structure:
code
This is a basic implementation.
Note: We are using request.cf.country which is Cloudflare specific. For other edge platforms, we need to adjust.
Also, we are not handling the case where the originResponse is a stream? We are using originResponse.body which is a ReadableStream. That should be okay.
But when we create a new Response, we are passing the same body stream? That's okay because we are not reading it.
However, note that if we set the user_id cookie and the action cookie, we are appending Set-Cookie headers. That's allowed.
But what about the response_header action? We are setting it on the finalResponse, which might overwrite an existing header? We use set, so yes.
We might want to append? But then we have to decide.
We can change:
code
if (action.type === 'response_header') {
// if the header already exists, we might want to append? But then we have to split by comma? That's complex.
// Let's assume we are setting a header that doesn't exist, or we want to overwrite.
finalResponse.headers.set(action.name, action.value);
}
This is a design decision.
Also, note that the request_header action sets the header on the request that goes to the origin. The origin might use that to vary the response.
This design should work.
However, we must consider that the personalization config might be large? We are reading the entire JSON from KV. We can store it as a string and parse? But KV stores strings, so we store as JSON string and parse.
We can also store the rules in a more efficient way? But for simplicity, we use JSON.
Now, for the A/B guardrails: we are using the rollout percentage and the hash to assign users.
Fallback defaults: we have a fallback at the rule level and a global default.
This meets the requirements.
But note: the edge function is doing a lot of work:
- reading cookies
- getting GeoIP
- parsing UA
- reading config from KV (with caching)
- evaluating rules
- fetching the origin (which is the expensive part)
We are doing one fetch to the origin (unless redirect). That's the same as without personalization.
The extra work is minimal.
However, if we have many rules, the evaluation might take time? But we break at the first match, so it's O(1) in the best case, O(n) in the worst.
We can optimize by ordering the rules by the most specific first? But that's up to the config.
We can also precompute a decision tree? But that's overkill.
Given the typical number of rules (maybe 10-20), it's acceptable.
This is a solid architecture.
Let me know if there are any questions.
I'll design a comprehensive server-driven personalization architecture leveraging edge computing with guardrails and fallbacks. This architecture prioritizes performance, safety, and reliability.
Architecture Overview
code
Client Request → Edge Function → (Personalization Decision) → Origin/Fallback → Response
↑ ↑
Context Gathering Config Store
(Req/Auth/Geo) (KV/Redis)
1. Core Components
A. Edge Function (Runtime Layer)
javascript
// Pseudocode for main edge function
async function handleRequest(request) {
// 1. Collect context (low-latency)
const context = await collectContext(request);
// 2. Load personalization config (cached)
const config = await getConfig(context);
// 3. Apply AB guardrails & decision logic
const decision = await evaluateRules(context, config);
// 4. Apply transformation/fetch with fallback
return await executeDecision(request, decision);
}
1. Staging: Test with 0.1% internal traffic
2. Canary: 1% traffic with full guardrails
3. Gradual: 1% → 5% → 25% (monitor each step)
4. Full: 100% if all metrics green
5. Rollback: Automatic if guardrails triggered
Fast Failures: Detection < 50ms, fallback < 100ms total
Stateless Edge: All state in KV/cookies, no worker memory reliance
This architecture provides enterprise-grade personalization with built-in safety nets, ensuring that performance SLAs are maintained even during partial failures, and that business metrics can be accurately attributed to personalization decisions.
However, if the origin doesn't support personalization via headers, we might have to modify the response. But that is heavy.
rules: array of {
condition: { ... }, // how to evaluate? We can have a simple key-value match, or a more complex expression? Let's keep it simple: an object that must be a subset of the user attributes.
treatment: action,
fallback: action (optional, if not present, then we break without applying? But then we break without doing anything? That's like ignoring the rule? We can say: if condition matches and there's no fallback, then we continue to next rule? That might be better.
Let's change:
for rule in rules:
if condition matches:
if rollout passes:
apply treatment and break
else:
if fallback exists:
apply fallback and break
else:
continue // try next rule
else:
continue
If we finish the loop without breaking, then apply global default.
This way, if a rule matches but doesn't have a fallback and the rollout fails, we continue to the next rule.
Example:
Rule1: condition: premium and US, rollout: 0.5, treatment: variantA, fallback: control.
Rule2: condition: premium, rollout: 1, treatment: variantB.
For a premium US user:
50%: Rule1 matches, rollout passes -> variantA, break.
50%: Rule1 matches, rollout fails -> has fallback? Yes, so control, break.
So Rule2 never applies to US premium.
But what if we want Rule2 to apply to all premium including US? Then we have to remove the condition from Rule1? Or we change the order:
Rule1: condition: premium, rollout: 1, treatment: variantB.
Rule2: condition: premium and US, rollout: 0.5, treatment: variantA, fallback: control.
Then for a premium US user:
Rule1 matches (premium) and rollout 100% -> variantB, break. So US premium always get variantB.
That's not what we want. We want 50% of US premium to get variantA and 50% to get control (variantB is for all premium?).
We see that the rule order matters and we have to design carefully.
Maybe we need to have independent experiments? That is, we want to run an experiment on US premium (variantA vs control) and also a different experiment on all premium (variantB vs control). But then we have two experiments that might conflict.
So, we might need to have a way to combine experiments? That's getting too complex for a simple edge function.
Given the time, I think we should stick to the first rule that matches and then break. And we design the rules in order of specificity and make sure that the more specific rules are first and that they cover the cases we want.
Alternatively, we can have a rule that is an experiment and then the next rule is for the same segment but a different experiment? Then we are running two experiments on the same user? That's not good.
So, maybe we should have a way to tag experiments and make sure they are mutually exclusive? But that's beyond the scope.
For simplicity, we assume that the rules are mutually exclusive in condition? Or we accept that the first rule that matches wins.
We can have a configuration that is generated by a system that ensures non-overlapping conditions? That would be ideal.
So, let's assume the conditions are non-overlapping. Then the first rule that matches is the one we want.
Then we don't need to worry about multiple matches.
Edge function:
// 1. Get or set user_id cookie.
let userId = request.cookies.get('user_id');
if (!userId) {
userId = generateUUID();
// set in response cookie
response.headers.append('Set-Cookie', `user_id=${userId}; Path=/; HttpOnly; Secure; SameSite=Lax`);
}
// 2. Get user attributes:
let country = getCountryFromIP(request.ip); // using a KV mapping or a built-in GeoIP? Cloudflare has built-in GeoIP.
let device = getDeviceFromUA(request.headers.get('User-Agent')); // simple regex match?
let segment = request.cookies.get('segment'); // if we set it elsewhere.
let userAttributes = { country, device, segment };
// 3. Load personalization config from KV (with caching in the worker, so we don't fetch on every request? We can use a cache with TTL, e.g., 5 minutes).
let config = getConfigFromKV(); // we can store the config in KV and read it, and cache in a variable with a timestamp.
// 4. Evaluate rules in order.
let appliedAction = null;
for (let rule of config.rules) {
if (rule.matches(userAttributes)) { // we need to define matches: for each key in rule.condition, check if userAttributes has the same value (or in the array if condition value is array).
// check rollout
let hash = hashString(rule.id + userId); // we need a consistent hash function
let rolloutPass = (hash % 100) < (rule.rollout * 100);
if (rolloutPass) {
appliedAction = rule.treatment;
break;
} else {
if (rule.fallback) {
appliedAction = rule.fallback;
break;
} else {
continue; // try next rule
}
}
}
}
if (!appliedAction) {
appliedAction = config.default; // global default
}
// 5. Apply the action.
// Action types:
// - request_header: add a header to the request (so the origin sees it)
// - response_header: add a header to the response (after fetching)
// - cookie: set a cookie in the response
// - redirect: send a redirect response (and stop)
// - url_rewrite: change the request URL and then fetch.
// We need to handle each type.
// If the action is redirect, we can send a redirect response and not fetch the origin.
// For others, we might need to fetch the origin (unless we are just setting a request header and then the origin uses it).
// Let's assume we are going to fetch the origin in all cases except redirect.
// If the action is url_rewrite, then we modify the request URL and then fetch.
// If the action is request_header, we set a header on the request.
// If the action is response_header or cookie, we wait until we get the response and then modify.
// So:
if (appliedAction.type === 'redirect') {
return Response.redirect(appliedAction.url, appliedAction.status || 302);
}
// For url_rewrite, we change the request URL.
if (appliedAction.type === 'url_rewrite') {
// We assume the action has a pattern and replacement? Or just a new URL?
// Let's assume it's a string replacement on the URL? Or we can have a function? We can store a template.
// Example:
// treatment: { type: "url_rewrite", pattern: "/product/(\\d+)", replacement: "/personalized/product/$1" }
// But we don't have the original URL in the condition? We can use the request URL.
// Alternatively, we can have a fixed new URL? But then we lose the path.
// We can have:
// treatment: { type: "url_rewrite", "url": "/personalized{path}" } // where {path} is the original path.
// But we might want to use the user attributes? We can have a template string that uses variables.
// Since we are in an edge function, we can use JavaScript to compute the new URL.
// Let's assume the action has a function that takes the request and userAttributes and returns a new URL string. But we are storing the config in KV as JSON, so we cannot store a function.
// So we need a simple templating. We can have:
// treatment: { type: "url_rewrite", "template": "/personalized{path}?user_id={user_id}" }
// Then we replace {path} with request.path, and {user_id} with userId.
// But we have to be cautious of injection.
// Alternatively, we can have a set of known variables and do string replacement.
// Let's define:
// template: a string that can contain placeholders like {path}, {userId}, {country}, etc.
// Then:
let newUrl = appliedAction.template
.replace(/{path}/g, request.path)
.replace(/{userId}/g, userId)
.replace(/{country}/g, country)
.replace(/{segment}/g, segment || '');
// But note: we might have query string? We can also have {query}?
// Alternatively, we can use the URL object:
let url = new URL(request.url);
// and then we can set pathname, search, etc.
// But the template might be a full URL? We can do:
// if the template starts with http, then it's a full URL, else it's relative to the current origin.
// We can do:
if (appliedAction.template.startsWith('http')) {
request.url = appliedAction.template; // but we are not allowed to change request.url? Actually, we can create a new request.
} else {
let newUrl = new URL(request.url);
newUrl.pathname = appliedAction.template; // but the template might include the path and query?
// This is getting messy.
}
Given the complexity, maybe we avoid url_rewrite and use request_header and let the origin handle the URL? But then the origin must be able to handle the header and change the URL.
Alternatively, we can have:
We don't do url_rewrite. Instead, we set a header and the origin uses that to decide which cache key to use? That's a common pattern.
So, let's drop url_rewrite and only support:
- request_header: set a header on the request (so the origin can use it to vary the response)
- response_header: set a header on the response (for client-side personalization? but we are server-driven)
- cookie: set a cookie in the response (so the client sends it next time)
- redirect: as is.
And then the origin must be designed to use the request header (like X-Personalization-Variant) to serve the right content.
That's simpler.
So, we only support:
treatment: {
type: "request_header",
name: "X-Personalization",
value: "variant_a"
}
and similarly for fallback.
And the global default is to set no header? Or set a default header? We can have the global default also be a request_header.
Then we don't need to modify the response.
So the edge function:
if (appliedAction.type === 'redirect') {
return Response.redirect(appliedAction.url, appliedAction.status || 302);
}
// For request_header, we set the header on the request.
if (appliedAction.type === 'request_header') {
request.headers.set(appliedAction.name, appliedAction.value);
}
// For cookie, we set the cookie in the response (but we haven't fetched yet, so we can set it in the response that we will eventually return).
// But note: we are going to fetch the origin with the modified request (with header) and then we get a response. Then we can set the cookie in that response.
// So we need to remember to set the cookie when we return the response.
// We can have a variable to collect cookies to set.
Steps:
let cookiesToSet = [];
if (appliedAction.type === 'cookie') {
cookiesToSet.push(appliedAction);
}
// Then we fetch the origin with the modified request (if we set a request header, we already set it on the request object).
let response = fetch(request);
// Then, for each cookie in cookiesToSet, we set it in the response.
for (let cookieAction of cookiesToSet) {
// cookieAction: { type: "cookie", name: "...", value: "...", options: {...} }
response.headers.append('Set-Cookie', `${cookieAction.name}=${cookieAction.value}; ${cookieAction.options}`);
}
return response;
But what if we have multiple actions? We only apply one action per rule (the treatment or fallback). So we only have one action.
However, we might have multiple rules? But we break at the first rule that matches. So only one action.
So we can do:
let action = appliedAction;
if (action.type === 'redirect') {
return Response.redirect(action.url, action.status || 302);
}
let requestWithHeaders = request;
if (action.type === 'request_header') {
requestWithHeaders = new Request(request);
requestWithHeaders.headers.set(action.name, action.value);
}
let response = await fetch(requestWithHeaders);
if (action.type === 'cookie') {
response.headers.append('Set-Cookie', `${action.name}=${action.value}; ${action.options}`);
}
return response;
For response_header, we can set it on the response:
if (action.type === 'response_header') {
response.headers.set(action.name, action.value);
}
But note: if we set a response header, we might overwrite an existing header? We use set, which overwrites. We might want to append? But then we have to decide.
Let's assume we set (overwrite).
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// 1. Get or set user_id cookie.
let userId = getCookie(request, 'user_id');
let response = null; // we might need to modify response to set cookie
if (!userId) {
userId = generateUUID();
response = new Response(response ? response.body : null, response ? response : {});
response.headers.append('Set-Cookie', `user_id=${userId}; Path=/; HttpOnly; Secure; SameSite=Lax`);
}
// 2. Get user attributes.
let country = request.cf ? request.cf.country : 'unknown'; // Cloudflare specific, for other edge we need another way.
let ua = request.headers.get('User-Agent') || '';
let device = ua.includes('Mobile') ? 'mobile' : 'desktop';
let segment = getCookie(request, 'segment');
let userAttributes = { country, device, segment };
// 3. Get config (with caching)
let config = await getConfig();
// 4. Evaluate rules.
let action = null;
for (let rule of config.rules) {
if (matches(rule.condition, userAttributes)) {
let hash = hashString(rule.id + userId);
let rolloutPass = (hash % 100) < (rule.rollout * 100);
if (rolloutPass) {
action = rule.treatment;
break;
} else {
if (rule.fallback) {
action = rule.fallback;
break;
}
// else continue
}
}
}
if (!action) {
action = config.default;
}
// 5. Apply action.
if (action.type === 'redirect') {
return Response.redirect(action.url, action.status || 302);
}
// For request_header, we need to modify the request.
let newRequest = request;
if (action.type === 'request_header') {
newRequest = new Request(request);
newRequest.headers.set(action.name, action.value);
}
// Fetch the origin.
let originResponse = await fetch(newRequest);
// If we need to set a cookie in the response, and we already have a response (from the fetch) then we modify it.
// But note: we might have already set a cookie (for user_id) in the response variable? We have to combine.
// We have two cases:
// a. We set a user_id cookie (if it was missing) and we have a response from the fetch. We need to add the Set-Cookie header for user_id to the originResponse.
// b. The action is to set a cookie, we need to add that too.
// So, let's create a new response if we need to set cookies? Or we can just modify the originResponse's headers.
// We can do:
let finalResponse = originResponse;
if (response) {
// We have a response with the user_id cookie. We need to merge the headers.
// But we cannot set headers on an existing Response? We can create a new Response with the same body and merged headers.
let headers = new Headers(originResponse.headers);
// copy all headers from response (which has the user_id cookie) to headers.
for (let [key, value] of response.headers) {
if (key.toLowerCase() === 'set-cookie') {
// We might have multiple set-cookie headers? We can append.
headers.append(key, value);
} else {
// For other headers, we might overwrite? But we only set Set-Cookie in the user_id response.
// So we can just set.
headers.set(key, value);
}
}
finalResponse = new Response(originResponse.body, {
status: originResponse.status,
statusText: originResponse.statusText,
headers: headers
});
}
// Now, if the action is to set a cookie (and we haven't already set it in the above step) then we set it.
if (action.type === 'cookie') {
finalResponse.headers.append('Set-Cookie', `${action.name}=${action.value}; ${action.options}`);
}
// If the action is response_header, set it.
if (action.type === 'response_header') {
finalResponse.headers.set(action.name, action.value);
}
return finalResponse;
}
function getCookie(request, name) {
let cookies = request.headers.get('Cookie') || '';
let match = cookies.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) return decodeURIComponent(match[2]);
return null;
}
function generateUUID() {
// simple UUID v4 generator
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0;
let v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function matches(condition, attributes) {
for (let key in condition) {
if (!attributes.hasOwnProperty(key)) return false;
let condValue = condition[key];
let attrValue = attributes[key];
if (Array.isArray(condValue)) {
if (!condValue.includes(attrValue)) return false;
} else {
if (condValue !== attrValue) return false;
}
}
return true;
}
function hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash);
}