A customer starts browsing a product catalog on mobile safari during their morning commute, lands in Variation B of your checkout experiment, and later opens their desktop browser at work to complete the purchase. If they see Variation A on desktop, your conversion funnel breaks, the user experience jars, and your statistical significance dissolves into contaminated data.
At 365Finds, we frequently encounter engineering teams treating Optimizely's User Profile Service (UPS) as an automatic panacea for cross-device experimentation. It is not an out-of-the-box switch. If you implement it naively, you risk introducing double-digit millisecond latency into your critical rendering path or locking users into obsolete test variants long after an experiment has concluded.
Here is how Optimizely handles bucketing across devices, when you actually need a User Profile Service, and how to build a production-grade centralized UPS that keeps variations locked without wrecking performance.
The Cross-Device Dilemma: Math vs. State
Optimizely Feature Experimentation SDKs are stateless by default. They determine variant assignments using a deterministic MurmurHash3 algorithm that combines a userId with an experimentId.
This mathematical foundation provides an underappreciated guarantee: if a user is authenticated with the same userId on both iOS and Web, and the datafile configuration has not changed, Optimizely will naturally bucket them into the exact same variation on both devices without storing a single byte of state.
Deterministic Bucketing:
MurmurHash3("user_12345" + "exp_checkout_flow") % 10000 = Bucket 4250 -> Variation B
(Identical output on Node.js, Python, iOS, and Android)
Why, then, do cross-device assignments tear?
- The Anonymous-to-Authenticated Chasm: Before logging in, the mobile device passes an ephemeral UUID (
device_ios_8819), while the desktop browser passes a cookie ID (cookie_desk_3310). MurmurHash yields completely different variations for these two distinct keys. - Experiment Evolution During Live Runs: If product managers adjust traffic allocations (e.g., ramping from 10% to 50%), alter audience conditions, or temporarily pause a variant, deterministic bucketing can re-hash an existing user into a different bucket on their next device visit.
This is where the User Profile Service (UPS) becomes mandatory. The UPS provides "sticky bucketing"—persisting the first decision made for a user so that subsequent visits across any platform respect that historical assignment.
How Optimizely Evaluates Variations with UPS
When a User Profile Service is registered with the Optimizely client, the SDK modifies its internal decision pipeline:
[Trigger Flag / Experiment Evaluation]
│
▼
[Forced Variations?] ──── Yes ───► [Return Forced Variation]
│ No
▼
[UPS lookup(userId)]
│
Entry found in bucket map?
├── Yes ──► [Validate Variation in Datafile] ──► [Return Sticky Variation]
└── No
│
▼
[Evaluate Audience Rules]
│
▼
[MurmurHash3 Bucketing]
│
▼
[UPS save(userProfile)]
│
▼
[Return New Variation]
Notice the critical sequence: lookup() precedes audience and traffic evaluation. If a valid variant is already recorded in the user's experiment_bucket_map, Optimizely honors it directly, skipping audience re-checks.
The UPS Interface and Data Contract
Optimizely requires the UPS implementation to expose two functions—lookup and save—conforming to a standard JSON schema:
{
"user_id": "usr_94820",
"experiment_bucket_map": {
"exp_onboarding_v2": {
"variation_id": "var_treatment_b"
},
"exp_pricing_table": {
"variation_id": "var_annual_focus"
}
}
}
lookup(userId): Receives theuserIdstring. Returns the user profile object if found, ornull/undefinedif no record exists.save(userProfile): Receives the updated profile object containinguser_idand the mergedexperiment_bucket_map. Persists this object to your storage backend.
Mobile SDKs (iOS/Android) provide default local implementations (CoreData or SQLite), while server-side SDKs (Node, Python, Java, Go) have no default persistence. A local mobile database cannot communicate with your desktop web server. To achieve cross-device consistency, you must replace device-local storage with a centralized, distributed datastore.
Implementing a Production-Grade Centralized UPS
In a distributed microservice or multi-platform web architecture, Redis is the standard backend for a centralized UPS due to sub-millisecond retrieval speeds.
However, calling Redis over a remote network during synchronous flag evaluation can degrade response times if not guarded properly. 365Finds recommends a two-tier caching pattern: an in-memory LRU cache (L1) coupled with Redis (L2), complete with a fail-open timeout guard.
TypeScript / Node.js Implementation
import Redis from 'ioredis';
import { LRUCache } from 'lru-cache';
import { UserProfile, UserProfileService } from '@optimizely/optimizely-sdk';
interface CentralizedUPSConfig {
redisClient: Redis;
ttlSeconds?: number;
lookupTimeoutMs?: number;
}
export class DistributedUserProfileService implements UserProfileService {
private redis: Redis;
private l1Cache: LRUCache<string, UserProfile>;
private ttlSeconds: number;
private lookupTimeoutMs: number;
constructor(config: CentralizedUPSConfig) {
this.redis = config.redisClient;
this.ttlSeconds = config.ttlSeconds || 60 * 60 * 24 * 60; // 60 days
this.lookupTimeoutMs = config.lookupTimeoutMs || 25; // Strict 25ms circuit breaker
// In-memory L1 cache to avoid network roundtrips for active sessions
this.l1Cache = new LRUCache<string, UserProfile>({
max: 50000,
ttl: 1000 * 60 * 10, // 10 minutes local cache
});
}
private getKey(userId: string): string {
return `optimizely:ups:${userId}`;
}
/**
* Fetch stored profile with fail-open timeout protection
*/
async lookup(userId: string): Promise<UserProfile | null> {
// 1. Check in-memory L1 cache
const cached = this.l1Cache.get(userId);
if (cached) return cached;
// 2. Fetch from centralized Redis with a strict deadline
try {
const redisPromise = this.redis.get(this.getKey(userId));
const timeoutPromise = new Promise<null>((_, reject) =>
setTimeout(() => reject(new Error('UPS Redis lookup timeout')), this.lookupTimeoutMs)
);
const raw = await Promise.race([redisPromise, timeoutPromise]);
if (!raw) return null;
const profile: UserProfile = JSON.parse(raw as string);
this.l1Cache.set(userId, profile);
return profile;
} catch (err) {
// Fail open: log the warning and let Optimizely fall back to MurmurHash bucketing
// Never block or crash page rendering over an experiment profile lookup
return null;
}
}
/**
* Persist updated bucket assignments
*/
async save(userProfile: UserProfile): Promise<void> {
const userId = userProfile.user_id;
if (!userId) return;
// Update L1 immediately
this.l1Cache.set(userId, userProfile);
// Asynchronously persist to centralized Redis with TTL
try {
await this.redis.set(
this.getKey(userId),
JSON.stringify(userProfile),
'EX',
this.ttlSeconds
);
} catch (err) {
// Log persistence error without disrupting user thread
console.warn(`[365Finds UPS] Failed to persist profile for user ${userId}:`, err);
}
}
}
Initializing the Optimizely Instance
import * as optimizelySDK from '@optimizely/optimizely-sdk';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
const ups = new DistributedUserProfileService({ redisClient: redis });
export const optimizelyClient = optimizelySDK.createInstance({
datafile: window.__DATAFILE__, // or fetched from Optimizely CDN
userProfileService: ups,
});
Bridging Anonymous to Authenticated Sessions
A centralized UPS solves cross-device consistency once a canonical user ID is known. But what happens when an anonymous user switches from their phone to their laptop, browses, and then logs in?
There are two primary architectural patterns to bridge this gap:
Pattern A: Backend Profile Stitching on Authentication (Recommended)
When the user logs in, capture both their temporary anonymous tracking ID and their verified account ID. Execute a merge operation in your centralized store:
[User logs in on Desktop Web]
│
├─ Anonymous ID: "anon_cookie_3310"
└─ Authenticated ID: "usr_94820"
│
▼
[Fetch UPS profile for "anon_cookie_3310"]
│
▼
[Merge experiment_bucket_map into "usr_94820"]
│
▼
[Save merged record under "usr_94820" with primary key]
When the user subsequently opens their mobile app and authenticates, the mobile app queries the UPS with usr_94820, instantly receiving the exact variation assigned during their earlier anonymous desktop session.
Pattern B: The Bucketing ID Alias
If profile merging in the database is too heavy, Optimizely supports an explicit bucketing_id in user attributes:
const user = optimizelyClient.createUserContext('usr_94820', {
$opt_bucketing_id: initialDeviceUuid, // Hashes against the original device seed
});
While lightweight, 365Finds finds this approach fragile across multiple devices: if the user has an iPhone UUID and a MacBook cookie, deciding which device UUID becomes the canonical $opt_bucketing_id recreates the exact coordination headache you sought to avoid. Explicit profile merging in Redis remains far more robust.
What 365Finds Recommends: The Hidden Trade-offs
Before wiring Redis to your experimentation engine, consider whether you actually need a centralized UPS. At 365Finds, we look at experimentation systems through an operational reality lens:
| Factor | Stateless Deterministic Bucketing | Centralized User Profile Service |
|---|---|---|
| Cross-Device Consistency (Logged-in) | Guaranteed (via identical MurmurHash) | Guaranteed (via persistent storage) |
| Cross-Device Consistency (Anonymous $\rightarrow$ Auth) | No (different seeds produce different variants) | Yes (via backend profile merging) |
| Mid-flight Traffic Ramps | Users near boundary may shift buckets | Users strictly locked into historical variant |
| Performance Overhead | Zero network calls (<0.1ms computation) | 1-25ms network lookup (requires L1 cache & timeout) |
| Infrastructure Cost | None | Redis cluster, connection pooling, and maintenance |
365Finds' Rules of Thumb:
- If your experiments target purely authenticated areas (e.g., in-app dashboards, B2B SaaS workflows): Skip the UPS entirely. MurmurHash is already cross-device consistent across iOS, Android, and web out of the box, provided you keep experiment definitions stable during active test runs.
- If your funnel involves high-stakes pre-login discovery and post-login conversion (e.g., e-commerce, checkout funnels): Deploy a centralized UPS backed by Redis, but never deploy it without an L1 in-memory cache and a strict fail-open timeout (<25ms). If Redis hesitates, let Optimizely fall back to MurmurHash rather than delaying your page render.
- Set an explicit TTL on profile keys. We recommend 60 to 90 days. Without a TTL, abandoned experiment assignments accumulate in your database indefinitely, creating "zombie assignments" that distort future tests if experiment keys are ever reused.