id: braze-frequency-throttle-guard
namespace: company.team
description: |
Braze will happily launch a campaign into an audience that already received three messages this week, and the first complaint arrives days later as an unsubscribe spike. A keyed webhook carrying the campaign id, name and target segment starts the launch review with a disabled daily schedule as the safety net, the Braze campaign list is pulled with a bearer key and a local fixture of per-user weekly sends stands in when the API returns nothing usable, and a Python pass counts the users whose weekly sends plus the new campaign would exceed the cap. When the throttle trips and the run is not a dry run the owner is emailed and the per-segment headroom is posted to Slack, otherwise the quiet verdict is logged. The verdict, the capped user count, the segment headroom list and the blocked flag are published as outputs, and any failure escalates to Slack.
triggers:
- id: campaign_launch_approval
type: io.kestra.plugin.core.trigger.Webhook
description: POST a campaign launch approval here with campaign_id, name and
segment so the guard can check the audience before anyone hits send.
key: "{{ secret('BRAZE_APPROVAL_WEBHOOK_KEY') }}"
- id: daily_frequency_review
type: io.kestra.plugin.core.trigger.Schedule
description: Daily 06:00 UTC review of every live campaign, shipped disabled so
no launch is throttled until an operator reads the thresholds and switches
it on.
cron: "0 6 * * *"
disabled: true
inputs:
- id: weekly_cap
type: INT
defaults: 3
description: How many messages one user may already have received this week
before the new campaign pushes them over the frequency limit.
- id: campaign_sends
type: INT
defaults: 1
description: How many messages this campaign adds per user, a single launch
email adds one and a drip step can add more.
- id: dry_run
type: BOOL
defaults: true
description: Report only while true, switch it to false to let the gate email
the owner and post the Slack alert.
tasks:
# --- 1. frequency workspace ---
- id: frequency_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the send fixture, the Braze response and
the cap analysis all read the same files for the whole review.
tasks:
# --- 2. send fixture ---
- id: write_sends_fixture
type: io.kestra.plugin.scripts.shell.Commands
description: Write a deterministic three user fixture with a heredoc, weekly
sends of two, four and five, so the cap check still has data when the
Braze API is unreachable.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
entryPoint: []
containerImage: alpine:3.20
outputFiles:
- weekly_sends.json
commands:
- |
set -u
cat > weekly_sends.json <<'JSON'
{
"as_of": "2026-01-06",
"users": [
{"user_id": "u-alice", "weekly_sends": 2, "segment": "loyal-readers"},
{"user_id": "u-bravo", "weekly_sends": 4, "segment": "loyal-readers"},
{"user_id": "u-charlie", "weekly_sends": 5, "segment": "trial-nurture"}
]
}
JSON
echo "wrote $(wc -c < weekly_sends.json) bytes of weekly send counts"
# --- 3. braze campaign list ---
- id: fetch_braze_campaigns
type: io.kestra.plugin.core.http.Request
description: GET the Braze campaign list with a bearer key and absorb a non 2xx
answer, so an API problem hands the decision to the fixture instead of
failing the launch review.
method: GET
uri: "https://rest.braze.com/messages/campaigns/list"
headers:
Authorization: "Bearer {{ secret('BRAZE_API_KEY') }}"
Accept: application/json
options:
allowFailed: true
followRedirects: true
timeout: PT30S
# --- 4. cap analysis ---
- id: analyze_frequency
type: io.kestra.plugin.scripts.python.Script
description: Read the Braze response or the fixture, project each user's weekly
sends plus this campaign against the cap, and emit verdict,
capped_users, segments and blocked through the outputs protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
WEEKLY_CAP: "{{ inputs.weekly_cap }}"
CAMPAIGN_SENDS: "{{ inputs.campaign_sends }}"
CAMPAIGN_ID: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).campaign_id
?? '') }}"
CAMPAIGN_NAME: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).name ??
'') }}"
CAMPAIGN_SEGMENT: "{{ trigger is not defined ? '' : ((trigger.body ??
{}).segment ?? '') }}"
BRAZE_BODY: "{{ (outputs.fetch_braze_campaigns.body ?? '') | json }}"
script: |
import json
import os
FIXTURE = "weekly_sends.json"
def as_int(value, fallback):
try:
return int(str(value).strip())
except (TypeError, ValueError):
return fallback
def loads_payload(raw):
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
try:
parsed = json.loads(text)
except ValueError:
return None
if isinstance(parsed, str):
try:
parsed = json.loads(parsed)
except ValueError:
return None
if isinstance(parsed, (dict, list)):
return parsed
return None
def extract_users(document):
rows = document.get("users") if isinstance(document, dict) else document
if not isinstance(rows, list):
return None
users = []
for row in rows:
if not isinstance(row, dict):
continue
try:
weekly = int(row.get("weekly_sends"))
except (TypeError, ValueError):
continue
user_id = str(row.get("user_id") or "").strip() or "unknown-user"
segment = str(row.get("segment") or "").strip() or "unassigned"
users.append({"user_id": user_id, "weekly_sends": weekly, "segment": segment})
return users or None
cap = as_int(os.environ.get("WEEKLY_CAP"), 3)
campaign_sends = as_int(os.environ.get("CAMPAIGN_SENDS"), 1)
campaign_id = (os.environ.get("CAMPAIGN_ID") or "").strip()
campaign_name = (os.environ.get("CAMPAIGN_NAME") or "").strip()
campaign_segment = (os.environ.get("CAMPAIGN_SEGMENT") or "").strip()
document = loads_payload(os.environ.get("BRAZE_BODY"))
users = extract_users(document)
source = "braze_api" if users else "fixture"
if not users:
fixture_text = ""
if os.path.exists(FIXTURE) and os.path.getsize(FIXTURE) > 0:
try:
with open(FIXTURE, "r", encoding="utf-8") as handle:
fixture_text = handle.read()
except OSError:
fixture_text = ""
users = extract_users(loads_payload(fixture_text))
source = "fixture" if users else "none"
if isinstance(document, dict):
for entry in document.get("campaigns") or []:
if not isinstance(entry, dict):
continue
if campaign_id and str(entry.get("id") or "") == campaign_id:
campaign_name = campaign_name or str(entry.get("name") or "")
campaign_segment = campaign_segment or str(entry.get("segment") or "")
break
segments = {}
if campaign_segment:
segments[campaign_segment] = {
"segment": campaign_segment,
"users": 0,
"capped_users": 0,
"max_projected": 0,
"headroom": cap,
}
capped_users = 0
for user in users or []:
projected = user["weekly_sends"] + campaign_sends
entry = segments.setdefault(user["segment"], {
"segment": user["segment"],
"users": 0,
"capped_users": 0,
"max_projected": 0,
"headroom": cap,
})
entry["users"] += 1
if projected > entry["max_projected"]:
entry["max_projected"] = projected
if projected > cap:
capped_users += 1
entry["capped_users"] += 1
for entry in segments.values():
entry["headroom"] = cap - entry["max_projected"]
segment_list = [segments[name] for name in sorted(segments)]
if not users:
verdict = "NO_SEND_DATA"
elif capped_users > 0:
verdict = "THROTTLE_REQUIRED"
else:
verdict = "CLEAR_TO_LAUNCH"
blocked = bool(capped_users > 0)
print("source=%s campaign=%s cap=%d campaign_sends=%d users=%d capped=%d segments=%d verdict=%s" % (
source, campaign_id or "unnamed", cap, campaign_sends,
len(users or []), capped_users, len(segment_list), verdict))
print("::" + json.dumps({"outputs": {
"verdict": verdict,
"capped_users": capped_users,
"segments": segment_list,
"blocked": blocked,
}}) + "::")
# --- 5. throttle gate ---
- id: frequency_gate
type: io.kestra.plugin.core.flow.If
description: Branch when the launch would push users past the cap and the run is
not a dry run, so only a real throttle emails the owner and pings the
channel.
condition: "{{ outputs.analyze_frequency.vars.capped_users > 0 and not
inputs.dry_run }}"
then:
# --- 6. segment headroom ---
- id: log_segment_headroom
type: io.kestra.plugin.core.flow.Loop
description: Walk every segment once and log its projected peak against the cap,
so the execution history shows exactly where the headroom went.
values: "{{ outputs.analyze_frequency.vars.segments }}"
concurrencyLimit: 1
tasks:
- id: log_headroom
type: io.kestra.plugin.core.log.Log
description: Record the current segment's peak projected sends, remaining
headroom and capped user count for the execution history.
message: "Cap headroom for segment {{ item.segment }} - peak projected {{
item.max_projected }} of the {{ inputs.weekly_cap }} send cap this
week, headroom {{ item.headroom }}, {{ item.capped_users }} of {{
item.users }} user(s) over."
# --- 7. owner email ---
- id: notify_owner
type: io.kestra.plugin.email.MailSend
description: Email the launch owner the verdict, the capped user count and the
segment list, so the campaign can be held or the audience split before
anyone hits send.
host: "{{ secret('SMTP_HOST') }}"
port: 465
username: "{{ secret('SMTP_USERNAME') }}"
password: "{{ secret('SMTP_PASSWORD') }}"
from: "{{ secret('SMTP_FROM') }}"
to: "{{ secret('LAUNCH_OWNER_EMAIL') }}"
subject: "Braze launch throttled - {{
outputs.analyze_frequency.vars.capped_users }} user(s) over the {{
inputs.weekly_cap }} send weekly cap"
htmlTextContent: |
<p>{{ secret('LAUNCH_OWNER_EMAIL') }},</p>
<p>Campaign <strong>{{ trigger is not defined ? 'the daily review' : ((trigger.body ?? {}).name ?? 'the daily review') }}</strong>
is held by the frequency guard. <strong>{{ outputs.analyze_frequency.vars.capped_users }}</strong> user(s)
already have enough weekly sends that adding this campaign of {{ inputs.campaign_sends }} message(s)
would pass the cap of {{ inputs.weekly_cap }}.</p>
<p>Verdict <strong>{{ outputs.analyze_frequency.vars.verdict }}</strong>, blocked
<strong>{{ outputs.analyze_frequency.vars.blocked }}</strong>.</p>
<pre>{{ outputs.analyze_frequency.vars.segments | toJson }}</pre>
<p>Split the segment, delay the send, or raise the cap input if this launch should go out anyway.
Execution {{ execution.id }}</p>
# --- 8. channel alert ---
- id: alert_throttle
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the lifecycle marketing channel that the launch is throttled,
with the capped user count and the number of segments that lost
headroom.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Braze frequency guard - {{ outputs.analyze_frequency.vars.verdict }} for campaign {{ trigger is not defined ? 'daily review' : ((trigger.body ?? {}).campaign_id ?? 'daily review') }}. {{ outputs.analyze_frequency.vars.capped_users }} user(s) would pass the {{ inputs.weekly_cap }} send weekly cap, blocked {{ outputs.analyze_frequency.vars.blocked }}. Segment headroom logged for {{ outputs.analyze_frequency.vars.segments | length }} segment(s), owner emailed. Execution {{ execution.id }}."
}
else:
# --- 9. clear or dry run ---
- id: log_no_throttle
type: io.kestra.plugin.core.log.Log
description: Record the quiet outcome so the execution history still proves the
review ran and why no notification was sent.
message: "Frequency guard - verdict {{ outputs.analyze_frequency.vars.verdict
}}, capped_users {{ outputs.analyze_frequency.vars.capped_users }},
blocked {{ outputs.analyze_frequency.vars.blocked }}, dry_run {{
inputs.dry_run }}, no notification sent."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: verdict
type: STRING
description: THROTTLE_REQUIRED when the launch would push users past the cap,
CLEAR_TO_LAUNCH when the audience still has headroom, NO_SEND_DATA when no
weekly send counts could be read.
value: "{{ outputs.analyze_frequency.vars.verdict }}"
- id: capped_users
type: INT
description: Number of users whose weekly sends plus this campaign would exceed
the cap, for example 2 against fixture sends of two, four and five.
value: "{{ outputs.analyze_frequency.vars.capped_users }}"
- id: segments
type: ARRAY
description: 'Segment headroom entries as objects, for example [{"segment":
"loyal-readers", "users": 2, "capped_users": 1, "max_projected": 5,
"headroom": -2}].'
value: "{{ outputs.analyze_frequency.vars.segments | toJson }}"
- id: blocked
type: BOOL
description: True when at least one user would exceed the cap, independent of
dry run, so downstream systems can branch on the frequency verdict alone.
value: "{{ outputs.analyze_frequency.vars.blocked }}"