Design referral and affiliate programs that turn your customers into active promoters for your business. You get a complete blueprint covering incentive structures, reward mechanics, and the specific triggers that encourage sharing. Use this whenever you want to launch a new word-of-mouth system or optimize an existing one that isn't meeting targets.
name: “referral-program”
description: “When the user wants to design, launch, or optimize a referral or affiliate program. Use when they mention ‘referral program,’ ‘affiliate program,’ ‘word of mouth,’ ‘refer a friend,’ ‘incentive program,’ ‘customer referrals,’ ‘brand ambassador,’ ‘partner program,’ ‘referral link,’ or ‘growth through referrals.’ Covers program mechanics, incentive design, and optimization — not just the idea of referrals but the actual system.”
license: MIT
metadata:
version: 1.0.0
author: Alireza Rezvani
category: marketing
updated: 2026-03-06
Referral Program
You are a growth engineer who has designed referral and affiliate programs for SaaS companies, marketplaces, and consumer apps. You know the difference between programs that compound and programs that collect dust. Your goal is to build a referral system that actually runs — one with the right mechanics, triggers, incentives, and measurement to make customers do your acquisition for you.
Before Starting
Check for context first:
If marketing-context.md exists, read it before asking questions. Use that context and only ask for information not already covered.
Gather this context (ask if not provided):
1. Product & Customer
What are you selling? (SaaS, marketplace, service, ecommerce)
Who is your ideal customer and what do they love about your product?
What’s your average LTV? (This determines incentive ceiling)
What’s your current CAC via other channels?
2. Program Goals
What outcome do you want? (More signups, more revenue, brand reach)
Is this B2C or B2B? (Different mechanics apply)
Do you want customers referring customers, or partners promoting your product?
3. Current State (if optimizing)
What program exists today?
What are the key metrics? (Referral rate, conversion rate, active referrers %)
What’s the reward structure?
Where does the loop break down?
How This Skill Works
Mode 1: Design a New Program
Starting from scratch. Build the full referral program — loop, incentives, triggers, and measurement.
Workflow:
Define the referral loop (4 stages)
Choose program type (customer referral vs. affiliate)
Design the incentive structure (what, when, for whom)
Identify trigger moments (when to ask for referrals)
Plan the share mechanics (how referrals actually happen)
Define measurement framework
Mode 2: Optimize an Existing Program
You have something running but it’s underperforming. Diagnose where the loop breaks.
Workflow:
Audit current metrics against benchmarks
Identify the specific weak point (low awareness, low share rate, low conversion, reward friction)
Run a focused fix — don’t redesign everything at once
Measure the impact before moving to the next lever
Mode 3: Launch an Affiliate Program
Different from customer referrals. Affiliates are external promoters — bloggers, influencers, complementary SaaS, industry newsletters — motivated by commission, not loyalty.
Workflow:
Define affiliate tiers and commission structure
Identify and recruit initial affiliate partners
Build the affiliate toolkit (links, assets, copy)
Set tracking and payout mechanics
Onboard and activate your first 10 affiliates
Referral vs. Affiliate — Choose the Right Mechanism
Customer Referral
Affiliate Program
Who promotes
Your existing customers
External partners, publishers, influencers
Motivation
Loyalty, reward, social currency
Commission, audience alignment
Best for
B2C, prosumer, SMB SaaS
B2B SaaS, high LTV products, content-heavy niches
Activation
Triggered by aha moment, milestone
Recruited proactively, onboarded
Payout timing
Account credit, discount, cash reward
Revenue share or flat fee per conversion
CAC impact
Low — reward < CAC
Variable — commission % determines
Scale
Scales with user base
Scales with partner recruitment
Rule of thumb: If your customers are enthusiastic and social, start with customer referrals. If your customers are businesses buying on behalf of a team, start with affiliates.
The Referral Loop
Every referral program runs on the same 4-stage loop. If any stage is weak, the loop breaks.
This is when you ask customers to refer. Timing is everything.
High-signal trigger moments:
After aha moment — when the customer first experiences core value (not at signup — too early)
After a milestone — “You just saved your 100th hour” / “Your 10th team member joined”
After great support — post-resolution NPS prompt → if 9-10, ask for referral
After renewal — customers who renew are telling you they’re satisfied
After a public win — customer tweets about you → follow up with referral link
What doesn’t work: Asking on day 1, asking in onboarding emails, asking in the footer of every email.
Stage 2: Share Action
Remove every possible point of friction.
Pre-filled share message (editable, not locked)
Personal referral link (not a generic coupon code)
Share options: email invite, link copy, social share, Slack/Teams share for B2B
Mobile-optimized for consumer products
One-click send — no manual copy-paste required
Stage 3: Referred User Converts
The referred user lands on your product. Now what?
Personalized landing (“Your friend Alex invited you — here’s your bonus…”)
Incentive visible on landing page
Referral attribution tracked from landing to conversion
Clear CTA — don’t make them hunt for what to do
Stage 4: Reward Delivered
Reward must be fast and clear. Delayed rewards break the loop.
Confirm reward eligibility as soon as referral signs up (not when they pay)
Notify the referrer immediately — don’t wait until month-end
Status visible in dashboard (“2 friends joined — you’ve earned $40”)
Incentive Design
Single-Sided vs. Double-Sided
Single-sided (referrer only gets rewarded): Use when your product has strong viral hooks and customers are already enthusiastic. Lower cost per referral.
Double-sided (both referrer and referred get rewarded): Use when you need to overcome inertia on both sides. Higher cost, higher conversion. Dropbox made this famous.
Rule: If your referral rate is <1%, go double-sided. If it’s >5%, single-sided is more profitable.
Reward Types
Type
Best For
Examples
Account credit
SaaS / subscription
”Get $20 credit”
Discount
Ecommerce / usage-based
”Get 1 month free”
Cash
High LTV, B2C
”$50 per referral”
Feature unlock
Freemium
”Unlock advanced analytics”
Status / recognition
Community / loyalty
”Ambassador status, exclusive badge”
Charity donation
Enterprise / mission-driven
”$25 to a cause you choose”
Sizing rule: Reward should be ≥10% of first month’s value for account credit. For cash, cap at 30% of first payment. Run scripts/referral_roi_calculator.py to model reward sizing against your LTV and CAC.
Tiered Rewards (Gamification)
When you want referrers to go from 1 referral to 10:
Asking at signup → Flag immediately. Asking a new user to refer before they’ve experienced value is a conversion killer. Move trigger to post-aha moment.
Reward too small relative to LTV → If reward is <5% of LTV and referral rate is low, the math is broken. Surface the sizing issue.
No reward notification system → If referred users convert but referrers aren’t notified immediately, the loop breaks. Flag the need for instant notification.
Generic share message → Pre-filled messages that sound like marketing copy get deleted. Flag and rewrite in first-person customer voice.
No attribution after the landing page → If referral tracking stops at first visit but conversion requires multiple sessions, referral is being undercounted. Flag tracking gap.
Affiliate program without a partner kit → If affiliates don’t have approved copy and assets, they’ll promote inaccurately or not at all. Flag before launch.
Output Artifacts
When you ask for…
You get…
”Design a referral program”
Full program spec: loop design, incentive structure, trigger moments, share mechanics, measurement plan
”Audit our referral program”
Metric scorecard vs. benchmarks, weak link diagnosis, prioritized optimization plan
”Model our incentive options”
ROI comparison of 3-5 reward structures using your LTV and CAC data
”Write referral program copy”
In-app prompts, referral email, referred user landing page headline, share messages
Actions have owners — “define reward structure” → assign an owner and timeline
Related Skills
launch-strategy: Use when planning the go-to-market for a product launch. NOT for building a referral program (different mechanics, different timeline).
email-sequence: Use when building the email flow that supports the referral program (trigger emails, reward notifications). NOT for the program design itself.
marketing-demand-acquisition: Use for multi-channel paid and organic acquisition strategy. NOT for referral-specific mechanics.
ab-test-setup: Use when A/B testing referral landing pages, reward structures, or trigger messaging. NOT for the program design.
content-creator: Use for creating affiliate partner content or referral-related blog posts. NOT for program mechanics.
Measurement Framework — Referral Program Metrics, Benchmarks, and Optimization Playbook
The metrics that tell you if your referral program is working, what's broken, and what to fix first.
The Core Metric Stack
Track these weekly. Everything else is secondary.
Metric
Formula
Benchmark (SaaS)
What It Tells You
Program awareness
(Users who know about program / Total active users) × 100
>40%
Are you even promoting it?
Active referrer rate
(Users who sent ≥1 referral / Total active users) × 100
5–15%
How many users are actually participating
Referrals sent per active referrer
Total referrals / Active referrers
2–5 per period
How motivated referrers are
Referral conversion rate
(Referrals that converted / Referrals sent) × 100
15–30%
Quality of referred traffic
Reward redemption rate
(Rewards redeemed / Rewards issued) × 100
>70%
Is the reward actually desirable?
CAC via referral
Total reward cost / New customers via referral
<50% of channel CAC
Program efficiency
K-factor (virality coefficient)
Referrals per user × Referral conversion rate
>0.5 for meaningful growth
Is it self-sustaining?
Benchmarks by Stage and Model
Early-Stage SaaS (<$1M ARR)
Metric
Expected
Strong
Active referrer rate
2–5%
>8%
Referral conversion rate
10–20%
>25%
CAC via referral vs. paid
30–50% of paid CAC
<25% of paid CAC
Growth-Stage SaaS ($1M–$10M ARR)
Metric
Expected
Strong
Active referrer rate
5–10%
>12%
Referral contribution to new signups
10–20%
>25%
Referral contribution to revenue
5–15%
>20%
Consumer / Prosumer Products
Metric
Expected
Strong
Active referrer rate
8–20%
>25%
Referral conversion rate
20–40%
>50% (with double-sided reward)
K-factor
0.3–0.7
>1.0 (true viral loop)
B2B Mid-Market (ACV $10k+)
Metric
Expected
Strong
Active referrer rate
3–8%
>10%
Referral conversion rate
20–40% (warm intros convert higher)
>50%
Average deal size via referral vs. standard
Similar
20–40% higher (trust shortens negotiation)
Diagnosing the Broken Stage
Diagnosis Framework
Is referral rate low? └── Is awareness low? → Promote the program └── Is trigger placement wrong? → Move to better moment └── Is reward insufficient? → Test higher reward └── Is share flow too complex? → SimplifyIs referral conversion low? └── Is the landing page cold? → Personalize for referred users └── Is the incentive for the referred user unclear? → Make it above the fold └── Is signup friction high? → Reduce required fieldsIs reward redemption low? └── Is reward notification delayed? → Send immediately on qualifying event └── Is reward type wrong? → Test cash vs. credit vs. feature unlock └── Is the redemption process complex? → Auto-apply credits, remove steps
The Optimization Playbook
Work in this order. Don't try to fix everything at once.
Phase 1: Foundation (Month 1)
Goal: Get to baseline awareness and share rate.
Audit whether users know the program exists
Add in-app promotion: dashboard banner, post-activation prompt, success state trigger
Add referral program to the weekly/monthly activation email
Ensure share flow works on mobile
Success gate: Program awareness >30%, Active referrer rate >3%
Phase 2: Trigger Optimization (Month 2)
Goal: Ask at the right moment, not just any moment.
Map all current trigger points
Move or add trigger to first aha moment (define aha moment first)
A/B test: trigger after aha vs. trigger after 7-day retention
Add NPS-linked trigger: score of 9-10 → immediate referral ask
Success gate: Active referrer rate increases by 30% over Phase 1
Phase 3: Incentive Tuning (Month 3)
Goal: Right reward, right timing, right delivery.
Survey churned referrers — why did they stop?
Test single-sided vs. double-sided if not already tested
Test reward type: credit vs. cash vs. feature unlock
Add reward status widget to dashboard: "You've earned $X. [View details]"
Reduce reward payout delay — reward immediately on qualifying event, not month-end
Success gate: Reward redemption rate >70%, CAC via referral <40% of paid CAC
Phase 4: Conversion of Referred Users (Month 4)
Goal: Referred users should convert at 2× organic rate.
Personalize referred user landing page (use referrer name if available)
Highlight referred user's incentive above the fold — don't bury it
A/B test: direct to product vs. direct to dedicated referral landing page
Add "referred by" onboarding track: faster to aha, lower time to first value
Success gate: Referred user conversion rate 20%+ (vs. organic baseline)
Phase 5: Scale and Gamification (Month 5+)
Goal: Turn your top 5% of referrers into a real advocacy channel.
Identify top referrers — reach out personally
Offer top referrers early access, ambassador status, or product input role
Launch tiered reward structure
Quarterly referral challenges: "Top 10 referrers this quarter win X"
CAC via Referral — Full Calculation
CAC via referral = (Reward cost per referral × Successful referrals) + Program overhead costs ─────────────────────────────────────────────────────────────────────────── New customers acquired via referralWhere:- Reward cost per referral = referrer reward + referred user reward- Program overhead = platform cost + engineering time + support time (amortized)- Successful referrals = referrals that converted to paying customer
Example:
200 referrals sent → 40 conversions (20% conversion rate)
Referrer reward: $30 per successful referral
Referred user reward: $20 (discount on first month)
CAC via referral = ($30 + $20) × 40 + $600 / 40 = $65 per customer
Compare to paid CAC, and you know if the program is worth it.
Use scripts/referral_roi_calculator.py to model this for your numbers.
Affiliate-Specific Metrics
Metric
Formula
Benchmark
Active affiliate rate
Active affiliates / Enrolled affiliates
20–40%
Revenue per active affiliate
Total affiliate revenue / Active affiliates
Varies by niche
Affiliate-driven CAC
Commission paid / New customers via affiliate
Should be <standard CAC
Top affiliate concentration
Revenue from top 20% of affiliates
Normal if 80%+ of revenue from top 20%
Average cookie-to-conversion time
Days from click to first payment
Benchmark against your sales cycle
Warning sign: If >80% of affiliate revenue is from 1–2 partners, you have concentration risk. One partner leaving could tank the channel overnight. Diversify proactively.
Reporting Template
Weekly referral program summary:
REFERRAL PROGRAM — Week of [DATE]Active referrers: X (↑/↓ vs. last week)Referrals sent: XConversions: X (rate: X%)Rewards issued: $XNew customers via referral: XCAC via referral: $X (vs. $X paid CAC)TOP THIS WEEK:- [Name/segment] sent 12 referrals, 4 converted- [Trigger optimization test] is showing +18% referrer rateISSUES:- [What's broken and the plan to fix it]NEXT ACTION:- [One thing we're doing this week to improve the program]
Program Mechanics — Referral and Affiliate Design Patterns
Detailed design patterns with real-world examples. Use this as a reference when designing programs — these are the mechanics that separate programs with 10% referral rates from ones with 0.5%.
The Two Fundamental Program Types
Type A: Customer-to-Customer Referral
Your best customers refer their peers. Classic example: Dropbox, Airbnb, Uber.
Core mechanics:
Referral link generated per user
Reward given when referred user completes a qualifying action (sign up, first purchase, first month paid)
Referrer sees their dashboard: links sent, signed up, rewards earned
What makes it work:
Existing customer trust transfers. Being referred by someone you trust removes 80% of purchase skepticism.
The referrer's reputation is on the line — they only refer people they think will benefit
Natural social proof at the moment of conversion
Type B: Partner / Affiliate Program
External publishers, influencers, agencies, or complementary SaaS tools promote you in exchange for commission.
Core mechanics:
Unique affiliate link or coupon per partner
Attribution tracked via cookie (30-90 day window typical)
Payout on qualifying events (first payment, monthly recurring, flat fee)
What makes it work:
Partners have existing audiences who trust them
Content-driven promotion outlasts a single ad — a blog post with your affiliate link can generate leads for 3 years
Commission-aligned incentives mean partners promote more when you convert better
Real-World Program Patterns
Pattern 1: Double-Sided Reward (Dropbox Model)
How it worked: Refer a friend = 500MB for you + 500MB for them.
Why it worked:
Both sides had skin in the game
The reward was intrinsic to the product (not a discount on something unrelated)
The referred user's incentive made them more likely to complete registration
Referrer felt generous, not transactional
When to use: When your core product has a natural "shareable" dimension. Digital products with quantity-based rewards (storage, credits, messages, seats) are perfect candidates.
When NOT to use: When your product has no natural unit to give. Don't give $10 Amazon gift cards just to copy Dropbox — tie the reward to product value.
Pattern 2: Tiered Ambassador Program (Referral + Status)
How it works: Customers unlock higher reward tiers by referring more users. Top tier gets named ambassador status, exclusive access, or direct relationship with the company.
Example structure:
Bronze (1-2 referrals): $20 credit per referralSilver (3-9 referrals): $30 credit per referral + priority supportGold (10+ referrals): $50 credit per referral + product advisory board invite + named case study
Why it works: For highly enthusiastic customers, status beats cash. Naming someone an "ambassador" triggers identity — they become advocates rather than just referrers.
When to use: Strong community around the product. Developer tools, creative SaaS, agency tools where practitioners identify with the category.
Pattern 3: Milestone Trigger (Conditional Reward)
How it works: Reward is not given at signup — it's given when the referred user reaches a specific milestone.
Example:
"Your friend gets $50 when they make their first withdrawal"
"You get 1 free month when your referral upgrades to a paid plan"
Why it works: Referred users are incentivized to actually use the product to unlock the reward. Referrers are incentivized to encourage their referral to stay active. Reduces reward fraud (fake accounts).
When to use: High-volume consumer products where gaming the system is a real risk. Financial services, marketplaces, usage-based products.
Pattern 4: Cohort-Based Referral Window
How it works: Referral rewards expire if the referred user doesn't convert within a set window.
Standard windows:
B2C: 7–14 days (high intent = fast decision)
B2B SMB: 30 days
B2B Enterprise: 90+ days (longer evaluation cycles)
Why it matters: Open-ended referral attribution creates accounting complexity and gaming risk. Time-bounded windows create urgency and clean accounting.
Pattern 5: Affiliate Commission Tiers by Partner Type
Not all affiliates are equal. Tiering by partner type lets you reward your best partners appropriately.
Example tier structure:
Standard affiliates (bloggers, small newsletters):└── 20% of first payment, 30-day cookiePremium affiliates (high-traffic publications, active agencies):└── 25% MRR for 12 months, 60-day cookie, co-marketing supportStrategic partners (complementary SaaS, resellers):└── 30% MRR ongoing, white-label option, dedicated account manager
Key principle: The higher the traffic quality and deal size, the higher the commission can go. An agency that sends you 5 enterprise deals per year is worth more than 100 bloggers who send you occasional trials.
Pattern 6: Product-Embedded Referral (Virality by Design)
The referral mechanism is built into the product experience, not bolted on as a "refer a friend" email.
Examples:
Calendar invite: "Powered by [Product]" link in email footer that every invitee sees
"Created with [Product]" watermark on exported documents (Canva, Notion)
"Invite your team" prompt mid-onboarding with a clear reason to do it now
"Share your results" on high-value output screens
Why it works: The referral happens at the moment of peak product value, using the product itself as the promotional vehicle. No separate "referral program" needed.
When to use: Productivity tools, creative tools, any product that produces shareable output. Build this alongside the product, not as an afterthought.
Pattern 7: B2B Account-Based Referral
In B2B, referrals are more targeted — you're asking for warm intros to specific account types, not a spray-and-pray link share.
How it works:
Identify which customers have the broadest networks in your ICP
Equip them with a referral kit (email template, one-pager, LinkedIn intro script)
Reward for completed intro + reward uplift for closed deal
Keep the referrer informed on progress (increases likelihood of them championing internally)
Example mechanics:
Step 1: Customer completes an intro call → $200 gift cardStep 2: Intro converts to a demo → $500 additionalStep 3: Demo converts to a deal → 10% of first year's contract value (capped at $5,000)
Why it works: High-trust referrals from B2B customers often shorten sales cycles dramatically. The referrer becomes an internal champion at the referred company, not just a warm lead.
Share Mechanics Deep Dive
The 3 Share Channels That Drive Volume
Channel
How It Works
Best For
Personal referral link
User copies/shares their link to a friend
Universal
Direct email invite
User enters friend's email, platform sends invite on their behalf
Consumer, prosumer
Social share
One-click to Twitter, LinkedIn, WhatsApp with pre-filled message
Consumer, community products
Pre-Written Share Messages — What Works
Works:
"I've been using [Product] for 3 months and it's saved me hours on [specific task]. You can get started free using my link: [link]"
Doesn't work:
"Check out this amazing product I use! [link]"
The difference: specificity and personal endorsement. Pre-fill your share messages with the actual benefit, not generic praise. Make it easy for users to be specific advocates, not just sharers.
Fraud Prevention
Referral fraud happens when users game the system (fake accounts, self-referrals, incentivized referrals).
Minimum safeguards:
Email verification required before reward is credited
Device fingerprinting to detect same-device self-referral
Reward withheld until referred user completes a qualifying action (first payment, 7-day active use)
Rate limiting on referral link sends per user
Warning signs of fraud:
Referral conversion rate suddenly spikes above 60% (normal is 15–30%)
High number of referrals from a single user (>20 in a week)
Referrals with similar email patterns or same IP block
Technology Options
For Customer Referral Programs
Tool
Best For
Pricing Tier
ReferralHero
SMB SaaS, waitlist referral
$49–$199/mo
Viral Loops
Consumer apps, e-commerce
$49–$199/mo
Referral Rock
Mid-market SaaS
$175–$800/mo
Custom (in-house)
When you want full control + have engineering
Build cost only
For Affiliate Programs
Tool
Best For
Notes
Rewardful
SaaS, Stripe-based
$49–$299/mo, easiest Stripe integration
PartnerStack
B2B SaaS
$500+/mo, best for partner tiers
Impact
Enterprise, multi-channel
Custom pricing
ShareASale
E-commerce, consumer
20% of commissions + fees
For Product-Embedded Viral Loops
Build these in-house. The "powered by" footer, "created with" watermark, or "invite your team" prompt needs to be native to the product experience, not a third-party widget.
#!/usr/bin/env python3"""referral_roi_calculator.py — Calculates referral program ROI.Models the economics of a referral program given your LTV, CAC, referral rate,reward cost, and conversion rate. Outputs program ROI, break-even referral rate,and optimal reward sizing.Usage: python3 referral_roi_calculator.py # runs embedded sample python3 referral_roi_calculator.py params.json # uses your params echo '{"ltv": 1200, "cac": 300}' | python3 referral_roi_calculator.pyJSON input format: { "ltv": 1200, # Customer Lifetime Value ($) "cac": 300, # Current avg CAC via paid channels ($) "active_users": 500, # Active users who could refer "referral_rate": 0.05, # % of active users who refer each month (0.05 = 5%) "referrals_per_referrer": 2.5, # Avg referrals sent per active referrer "referral_conversion_rate": 0.20, # % of referrals who become customers "referrer_reward": 50, # Reward paid to referrer per successful referral ($) "referred_reward": 30, # Reward paid to referred user (0 if single-sided) ($) "program_overhead_monthly": 200, # Platform + ops cost per month ($) "churn_rate_monthly": 0.03, # Monthly churn rate (used for LTV validation) "months_to_model": 12 # How many months to project }"""import jsonimport sysfrom collections import OrderedDict# ---------------------------------------------------------------------------# Core calculation functions# ---------------------------------------------------------------------------def calculate_referrals_per_month(params): """How many successful referrals per month?""" active_users = params["active_users"] referral_rate = params["referral_rate"] referrals_per_referrer = params["referrals_per_referrer"] conversion_rate = params["referral_conversion_rate"] active_referrers = active_users * referral_rate referrals_sent = active_referrers * referrals_per_referrer conversions = referrals_sent * conversion_rate return { "active_referrers": round(active_referrers, 1), "referrals_sent": round(referrals_sent, 1), "new_customers_per_month": round(conversions, 1), }def calculate_monthly_program_cost(params, new_customers_per_month): """Total cost of running the program for one month.""" reward_per_conversion = params["referrer_reward"] + params["referred_reward"] reward_cost = reward_per_conversion * new_customers_per_month overhead = params["program_overhead_monthly"] return { "reward_cost": round(reward_cost, 2), "overhead_cost": round(overhead, 2), "total_cost": round(reward_cost + overhead, 2), "reward_per_conversion": round(reward_per_conversion, 2), }def calculate_monthly_revenue(params, new_customers_per_month): """Revenue generated from referred customers in the first month.""" # First-month value is LTV / (1 / monthly_churn) = LTV * monthly_churn # Simplified: use LTV * monthly_churn as first-month expected revenue contribution # More conservative: just count as one acquisition with full LTV expected ltv = params["ltv"] revenue = new_customers_per_month * ltv return round(revenue, 2)def calculate_cac_via_referral(cost_data, new_customers_per_month): if new_customers_per_month == 0: return float('inf') return round(cost_data["total_cost"] / new_customers_per_month, 2)def calculate_break_even_referral_rate(params): """ What referral rate do we need so that CAC via referral equals reward_per_conversion + overhead_per_customer_amortized? We want: total_cost / new_customers = cac_target Solving for referral_rate where cac_target = 50% of paid CAC (our target) """ target_cac = params["cac"] * 0.5 # goal: 50% of current CAC ltv = params["ltv"] active_users = params["active_users"] referrals_per_referrer = params["referrals_per_referrer"] conversion_rate = params["referral_conversion_rate"] reward_per_conversion = params["referrer_reward"] + params["referred_reward"] overhead = params["program_overhead_monthly"] # CAC_referral = (reward × conversions + overhead) / conversions # = reward + overhead/conversions # Solve: target_cac = reward + overhead / (active_users × rate × referrals_per_referrer × conversion_rate) # conversions_needed = overhead / (target_cac - reward) if target_cac <= reward_per_conversion: return None # impossible — reward alone exceeds target CAC conversions_needed = overhead / (target_cac - reward_per_conversion) referral_rate_needed = conversions_needed / (active_users * referrals_per_referrer * conversion_rate) return round(referral_rate_needed, 4)def calculate_optimal_reward(params): """ What's the maximum reward you can afford while keeping CAC via referral under 60% of paid CAC? max_total_reward = 0.60 × paid_CAC (using conversion-amortized overhead) """ target_cac = params["cac"] * 0.60 overhead_amortized = params["program_overhead_monthly"] / max( calculate_referrals_per_month(params)["new_customers_per_month"], 1 ) max_reward = target_cac - overhead_amortized # Split recommendation: 60% referrer, 40% referred (double-sided) referrer_portion = round(max_reward * 0.60, 2) referred_portion = round(max_reward * 0.40, 2) return { "max_total_reward": round(max(max_reward, 0), 2), "recommended_referrer_reward": max(referrer_portion, 0), "recommended_referred_reward": max(referred_portion, 0), "reward_as_pct_ltv": round((max_reward / params["ltv"]) * 100, 1) if params["ltv"] > 0 else 0, }def calculate_roi(params): """ Program ROI over the modeling period. ROI = (Revenue from referred customers - Program costs) / Program costs """ months = params["months_to_model"] monthly = calculate_referrals_per_month(params) new_customers = monthly["new_customers_per_month"] costs = calculate_monthly_program_cost(params, new_customers) total_cost = costs["total_cost"] * months total_ltv_generated = new_customers * params["ltv"] * months net_benefit = total_ltv_generated - total_cost roi = (net_benefit / total_cost * 100) if total_cost > 0 else 0 return { "total_cost": round(total_cost, 2), "total_ltv_generated": round(total_ltv_generated, 2), "net_benefit": round(net_benefit, 2), "roi_pct": round(roi, 1), }def build_monthly_projection(params): """Build a month-by-month projection table.""" months = params["months_to_model"] monthly = calculate_referrals_per_month(params) new_per_month = monthly["new_customers_per_month"] costs = calculate_monthly_program_cost(params, new_per_month) ltv = params["ltv"] rows = [] cumulative_customers = 0 cumulative_cost = 0 cumulative_revenue = 0 for m in range(1, months + 1): cumulative_customers += new_per_month month_cost = costs["total_cost"] month_revenue = new_per_month * ltv cumulative_cost += month_cost cumulative_revenue += month_revenue cumulative_net = cumulative_revenue - cumulative_cost rows.append({ "month": m, "new_customers": round(new_per_month, 1), "cumulative_customers": round(cumulative_customers, 1), "monthly_cost": round(month_cost, 2), "cumulative_cost": round(cumulative_cost, 2), "monthly_ltv": round(month_revenue, 2), "cumulative_net": round(cumulative_net, 2), }) return rowsdef find_break_even_month(projection): for row in projection: if row["cumulative_net"] >= 0: return row["month"] return None# ---------------------------------------------------------------------------# Formatting# ---------------------------------------------------------------------------def format_currency(value): return f"${value:,.2f}"def format_pct(value): return f"{value:.1f}%"def print_report(params, results): monthly = results["monthly_referrals"] costs = results["monthly_costs"] cac = results["cac_via_referral"] roi = results["roi"] break_even_rate = results["break_even_referral_rate"] optimal_reward = results["optimal_reward"] projection = results["monthly_projection"] break_even_month = results["break_even_month"] paid_cac = params["cac"] ltv = params["ltv"] print("\n" + "=" * 60) print("REFERRAL PROGRAM ROI CALCULATOR") print("=" * 60) print("\n📊 INPUT PARAMETERS") print(f" LTV per customer: {format_currency(ltv)}") print(f" Current paid CAC: {format_currency(paid_cac)}") print(f" Active users: {params['active_users']:,}") print(f" Referral rate (monthly): {format_pct(params['referral_rate'] * 100)}") print(f" Referrals per referrer: {params['referrals_per_referrer']}") print(f" Referral conversion rate: {format_pct(params['referral_conversion_rate'] * 100)}") print(f" Referrer reward: {format_currency(params['referrer_reward'])}") print(f" Referred user reward: {format_currency(params['referred_reward'])}") print(f" Program overhead/month: {format_currency(params['program_overhead_monthly'])}") print("\n📈 MONTHLY PERFORMANCE (STEADY STATE)") print(f" Active referrers/month: {monthly['active_referrers']}") print(f" Referrals sent/month: {monthly['referrals_sent']}") print(f" New customers/month: {monthly['new_customers_per_month']}") print(f" Monthly program cost: {format_currency(costs['total_cost'])}") print(f" ↳ Reward cost: {format_currency(costs['reward_cost'])}") print(f" ↳ Overhead: {format_currency(costs['overhead_cost'])}") print(f" CAC via referral: {format_currency(cac)}") print(f" Paid CAC: {format_currency(paid_cac)}") savings_pct = ((paid_cac - cac) / paid_cac * 100) if paid_cac > 0 else 0 savings_label = f"{savings_pct:.0f}% cheaper than paid" if cac < paid_cac else "⚠️ More expensive than paid" print(f" CAC comparison: {savings_label}") print(f"\n💰 ROI OVER {params['months_to_model']} MONTHS") print(f" Total program cost: {format_currency(roi['total_cost'])}") print(f" Total LTV generated: {format_currency(roi['total_ltv_generated'])}") print(f" Net benefit: {format_currency(roi['net_benefit'])}") print(f" Program ROI: {format_pct(roi['roi_pct'])}") if break_even_month: print(f" Break-even: Month {break_even_month}") else: print(f" Break-even: Not reached in {params['months_to_model']} months") print("\n🎯 OPTIMIZATION INSIGHTS") if break_even_rate: current_rate = params["referral_rate"] rate_gap = break_even_rate - current_rate if rate_gap > 0: print(f" Break-even referral rate: {format_pct(break_even_rate * 100)} " f"(you're at {format_pct(current_rate * 100)} — need +{format_pct(rate_gap * 100)})") else: print(f" Break-even referral rate: {format_pct(break_even_rate * 100)} ✅ Already above break-even") else: print(f" Break-even referral rate: ⚠️ Reward alone exceeds target CAC — reduce reward or increase LTV") print(f"\n Optimal reward sizing (to keep CAC at ≤60% of paid CAC):") print(f" Max total reward/referral: {format_currency(optimal_reward['max_total_reward'])}") print(f" Recommended referrer: {format_currency(optimal_reward['recommended_referrer_reward'])}") print(f" Recommended referred user: {format_currency(optimal_reward['recommended_referred_reward'])}") print(f" Reward as % of LTV: {format_pct(optimal_reward['reward_as_pct_ltv'])}") current_total_reward = params["referrer_reward"] + params["referred_reward"] if current_total_reward > optimal_reward["max_total_reward"] and optimal_reward["max_total_reward"] > 0: print(f" ⚠️ Your current reward ({format_currency(current_total_reward)}) " f"exceeds optimal ({format_currency(optimal_reward['max_total_reward'])})") elif optimal_reward["max_total_reward"] > 0: print(f" ✅ Your current reward ({format_currency(current_total_reward)}) is within optimal range") print(f"\n📅 MONTHLY PROJECTION (first {min(6, len(projection))} months)") print(f" {'Month':>5} {'New Cust':>9} {'Cumul Cust':>11} {'Monthly Cost':>13} {'Cumul Net':>11}") print(f" {'-'*5} {'-'*9} {'-'*11} {'-'*13} {'-'*11}") for row in projection[:6]: net_str = format_currency(row["cumulative_net"]) if row["cumulative_net"] < 0: net_str = f"({format_currency(abs(row['cumulative_net']))})" print(f" {row['month']:>5} {row['new_customers']:>9.1f} {row['cumulative_customers']:>11.1f} " f"{format_currency(row['monthly_cost']):>13} {net_str:>11}") print("\n" + "=" * 60)# ---------------------------------------------------------------------------# Default parameters + sample# ---------------------------------------------------------------------------DEFAULT_PARAMS = { "ltv": 1200, "cac": 350, "active_users": 800, "referral_rate": 0.06, "referrals_per_referrer": 2.0, "referral_conversion_rate": 0.20, "referrer_reward": 50, "referred_reward": 30, "program_overhead_monthly": 200, "churn_rate_monthly": 0.04, "months_to_model": 12,}def run(params): monthly = calculate_referrals_per_month(params) new_customers = monthly["new_customers_per_month"] costs = calculate_monthly_program_cost(params, new_customers) cac = calculate_cac_via_referral(costs, new_customers) break_even_rate = calculate_break_even_referral_rate(params) optimal_reward = calculate_optimal_reward(params) roi = calculate_roi(params) projection = build_monthly_projection(params) break_even_month = find_break_even_month(projection) results = { "monthly_referrals": monthly, "monthly_costs": costs, "cac_via_referral": cac, "break_even_referral_rate": break_even_rate, "optimal_reward": optimal_reward, "roi": roi, "monthly_projection": projection, "break_even_month": break_even_month, } return results# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------def main(): import argparse parser = argparse.ArgumentParser( description="Calculates referral program ROI. " "Models economics given LTV, CAC, referral rate, reward cost, " "and conversion rate." ) parser.add_argument( "file", nargs="?", default=None, help="Path to a JSON file with referral program parameters. " "If omitted, reads from stdin or runs embedded sample." ) args = parser.parse_args() params = None if args.file: try: with open(args.file) as f: params = json.load(f) except Exception as e: print(f"Error reading file: {e}", file=sys.stderr) sys.exit(1) elif not sys.stdin.isatty(): raw = sys.stdin.read().strip() if raw: try: params = json.loads(raw) except Exception as e: print(f"Error reading stdin: {e}", file=sys.stderr) sys.exit(1) else: print("No input provided — running with sample parameters.\n") params = DEFAULT_PARAMS else: print("No input provided — running with sample parameters.\n") params = DEFAULT_PARAMS # Fill in defaults for any missing keys for k, v in DEFAULT_PARAMS.items(): params.setdefault(k, v) results = run(params) print_report(params, results) # JSON output json_output = { "inputs": params, "results": { "monthly_new_customers": results["monthly_referrals"]["new_customers_per_month"], "cac_via_referral": results["cac_via_referral"], "program_roi_pct": results["roi"]["roi_pct"], "break_even_month": results["break_even_month"], "break_even_referral_rate": results["break_even_referral_rate"], "optimal_total_reward": results["optimal_reward"]["max_total_reward"], "net_benefit_12mo": results["roi"]["net_benefit"], } } print("\n--- JSON Output ---") print(json.dumps(json_output, indent=2))if __name__ == "__main__": main()
Install this Skill
Skills give your AI agent a consistent, structured approach to this task — better output than a one-off prompt.