KPI Optimization & Customer Segmentation

01 Challenge

Segments from data analysis (e.g. RFM) stay buried in reports – the shop still shows every visitor the same content, even when they are not logged in.

02 Approach

A personalization engine between shop and database: identity resolution via cookie and login, segment lookup in Redis and deterministic A/B assignment via hashing.

03 Result

A blueprint that serves matching content to every segment in real time and makes every variant measurable – with a consent fallback and edge execution for low latency.

Stack
Python / FastAPIRedisJavaScriptPostHog / GA4Edge Functions

In modern digital ecosystems, static data analysis is no longer sufficient. This project demonstrates building a real-time personalization engine that translates analytical insights (such as RFM segmentation) directly into actionable user experiences. The goal is to maximize Customer Lifetime Value (CLV) through data-driven individualization.

The implemented architecture links Identity Resolution with dynamic content delivery and validates optimization measures through statistically sound A/B tests. This enables continuous improvement of Key Performance Indicators (KPIs) based on verified user behavior.

Segment strategies
3
Retention · Churn · Onboarding
A/B split
50/50
deterministic via SHA-256
Days
365
lifetime of the guest ID
Target latency
< 50 ms
with edge functions

Strategy: Segment-Based Targeting

The translation of abstract customer data (e.g., from an RFM classification) into concrete business logic is the core of this approach:

  • High-Value Retention: “Champions” receive exclusive offers to strengthen brand loyalty.
  • Churn Prevention: “At Risk” customers are recovered through targeted reactivation campaigns.
  • Onboarding Optimization: New customers receive trust-building content to increase conversions.

The system decides in real time which content to serve, to maximize relevance for the user.

Technical Architecture

The implementation uses a microservice architecture (e.g., with Python/FastAPI) that sits between the frontend (shop) and the database.

System architecture of the personalization engine
Fig. 1 — System architecture: shop frontend, personalization API and database
  1. 01VisitShop loads and calls the personalization APIFrontend
  2. 02IdentityGuest ID from cookie or user ID after loginCookie
  3. 03SegmentFast lookup of the customer segmentRedis
  4. 04VariantDeterministic A/B assignment via hashSHA-256
  5. 05TrackingEvent with segment, experiment and variantAnalytics
Fig. 2 — From page view to measured variant

1. Identification & Tracking (Frontend)

The biggest challenge: How do we recognize customers who are not logged in?

This is where the concept of Identity Resolution comes in. We use a combination of cookies and login data:

  1. Anonymous ID (Guest): On the first visit, each user receives a random UUID stored in a cookie (e.g., guest_123).
  2. User ID (Logged in): Once the user logs in, we link guest_123 with their real user_id_99.
  3. Recognition: When the user returns later (without logging in), we recognize them via the cookie (guest_123) and know in the backend: “This is actually user_id_99 (a Champion)”.
// Example: Frontend logic for identification
function getIdentity() {
  let guestId = getCookie('guest_id');
  if (!guestId) {
    guestId = generateUUID(); // Create new ID for unknown visitors
    setCookie('guest_id', guestId, 365); // Store for 1 year
  }
  // If user is logged in, use UserID, otherwise use GuestID
  return window.currentUser ? window.currentUser.id : guestId;
}

// Request to the Personalization API
async function fetchPersonalizedContent() {
  const id = getIdentity();
  const response = await fetch('https://api.myshop.com/personalize', {
    method: 'POST',
    body: JSON.stringify({ user_id: id }),
    headers: { 'Content-Type': 'application/json' }
  });
  
  const data = await response.json();
  renderComponent(data.variant); 
}

2. The Decision Engine (Backend)

The core is the backend service. It decides in milliseconds what content the user sees.

Step A: Fetch segment The service checks in a fast database (e.g., Redis) which segment the user belongs to.

Step B: A/B test assignment To check whether a measure works, we run A/B tests. Even within “Champions,” we might want to test whether image A or image B performs better.

Here is a simplified Python example of the logic:

import hashlib

def get_user_variant(user_id, experiment_id):
    """
    Deterministic assignment of a user to a variant (A or B).
    Uses hashing so the user sees the same variant on every visit.
    """
    hash_input = f"{user_id}-{experiment_id}".encode('utf-8')
    hash_val = int(hashlib.sha256(hash_input).hexdigest(), 16)
    
    # 50/50 Split
    return 'Variant_A' if hash_val % 2 == 0 else 'Variant_B'

def get_content_for_user(user_id):
    # 1. Load segment (e.g. from Redis/database)
    segment = database.get_user_segment(user_id) # e.g. "Champions"
    
    # 2. Logic based on segment
    if segment == "Champions":
        # A/B Test for Champions: "Early Access" vs. "VIP Event"
        variant = get_user_variant(user_id, "champion_experiment_v1")
        return {
            "component": "hero_banner",
            "variant": variant,
            "headline": "Exclusively for you: The new collection" if variant == 'Variant_A' else "VIP Invitation: Fashion Night"
        }
        
    elif segment == "At_Risk":
        return {
            "component": "popup_modal",
            "variant": "winback_discount",
            "discount_code": "WELCOMEBACK20"
        }
        
    else:
        # Fallback for unknown users / default segment
        return {"component": "standard_hero"}

Tracking & Analysis

Serving different variants is useless without measuring success. Every interaction must be tracked.

We send events to our analytics tool (e.g., PostHog, Google Analytics 4, or a custom data warehouse):

  • Event: view_item
  • Properties: segment: “Champions” · experiment_id: “champion_experiment_v1” · variant: “Variant_A”

Key Considerations: Privacy & Performance

Technically much is possible, but in practice there are two critical factors that are often overlooked.

Data Privacy (GDPR)

Before linking IDs or showing personalized content, we need the user’s consent. Without approval in the cookie banner, no tracking is allowed.

Without consent

  • No guest ID, no link to the user ID
  • No event tracking
  • Fallback: standard variant for everyone

With consent

  • Recognition via cookie and login
  • Segment-specific variant incl. A/B test
  • Events with segment, experiment and variant

Performance (Latency)

The API call for personalization often happens when the page loads. If the API takes 500 ms, the user waits in front of a blank screen.

Conclusion

By combining Data Science (RFM Analysis) and Software Engineering (API & A/B Testing), we create a dynamic shopping experience. We no longer guess what the customer wants — we know it from the data and validate our hypotheses through tests.

This is the blueprint for modern, data-driven e-commerce marketing.

👉 Foundation: The segments used here come from my project Customer Segmentation via RFM Analysis.