HomeCase studiesReal-Time Session-Aware AI Product Recommendation Engine Powered...

Case study · Stockholm, Sweden

Real-Time Session-Aware AI Product Recommendation Engine Powered by Python, PyTorch, and Redis

Personalized Retail Merchandising

Static co-occurrence tables and batch nightly collaborative filtering fail when anonymous retail shoppers shift intent within seconds across categories, sizes, and price tiers. Engineered for multi-category e-commerce retailers in Stockholm, we built an AI product recommendation engine powered by Python, PyTorch, and Redis. A two-stage retrieval and ranking pipeline combines multi-modal item embeddings with transformer-based session modeling, while Redis serves sub-millisecond candidate lookups and real-time clickstream features wrapped in configurable merchandising guardrails.

Industry
Personalized Retail Merchandising
Solution
A low-latency two-stage neural recommendation and merchandising API combining PyTorch retrieval/ranking models, Python FastAPI inference services, and Redis real-time session feature stores.
Platforms
Web & API
Stack
Python · PyTorch · Redis · FastAPI · PostgreSQL · ONNX Runtime
Location
Stockholm, Sweden · delivered remotely
Role
Engineering, with the team behind for mobile and QA

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.

01 — Questions

asked about this kind of project

How does the engine recommend relevant items to first-time anonymous visitors without purchase history?

Every page view, filter click, and dwell event appends to an ephemeral session vector stored in Redis with a sliding TTL. Within two or three interactions, the PyTorch session encoder shifts candidate retrieval toward the shopper's active intent without requiring a login.

How do newly launched products appear in recommendations before accumulating click history?

The item tower encodes structured catalog metadata—category taxonomy, brand, fabric, price tier, and product imagery embeddings—rather than relying solely on interaction IDs. New SKUs enter Redis vector indexes immediately upon catalog publish.

How do merchandisers enforce business constraints like hiding out-of-stock sizes or boosting seasonal collections?

Neural scores pass through a deterministic post-ranking filter and re-weighting layer right inside FastAPI. Redis stock bitmasks strip unavailable sizes in real time, while PostgreSQL merchandising rules apply controlled diversity caps and campaign boosts.

Why export PyTorch models to ONNX Runtime for online serving instead of calling raw PyTorch eager mode?

Converting trained ranking models to quantized ONNX graphs eliminates Python GIL overhead across batched candidate scoring and lowers tail inference latency, keeping total carousel API response times comfortably inside strict storefront budgets.

How do you prevent feedback loops where the engine only promotes already popular bestsellers?

Training batches incorporate popularity-corrected negative sampling, and the online re-ranker enforces Maximal Marginal Relevance diversity constraints across brands and categories alongside controlled exploration slots.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.