Sub topic 10
Choosing content: rules, next best action and bandits
This chapter assumes you know what a segment is, how a content template with fallbacks works, and basic click-rate arithmetic. You should also be able to read short Python functions. By the end you will be able to decide when to pick content with fixed rules, when to rank options by expected value, and when to let a bandit learn the choice from live traffic.
The decisioning problem
Segments tell you who a customer resembles. Content modules tell you what you can show. Decisioning is the step in between: for this customer, in this moment, which module do we send?
Three approaches cover most production systems:
- Rules map conditions directly to content. A person writes them, and they do the same thing every time.
- Next best action (NBA) scores every eligible option for a customer and picks the highest. The scores usually come from predictive models.
- Bandits choose among options and update their estimates after each outcome, so the choice improves while the campaign runs.
These are not exclusive. Most mature programmes layer them, as the diagram shows.
The last box matters more than it looks. Without a log of what was chosen, why, and what happened, you cannot test, debug or audit any of the three approaches.
Rules
A rule is an if-then statement over customer attributes. For example: if the segment is lapsed and the customer has an abandoned basket, send the basket reminder.
Rules are the right tool when:
- The logic is a business or legal requirement. Examples are "never show alcohol offers to under-18s" and "suppress marketing for customers who withdrew consent".
- You have no data yet. A new product has no click history for a model to learn from.
- Stakeholders need to read and approve the logic.
Rules fail in predictable ways. They accumulate: after a year you have 200 rules, and nobody knows which fires first. They go stale, because a threshold such as "inactive for 30 days" was chosen once and never revisited. They also conflict, because two rules can match the same customer.
Two habits keep rules manageable. Give every rule an explicit priority number, and write down the winner when several match. Always end the list with a default that matches everyone.
Next best action
NBA turns the question into scoring. For each candidate action you estimate something like the expected value of showing it to this customer, then pick the maximum.
A common formula is:
expected value = probability of response × value if they respond
The probability comes from a predictive model, such as the propensity models from the earlier chapter. The value comes from margin, lifetime value, or a flat business estimate.
NBA is usually built in two stages. First, eligibility filters remove actions that must not be shown. Then scoring ranks what is left. Keeping these stages separate prevents a high-scoring but forbidden action from slipping through.
def next_best_action(customer, actions, default="brand_newsletter"):
"""Return the name of the eligible action with the highest expected value."""
eligible = [
a for a in actions
if a["required_consent"] in customer["consents"]
and customer["contacts_last_7d"] < a["weekly_cap"]
]
if not eligible:
return default
def expected_value(action):
probability = customer["propensity"].get(action["name"], 0.0)
return probability * action["value"]
return max(eligible, key=expected_value)["name"]
actions = [
{"name": "win_back_offer", "required_consent": "email_marketing",
"weekly_cap": 2, "value": 30.0},
{"name": "loyalty_points", "required_consent": "email_marketing",
"weekly_cap": 1, "value": 12.0},
{"name": "service_reminder", "required_consent": "service_messages",
"weekly_cap": 3, "value": 5.0},
]
customer = {
"consents": {"email_marketing"},
"contacts_last_7d": 1,
"propensity": {"win_back_offer": 0.05, "loyalty_points": 0.20},
}
print(next_best_action(customer, actions))Here win_back_offer has an expected value of 0.05 × 30 = 1.50 and loyalty_points has 0.20 × 12 = 2.40. But loyalty_points has a weekly cap of 1 and this customer has already received one contact, so it is filtered out. The function returns win_back_offer. The consent filter removes service_reminder. If both marketing actions were filtered out, the function would return the default.
NBA has its own risks:
- Model scores are only as good as the training data. A propensity model trained on past campaigns learns who was targeted before, not only who responds.
- Scores from different models are not always comparable. A churn probability and a purchase probability on the same scale can still be calibrated differently.
- Pure ranking never explores. If the model underrates an action, it will rarely be shown, so the model never gets the data to correct itself.
That last point is what bandits address.
Bandits
A multi-armed bandit treats each content option as an "arm" and balances two goals: exploiting the option that looks best so far, and exploring others to improve your estimates. A fixed A/B test explores for a set period and then you act on the result. A bandit shifts traffic toward winners continuously.
The simplest version is epsilon-greedy. With probability epsilon (often 0.05 to 0.1) it picks a random option. Otherwise it picks the option with the best observed click rate.
import random
def choose_variant(stats, epsilon=0.1, rng=random):
"""stats maps variant name to {'sends': int, 'clicks': int}."""
if rng.random() < epsilon:
return rng.choice(list(stats))
return max(stats, key=lambda v: stats[v]["clicks"] / max(stats[v]["sends"], 1))
def record(stats, variant, clicked):
stats[variant]["sends"] += 1
stats[variant]["clicks"] += int(clicked)
true_rates = {"discount_banner": 0.08, "new_arrivals": 0.12}
stats = {name: {"sends": 0, "clicks": 0} for name in true_rates}
rng = random.Random(7)
for _ in range(5000):
variant = choose_variant(stats, epsilon=0.1, rng=rng)
record(stats, variant, rng.random() < true_rates[variant])
for name, s in stats.items():
rate = s["clicks"] / s["sends"] if s["sends"] else 0.0
print(name, s["sends"], round(rate, 3))The simulation knows the true click rates, which a real system never does. It is a way to check that the selection logic shifts traffic toward new_arrivals over time. Because rng is seeded, the run is repeatable.
Notice what happens at the start. Both variants have zero sends and a score of 0, so the greedy branch picks whichever comes first in the dictionary. If that variant gets an early click, it can lead for a long time. Epsilon is the only thing that rescues the other variant, which is why epsilon must not be zero.
Beyond epsilon-greedy
Epsilon-greedy wastes traffic: it keeps exploring at the same rate even after one option is clearly worse. Two common improvements:
- Thompson sampling keeps a probability distribution over each option's true rate and samples from it. Options that are uncertain get explored more, and clearly poor ones fade out on their own.
- Contextual bandits use customer features (segment, device, time of day) so the best option can differ by context. This is the bridge between bandits and NBA.
Bandit gotchas
- Delayed feedback. A purchase may arrive days after the email. If you update on clicks only, the bandit optimises clicks, which may not match revenue.
- Non-stationarity. The best option in December is not the best in March. Use a decay or a sliding window so old data fades.
- Interference with measurement. A bandit gives unequal traffic across options, which makes clean comparison harder. Keep a randomised holdout outside the bandit, as covered in the experimentation chapter.
- Cold-start options. A new variant with zero sends can never win the greedy comparison. Give new arms a minimum number of exposures.
Choosing between them
| Situation | Best fit | Why |
|---|---|---|
| Legal, consent or brand requirement | Rules | Must be deterministic and auditable |
| New product, no history | Rules, then a bandit | Rules give a safe start, a bandit gathers data |
| Many customers, several candidate offers, trained models | NBA | Ranks by expected value per customer |
| Few content variants, fast feedback (clicks) | Bandit | Learns quickly and needs no model |
| Slow or sparse outcomes (annual renewals) | Rules or NBA | Bandits starve for feedback |
| Need to prove incremental effect | Rules plus randomised holdout | Cleanest comparison |
Common errors
- Optimising the wrong metric. Click rate rises when subject lines get more sensational, but purchases may not. Pick a reward that is close to the business goal.
- No default path. If every rule fails or the scoring service times out, the customer should still receive something sensible.
- Mixing exploration with mandatory messages. Transactional or legal messages must not go through a bandit.
- Declaring a winner too early. Early rates are noisy. With 20 sends and 3 clicks, the true rate could plausibly be anywhere from about 4% to 36%.
- Feedback loops. If NBA keeps showing one offer to a segment, that offer collects most of the data and looks best simply because it is well measured.
Exercise
A retailer has 200 sends of variant A with 18 clicks, and 180 sends of variant B with 25 clicks. The system uses epsilon-greedy with epsilon = 0.1 and two variants. Roughly what share of sends will go to each variant at the next decision, and why would setting epsilon to 0 be a risk even though B looks better?
Show answer
A has a click rate of 18/200 = 9% and B has 25/180 ≈ 13.9%, so B is the greedy choice. With probability 0.9 the system picks B. With probability 0.1 it picks randomly between A and B, so each gets 0.05. B therefore receives about 95% of sends and A about 5%. With epsilon = 0 the system never sends A again. If B's lead is only early noise, or if A would improve after a seasonal change, the system would never find out, because A can no longer gather new data.