Recommendations at the right moment: from product page to checkout

TL;DR

Difficulty: Advanced

A recommendation helps only when it answers the shopper's question at that moment.

  • Alternatives while they choose, complements once they have chosen, care and next purchases after the order, and nothing while they pay.
  • Start with rules, then count what is bought together and correct for popularity with lift, a minimum count and shrinkage.
  • Let business rules decide what may be shown: stock, margin, price, variety, truthful labels. Never pre add anything to the basket.
  • Measure every row with a holdout and a confidence interval, because "revenue from recommendations" counts purchases that would have happened anyway.

Most shops run one row of bestsellers on every page and trust a dashboard that credits it with a quarter of their revenue. This chapter works out what each placement should really show, how to find what goes with what, which rules keep the row honest, and how an invented homeware shop in Limerick measures what its recommendations are actually worth.

A recommendation answers a question the shopper has right now

Most online shops have a row headed "You may also like", set up once, pointed at the bestsellers and left on every page. Then a dashboard in the recommendation tool reports a large number called "revenue from recommendations", and everyone feels it is working.

This chapter answers a sharper question: what should I recommend, to whom, and when? The short answer is that a recommendation only helps when it answers the question the shopper has at that moment. Someone still choosing a lamp wants to compare lamps. Someone who has just put a lamp in the basket wants the bulb that fits it. Someone who bought the lamp last week wants nothing from you except a delivery date. One row with the same bestsellers serves none of them.

A few terms first, so nobody is left behind.

  • A placement is a spot where a row of recommendations can appear: the home page, a category page, the product page, the basket, the checkout, the order confirmation page, or an email.
  • An anchor is the product (or the basket) the recommendation is based on. On a product page the anchor is the product on screen.
  • A candidate is a product the method suggests. Rules then decide which candidates may actually be shown.
  • A holdout is a randomly chosen group of visitors who do not see the recommendations, so you can compare them with everyone else and see what the row really changes.

This chapter brings together three crafts: knowing the shopper's moment, the maths of what goes with what, and honest measurement. The previous chapter, getting to know your customers with first and zero party data, covered which signals you may collect and on what legal basis. Here I assume you have them. The technical companion piece, building custom AI recommendations in Solidus, goes deep on collaborative filtering with alternating least squares, content based filtering and training in Python. I do not repeat that. This chapter decides what each placement shows, adds the methods that piece leaves out, and spends real time on measurement, where most shops fool themselves.

Example: one row everywhere at Shannonside Home

Shannonside Home is the invented homeware shop that runs through this series. It sells ceramics, kitchen textiles, lamps and small furniture from Limerick at shannonsidehome.example, about 1,400 products. Niamh owns it, Callum is her developer. The baseline numbers of the example: 110,000 sessions a month, a conversion rate of 1.8%, an average order value of €84, a gross margin of 52% on product.

That makes the monthly revenue:

R=S×CR×AOV=110,000×0.018×84=166,320R = S \times CR \times AOV = 110{,}000 \times 0.018 \times 84 = 166{,}320

so €166,320 a month, where RR is revenue per month, SS the number of sessions, CRCR the conversion rate per session and AOVAOV the average order value. The formula is the funnel multiplication from the first chapter of this series, explained in Foundations: ratios and rates.

Today Shannonside has one recommendation row, "You may also like", on the product page, the basket and the order confirmation page. It shows the eight bestsellers of the last 30 days, the same eight for everyone. The tool's dashboard says recommendations "drove €44,000 of revenue" last month, which would be more than a quarter of all revenue. Niamh is pleased. Callum is suspicious. By the end of this chapter, both of them will know what the row is really worth, and what to show where instead.

Six kinds of recommendation answer six different questions

Not all recommendations are the same thing. Each kind answers a different question in the shopper's head, and mixing them up is the most common mistake I see.

KindThe shopper's questionBuilt from
Similar (alternatives)"Is there something like this that suits me better?"Same category, attributes, price band, or items viewed together
Complementary"What do I need to go with this?"Rules you write, or items bought together
Frequently bought together"What do other people add to this?"Co occurrence in orders
Recently viewed"Where was that thing I looked at?"The visitor's own session or account
Trending or bestselling"What is good here?" (a new visitor with no context)Sales counts over a recent window
Personalised"What suits me, given what I have done here?"The customer's history, models such as collaborative filtering

Baymard Institute, which runs large usability studies of online shops, draws the same line between alternatives and supplementary products. Their research found that shoppers need both, in sequence: first they find the right product, then they look for what goes with it. In their 2014 benchmark of 50 major sites, only 42% offered both kinds on the product page as separate, clearly labelled lists. The rest showed one kind or mixed them in one row1.

Example: one mug, six answers

Take one product at Shannonside: the Burren stoneware mug in blue glaze, €18. Here is what each kind of recommendation would show next to it.

  • Similar: four other stoneware mugs between €14 and €25, including the same mug in green and a larger latte mug.
  • Complementary: the matching side plate (€16), the set of four cork coasters (€14), and the oak mug tree (€28).
  • Frequently bought together: whatever the order data says. At Shannonside that turns out to be the coasters and, surprisingly, a linen tea towel (more on that below).
  • Recently viewed: the three products this visitor looked at before, perhaps a teapot and two lamps.
  • Trending: the eight bestsellers of the month, mostly candles and tea towels before Christmas.
  • Personalised: for a returning customer who bought the matching dinner plates in spring, the side plates and bowls from the same range.

Six rows, six different products. Which one belongs on the page depends on where the shopper stands, which is the next section.

The moment decides the kind

The same shopper wants different things at different steps. The table below is the placement plan I start from with any shop. It is a starting point to test, not a law.

PlacementWhere the shopper standsWhat to showHow manyWhat to avoid
Home pageJust arrived, often no contextRecently viewed for returning visitors. Categories and a few bestsellers for new ones4 to 8A wall of rows that pushes navigation off the first screen
Category pageBrowsing a rangeUsually nothing extra: the category list is the recommendation. At most "popular in this category"0 to 4Rows that compete with filters and sorting
Product page, upper partDeciding about this productAlternatives, clearly labelled ("Similar mugs")4 to 8Complements before the shopper has decided
Product page, lower partDecided, or closeComplements ("Goes well with") and frequently bought together3 to 4A mixed row of alternatives and complements
Basket and "added to basket" messageCommitted to some itemsComplements to what is in the basket, lower priced than the anchor2 to 3Alternatives, which reopen the decision
CheckoutPayingNothing, or one small relevant add on the shopper ticks themselves0 to 1Anything pre added, anything that distracts from paying
Order confirmation pageDone, relievedCare items and next purchases for what they bought3 to 4Alternatives to what they just bought
Email after the orderWaiting for delivery, then using itCare tips, complements, later replenishment2 to 4Recommending the item they just bought
Empty search, out of stock productStuckClose alternatives that are in stock4 to 6A dead end

Baymard's research shapes this table. They found that cross sells in the basket can distract shoppers from checking out, which is why complements belong mainly on the product page, with the basket kept for the few that are needed1. In a later study of baskets they found that 52% of the desktop sites they benchmarked showed basket suggestions that were either irrelevant or based only on what other customers bought, and that a single questionable suggestion made users lose faith in all of them2. The same study found that items needed to make the purchase work, such as matching parts and accessories, are received as good service rather than a sales pitch2.

The checkout row is the one I cut most often. The article on cross sell and upsell at checkout goes deeper on the mechanics at that step. Later in this chapter you will see what the law says about it.

Tap or click to open full screen and move around

Example: Niamh's new placement plan

Niamh and Callum walk through Shannonside's pages with the table and make five decisions.

  1. Home page: returning visitors see "Recently viewed" (four items). New visitors see the four main categories as large tiles and one row of "New in" (six items). The bestseller row goes.
  2. Product page: a row "Similar mugs" (six items) sits right under the price and the delivery information, where someone unsure is still deciding. A second row "Goes well with" (four items) sits after the description and the reviews.
  3. Basket: one row "You might need" with at most three complements, each under half the price of the main item in the basket. For a lamp, that is the bulb and a dimmer plug, not another lamp.
  4. Checkout: nothing.
  5. Order confirmation page and the dispatch email: "Looking after your stoneware" with a care guide link, plus the matching pieces from the same range.

The bestsellers have not vanished. They now appear only as a fallback for new visitors. Everywhere else, the anchor product decides what is shown.

Start with rules you can explain

Before any algorithm, write rules. A rule is a sentence a person could say: "Every lamp shows the bulb that fits it." Rules are fast, cost nothing to run, never surprise you, and cover the cases that matter most: the complements a product cannot work without.

Three kinds of rule cover most of a homeware catalogue:

  • Hand picked pairs: for the top sellers, Niamh picks the complements herself. She knows the range better than any model.
  • Category rules: every product in "Table lamps" gets candidates from "Bulbs". Every rug gets the rug underlay in the right size. Every product in "Vases" gets "Dried flowers".
  • Attribute rules: a product with the attribute range: Burren gets the other pieces of the Burren range. A lamp with fitting E27 only gets E27 bulbs.

The weakness of rules is coverage. Nobody writes rules for 1,400 products, and rules never find the pairing nobody thought of. That is what the data methods in the next sections add.

Example: 40 rules cover most of the revenue

Callum exports last year's revenue by product. The top 150 products bring in about two thirds of it. Niamh spends one afternoon writing complements for them: 25 hand picked pairs for the big ranges, 12 category rules and three attribute rules (range, bulb fitting, rug size). 40 rules in total. Every product page in "Table lamps" now shows the right bulb, because the attribute rule matches the fitting. A lamp without a fitting recorded shows no bulb at all, which is the right failure: an empty row is better than a wrong bulb.

Count what is bought together, then correct for popularity

The simplest data method is to count how often two products appear in the same order. That count is called co occurrence. Count it for every pair and you get "frequently bought together" for every product, including the pairings nobody wrote a rule for.

Raw counts have one big flaw: they reward popularity. A product that is in many orders turns up next to everything. The fix is to ask how much more often two products appear together than you would expect by chance. That ratio is called lift.

P(B)=nBN,conf(A→B)=nABnA,lift(A→B)=conf(A→B)P(B)P(B) = \frac{n_B}{N}, \qquad \text{conf}(A \to B) = \frac{n_{AB}}{n_A}, \qquad \text{lift}(A \to B) = \frac{\text{conf}(A \to B)}{P(B)}

where NN is the number of orders in the period, nAn_A the number of orders containing product AA, nBn_B the number containing product BB, nABn_{AB} the number containing both, P(B)P(B) the share of all orders that contain BB, and conf(A→B)\text{conf}(A \to B) the share of orders with AA that also contain BB (called the confidence). A lift of 1 means BB turns up with AA exactly as often as it turns up anywhere. A lift of 2 means twice as often. The background is in Foundations: probability and Foundations: indexing and base rates. The Solidus article uses the difference between the two shares instead of the ratio. Both correct for popularity, and the ratio is easier to compare across products of very different sizes.

Example: coasters beat tea towels for the mug

Shannonside had N=23,760N = 23{,}760 orders in the last 12 months (110,000 sessions times 1.8% times 12). The Burren mug is in nA=1,900n_A = 1{,}900 of them.

  • The cork coasters are in nB=1,100n_B = 1{,}100 orders, and 190 of them also contain the mug.
  • The linen tea towel is in 3,600 orders, and 260 of them also contain the mug.

Counting alone says the tea towel is the better partner: 260 is more than 190. Now the lift.

For the coasters: P(B)=1,100/23,760=0.0463P(B) = 1{,}100 / 23{,}760 = 0.0463. The confidence is 190/1,900=0.100190 / 1{,}900 = 0.100. Lift =0.100/0.0463=2.16= 0.100 / 0.0463 = 2.16.

For the tea towel: P=3,600/23,760=0.1515P = 3{,}600 / 23{,}760 = 0.1515. The confidence is 260/1,900=0.137260 / 1{,}900 = 0.137. Lift =0.137/0.1515=0.90= 0.137 / 0.1515 = 0.90.

The tea towel is simply in everyone's basket: it turns up with the mug slightly less often than in an average order. The coasters turn up with the mug more than twice as often as chance. The coasters are the real partner.

Example data from Shannonside Home. The tea towel appears in more orders with the mug, 260 against 190 for the coasters, but its lift is 0.90, below chance. The coasters have a lift of 2.16, more than twice as often as chance. Tap or click to open full screen and move around

Small counts lie: set a minimum and shrink

Lift has a weakness of its own. With very small counts it explodes. If a rare vase appeared in three orders and one of them also contained an equally rare candle holder, the lift would be in the hundreds, from a single order. A shop with 1,400 products has thousands of such pairs.

Two guards fix that. First, a minimum: ignore pairs that appear together in fewer than five orders. Second, shrinkage: pretend every product has kk extra orders that behave exactly like the average order, which pulls small samples towards a lift of 1 and leaves large samples almost untouched.

confk(A→B)=nAB+k P(B)nA+k,liftk(A→B)=confk(A→B)P(B)\text{conf}_k(A \to B) = \frac{n_{AB} + k \, P(B)}{n_A + k}, \qquad \text{lift}_k(A \to B) = \frac{\text{conf}_k(A \to B)}{P(B)}

where kk is the number of imaginary average orders (20 is a reasonable start for a shop of this size), and the other symbols are as before. The idea is the same as an average that needs enough data before you trust it. See Foundations: sampling.

Example: the lamp base and its shade

The ceramic lamp base "Corrib" is in 40 orders. Its matching linen shade is in 60. Both together: 6 orders. That passes the minimum of five.

P(B)=60/23,760=0.00253P(B) = 60 / 23{,}760 = 0.00253. Raw confidence: 6/40=0.156 / 40 = 0.15. Raw lift: 0.15/0.00253=59.40.15 / 0.00253 = 59.4.

With k=20k = 20: confk=(6+20×0.00253)/(40+20)=6.05/60=0.101\text{conf}_k = (6 + 20 \times 0.00253) / (40 + 20) = 6.05 / 60 = 0.101. Shrunk lift: 0.101/0.00253=39.90.101 / 0.00253 = 39.9.

Still very high, which is right: the shade genuinely belongs with the base. For the mug and the coasters the shrunk lift is 2.15 instead of 2.16, almost unchanged, because 1,900 orders is plenty. Shrinkage hits only where the evidence is thin, which is exactly what you want.

Item to item collaborative filtering compares customers, not just orders

Counting within one order misses purchases spread over time. Someone buys a sofa in March and the cushions in April. Those never share an order, so co occurrence never sees them.

The method Amazon described in 2003, item to item collaborative filtering, works at the level of customers instead. For every product it builds a list of the customers who bought it. Two products are similar when the same customers bought both. Greg Linden, Brent Smith and Jeremy York explain that the expensive part, building a table of similar items for every product, runs offline, and that the online part, looking up the similar items for what a customer bought, depends only on how many products that customer bought, not on the size of the catalogue or the customer base3. That is why it scales and why it is still the sensible first step for most shops. They name the cosine measure as a common way to compute the similarity3.

cos⁡(A,B)=cABcA cB\cos(A, B) = \frac{c_{AB}}{\sqrt{c_A \, c_B}}

where cAc_A is the number of customers who bought product AA, cBc_B the number who bought BB, and cABc_{AB} the number who bought both, at any time in the window. This is the cosine of the angle between two lists of zeros and ones, one entry per customer. With only zeros and ones it simplifies to this count formula. Like lift, it punishes popularity: the bigger cBc_B, the bigger the denominator. The idea of measuring how two things move together is in Foundations: correlation.

Example: the sofa and the cushions

Shannonside's two seater "Clare" sofa was bought by 180 customers in the year. The wool cushion cover set was bought by 900 customers. 54 customers bought both, but only 9 of them in the same order, because most customers waited for the sofa to arrive before choosing cushions.

At order level the pair barely registers: 9 orders together is a weak signal. At customer level:

cos⁡=54180×900=54402.5=0.134\cos = \frac{54}{\sqrt{180 \times 900}} = \frac{54}{402.5} = 0.134

For comparison, the mug and the coasters at order level give 190/1,900×1,100=190/1,445.7=0.131190 / \sqrt{1{,}900 \times 1{,}100} = 190 / 1{,}445.7 = 0.131, an equally strong pairing. Callum adds the customer level table for products with long consideration (furniture and lamps) and keeps the order level lift for small items. The customer level version needs customers you can recognise across visits, which means signed in customers or orders matched by email address, within the limits set in the previous chapter.

Embeddings find neighbours the counts never saw

Counting methods only know pairs that have actually happened. A product that has never been bought with the mug can never be recommended with it, even if it is obviously similar. Embeddings fix that. An embedding is a short list of numbers for every product, learned from data, so that products used in similar contexts get similar numbers. Two products can then be close even if they never shared an order, because they shared neighbours.

Oren Barkan and Noam Koenigstein showed in 2016 that the word2vec method from language processing works for products: treat each order or browsing session as a "sentence" and each product as a "word", and the model learns product vectors in which items that appear in similar baskets sit close together. They call it item2vec and report it competitive with a classic matrix factorisation baseline4. The Solidus article covers the other common route, matrix factorisation with alternating least squares, in full code.

Similarity between two embeddings is again the cosine, now over real numbers:

cos⁡(a,b)=∑j=1dajbj∑j=1daj2 ∑j=1dbj2\cos(\mathbf{a}, \mathbf{b}) = \frac{\sum_{j=1}^{d} a_j b_j}{\sqrt{\sum_{j=1}^{d} a_j^2} \, \sqrt{\sum_{j=1}^{d} b_j^2}}

where a\mathbf{a} and b\mathbf{b} are the vectors of two products, aja_j and bjb_j their jjth numbers, and dd the length of the vectors (typically 32 to 128). The vector and matrix background is in Foundations: matrices.

Example: a new green mug finds its neighbours

Imagine vectors with only three numbers, to keep the arithmetic visible. After training on browsing sessions, the blue Burren mug has a=(0.8,0.1,0.5)\mathbf{a} = (0.8, 0.1, 0.5). The green Burren mug, added in September and bought only 14 times so far, has b=(0.7,0.2,0.6)\mathbf{b} = (0.7, 0.2, 0.6), because people viewed it in the same sessions as the blue one. An oak chopping board has c=(0.1,0.9,0.2)\mathbf{c} = (0.1, 0.9, 0.2).

Blue mug and green mug: the top is 0.8×0.7+0.1×0.2+0.5×0.6=0.56+0.02+0.30=0.880.8 \times 0.7 + 0.1 \times 0.2 + 0.5 \times 0.6 = 0.56 + 0.02 + 0.30 = 0.88. The lengths are 0.64+0.01+0.25=0.949\sqrt{0.64 + 0.01 + 0.25} = 0.949 and 0.49+0.04+0.36=0.943\sqrt{0.49 + 0.04 + 0.36} = 0.943. Cosine =0.88/(0.949×0.943)=0.983= 0.88 / (0.949 \times 0.943) = 0.983.

Blue mug and chopping board: top =0.08+0.09+0.10=0.27= 0.08 + 0.09 + 0.10 = 0.27. Length of c\mathbf{c}: 0.01+0.81+0.04=0.927\sqrt{0.01 + 0.81 + 0.04} = 0.927. Cosine =0.27/(0.949×0.927)=0.307= 0.27 / (0.949 \times 0.927) = 0.307.

The green mug is a near neighbour although it has never been bought with the blue one. That makes embeddings useful for "similar" rows. My honest verdict for a shop of Shannonside's size: rules plus lift plus customer level cosine cover most of the value. Embeddings earn their keep once the catalogue changes fast or the shop has many products with few sales each. Browsing sessions as training data also need consent for the tracking behind them.

Cold start: new products, new visitors, a new shop

Every data method needs history. Cold start is the name for the cases where there is none. There are three, and each has its own answer.

  • A new product has no orders. Give it candidates from rules (category and attribute) and from content: products with the same range, material and price band. Reserve one slot in a row for new items for their first weeks, so they can collect the data that the counting methods need.
  • A new visitor has no history. Use context: the page they landed on, the campaign they came from, the category they are in. Fall back to "popular in this category" rather than sitewide bestsellers, because the category already says something about them.
  • A new shop has neither. Run on rules alone for the first months. With fewer than a few thousand orders, co occurrence is mostly noise.

Example: 30 new lamps in October

Shannonside adds 30 new lamps in October, ahead of the darker months. None has an order. Callum's setup does three things. The "Similar lamps" row picks candidates by category, fitting and a price within 40% of the anchor, so new lamps appear next to old ones from day one. One of the six slots in that row is reserved for a lamp added in the last 60 days. And the bulb rule from Niamh's attribute rules gives every new lamp the right bulb immediately. By December, the new lamps have enough orders for the lift table to take over, and the reserved slot moves on to January's arrivals.

Business rules decide what may be shown

The method produces candidates. Business rules decide which of them may appear. This is where a recommendation system turns from a maths exercise into part of running a shop, and most of the quality a shopper notices comes from here.

The filters I apply, roughly in this order:

  1. Available and in stock. Never recommend something the shopper cannot buy. Solidus can answer this per variant, including across stock locations5.
  2. Not already in the basket, and not the anchor itself.
  3. Not just bought. A customer who bought the sofa last month does not need the sofa again. Consumables (candles, bulbs) are the exception and come back at their natural replacement time.
  4. Deliverable. If furniture only ships within Ireland, do not show it to a shopper whose basket goes to France.
  5. A margin floor. A complement that loses money on every sale is not a recommendation, it is a leak. Contribution margin per order explains which costs belong in that floor.
  6. A sensible price relation. In the basket, complements cost less than the main item. On the product page, alternatives sit in a similar price band.
  7. Variety. At most two items from the same category in one row, so the row teaches the shopper what else the shop sells. Baymard recommends drawing suggestions from several categories for exactly that reason1.
  8. Labels that tell the truth. "Goes well with" for complements, "Similar" for alternatives, "Customers also bought" only when it is literally that. Baymard warns that shoppers assume a recommended accessory is compatible, so a label like "Recommended for you" on an item that does not fit costs trust1.

Example: from 10 candidates to four

The lift table offers 10 candidates for the Corrib lamp base in a basket that ships to Limerick. Callum's filters go through them:

CandidatePriceKept?Reason
Linen shade, Corrib€52YesComplement, in stock
E27 bulb, warm white€7YesFits the lamp, in stock
Smart plug dimmer€21YesComplement, in stock
Linen shade, Corrib, oatmeal€52NoThe same shade in another colour: one colour per product in a row
Ceramic lamp base, Inagh€92NoAn alternative: reopens the decision in the basket
Oak side table€160NoCosts more than the anchor (€98)
Gift wrapping€4.50NoNever a recommendation. An option the shopper chooses
Brass picture light€72NoOut of stock
Candle set€14YesDifferent category, decent margin
Discount bulbs, 2 pack€3.50NoBelow the margin floor after packing and postage

Four remain, in three categories. The row now reads "You might need: the matching shade, a bulb, a dimmer plug, candles". Each one makes sense to a person who just chose a lamp.

Build it: co occurrence in SQL and one Rails service

Here is a compact version of what Callum builds on Ruby on Rails and Solidus. It has three parts: a nightly SQL job that writes the pairs table, a recurring schedule, and one service object that turns candidates into a row for a given placement. Solidus keeps orders in spree_orders, the lines of each order in spree_line_items, and each line points to a spree_variants row, which belongs to a product.

First, the table that holds the pairs, as a Rails migration.

# db/migrate/20270301090000_create_product_pairs.rb
class CreateProductPairs < ActiveRecord::Migration[8.0]
  def change
    create_table :product_pairs do |t|
      t.references :product, null: false, foreign_key: { to_table: :spree_products }
      t.references :related, null: false, foreign_key: { to_table: :spree_products }
      t.integer :orders_together, null: false
      t.decimal :lift, precision: 10, scale: 4, null: false
      t.decimal :cosine, precision: 10, scale: 6, null: false
      t.timestamps
    end
    add_index :product_pairs, [:product_id, :lift]
  end
end

Next, the query. It works in PostgreSQL, takes the completed orders of the last 12 months, keeps pairs seen in at least five orders and computes the shrunk lift with k=20k = 20 and the cosine, exactly as in the formulas above.

-- Products bought together in the last 365 days, with shrunk lift (k = 20)
WITH order_products AS (
  SELECT DISTINCT o.id AS order_id, v.product_id
  FROM spree_orders o
  JOIN spree_line_items li ON li.order_id = o.id
  JOIN spree_variants v ON v.id = li.variant_id
  WHERE o.completed_at >= now() - interval '365 days'
    AND o.state <> 'canceled'
),
total AS (
  SELECT count(DISTINCT order_id)::numeric AS n FROM order_products
),
counts AS (
  SELECT product_id, count(*) AS n FROM order_products GROUP BY product_id
),
pairs AS (
  SELECT a.product_id, b.product_id AS related_id, count(*) AS n_ab
  FROM order_products a
  JOIN order_products b
    ON b.order_id = a.order_id AND b.product_id <> a.product_id
  GROUP BY a.product_id, b.product_id
  HAVING count(*) >= 5
)
SELECT p.product_id,
       p.related_id,
       p.n_ab AS orders_together,
       ((p.n_ab + 20 * cb.n / t.n) / (ca.n + 20)) / (cb.n / t.n) AS lift,
       p.n_ab / sqrt(ca.n * cb.n) AS cosine
FROM pairs p
JOIN counts ca ON ca.product_id = p.product_id
JOIN counts cb ON cb.product_id = p.related_id
CROSS JOIN total t;

In plain words: order_products lists each product once per order, counts gives nAn_A for every product, pairs gives nABn_{AB} for every pair seen at least five times, and the final select turns them into lift and cosine. Cancelled orders are left out, because they are not purchases.

A job runs the query every night and swaps the table contents in one transaction, so the shop never sees a half filled table.

# app/jobs/product_pairs_job.rb
class ProductPairsJob < ApplicationJob
  queue_as :default

  # The query above, saved without its final semicolon
  QUERY = Rails.root.join("db/queries/product_pairs.sql").read.strip.delete_suffix(";")

  def perform
    ProductPair.transaction do
      ProductPair.delete_all
      ActiveRecord::Base.connection.execute(<<~SQL)
        INSERT INTO product_pairs
          (product_id, related_id, orders_together, lift, cosine, created_at, updated_at)
        SELECT product_id, related_id, orders_together, lift, cosine, now(), now()
        FROM (#{QUERY}) AS computed
      SQL
    end
  end
end

# app/models/product_pair.rb
class ProductPair < ApplicationRecord
  belongs_to :product, class_name: "Spree::Product"
  belongs_to :related, class_name: "Spree::Product"
end

Rails 8 ships with Solid Queue, which reads recurring tasks from config/recurring.yml, as its README describes6.

# config/recurring.yml
production:
  refresh_product_pairs:
    class: ProductPairsJob
    schedule: every day at 3am

Finally, the service that decides what a placement shows. Each placement names its kind and its limit. Candidates come from the pairs table (complements) or from the anchor's category and price band (alternatives). Then the business rules filter, and a variety cap finishes the row.

# app/services/recommendations/picker.rb
module Recommendations
  class Picker
    PLACEMENTS = {
      product_similar:    { kind: :similar,       limit: 6 },
      product_together:   { kind: :complementary, limit: 4 },
      basket:             { kind: :complementary, limit: 3, max_price_share: 0.5 },
      order_confirmation: { kind: :complementary, limit: 4 }
    }.freeze

    MARGIN_FLOOR = 0.30
    PER_CATEGORY = 2

    def initialize(placement:, anchors:, user: nil)
      @config  = PLACEMENTS.fetch(placement)
      @anchors = Array(anchors)
      @user    = user
    end

    def call
      candidates
        .select { |product| allowed?(product) }
        .then { |list| with_variety(list) }
        .first(@config[:limit])
    end

    private

    def candidates
      @config[:kind] == :similar ? similar : complementary
    end

    # Alternatives: same category, price within 40 % of the anchor
    def similar
      anchor = @anchors.first
      band = (anchor.price * 0.6)..(anchor.price * 1.4)
      Spree::Product.available.in_taxons(*anchor.taxons)
        .where.not(id: anchor.id).includes(:master, :taxons).limit(40)
        .select { |product| band.cover?(product.price) }
    end

    # Complements: the strongest pairs for every anchor, best lift first
    def complementary
      ids = ProductPair.where(product_id: @anchors.map(&:id))
        .order(lift: :desc).limit(40).pluck(:related_id).uniq
      found = Spree::Product.available.where(id: ids)
        .includes(:master, :taxons).index_by(&:id)
      ids.filter_map { |id| found[id] }
    end

    def allowed?(product)
      return false if excluded_ids.include?(product.id)
      return false unless product.total_on_hand.positive?
      return false unless margin_ok?(product)
      return false unless price_ok?(product)
      true
    end

    def margin_ok?(product)
      cost = product.cost_price
      return true if cost.nil? || product.price.to_d.zero?
      (product.price - cost) / product.price >= MARGIN_FLOOR
    end

    def price_ok?(product)
      share = @config[:max_price_share]
      return true unless share
      product.price <= @anchors.map(&:price).max * share
    end

    # The anchors themselves, plus anything this customer bought in 180 days
    def excluded_ids
      @excluded_ids ||= @anchors.map(&:id) + recently_bought_ids
    end

    def recently_bought_ids
      return [] unless @user
      Spree::Variant.joins(line_items: :order)
        .where(spree_orders: { user_id: @user.id, completed_at: 180.days.ago.. })
        .distinct.pluck(:product_id)
    end

    def with_variety(list)
      seen = Hash.new(0)
      list.select do |product|
        key = product.taxons.first&.id
        (seen[key] += 1) <= PER_CATEGORY
      end
    end
  end
end

Two details are worth a sentence each. total_on_hand comes from Solidus and returns infinity for products that do not track stock, so made to order items pass the stock check5. Deliverability is left out here because it depends on how your shipping categories are set up. In Solidus it belongs in the same allowed? method. The full event tracking, training and caching setup is in the Solidus recommendations article, including how to subscribe to the order_finalized event on Spree::Bus7.

Example: what the picker returns for the mug

On the Burren mug's product page, the controller calls Recommendations::Picker.new(placement: :product_together, anchors: [mug], user: current_spree_user).call. The pairs table offers 12 candidates, sorted by lift: the side plate, the coasters, the mug tree, the teapot, two bowls, three more mugs from the range and three candles. The tea towel is not among them, because with a lift of 0.90 it ranks far below the real partners.

The customer viewing the page bought two of the other mugs in October, so the picker drops them as recently bought. The variety cap then allows two items per category: the side plate and the first bowl fill the tableware slots, so the second bowl and the third mug go. What remains, in order of lift, is the side plate, the coasters, the mug tree and the teapot. The limit is four, so that is the row.

In the basket the same mug gives a different answer. The basket placement caps complements at half the anchor's price, so at €9. The coasters (€14), the side plate (€16) and the mug tree (€28) are all over the cap. Only the single cork coaster at €4, a separate product in the pairs table, passes. The basket row shows one item instead of three. That is the dynamic number of suggestions Baymard recommends: fewer, better items rather than a fixed count filled with weak ones2.

Measure with a holdout, not with "revenue from recommendations"

Now the question Callum was suspicious about. What is the row actually worth?

Recommendation tools usually report "revenue from recommendations": the revenue of every order that contains a product someone clicked in a recommendation row. That number answers the wrong question. It counts every purchase that passed through the row, including all the ones that would have happened anyway because the shopper was going to buy the coasters regardless and the row was simply the nearest link.

How big is "anyway"? Amit Sharma, Jake Hofman and Duncan Watts studied browsing logs of 2.1 million Amazon users over nine months and estimated that at least 75% of the click throughs on recommendations would likely have happened without the recommendations8. Anuj Kumar and Kartik Hosanagar ran a randomised field experiment on a fashion retailer's site, with and without recommendation links, and found that the links raised the combined sales of a product and its recommended alternatives by about 11% on average, with the gains unevenly spread across products9. Real, but far smaller than attributed figures. Dietmar Jannach and Michael Jugovac reviewed published field tests of recommender systems and concluded that their business value is much less clear than their value to shoppers, and that the measures used vary widely between studies10.

The honest measurement is a holdout: split visitors at random, show the row to one group and not to the other, and compare what each group spends. The difference is what the row adds, the incremental revenue. Attribution for online shops explains the same idea for advertising, and experiments inside your own shop covers feature flags and assignment in depth.

Three design choices matter:

  • Randomise by visitor, not by page view. Hash a stable visitor identifier (for signed in customers, the customer id. Otherwise a first party identifier set with consent), so the same person always sees the same version.
  • Measure the business outcome per visitor, not clicks on the row. Revenue per visitor, or better gross profit per visitor, over the whole visit and the following days.
  • Test each placement with its own random split. Hash the visitor id together with the placement name, so the product page test and the basket test split visitors independently. Then four placements can be tested at once, and each comparison stays clean.

The comparison is a difference between two averages, with a confidence interval around it:

Δ=xˉT−xˉC,SE=sT2nT+sC2nC,95% CI=Δ±1.96×SE\Delta = \bar{x}_T - \bar{x}_C, \qquad SE = \sqrt{\frac{s_T^2}{n_T} + \frac{s_C^2}{n_C}}, \qquad 95\%\ \text{CI} = \Delta \pm 1.96 \times SE

where xˉT\bar{x}_T and xˉC\bar{x}_C are the average revenue per visitor with the row (treatment) and without it (control), sTs_T and sCs_C the standard deviations of revenue per visitor in each group, nTn_T and nCn_C the number of visitors in each group, SESE the standard error of the difference, and 1.96 the factor for 95% confidence. If the interval does not include zero, the row has a measurable effect. The method is explained in Foundations: confidence intervals and Foundations: hypothesis tests.

Example: 12 weeks of holdouts at Shannonside

Shannonside has about 80,000 different visitors a month, so revenue per visitor is 166,320/80,000=2.08166{,}320 / 80{,}000 = 2.08 euro, €2.08. Revenue per visitor is very uneven: most visitors spend nothing, a few spend hundreds. In Shannonside's data the standard deviation is €18.40 per visitor.

Callum runs four tests at once for 12 weeks, each with its own 50/50 split: the product page "Goes well with" row, the basket row, the home page "Recently viewed" row and a checkout add on (a gift card holder for €2). Over the 12 weeks 240,000 different visitors arrive, so each group in each test has n=120,000n = 120{,}000.

The standard error is the same for all four, because the groups are the same size and the spread is similar:

SE=18.402120,000+18.402120,000=0.00282+0.00282=0.0751SE = \sqrt{\frac{18.40^2}{120{,}000} + \frac{18.40^2}{120{,}000}} = \sqrt{0.00282 + 0.00282} = 0.0751

So the 95% interval is the measured difference plus or minus 1.96×0.0751=0.1471.96 \times 0.0751 = 0.147 euro, about 15 cent.

PlacementDifference per visitor95% intervalVerdict
Product page "Goes well with"€0.18€0.03 to €0.33Adds revenue, keep
Basket "You might need"€0.06minus €0.09 to €0.21Unclear, keep testing
Home page "Recently viewed"€0.01minus €0.14 to €0.16No measurable effect
Checkout add onminus €0.03minus €0.18 to €0.12No measurable effect, remove
Example data from Shannonside Home's 12 week holdout tests, in cent per visitor. Product page row: estimate 18, interval 3 to 33. Basket row: estimate 6, interval minus 9 to 21. Home page row: estimate 1, interval minus 14 to 16. Checkout add on: estimate minus 3, interval minus 18 to 12. Only the product page row's interval stays above zero. Tap or click to open full screen and move around

Now the comparison Callum wanted. The product page row adds €0.18 per visitor, so about 0.18×80,000=14,4000.18 \times 80{,}000 = 14{,}400 euro a month, with an interval from about €2,600 to €26,200. At a 52% product margin that is roughly €7,490 of gross profit a month before any extra costs. Adding all four point estimates gives (0.18+0.06+0.01−0.03)×80,000=17,600(0.18 + 0.06 + 0.01 - 0.03) \times 80{,}000 = 17{,}600 euro, and three of those four estimates are not distinguishable from zero. The tool claimed €44,000.

Example data from Shannonside Home, per month. The recommendation tool attributes 44,000 euro to recommendations. The holdout measures 14,400 euro added by the product page row and 17,600 euro as the sum of all four placements' estimates. Tap or click to open full screen and move around

The row is worth having. It is worth about a third of what the dashboard said, and the checkout add on is worth nothing. Niamh removes the checkout add on, keeps the product page row, and leaves the basket test running.

How big an effect your traffic can see

Before a test starts, work out the smallest effect it could reliably find. That is the minimum detectable effect. If it is larger than any effect you could plausibly expect, the test cannot answer your question, however long you stare at it.

MDE=(z1−α/2+z1−β)×σ×2nMDE = (z_{1-\alpha/2} + z_{1-\beta}) \times \sigma \times \sqrt{\frac{2}{n}}

where MDEMDE is the minimum detectable effect per visitor, z1−α/2=1.96z_{1-\alpha/2} = 1.96 for 95% confidence, z1−β=0.84z_{1-\beta} = 0.84 for 80% power (the chance of finding an effect that is really there), σ\sigma the standard deviation of revenue per visitor, and nn the number of visitors in each group. The full reasoning is in Foundations: sample size.

Example: why the basket test is still running

For Shannonside's 12 week tests:

MDE=(1.96+0.84)×18.40×2120,000=2.80×18.40×0.00408=0.21MDE = (1.96 + 0.84) \times 18.40 \times \sqrt{\frac{2}{120{,}000}} = 2.80 \times 18.40 \times 0.00408 = 0.21

where σ=18.40\sigma = 18.40 is the standard deviation in euro and n=120,000n = 120{,}000 the visitors per group, as above, so the minimum detectable effect is €0.21 per visitor (Foundations: sample size).

That is about 10% of the €2.08 revenue per visitor. So the tests could reliably detect only effects of around 10% of all revenue. The product page row's €0.18 is below that. It showed up anyway, which happens about 67% of the time for an effect of that size with this many visitors. The basket row's €0.06 (about 3%) would need roughly 12 times as many visitors per group to detect reliably, because the sample size grows with the square of how much smaller the effect is.

There are three honest ways out. Run the test longer. Narrow the population to the visitors who actually reach the placement (only basket visitors for the basket test), which removes a lot of zeros. Or reduce the noise with data you already have: Alex Deng, Ya Xu, Ron Kohavi and Toby Walker described a method called CUPED that adjusts each visitor's result using their behaviour before the experiment, and reported variance reductions of about 50% at Microsoft11. Halving the variance cuts the detectable effect by a factor of 2\sqrt{2}, from €0.21 to about €0.15 for Shannonside, for returning visitors who have a history. What you should not do is stop the test the day the interval first misses zero, or declare victory on the click through rate of the row.

The checkout and the law: recommend, never pre add

Recommending a product is ordinary selling. Putting it into the basket for the shopper is something else, and the law in all four of my markets draws the line at the same place: any payment on top of the main purchase needs the shopper's express consent, and a default the shopper has to undo does not count. This is general information, not legal advice.

  • Ireland: section 123 of the Consumer Rights Act 2022 says that before a consumer is bound by a contract, the trader must seek the consumer's express consent to any payment on top of the price agreed for the main purchase. Consent inferred from a default option that the consumer has to reject to avoid the extra payment is not express consent. A trader who takes such a payment must refund it, and in a dispute it is for the trader to show that the consent was express12. The Competition and Consumer Protection Commission (CCPC) enforces consumer law in Ireland.

That is close to the "bought together, already ticked" box some widgets offer. The safe pattern is a row of suggestions with an "Add" button per item, nothing selected by default, and a basket that shows clearly what was added and at what price. Recommendations based on browsing behaviour also need consent for the tracking behind them. The previous chapter and personalisation without surveillance cover where that line sits. And some inferences should not be made at all, consent or not: the Target pregnancy story is the classic warning.

Example: the bundle box Niamh almost switched on

The recommendation tool Niamh trialled offers a "Complete the set" box on the product page: the mug, the side plate and the coasters, all three ticked, "Add all three to basket, €48". The shopper can untick the plate and coasters. Under section 123, a shopper who leaves the box as it is has not given express consent to the extra €30, because that consent would be inferred from a default option they had to reject12. Callum rebuilds it: the mug is in the basket because the shopper chose it, and the plate and coasters each have their own "Add" button, unticked. The total updates only when the shopper clicks.

Rented platforms and what they give you

On a rented platform you usually start with something that works. Shopify, for example, offers a Product Recommendations API in its storefront with two intents, related and complementary, returning up to 10 products, and points merchants to its Search & Discovery app to customise product recommendations13. For a small shop that wants a sensible "related" row and a hand curated "goes well with" row without any operations, that is a reasonable answer, and I would say so to anyone in that position.

What changes on your own system, such as Ruby on Rails with Solidus, is ownership and reach. The rules can use any data the shop has (cost prices for a margin floor, stock by location, delivery restrictions, returns), because every process runs in your own code. The pairs table and the models are yours. And the holdout is part of the shop rather than a report someone else computes. Where Rails and Solidus shine and where a rented platform is enough weighs that choice properly.

Example: the same plan on two platforms

On a rented platform, Shannonside's "Similar mugs" row could use the related intent, and the "Goes well with" row could be curated by hand for the top 150 products, much like Niamh's 40 rules. Before relying on it, Niamh would check two things: can she filter by her own cost prices and delivery restrictions, and can she run a holdout on the row? If both work with the tools she has, the rented platform is grand for now. If not, those two gaps are the list of what she would build on her own system.

What to build first

The order matters, because each step pays for the next.

  1. Fix the placements. Separate alternatives from complements on the product page, cut the checkout row, and label every row truthfully. No algorithm needed.
  2. Write the rules for the top sellers and the must have complements (bulbs, underlays, matching pieces).
  3. Add the lift table for "frequently bought together", with a minimum count and shrinkage, refreshed nightly.
  4. Apply the business rules: stock, margin floor, not just bought, price relation, variety.
  5. Set up the holdout before you change anything else, and work out the minimum detectable effect first.
  6. Add customer level cosine for long consideration products, and embeddings only when the catalogue or the traffic justifies them.
  7. Carry the complements into email after the order. After the purchase covers timing, and email and SMS for online shops the consent rules for sending them.

Example: Shannonside's three months

Month one: Niamh rewrites the placements and the 40 rules. Callum builds the pairs table and the picker. Month two: the holdouts start, with the minimum detectable effect written down in advance. Month three: the checkout add on goes, the product page row stays, the basket test continues, and the order confirmation page gets its care guide and matching pieces, tested the same way. The holdout number replaces the dashboard number in every meeting.

Conclusion

A recommendation earns its place when it answers the question the shopper has at that moment: alternatives while they choose, complements once they have chosen, care and next purchases after they have paid, and nothing while they pay. Start with rules you can explain, then count what is bought together and correct for popularity with lift, guarded by a minimum count and shrinkage. Compare customers rather than orders for purchases spread over time, and add embeddings only when the catalogue needs them. Let business rules decide what may be shown: stock, margin, price, variety and truthful labels. Never pre add anything to the basket. And measure every row with a holdout and a confidence interval, sized in advance, because "revenue from recommendations" counts the purchases that would have happened anyway.

If your recommendation row shows the same bestsellers everywhere and nobody knows what it earns, book the free workshop: I map what each placement should show and how to measure it, and the first two weeks of work are on me.

Sources

  1. 1.

    Jamie Holst, Product Page Usability: Recommend Both Alternative and Supplementary Products (Only 42% Get it Right), Baymard Institute, 25 November 2014, https://baymard.com/blog/product-page-suggestions

  2. 2.

    Sally Collins, 6 Ways to Improve the Relevance of Cross Sells in the Cart (52% of Desktop Sites Don't Do Enough), Baymard Institute, 12 January 2021, https://baymard.com/blog/product-recommendations-cart

  3. 3.

    Greg Linden, Brent Smith and Jeremy York, Amazon.com recommendations: item to item collaborative filtering, IEEE Internet Computing, volume 7, number 1, pages 76 to 80, January and February 2003, https://www.cs.umd.edu/~samir/498/Amazon-Recommendations.pdf

  4. 4.

    Oren Barkan and Noam Koenigstein, Item2Vec: neural item embedding for collaborative filtering, arXiv 1603.04259, 2016, https://arxiv.org/abs/1603.04259

  5. 5.

    Solidus, Spree::Variant source code (can_supply? and total_on_hand) and Spree::Product#total_on_hand, GitHub, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/variant.rb

  6. 6.

    Rails, Solid Queue README, recurring tasks, GitHub, https://github.com/rails/solid_queue/blob/main/README.md

  7. 7.

    Solidus, Subscribing to events, Solidus Guides, https://guides.solidus.io/customization/subscribing-to-events

  8. 8.

    Amit Sharma, Jake M. Hofman and Duncan J. Watts, Estimating the causal impact of recommendation systems from observational data, ACM Conference on Economics and Computation, 2015, https://arxiv.org/abs/1510.05569

  9. 9.

    Anuj Kumar and Kartik Hosanagar, Measuring the value of recommendation links on product demand, Information Systems Research, volume 30, number 3, pages 819 to 838, 2019, https://ideas.repec.org/a/inm/orisre/v30y2019i3p819-838.html

  10. 10.

    Dietmar Jannach and Michael Jugovac, Measuring the business value of recommender systems, ACM Transactions on Management Information Systems, volume 10, number 4, 2019, https://arxiv.org/abs/1908.08328

  11. 11.

    Alex Deng, Ya Xu, Ron Kohavi and Toby Walker, Improving the sensitivity of online controlled experiments by [using] pre experiment data, WSDM 2013, Rome, https://exp-platform.com/cuped/

  12. 12.

    Consumer Rights Act 2022, section 123, Additional payments, Irish Statute Book, https://www.irishstatutebook.ie/2022/en/act/pub/0037/sec0123.html

  13. 13.

    Shopify, Product Recommendations API reference (Ajax API), Shopify Dev Docs, checked 22 November 2026, https://shopify.dev/docs/api/ajax/reference/product-recommendations