HomeBlogHow to Build an AI Product...

Engineering Guide · 9 min read · May 17, 2026

How to Build an AI Product Recommendation Engine

Most e-commerce recommendation widgets fail because they suggest out-of-stock variants, leak latency onto product pages, or break completely on new SKUs. A hybrid architecture pairing PostgreSQL pgvector embeddings, co-purchase SQL aggregates, and Redis read-through caching delivers fast, stock-accurate recommendations without operating a separate ML cluster.

Author
Smit Desai
Published
May 17, 2026
Read time
9 min read
Topic
E-Commerce
Services
Custom Web · Mobile Apps · All Services

Generic "You may also like" carousels usually fail for boring engineering reasons, not bad math. Either the widget runs a slow database query that stalls Largest Contentful Paint, recommends an item whose last medium size sold out ten minutes ago, or shows nothing at all on newly launched SKUs because there is no click history yet.

In production stores we have built and audited—across 170+ shipped case studies—the recommendation engines that actually lift average order value are rarely exotic deep-learning pipelines. They are hybrid systems that combine cheap behavioral co-occurrence data, semantic product embeddings, strict inventory filtering, and aggressive caching.

Why Naive Recommendation Approaches Break in Production

Before picking an algorithm, map where each single-strategy engine fails under real storefront conditions:

  1. Pure collaborative filtering ("bought together") collapses on new arrivals and seasonal drops because zero orders means zero edges in the co-purchase graph.
  2. Pure vector similarity suggests five near-identical black t-shirts on a black t-shirt page instead of complementary items like jackets or belts.
  3. Third-party JavaScript widgets inject heavy external scripts, trigger layout shifts that hurt SEO, and often lag behind real-time warehouse stock levels.

Google's own guidance on e-commerce site structure and performance highlights how client-side rendering bloat and broken product availability hurt both crawl efficiency and buyer trust. Keeping recommendation assembly close to your primary catalog database fixes both problems at once.

The Three-Signal Hybrid Architecture

A durable recommendation engine blends three distinct signals into one ranked candidate list per SKU and per active cart:

Signal Type Data Source Solves What Problem Refresh Cadence
Semantic Embeddings Title, specs, material, category text Cold-start SKUs & "similar alternatives" On product create/update
Co-Purchase Graph Completed order_items pairs Cross-sell & complementary basket items Nightly or hourly batch job
Live Business Rules Stock > 0, margin tier, compatibility Prevents dead clicks & margin erosion Read-time filter / Redis invalidation

Notice that none of this requires running PyTorch inference servers on GPU instances. You generate text embeddings via an API call once whenever a merchant edits a product, compute co-purchase counts in SQL, and combine them cleanly.

Storing Catalog Embeddings and Co-Purchase Weights

If your application already runs PostgreSQL, enabling pgvector keeps catalog attributes, stock counts, and vector search in a single ACID store—eliminating sync bugs between your primary database and a separate vector service.

CREATE EXTENSION IF NOT EXISTS vector;

ALTER TABLE products
    ADD COLUMN embedding vector(1536),
    ADD COLUMN embedding_updated_at TIMESTAMP;

CREATE INDEX idx_products_embedding_hnsw
    ON products USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

CREATE TABLE product_affinities (
    source_product_id BIGINT NOT NULL,
    target_product_id BIGINT NOT NULL,
    co_purchase_score DOUBLE PRECISION NOT NULL,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (source_product_id, target_product_id)
);

When you query similar products, you can filter by status = 'active', stock_quantity > 0, and category exclusions in the same SQL statement rather than post-filtering 50 vector hits in application memory and ending up with two valid items.

Blending Behavioral and Semantic Scores Safely

For a product detail page, you want two distinct carousels backed by different queries:

  • Alternatives ("Similar products"): Heavy weight on vector cosine similarity within the same category, filtered to in-stock variants in a comparable price band (0.7x to 1.4x of the current SKU).
  • Complements ("Frequently paired with"): Heavy weight on product_affinities co-purchase lift, excluding the exact same subcategory unless the item is commonly bought in multiples.

Here is how a clean blended SQL ranking query looks when combining precomputed affinities with vector proximity:

WITH target AS (
    SELECT id, category_id, price_cents, embedding
    FROM products
    WHERE id = :product_id
)
SELECT
    p.id,
    p.slug,
    p.title,
    p.price_cents,
    (
        COALESCE(a.co_purchase_score, 0.0) * 0.65 +
        (1.0 - (p.embedding <=> t.embedding)) * 0.35
    ) AS final_score
FROM products p
CROSS JOIN target t
LEFT JOIN product_affinities a
    ON a.source_product_id = t.id AND a.target_product_id = p.id
WHERE p.id <> t.id
  AND p.is_active = TRUE
  AND p.available_stock > 0
  AND p.price_cents BETWEEN t.price_cents * 0.3 AND t.price_cents * 2.5
ORDER BY final_score DESC
LIMIT 8;

Guarding Against Popularity Bias

Without normalization, your top three best-selling cheap accessories (like $5 socks or screen wipes) will dominate every co-purchase query in the store. Compute lift or PMI (Pointwise Mutual Information) during your batch aggregation instead of raw co-occurrence counts:

$$\text{score}(A, B) = \frac{P(A \cap B)}{P(A) \cdot P(B)^\alpha}$$

Setting $\alpha \approx 0.75$ dampens runaway bestsellers so genuinely relevant pairings rise to the top of the list.

Sub-10ms Serving with Redis and Event-Driven Invalidation

Product pages cannot wait 80ms for an HNSW vector scan under peak traffic. Pre-warm candidate lists per SKU into Redis with a 6-hour TTL, and keep a lean stock-status bitmask or hash in Redis so you can drop out-of-stock SKUs in under two milliseconds.

async function getRecommendations(productId: number): Promise<ProductCard[]> {
  const cacheKey = `recs:v2:pdp:${productId}`;
  const cached = await redis.get(cacheKey);

  if (cached) {
    const candidates: ProductCard[] = JSON.parse(cached);
    const stockMap = await getLiveStockFlags(candidates.map((c) => c.id));
    return candidates.filter((item) => stockMap[item.id] === true).slice(0, 4);
  }

  const fresh = await computeHybridRecommendations(productId);
  await redis.set(cacheKey, JSON.stringify(fresh), 'EX', 21600);
  return fresh.slice(0, 4);
}

Over-caching recommendations without stock invalidation is a quiet conversion killer. Whenever an order reserves the last unit of a SKU, publish an event to flip that SKU's Redis stock flag immediately—leaving the expensive ranked list cached while guaranteeing shoppers never click through to an unavailable item. Edge caching strategies described on Cloudflare's engineering blog pair well here: serve static product HTML fast, and hydrate or edge-stitch live recommendation blocks via a lightweight JSON endpoint.

Measuring What Works: Offline Checks vs. Live A/B Splits

Do not optimize for click-through rate alone—a carousel of $3 add-ons draws clicks while lowering net margin or cannibalizing larger bundles. Track three metrics across a 50/50 session split:

  • Attach rate: Share of orders containing a recommended SKU added from the widget.
  • Net contribution per session: Revenue minus COGS and shipping, not raw clicks.
  • Fallback rate: How often stockouts drop valid recommendations below four items.

When fallback triggers, serve in-stock category bestsellers rather than an empty gap. Whether you launched on a lean $399 seven-day website or a custom web application, this tiered design degrades gracefully as your catalog grows.

Build vs. Managed Recommendation Vendors

Criterion Custom Hybrid Engine (pgvector + SQL) Third-Party Recommendation SaaS
Monthly Cost at 1M Views Marginal DB + Redis memory Often $500–$2,500+/month tiered pricing
Inventory Accuracy Real-time transactional consistency Dependent on catalog webhook/feed sync
Custom Margin Rules Native SQL filters on margin, brand, stock Limited to vendor rule-builder UI
Engineering Ownership 1–2 weeks to implement and tune Fast JS snippet, opaque ranking black box
Cold-Start Handling Full control over embedding attributes Varies widely by plan tier

If your team already runs a custom e-commerce stack with clean SKU attributes, building your own hybrid engine protects margins and avoids shipping clickstreams to another SaaS vendor.

How SmitDev Delivers Production Recommendation Systems

At SmitDev, we build recommendation and search pipelines around real catalog constraints—inventory freshness, margin rules, and sub-50ms storefront budgets—drawing on 170+ shipped case studies and server-level reliability work like managing 300+ WordPress sites for a Finnish partner.

Engage me via our $1,999/month dedicated delivery retainer or focused engineering sprints at $55/day for 8–9 hours of daily build work. Reach out via our contact page with your catalog size and stack to map out an implementation plan.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

e-commerce

How much order history do you need before product recommendations work?

You do not need millions of orders to start. Semantic embeddings built from titles, attributes, and categories handle new and low-traffic SKUs immediately, while co-purchase weights kick in as soon as you have a few thousand completed baskets.

Should recommendations be computed live on every product page request?

No. Computing vector distances and inventory joins synchronously on every page load adds unnecessary database pressure. Precompute candidate lists asynchronously, cache them in Redis, and only apply lightweight stock/price checks at read time.

Why do pure AI vector recommendations sometimes suggest weird items?

Text embeddings capture semantic similarity, not commercial compatibility—for example, matching two completely different phone cases instead of pairing a phone with a charger. Blending behavioral co-purchase signals with hard category/compatibility rules fixes this.

Do I need Pinecone or a dedicated ML team to run this in production?

Not for catalogs under a few million SKUs. PostgreSQL with pgvector plus a background worker queue runs inside your existing stack, keeps inventory filters transactional, and avoids syncing data across extra vendors.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

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.