Skip to content

Founder-led. Limited engagements.Talk to Us →

Part 16 of 30 · 30 Days of Building AI Systems

AI Recommendation System | 30 Days of Building AI Systems, Day 16

Build an AI recommendation system: candidate generation, ranking, business rules, feedback loops, and where LLMs actually help, from explanations to cold start.

By 6 min readAI Systems · Recommendation Systems · Machine Learning · Personalization
AI Recommendation System | 30 Days of Building AI Systems, Day 16

Yesterday we built a text-to-SQL analyst that answers questions people ask. Today we build a system that answers a question users never ask out loud: what should I look at next? The AI Recommendation System learns from user behavior and item data to deliver personalized recommendations, explains why, and improves with feedback. One honest note up front: this is a classic machine learning problem. The models doing the core work are collaborative filtering, content-based, and learned ranking models. LLMs play a supporting role, and we will be specific about where.

AI Recommendation System — CodeITronics infographic Save this sheet. The rest of this note walks through it section by section.

What We Are Building

A recommendation system that:

  • Understands user preferences and learns from behavior
  • Uses multiple data sources: profiles, item catalog, interactions, reviews, context
  • Generates personalized recommendations, in real time where needed
  • Explains why items are recommended
  • Improves over time from feedback

Use cases on the sheet: e-commerce products, streaming movies and shows, music, news and articles, courses, job portals, travel, and social connections.

System Architecture

User and Item Data -> Data Collection and Processing -> Feature Engineering
   -> ML Models -> Ranking and Filtering -> Recommendations API
   -> Feedback and Learning

The request-time flow on the sheet: user request, retrieve user profile and context, candidate generation, score prediction, ranking and filtering, top-N recommendations, display. Behind it, an offline loop runs: data sources feed a feature store, models are trained and retrained, and feedback collection (clicks, views, purchases, ratings, skips) flows back into training.

The most important idea is the two-stage design. You cannot score every item in a large catalog for every request with an expensive model. So:

  1. Candidate generation pulls a few hundred plausible items quickly, from several sources.
  2. Ranking scores those candidates with a richer model and many features.
  3. Filtering and business rules remove out-of-stock items, already-purchased items, and policy violations, and enforce diversity.
def recommend(user_id: str, k: int = 10) -> list[Rec]:
    user = features.get_user(user_id)
    candidates = (
        ann_index.query(user.embedding, top_k=300)        # similar to what they engage with
        + co_occurrence.for_items(user.recent_items, 100) # people who bought X also bought Y
        + trending.for_segment(user.segment, 50)          # safety net for sparse users
    )
    candidates = apply_business_rules(dedupe(candidates), user)
    scored = ranker.score(user, candidates)               # e.g. a gradient-boosted ranker
    return diversify(scored, k=k, max_per_category=3)

This is structural pseudocode, but every production recommender looks roughly like it.

Key Components

ComponentRole
Data ingestion pipelineCollects events and catalog updates, often through Kafka
Feature storeUser, item, interaction, and context features shared by training and serving
Model training and evaluationOffline training, metrics, model versioning
Vector databaseEmbeddings for nearest-neighbor candidate retrieval
Real-time servingLow-latency API returning top-N
CachingRedis for precomputed recommendations
Monitoring and analyticsCTR, conversion, latency, coverage
Feedback loop and retrainingTurns interactions into new training data

Recommendation Approaches

ApproachHow it worksGood atWeak at
Collaborative filteringRecommends items liked by similar usersDiscovering non-obvious itemsNew users and items
Content-basedRecommends items similar to what the user likedNew items with good metadataVariety, can feel repetitive
HybridCombines both, often in the rankerAccuracy and coverageMore complexity
Deep learning modelsNeural networks learn complex patternsLarge scale, rich signalsData and infra cost

The sheet's key insight is right: the best systems combine good data, sensible models, and continuous learning. For most teams, a hybrid with item embeddings for candidates and a gradient-boosted ranker beats a sophisticated deep model with weak data.

Where LLMs Fit

LLMs are not the ranking engine. Asking a chat model to pick products for millions of users is slow, expensive, and hard to evaluate. They are genuinely useful in four places:

  • Cold start. A brand-new item has no interaction history. Embedding its title and description with a text embedding model places it near similar items immediately, so it can enter candidate generation on day one.
  • Catalog enrichment. An LLM can extract structured attributes (topic, level, format) from messy item descriptions, improving content-based features.
  • Explanations. The ranker produces reason codes ("similar to items you viewed", "popular with users like you"). An LLM can turn those into a natural sentence. It should describe the computed reasons, never invent new ones.
  • Conversational recommendations. "Something like that AI course, but shorter and more practical" can be parsed by an LLM into filters and a query embedding, then handed to the normal retrieval and ranking pipeline.

A Minimal Tech Stack

LayerMinimal choice
FrontendNext.js
Backend and servingPython (FastAPI)
ModelsLightFM or implicit for collaborative filtering, a gradient-boosted ranker, PyTorch later
CandidatesPinecone, Weaviate, or pgvector
DataPostgreSQL, Pandas, Spark at scale
EventsKafka or RabbitMQ
Cache and monitoringRedis, Prometheus, Grafana

Many teams start with batch recommendations computed nightly and cached in Redis. Real-time ranking comes later, when you can show it matters.

Example Recommendation

The sheet's example user, John Doe, is interested in tech, AI, and startups. He has viewed a set of items, purchased a couple, and rated several. His recommendations include an introductory AI course, a startup book, an AI tools article, and a video course, each with a match score.

The "Why these recommendations?" panel shows four reasons: based on your interest in AI, similar to items you viewed, highly rated by users like you, and trending in your network. Those reasons map directly to candidate sources. Interest-based items come from content similarity, "users like you" from collaborative filtering, trending from a popularity source. Keeping that mapping explicit is what makes explanations honest.

Production Concerns

Evaluation. Offline, measure Precision@K, Recall@K, and NDCG@K on held-out interactions, plus coverage (share of catalog ever recommended) and diversity. Online, measure CTR, conversion rate, and latency through A/B tests. Offline gains do not always survive online, so A/B tests make the final call.

Cold start and sparsity. Use content features, onboarding preferences, and popular items for new users. Use embeddings and implicit feedback to handle sparse data.

Feedback loops and bias. Recommenders learn from what they showed, which reinforces popular items. Add exploration, diversity constraints, and fairness monitoring.

Scalability and freshness. Approximate nearest neighbor search and caching keep latency low. Stream processing and incremental updates keep recommendations current.

Cost. Precompute where you can. If you use LLM explanations, generate them only for items actually displayed, and cache them.

Key Takeaways

  • Recommendation is a classic ML problem built on candidate generation, ranking, and business rules.
  • Hybrid approaches with good data beat clever models with weak data.
  • LLMs help with cold start, catalog enrichment, explanations, and conversational queries, not core ranking.
  • Explanations must come from real reason codes, not generated justifications.
  • A/B tests decide whether recommendations actually work.

FAQs

Can I just ask an LLM to recommend products?

For a small catalog and low traffic, it can work as a prototype. At scale it is slow, costly, hard to evaluate, and ignores behavioral signals that make recommendations good.

What should I build first?

Popular items by segment plus "similar items" based on embeddings. That baseline is useful immediately and gives you a benchmark for anything fancier.

How often should models retrain?

It depends on how fast your catalog and behavior change. Daily retraining is a common starting point, with real-time features for session behavior.

Up Next

Day 17 builds the AI Anomaly Detection System: statistical and ML methods that learn normal behavior, score deviations in real time, and alert without drowning the team in false positives, with LLMs helping explain alerts rather than detect them. If you want recommendations built into your product, get in touch.

Keep reading

AI Text-to-SQL Data Analyst | 30 Days of Building AI Systems, Day 15

Build an AI text-to-SQL data analyst: schema grounding, SQL generation, validation and read-only guards, safe execution, charts, and plain-language answers.

AI Business Intelligence System | 30 Days of Building AI Systems, Day 14

Build an AI business intelligence system: data pipelines, a warehouse, a governed semantic layer, and an LLM that turns metrics into insights and alerts.

AI Customer Support Agent | 30 Days of Building AI Systems, Day 13

Build an autonomous AI customer support agent: RAG answers, tool actions like order lookups and refunds, a clear escalation policy, and guardrails that hold.

Subscribe to the edition

One useful systems note a week from real Salesforce and automation builds. Unsubscribe in one click.

Letters

Letters to the editor

No letters yet. Questions and counterpoints are welcome.