Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 40 ยท Growth, SEO and Analytics

Analytics, Funnels and Metrics

Learn how shops measure themselves: events and the data layer, funnels, conversion rate, AOV, LTV, CAC, cohorts, server-side tracking and consent, with a live funnel analysis.

You cannot improve a shop you cannot measure. Analytics answers questions such as: where do shoppers drop out, which channel brings customers that come back, and did last week's checkout change help or hurt? As a developer you are the person who decides which events exist, what they contain and whether the numbers can be trusted. Bad tracking is worse than none, because people make decisions from it.

This lesson explains the vocabulary (events, funnels, rates, averages, cohorts), shows how to compute the standard shop metrics, and covers the two modern complications: tracking from the server instead of the browser, and respecting consent.

Events and the data layer

Almost all analytics is built from events. An event is a small record of something that happened: who did it, what it was, when, and the details. A typical shop sends a handful of standard events:

Event When it fires Useful fields
view_item A product page is shown product id, price, currency
add_to_cart An item is added product id, quantity, price
begin_checkout The shopper starts checkout cart value, item count
purchase The order is confirmed order id, total, tax, shipping, coupon, items
refund A refund is issued order id, amount

Name events once, in one document, and keep names stable. Renaming add_to_cart to addToCart splits your history in two.

Many shops put the data in a data layer: a plain JavaScript array or object on the page that holds structured facts. The analytics and advertising tools read from it instead of scraping the HTML. This separates "what happened" (your code) from "who wants to know" (tools you can change without editing templates). A push looks like this:

JavaScript
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  event: "add_to_cart",
  currency: "EUR",
  value: 89.9,
  items: [{ item_id: "TS-100-42", item_name: "Trail Shoe", price: 89.9, quantity: 1 }],
});

Two rules prevent most errors. First, send identifiers and amounts from the same source as the order (see The Order Lifecycle and State Machines), not values re-typed in a template. Second, send each purchase once. A thank-you page that reloads, or that the shopper bookmarks, fires purchase again and doubles revenue. Include the order id and let the receiving side drop duplicates, the same trick used for payments in Idempotency and Reliable Payments.

The funnel

A funnel is the ordered list of steps toward a goal, with the number of visitors who reach each step. For a shop it is usually product view, add to cart, begin checkout, purchase. Two numbers per step matter: the share of the previous step (the step conversion) and the share of the top (the overall conversion).

flowchart LR
    A["Viewed a product<br/>100%"] --> B["Added to cart<br/>about 40%"]
    B --> C["Began checkout<br/>about 25%"]
    C --> D["Purchased<br/>about 12%"]
    B -.->|"drop-off"| X["Left"]
    C -.->|"drop-off"| X

Each arrow loses people. The biggest relative loss is where to look first.

Be careful with what you count. Counting events overcounts, because one shopper may add three items. Count sessions or users that reached the step. Also decide whether order matters: a shopper who goes straight to checkout from a saved cart never viewed a product in this session. Pick a rule and write it down.

Python Funnel analysis from raw events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Try adding a session that purchases without viewing an item and see which rates change. Notice that the sets make a repeated event harmless.

The standard metrics

Conversion rate is orders divided by sessions (or by visitors; say which). A shop at 2 to 3 percent is typical across many industries, but ranges vary widely by price, traffic source and device, so compare yourself with your own history first.

Average order value (AOV) is revenue divided by the number of orders. Define revenue clearly: before or after discounts, tax and shipping, and net of refunds? Most teams report merchandise revenue without tax. Raising AOV is the aim of bundles, free-shipping thresholds and cross-sell (Merchandising and Recommendations).

Customer acquisition cost (CAC) is marketing spend divided by the number of new customers it brought. Count only new customers; including repeat buyers makes ads look better than they are.

Lifetime value (LTV) is the value a customer brings over time. A simple version is AOV times orders per year times gross margin times the number of years. Use margin, not revenue: a customer who spends 1,000 at 10 percent margin is worth far less than one who spends 500 at 50 percent. A common health check is LTV divided by CAC; many businesses want at least 3, but cash flow matters too, since LTV arrives slowly and CAC is paid now.

Cohorts group customers by when they started, so you can see whether newer customers behave better than older ones. The question is "of customers who first ordered in month 1, how many ordered again in month 2 and month 3?" Averages over all customers hide trends that cohorts reveal. A rising total revenue can hide a retention that falls every month.

Python Cohorts, CAC and LTV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Month+0 is always 100 percent because the cohort is defined by that first order. This shop's LTV/CAC ratio is about 1.7, well under the rule of thumb of 3. Try lowering ad_spend to 2000 and see how much the ratio improves.

Server-side tracking

Browser tracking has problems. Ad blockers and privacy features remove scripts, users close the tab before a script fires, and browsers shorten cookie lifetimes. The result is orders in your database that analytics never saw.

Server-side tracking sends the event from your backend instead. The most important one is purchase: your server knows the order is paid (often from a payment webhook, see Webhooks and Signature Verification), so it can send the event with exact amounts, whatever the browser did. A common design:

  1. The browser records a client or session identifier and any campaign parameters at landing, and stores them on the cart or order.
  2. When the order is paid, the server sends the event to the analytics or advertising API with that identifier and the order id for deduplication.
  3. If the browser also sent the event, the shared order id lets the receiver count it once.

Server-side tracking is not a way around consent. It moves where the data is sent from, not whether you may send it.

In the EU, UK and many other regions, non-essential tracking needs the visitor's permission before it starts. Analytics and advertising scripts usually count as non-essential. The practical consequences:

  • Load tracking scripts only after consent, and stop when it is withdrawn. Store the choice (see GDPR, Consumer Law and Accessibility).
  • Design for gaps. Some visitors decline, so your analytics undercounts. Treat the orders table as the source of truth for revenue, and analytics as a sample for behavior.
  • Collect the minimum. Do not put emails, names or addresses in event fields or URLs; pseudonymous identifiers are safer.
  • Keep personal data out of URLs, because URLs end up in logs, referrers and third-party tools.

Common mistakes

  • Comparing metrics with different definitions (revenue with and without tax).
  • Looking at averages only; segment by device, country and channel, because a mobile problem can hide inside a healthy total.
  • Drawing conclusions from tiny samples. A change from 2 to 3 orders is noise.
  • Testing a change for two days that include a sale. Run experiments over whole weeks and compare like with like.
  • Never reconciling analytics with the order database. Do it monthly; large gaps point to broken tags or duplicates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a funnel step count sessions that reached it instead of counting raw events?

    A shopper who adds three items fires three add_to_cart events. Counting sessions that reached the step gives a meaningful drop-off rate.
  2. 2. A thank-you page fires the purchase event every time it loads. What is the best protection against doubled revenue?

    A stable order id makes the event idempotent, so a reload or a second source (browser plus server) is counted only once.
  3. 3. Which version of LTV is the most useful for deciding how much you can spend to acquire a customer?

    Margin shows what is left to pay for acquisition and running the business, and a fixed period keeps the number honest.
  4. 4. What does server-side purchase tracking change about consent?

    Server-side tracking changes where the event is sent from, not whether tracking is allowed. Consent rules still apply.

Summary

  • Analytics is built from named, stable events; a data layer separates what happened from the tools that consume it.
  • Send amounts and ids from the order itself and include the order id so duplicates can be dropped.
  • A funnel counts sessions per step; look at both step conversion and overall conversion.
  • Define each metric precisely: conversion rate, AOV, CAC (new customers only) and margin-based LTV.
  • Cohorts show retention trends that averages hide.
  • Server-side tracking recovers events lost in the browser, but consent rules still apply.
  • Treat the order database as the truth for revenue and analytics as behavior data with gaps.

Next, look at the messages you send after the order: Transactional Email and Customer Lifecycle.