Sub topic 11
Rolling out and automating the sunset flow
This chapter turns the sunset policy into a flow that runs on a schedule without surprising you. It assumes you already have a written policy with an engagement definition, an inactivity window, a re-engagement step, and a list of exceptions. It also assumes you can read basic SQL and Python, and that your email service provider (ESP) lets you suppress addresses and trigger sends through an API or a segment export.
Why roll out in phases
A sunset policy that looks correct on paper can still suppress far more people than you expect. The usual causes are missing click data, a tracking change, or an exception that was never encoded. Suppression is reversible if you keep records, but a bad run still costs you reach and revenue until someone notices. Phased rollout limits the cost of finding those mistakes.
Use four phases, and move on only when the current one gives numbers you can explain.
- Report only. Run the candidate query and the stage function against production data. Send nothing and change nothing. Compare the counts with your expectations.
- Re-engagement pilot. Send the re-engagement message to a small slice, for example 5 to 10 percent of candidates chosen at random. Confirm that the tracking, the landing page, and the "stay subscribed" action all work.
- First suppression. After the grace period for the pilot slice ends, suppress only that slice. Check complaint, bounce, and revenue numbers against a comparable group that was not touched.
- Full automation. Enable the scheduled job for everyone, with the guardrails described below.
The first full run has a special problem. On day one, a large share of your list may already be past the window. Processing them all at once gives you one huge re-engagement send, which is a sudden volume spike that can itself hurt deliverability. Work through the backlog in batches over several weeks.
The flow as a state machine
Each subscriber is in exactly one stage on any given day. The scheduled job computes the stage, then performs the action that the stage requires. Re-engagement and suppression are the only stages that cause side effects.
Two properties of this design matter for automation.
- The stage is derived, not stored. You store the facts (when the person subscribed, when they last engaged, when the re-engagement message was sent) and compute the stage from them each run. If the job fails halfway, the next run recomputes the same answer, so you never repair a half-updated stage column.
- Engagement resets everything. A click during the waiting period moves the person back to active. In the stage function this happens because
last_engaged_atbecomes newer than the window. You should also decide whether a stalereengagement_sent_atshould be cleared. If you keep it, a person who engages and then goes quiet again within 30 days of that old timestamp could be suppressed without a fresh re-engagement message. Clear it, or store a campaign id, so that each inactivity episode gets its own message.
A daily job you can run
The following script contains the stage function from the policy chapter, a planning step, a guardrail, and an apply step. It uses in-memory data so you can run it as shown. In production you would load subscribers from your database and replace the marked lines with ESP calls. It needs Python 3.10 or later.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass
class Subscriber:
id: int
email: str
subscribed_at: datetime
last_engaged_at: datetime | None
reengagement_sent_at: datetime | None
exempt: bool = False
status: str = "subscribed"
def sunset_stage(
subscribed_at: datetime,
last_engaged_at: datetime | None,
reengagement_sent_at: datetime | None,
now: datetime,
window_days: int = 180,
grace_days: int = 30,
) -> str:
reference = last_engaged_at or subscribed_at
if now - reference < timedelta(days=window_days):
return "active"
if reengagement_sent_at is None:
return "send_reengagement"
if now - reengagement_sent_at < timedelta(days=grace_days):
return "waiting"
return "suppress"
STAGES = ["active", "send_reengagement", "waiting", "suppress"]
def plan(subscribers, now, max_suppress_share=0.05, daily_send_cap=500):
buckets = {stage: [] for stage in STAGES}
skipped = 0
for sub in subscribers:
if sub.status != "subscribed":
continue
if sub.exempt:
skipped += 1
continue
stage = sunset_stage(
sub.subscribed_at, sub.last_engaged_at, sub.reengagement_sent_at, now
)
buckets[stage].append(sub)
eligible = sum(len(v) for v in buckets.values())
if eligible and len(buckets["suppress"]) / eligible > max_suppress_share:
raise RuntimeError(
f"Guardrail: {len(buckets['suppress'])} of {eligible} would be "
f"suppressed, above the {max_suppress_share:.0%} limit. Aborting."
)
buckets["send_reengagement"] = buckets["send_reengagement"][:daily_send_cap]
return buckets, skipped
def apply(buckets, now, dry_run=True):
for sub in buckets["send_reengagement"]:
if not dry_run:
# Replace with your ESP call to send the re-engagement message.
sub.reengagement_sent_at = now
for sub in buckets["suppress"]:
if not dry_run:
# Replace with your ESP call to add the address to the suppression list.
sub.status = "suppressed"
def run(subscribers, now, dry_run=True, **limits):
buckets, skipped = plan(subscribers, now, **limits)
for stage in STAGES:
print(f"{stage}: {len(buckets[stage])}")
print(f"exempt_skipped: {skipped}")
apply(buckets, now, dry_run=dry_run)
if __name__ == "__main__":
utc = timezone.utc
now = datetime(2026, 11, 26, tzinfo=utc)
old = datetime(2025, 1, 1, tzinfo=utc)
stale = datetime(2025, 12, 1, tzinfo=utc)
people = [
Subscriber(1, "[email protected]", old, datetime(2026, 10, 1, tzinfo=utc), None),
Subscriber(2, "[email protected]", old, None, None),
Subscriber(3, "[email protected]", old, stale, datetime(2026, 11, 10, tzinfo=utc)),
Subscriber(4, "[email protected]", old, stale, datetime(2026, 9, 1, tzinfo=utc)),
Subscriber(5, "[email protected]", old, stale, datetime(2026, 9, 1, tzinfo=utc), exempt=True),
]
run(people, now, dry_run=True, max_suppress_share=0.5)Running it prints one line per stage:
active: 1
send_reengagement: 1
waiting: 1
suppress: 1
exempt_skipped: 1The dry run changes nothing. Pass dry_run=False and the same plan is applied. Subscriber 5 would otherwise be suppressed, but the exempt flag removes them before the stage is computed.
Guardrails that belong in the job
The guardrail in plan is the most important line in the script. Automation makes mistakes fast, so build in limits that stop a bad run before it does damage.
- Maximum suppression share. If one run would suppress more than a set share of the list (the example uses 5 percent), the job aborts and alerts a person. A sudden spike usually means the engagement data is broken, not that your subscribers all lost interest at once.
- Daily send cap. The cap on re-engagement sends controls volume and lets you drain a backlog gradually. A cap of a few hundred is typical for a small list. For a large one, size it as a small fraction of your normal daily volume.
- Freshness check on the data. Before computing stages, confirm that click and purchase events arrived recently. If your event pipeline stalled for a week, everyone looks inactive. Compare the newest
occurred_atin the events table against the current time and abort if the gap is longer than a day or two. - Dry-run flag and kill switch. Keep a configuration value that forces dry-run mode. Turning the flow off should not require a code deploy.
- Exceptions applied first. New subscribers, transactional-only contacts, and seasonal senders' contacts should be removed before the stage is computed, as shown by the
exemptflag. Computing the stage first and filtering later invites a bug where one code path forgets the filter.
Scheduling and ordering
Run the job once a day, at a quiet hour, after the engagement events for the previous day have loaded. Daily is enough for a 180-day window. A faster schedule adds load without changing outcomes.
Within one run, handle stages in this order: compute stages, check guardrails, suppress, then send. Suppressing first means that a failure in the send step cannot cause an address that should be gone to receive another message. If your ESP separates suppression from sending, also confirm that the re-engagement message is excluded from your suppression list by design. Otherwise the suppression list would block the very message meant to win people back.
Keep a log row for every action: subscriber id, stage, action, timestamp, and the policy version. This log is what the record-keeping chapter relies on, and it lets you answer "why was this person suppressed?" months later.
Common failure modes
| Problem | Typical cause | Prevention |
|---|---|---|
| Large share of the list suppressed in one run | Click tracking broke, or event table is stale | Freshness check and maximum suppression share |
| Same person gets the re-engagement message twice | Job retried and `reengagement_sent_at` was not saved | Write the timestamp as part of the send, and exclude anyone who has one |
| Customers who just purchased get suppressed | Purchases not included in the engagement definition | Query clicks and purchases together, as in the candidate query |
| Naive and aware datetimes raise an error | Database returns UTC-aware values, script uses local time | Use timezone-aware UTC everywhere |
| Re-engagement message blocked | Suppression list applied to that send | Build the send segment from stage, not from the suppression list alone |
| Seasonal buyers removed before their season | Window shorter than the gap between purchases | Exception rule for those contacts, set before rollout |
Watching the rollout
During the first weeks, check a small dashboard each day. These numbers tell you whether the flow behaves as designed.
- Counts per stage and per day, so a change in the backlog is visible.
- Re-engagement click rate and the share who stay subscribed. A very low rate is normal. A rate of exactly zero suggests a broken link or tracking.
- Unsubscribe and complaint rates on the re-engagement message. They are usually higher than on regular mail, so compare against previous re-engagement sends, not your newsletter.
- Hard bounce and complaint rates on your regular sends, which should fall over several weeks as the suppressed group leaves.
Give the effect time to appear. Mailbox providers adjust their view of a sender gradually, so judging results after a few days will mislead you. The next chapter covers how to measure deliverability and revenue changes properly, including how to hold out a comparison group.
Exercise
Your daily job reports that 31 percent of the list would be suppressed today, up from 0.4 percent yesterday. The guardrail limit is 5 percent. Name two likely causes you would check before touching the limit, and say what you would do with the job in the meantime.
Show answer
Likely causes are a stalled or broken engagement event pipeline (check the newest occurred_at in the events table) and a change in click tracking, such as a domain or link-wrapping change that stopped recording clicks. A bad deploy that changed the window or dropped the purchase event type would also produce this. Leave the job aborted, or keep it in dry-run mode, until the cause is found and fixed. Raising the limit would hide the problem and suppress people who are actually engaged.
Exercise
A subscriber clicked a link on day 10 of the 30-day grace period, then went quiet again. Ninety days later their last click is 100 days old and their old reengagementsentat is 120 days old. What does sunset_stage return today, and what rule would you add so they get a fresh chance?
Show answer
The last click is 100 days old, which is inside the 180-day window, so sunsetstage returns "active" today. Once the window passes, the old reengagementsentat would be more than 30 days old, so the function would return "suppress" without a new message. To prevent that, clear reengagementsent_at when the person engages, or store a campaign id with each send so every inactivity episode gets its own re-engagement message.