1. Overview & Business Case
A large e-commerce platform processes millions of orders per month across consumer electronics, apparel, home goods, and FMCG categories. With a registered customer base exceeding 15 million and a product catalogue of 2+ million SKUs, the platform faced a set of interconnected problems that traditional BI and rule-based systems could not solve at the speed or precision the business needed.
The data to solve these problems already existed in the platform's databases — order history, clickstream events, support tickets, email engagement. What was missing was the intelligence layer to make that data predictive rather than merely descriptive: to anticipate churn before it happens, value customers correctly, and forecast demand precisely enough to avoid both stockouts and overstock.
Business Problems This System Solves
- The personalization gap: Email campaigns sent to entire segments with the same message; product recommendations driven by simple collaborative filtering that ignored recent purchase context and lifecycle stage.
- Invisible churn: Customers quietly stopped purchasing with no early warning. Retention campaigns were reactive — triggered only after a customer had already churned, making reactivation roughly 5× more expensive than prevention.
- Inventory blindness: Demand forecasting relied on historical sales averages with manual seasonal adjustments, causing costly stockouts during peak periods and overstock in slow-moving categories.
- LTV misallocation: Customer acquisition spend was allocated based on channel cost rather than predicted lifetime value — high-potential customers received the same marketing budget as low-LTV transient shoppers.
2. System Architecture
The platform follows a layered microservices architecture, mirroring the same architectural philosophy used across JoNoleecy AI implementations: a clean separation between presentation, business services, AI/LLM inference, agent orchestration, and data — communicating through well-defined REST APIs and an event-driven Kafka backbone.
Technology Stack
| Layer | Technology | Rationale |
|---|---|---|
| Backend | Java 17 + Spring Boot 3.2 + WebFlux | Reactive streams for high-throughput prediction serving at millions-of-customer scale |
| Frontend | React 18 + TypeScript + Recharts | Rich interactive analytics dashboards with real-time chart updates via WebSocket |
| Primary Database | MySQL 8.0 (AWS RDS Multi-AZ) | Customer profiles, order history, prediction outputs — ACID compliance, read replicas for analytics |
| Analytics Warehouse | Snowflake | Petabyte-scale analytical queries; Snowpark for in-warehouse feature computation |
| Feature Store | AWS SageMaker Feature Store | Consistent feature serving for online (real-time) and offline (training) use cases |
| Event Streaming | Apache Kafka (MSK) | Real-time clickstream, order, and browse event ingestion at millions of events/hour |
| Cache | Redis 7 Cluster | Customer segment, recommendation, and prediction cache — sub-millisecond serving |
| Vector DB | Pinecone | Product and customer embeddings for semantic recommendation and similarity search |
| LLM Primary | GPT-4o Turbo (Azure OpenAI) | Cohort narrative generation, insight summarization, marketing copy |
| LLM Batch | Claude 3.5 Haiku | High-volume nightly batch: product enrichment, category summaries, email subject lines |
| ML Framework | XGBoost + LightGBM + PyTorch | Gradient boosting for tabular predictions; deep learning for demand forecasting |
| ML Platform | AWS SageMaker + MLflow | Managed training, experiment tracking, model registry, A/B testing |
Architecture Principles
- AI as a service layer, not embedded logic: All ML inference is isolated behind a clean API so models can be retrained or swapped without touching business logic.
- Event-driven for real-time responsiveness: Orders, clickstream events, and engagement signals are published to Kafka and consumed immediately by prediction services.
- Human-approved actions only: Every campaign, discount, or outreach recommended by an agent requires marketing or merchandising sign-off before execution.
- Explainability by design: Every churn and LTV prediction includes SHAP-based feature attribution so business teams understand why, not just what.
3. Data Model — MySQL Schema Design
The core MySQL schema centres on the Customer entity, with related tables capturing orders, clickstream behaviour, and AI prediction outputs. All tables follow consistent audit and indexing conventions optimised for both transactional writes and analytical read patterns.
Core Entity: Customers
Behavioural & AI Prediction Tables
Event-Driven Architecture with Kafka
4. Backend — Spring Boot Prediction Service
The backend is a Spring Boot 3.x WebFlux application, chosen specifically for its reactive, non-blocking I/O model — essential for serving real-time predictions to logged-in customers within a sub-100ms budget while a nightly batch job scores all 15 million customers in parallel.
Customer Prediction Service — Core Logic
5. AI & LLM Layer
As with every JoNoleecy AI implementation, this platform separates classical ML models (for numerical scoring: churn, LTV, demand) from a Large Language Model layer responsible for translating those predictions into business-readable insight and generating personalised marketing language.
LLM Selection: GPT-4o Turbo as Primary, Claude Haiku for Batch
| Criterion | Why It Matters Here | Model Choice |
|---|---|---|
| Narrative quality | Cohort insights and campaign copy must read naturally to non-technical merchandising teams | GPT-4o Turbo — strong business-tone generation |
| Cost at volume | Nightly batch tasks touch millions of products and customer segments | Claude 3.5 Haiku — low cost per token for high-volume batch |
| Structured output | Insight payloads must parse cleanly into typed Java objects for the dashboard | Both models support reliable JSON-mode output |
| Text-to-SQL | Merchandisers ask natural-language questions against the Snowflake warehouse | GPT-4o Turbo with schema-grounded prompting |
Cohort Insight Generation — Prompt Design
LLM Use Cases Across the Platform
- Cohort narrative generation: nightly transformation of ML outputs into business-readable insight summaries for the analytics dashboard.
- Email campaign personalization: personalised subject lines and preview text per customer segment, tied to predicted behaviour and LTV tier.
- Product description enrichment (batch, Claude Haiku): semantic tags and embeddings improving recommendation relevance across the 2M+ SKU catalogue.
- Natural language analytics queries: merchandisers type questions like "Which categories are driving churn in the 25–35 segment?" — the LLM generates and executes the Snowflake SQL.
6. Multi-Agent Architecture
Five specialised agents collaborate under a top-level orchestrator — each with a focused role, dedicated tools, and the ability to publish events that trigger downstream agents.
Churn scoring, LTV calculation, demand forecasting, and campaign optimisation each require different data, different reasoning patterns, and different failure-tolerance levels. A single monolithic prompt trying to do all four produces mediocre results everywhere; specialised agents with focused context produce substantially better outcomes at each task.
Agent Roster
Analytics Orchestrator Agent
Top-level agent receiving requests from the Spring Boot layer. Decomposes requests, routes to specialist agents, and assembles the final response. Implemented with LangGraph4j for stateful, multi-step orchestration.
Churn Prediction Agent
Monitors the Kafka event stream for behavioural signals predicting churn — declining session frequency, rising return rate, category narrowing. Classifies the trigger pattern (price-driven, competitive, experience-driven, lifecycle) and recommends an intervention type.
LTV Scoring Agent
Runs on every completed order to recalculate predicted 12-month Customer Lifetime Value. Segments customers into five tiers (Champion, Loyal, Potential, At-Risk, Lost) and publishes tier changes that trigger ad-bid adjustments and loyalty tier updates.
Demand Forecast Agent
Runs nightly SKU-level forecasts for a 28-day horizon, ingesting historical sales, current inventory, promotional calendar, and external signals like weather and search trend data. Outputs feed directly into automated reorder triggers.
Insight Narrator Agent
Transforms raw model outputs and trend data into business-readable narratives for the analytics dashboard — cohort summaries, weekly trend reports, and anomaly explanations, on schedule and on-demand.
Campaign Optimizer Agent
Given a marketing objective and budget, identifies the optimal cohort, channel mix, offer type, and timing. Campaign configurations are sent to a CRM approval queue — always requiring human sign-off before send.
7. MCP — Model Context Protocol Integration
As with the collections platform, MCP gives the agent layer structured, type-safe access to customer data, the analytics warehouse, and downstream services — without hardcoding tool implementations inside prompts.
Without MCP, every tool an agent needs must be described in natural language and its output parsed manually. MCP provides a typed contract: the LLM declares what it needs, the MCP server fetches it, and the result returns in a structured format the Java layer can validate.
MCP Server Design — E-Commerce Analytics Tools
| MCP Tool Name | Description | Returns |
|---|---|---|
get_customer_predictions | Returns all current predictions for a customer: churn, LTV, next purchase, segment | CustomerPredictions (JSON) |
query_customer_cohort | Returns customers matching prediction criteria (e.g., high churn + high LTV) | Page<CustomerSummary> |
run_analytics_query | Converts a natural language question into validated Snowflake SQL and returns results | QueryResult |
get_demand_forecast | Returns 28-day demand forecast for a product SKU with confidence intervals | DemandForecast |
trigger_retention_campaign | Write-tool: queues a retention campaign for a customer cohort | CampaignQueueResult |
8. React Frontend — Analytics Dashboard
The frontend is a React 18 + TypeScript application built around React Query for server state. The primary surface is a Churn Risk Dashboard giving merchandising and retention teams a live view into at-risk revenue and actionable interventions.
The dashboard never auto-sends a campaign. Every retention action recommended by the Campaign Optimizer Agent is queued for human review — the marketing manager approves the batch before send, with full visibility into the AI's reasoning and predicted ROI.
9. Predictive Model Architecture
Model 1: Customer Churn Predictor (LightGBM)
Model 2: Customer Lifetime Value Predictor (XGBoost)
Model 3: Demand Forecasting (Temporal Fusion Transformer)
10. Key System Flows
Flow 1: Real-Time Personalization on Homepage Load
Customer Identified
JWT decoded → customer_id extracted. Prediction cache checked in Redis (<5ms hit latency).
Predictions Retrieved
Cached churn, LTV tier, next-purchase category, and price sensitivity returned — <10ms on cache hit.
Personalization Applied
Recommendation engine selects homepage modules based on customer embedding and predictions — at-risk customers see loyalty messaging, high-LTV customers see premium products.
Clickstream Logged
Page interactions streamed to Kafka, feeding the next prediction cycle.
Flow 2: Churn Alert → Retention Campaign
Churn Threshold Crossed
Order event triggers rescoring. Probability moves 0.61 → 0.78, exceeding the 0.70 alert threshold. Event published to Kafka.
Campaign Optimizer Agent Invoked
Agent fetches customer profile, LTV tier, churn trigger type, and historical campaign response rates via MCP tools.
Intervention Selected
Loyal + price-driven churn → 10% loyalty reward via email (not a blanket discount — protects margin). LLM generates personalised subject line.
Human Approval & Send
Campaign queued in CRM with full context. Marketing manager approves; campaign sent within 2 hours of the original churn signal, with automatic A/B tracking.
11. Deployment & MLOps
The platform runs on AWS EKS, with each service deployed as an independent containerised microservice, infrastructure defined in Terraform, and changes flowing through GitHub Actions CI/CD with mandatory test gates.
| Capability | Implementation | Scale Target |
|---|---|---|
| Real-time prediction serving | Spring WebFlux + Kubernetes HPA | <50ms p99, 10K req/sec |
| Batch scoring (nightly) | Spring Batch + SageMaker Processing | 15M+ customers in <4 hours |
| Feature computation | Kafka Streams + Flink | Real-time, <30s feature freshness |
| Model retraining (churn) | SageMaker Training Job, weekly | Full retrain in <2 hours |
| Model monitoring | Evidently AI + Grafana | Daily PSI/KS drift checks |
| LLM cost management | Prompt caching, Haiku for batch tasks | <$0.02 per customer insight generated |
| Model registry | MLflow on AWS | Full lineage, comparison, rollback |
12. Outcomes & Metrics
Measured over a representative 6-month production period across the platform's customer base, compared against the prior rules-based baseline: