Marketing Attribution, Funnel Analytics & MMM
On this page
- Why Every Ad Platform Claims Credit for the Same Sale
- Attribution Models Compared
- Strict UTM Governance & Validation
- Computing First-Touch, Last-Touch & Position-Based Attribution in Python & SQL
- Adstock Decay & Saturation Intuition (MMM)
- Geo-Holdout Incrementality Test Calculation
- Channel Reconciliation Checklist
- Computing Adstock Carryover in Python
- Capturing "Dark Social" & Filtering Bot Noise
- Debugging in Production: How Attribution Breaks
- Practice
Why Every Ad Platform Claims Credit for the Same Sale#
If you sum the conversions reported inside Meta Ads, Google Ads, LinkedIn, and your email platform, the total is routinely 1.5x to 2.5x higher than the actual revenue in your bank account. Each platform grades its own homework using generous view-through and click-through attribution windows.
Reliable growth teams combine strict UTM governance and first-party event tracking with self-reported attribution and holdout / incrementality tests, using AI to write SQL queries, normalize messy channel names, and spot weekly funnel anomalies.
Attribution Models Compared#
| Model | How Credit Is Assigned | Best Use Case | Major Blind Spot |
|---|---|---|---|
| First-Touch | 100% to the first tracked session | Measuring top-of-funnel discovery | Ignores nurturing and closing touchpoints |
| Last-Touch | 100% to the final session before conversion | Evaluating high-intent capture | Starves content, YouTube, and awareness |
| Linear / Position-Based | Equal split or 40/20/40 across touches | Multi-week B2B journeys | Arbitrary weights; misses offline touches |
| Incrementality / Holdout | Compares exposed test region vs. unexposed control | Proving true causal revenue lift | Needs sufficient traffic and clean geo splits |
Strict UTM Governance & Validation#
Attribution collapses when one teammate writes utm_source=LinkedIn, another writes linkedin, and a third forgets utm_medium. Enforce a lowercase snake_case UTM validator in CI or your campaign sheet, and inspect live links with the URL parser:
from urllib.parse import urlparse, parse_qs
ALLOWED_MEDIUMS = {"cpc", "social", "email", "referral", "partner"}
def validate_utm_url(url: str) -> list[str]:
qs = parse_qs(urlparse(url).query)
errors = []
for req in ("utm_source", "utm_medium", "utm_campaign"):
val = qs.get(req, [""])[0]
if not val:
errors.append(f"missing {req}")
elif val != val.lower() or " " in val:
errors.append(f"{req} must be lowercase without spaces: '{val}'")
med = qs.get("utm_medium", [""])[0]
if med and med not in ALLOWED_MEDIUMS:
errors.append(f"unknown utm_medium: '{med}'")
return errors
print(validate_utm_url("https://simpleprog.com/tools?utm_source=x&utm_medium=social&utm_campaign=curl_launch"))
print(validate_utm_url("https://simpleprog.com/tools?utm_source=LinkedIn&utm_medium=paid_post"))
Output:
[]
["utm_source must be lowercase without spaces: 'LinkedIn'", "unknown utm_medium: 'paid_post'", 'missing utm_campaign']
Computing First-Touch, Last-Touch & Position-Based Attribution in Python & SQL#
With clean session logs, comparing models exposes where last-touch misleads you. Notice how storing both first_touch_source and last_touch_source on the account row lets SQL answer both views cleanly:
WITH ranked_touches AS (
SELECT
account_id,
source,
ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY occurred_at ASC) AS rn_first,
ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY occurred_at DESC) AS rn_last
FROM touchpoints
)
SELECT
COALESCE(f.source, 'direct') AS first_touch_source,
COALESCE(l.source, 'direct') AS last_touch_source,
COUNT(a.id) AS accounts,
SUM(a.revenue_usd) AS revenue_usd
FROM accounts a
LEFT JOIN ranked_touches f ON f.account_id = a.id AND f.rn_first = 1
LEFT JOIN ranked_touches l ON l.account_id = a.id AND l.rn_last = 1
GROUP BY 1, 2
ORDER BY revenue_usd DESC;
In Python, comparing 40/20/40 position-based credit against last-touch shows why cutting SEO/community channels breaks pipeline:
from collections import defaultdict
journeys = [
{"user": "u1", "touches": ["seo_guide", "youtube", "direct"], "revenue": 120.0},
{"user": "u2", "touches": ["google_ads", "email_nurture"], "revenue": 80.0},
{"user": "u3", "touches": ["reddit_post", "direct"], "revenue": 200.0},
{"user": "u4", "touches": ["seo_tool", "direct"], "revenue": 150.0},
]
first_touch, last_touch, pos_based = defaultdict(float), defaultdict(float), defaultdict(float)
for j in journeys:
t, rev = j["touches"], j["revenue"]
first_touch[t[0]] += rev
last_touch[t[-1]] += rev
if len(t) == 1:
pos_based[t[0]] += rev
elif len(t) == 2:
pos_based[t[0]] += rev * 0.5
pos_based[t[1]] += rev * 0.5
else:
pos_based[t[0]] += rev * 0.4
pos_based[t[-1]] += rev * 0.4
mid_share = (rev * 0.2) / (len(t) - 2)
for mid in t[1:-1]:
pos_based[mid] += mid_share
print("First-touch:", dict(first_touch))
print("Last-touch: ", dict(last_touch))
print("40/20/40: ", {k: round(v, 1) for k, v in pos_based.items()})
Output:
First-touch: {'seo_guide': 120.0, 'google_ads': 80.0, 'reddit_post': 200.0, 'seo_tool': 150.0}
Last-touch: {'direct': 470.0, 'email_nurture': 80.0}
40/20/40: {'seo_guide': 48.0, 'youtube': 24.0, 'direct': 223.0, 'google_ads': 40.0, 'email_nurture': 40.0, 'reddit_post': 100.0, 'seo_tool': 75.0}
Adstock Decay & Saturation Intuition (MMM)#
Even without 24 months of data for full Bayesian Marketing Mix Modeling, understand two physical laws of ad spend: adstock (an ad seen today still influences conversions tomorrow with exponential decay lambda) and saturation (doubling spend does not double conversions; marginal CPA rises along a diminishing-returns curve). Modeling those two curves in Python prevents teams from linearly extrapolating a $50/day campaign's CPA to $5,000/day:
def hill_saturation(spend: float, max_conv: float, half_sat: float, slope: float = 1.5) -> float:
'''Model diminishing returns as spend scales.'''
if spend <= 0:
return 0.0
s = spend ** slope
return round(max_conv * (s / (s + (half_sat ** slope))), 1)
for s in (500, 1500, 3000, 6000):
conv = hill_saturation(s, max_conv=120, half_sat=2000)
cpa = round(s / max(conv, 1), 2)
print(f"Spend=${s:4d} -> est_conv={conv:5.1f} | marginal CPA=${cpa}")
Output:
Spend=$ 500 -> est_conv= 13.4 | marginal CPA=$37.31
Spend=$1500 -> est_conv= 47.3 | marginal CPA=$31.71
Spend=$3000 -> est_conv= 77.4 | marginal CPA=$38.76
Spend=$6000 -> est_conv=100.7 | marginal CPA=$59.58
Geo-Holdout Incrementality Test Calculation#
When platform-reported ROAS looks suspiciously high (especially on retargeting or brand search), split comparable regions into Test (ads on) and Control (ads paused) for 14 days and compute the net incremental lift:
def incrementality_lift(test_rev: float, test_baseline: float, ctrl_rev: float, ctrl_baseline: float, ad_spend: float) -> dict:
ctrl_growth = ctrl_rev / ctrl_baseline
expected_test_rev = test_baseline * ctrl_growth
incremental_rev = round(test_rev - expected_test_rev, 2)
iroas = round(incremental_rev / ad_spend, 2) if ad_spend else 0.0
return {"expected_test_rev": round(expected_test_rev, 2), "incremental_rev": incremental_rev, "incremental_roas": iroas}
print(incrementality_lift(test_rev=18500, test_baseline=14000, ctrl_rev=14700, ctrl_baseline=14000, ad_spend=2500))
Output:
{'expected_test_rev': 14700.0, 'incremental_rev': 3800.0, 'incremental_roas': 1.52}
Channel Reconciliation Checklist#
Every Monday, reconcile three numbers side by side: (1) ad-platform reported conversions, (2) first-party SQL first_touch_source signups, and (3) self-reported "How did you hear about us?" counts. Large gaps between (1) and (2) highlight view-through over-claiming; large gaps between (2) and (3) highlight dark social and AI-search discovery.
Keep one weekly summary table in SQLite or Postgres tracking human_sessions, tool_activations, signups, paid_conversions, ad_spend, and blended_cac (ad_spend / paid_conversions). Reviewing blended CAC alongside first_touch_source trends every Monday stops channel-specific vanity metrics from distorting budget decisions, and gives you an objective baseline before adjusting spend across Google, Meta, or content syndication.
Computing Adstock Carryover in Python#
Ad spend does not stop working at midnight when a campaign pauses. With a weekly decay factor lambda (typically 0.3 to 0.6 for paid search and social), adstock_t = spend_t + lambda * adstock_{t-1}:
def compute_adstock(weekly_spend: list[float], decay: float = 0.4) -> list[float]:
carried = []
prev = 0.0
for s in weekly_spend:
val = s + decay * prev
carried.append(round(val, 1))
prev = val
return carried
print("Effective weekly pressure:", compute_adstock([1000, 1000, 0, 0]))
Output:
Effective weekly pressure: [1000.0, 1400.0, 560.0, 224.0]
Notice that in week 3 ($0 spend), $560 of effective ad pressure still carries over from prior weeks, which is why short 3-day on/off tests misattribute lagged conversions.
Capturing "Dark Social" & Filtering Bot Noise#
Word-of-mouth, podcasts, Discord/Slack recommendations, Hacker News comments, and AI search answers often arrive with no Referer header and no UTM tags, so analytics classifies them as Direct. Fix that blind spot with a single optional "How did you hear about us?" text field on your signup form, then use a weekly LLM classification script to map free-text replies ("saw your scraping sandbox on r/webscraping", "ChatGPT recommended your curl converter") into clean channel buckets.
Similarly, cloud-hosted headless browsers spoofing mobile Chrome still fire analytics scripts and inflate single-page-view metrics. Separate real human engagement (multi-page sessions, tool usage, >10s time-on-page, signups) from 1-hit datacenter bursts when reporting weekly traffic.
Debugging in Production: How Attribution Breaks#
- Inconsistent UTM casing and naming.
utm_source=LinkedIn,linkedin, andlisplit one channel into three rows. Fix: Enforcevalidate_utm_url()before publishing any campaign link. - Confusing branded search with incremental growth. Bidding heavily on your own brand name in Google Ads produces great last-touch ROAS because users were already searching for you after reading your content. Fix: Run a 2-week geo-holdout (pause brand search in 20% of regions) to measure true incremental lift.
- Short cookie windows on multi-week B2B cycles. A 7-day cookie loses the original discovery source on a 30-day sales cycle. Fix: Persist
first_touch_sourceon the server-side user record on day one. - Over-engineering MMM too early. Full Bayesian MMM requires 18 to 24 months of weekly spend variation. Early-stage teams get far more value from clean first-touch + self-reported attribution + simple geo-holdouts.
Practice#
- Run
validate_utm_url()over 10 active links from your site, emails, or social profiles and fix any casing or missing parameter errors. - Run the Python attribution comparison above on 20 sample user journeys and observe how
directshrinks under first-touch and 40/20/40. - Add a single optional "How did you hear about us?" field to your onboarding or contact flow and classify 15 responses into canonical channel buckets.
Check your understanding
4 quick questions on this lesson. Get them all right and the lesson is marked complete.