Delivered remotely for a business based in Stockholm, Sweden. Names withheld by agreement.
Project Overview
Generic "customers also bought" widgets built on overnight SQL co-occurrence batch jobs quickly turn stale in fast-moving retail catalogs. When an anonymous shopper switches from browsing winter boots to comparing waterproof shells, static recommendations keep surfacing irrelevant items—or worse, promote sizes that sold out hours earlier.
For Nordic multi-brand commerce teams in Stockholm, we designed and shipped a real-time AI product recommendation engine anchored on Python, PyTorch, and Redis. The platform balances neural relevance with strict storefront latency budgets and transparent merchandising controls across homepages, product detail pages, cart drawers, and email APIs.
Personalization & Latency Challenges
Replacing legacy rule-based widgets across high-traffic retail storefronts exposed four distinct machine learning and systems bottlenecks:
- Anonymous session blindness: Most storefront sessions begin without authentication, rendering user-ID collaborative filtering useless until checkout.
- Cold-start catalog lag: Seasonal drops introduced hundreds of fresh SKUs weekly that received zero exposure under pure interaction-count models.
- Inventory and margin mismatch: Pure click-through optimization frequently recommended heavily discounted clearance stock or sizes unavailable in the shopper's region.
- Inference tail latency: Heavy neural scorers choked under concurrent traffic spikes unless retrieval and re-ranking were tightly decoupled.
Architectural Strategy
We implemented a two-stage retrieve-and-rank pipeline coupled with a hybrid Redis feature store. During stage one, a PyTorch two-tower model maps rich item attributes and compressed session histories into a shared embedding space, enabling sub-millisecond approximate nearest-neighbor candidate retrieval directly from Redis.
During stage two, a lightweight neural sequence re-ranker evaluates the top few hundred candidates against live contextual features—current basket contents, price sensitivity, device viewport, and real-time stock masks—exported to quantized ONNX Runtime inside Python FastAPI workers. Finally, a deterministic merchandising layer enforces brand diversity, margin floors, and seasonal pin rules before returning JSON payloads.
Core Capabilities
- In-Session Intent Adaptation: Captures view, dwell, variant-hover, and cart events via Kafka into Redis lists so recommendations pivot immediately as browsing intent shifts.
- Multi-Modal Cold-Start Indexing: Combines catalog taxonomy, text descriptions, and visual product embeddings inside the PyTorch item tower so new arrivals rank from day one.
- Placement-Specific Objectives: Tunes distinct ranking heads for PDP "complete the look" compatibility, cart-drawer low-friction add-ons, and homepage discovery feeds.
- Real-Time Stock & Merchandising Guardrails: Applies Redis SKU availability masks and PostgreSQL-configured boost, bury, and category-cap constraints on every request.
- Built-In A/B Experimentation & Telemetry: Splits traffic deterministically across candidate models while logging impression-level positions for unbiased offline counterfactual evaluation.
Technical Architecture
Storefront clickstreams stream through Kafka into Python feature consumers that update sliding session contexts and real-time popularity/stock bitmasks in Redis. When a storefront requests recommendations, FastAPI pulls session features, executes ANN vector retrieval in Redis, scores candidates via ONNX-compiled PyTorch rankers, and applies deterministic merchandising filters.
Flow: Storefront Clickstream → Kafka Event Stream → Python Feature Aggregator → Redis Session State & Vector Index → FastAPI + ONNX PyTorch Re-Ranker → Deterministic Merchandising Filter → Storefront Placement API
Keeping hot vectors, session windows, and stock masks co-located in Redis eliminates multi-hop network fan-outs during online page loads while letting PyTorch training pipelines run independently on GPU nodes.
Technology Stack
| Category | Technology detail |
|---|---|
| Model Training | PyTorch training two-tower retrieval networks and cross-feature session re-rankers |
| Inference Serving | Python FastAPI microservices executing quantized ONNX Runtime scoring graphs |
| Feature & Vector Store | Redis Stack caching live session click sequences, item vectors, and stock masks |
| Event Streaming | Kafka ingesting clickstream views, add-to-cart signals, and checkout conversions |
| Merchandising Store | PostgreSQL persisting boost/bury rules, pinned campaigns, and A/B experiment configs |
| Pipeline Orchestration | Scheduled Python workflows refreshing embeddings, hard negatives, and offline eval metrics |
| Experimentation Engine | Deterministic hash bucketing routing traffic cleanly across champion and challenger models |
| Observability | Prometheus latency histograms and drift monitors tracking CTR, coverage, and diversity |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Full cross-attention transformers over thousands of SKUs breach storefront latency SLAs | Split scoring into PyTorch two-tower ANN retrieval in Redis (~200 candidates) followed by a compact ONNX re-ranker; trades exhaustive pairwise scoring for predictable low-latency responses. |
| Online click models degrade when trained without impression context | Logged exact rendered carousel positions and propensity weights to Kafka so offline PyTorch training corrects position bias rather than over-fitting slot-one clicks. |
| Redis memory consumption climbs quickly when storing high-dimensional embeddings per variant | Stored embeddings at the style/parent product level with FP16/int8 quantization and enforced variant stock filtering via compact Redis bitsets. |
| Merchandisers distrust black-box models that ignore commercial campaigns | Added an explicit PostgreSQL rule-overlay stage with reason codes returned in debug headers, trading pure ML optimality for commercial alignment and auditability. |
Security, Privacy & Model Governance
Personalization pipelines operating across European retail markets require strict privacy hygiene by design. Session tracking relies on rotating pseudonymous session tokens rather than raw PII, ensuring PyTorch training datasets contain behavioral interaction sequences and product attributes without names, emails, or payment identifiers.
Model artifact registries sign ONNX checkpoints prior to deployment, and FastAPI serving pods fall back gracefully to pre-computed category popularity caches in Redis if an experimental challenger model experiences elevated error rates or timeout anomalies.
Performance & Inference Scale
Retail traffic surges dramatically during seasonal campaign launches and flash drops. Exporting PyTorch ranking graphs to ONNX Runtime with INT8 quantization and micro-batching concurrent feature lookups inside FastAPI yields high throughput per CPU core without requiring expensive GPU instances in the online serving path.
Redis vector search executes in memory alongside pre-warmed item feature hashes, ensuring storefronts render personalized carousels cleanly within strict page-load budgets while background Kafka consumers continuously refresh session embeddings.
Operational Outcomes
Moving from static SQL co-occurrence batches to a PyTorch and Redis session-aware ranking architecture transformed both shopper discovery and merchandising workflows:
- Relevant first-visit discovery: Anonymous visitors receive contextually tailored product carousels within a few clicks rather than generic site-wide bestsellers.
- Immediate new-arrival visibility: Multi-modal item embeddings surface fresh seasonal launches automatically without waiting weeks for historical order volume.
- Eliminated dead-end clicks: Live Redis stock bitmasks strip depleted variants prior to rendering, keeping recommendation carousels consistently shoppable.
- Collaborative merchandising control: Category managers tune diversity caps and campaign boosts transparently through audited rules instead of wrestling with opaque model weights.