Never twice, never zero: retries and dedup in production
By the end of this lesson you will have alerts/state.json, committed by the workflow after every run, so that a second run on the same day sends nothing and spends nothing, a failed send goes out on the next run, and a missed day is caught up rather than skipped; plus one retry policy for 402, 429, 404 and 5xx.
What you will see: two runs. The first ends delivered: telegram, 1 message; the second says nothing new since <bar date>: 0 calls, and no second message arrives. In mock mode the second run also sends nothing, but it says nothing new since 2026-10-30 after its (free) fetch: the fixtures' newest bar is older than today, so the shortcut that skips the fetch cannot apply.
The idea: the job will run twice, and it will also miss
It runs twice when you press Run workflow after the scheduled run, re-run a failure, or a host fires one run twice, as Vercel says its cron can. It misses when GitHub drops a run under load, when a run dies halfway, and when the day's calls are gone. So: never twice, and never zero: a crossing that happened reaches you, late if it must.
An alert that fires 300 times is mute gave the tool, a key per firing: here <rule id>:<bar date>. Two runs on one evening compute the same key; a Tuesday run catching up on Monday computes Monday's. The run's own time is nowhere in it.
Send, then record
Record-then-send loses the alert if the job dies in between; send-then-record repeats it. For an alert you rely on, a rare duplicate beats a silent miss: mark the key pending, send, mark it sent, and resend anything pending next run. A run still sends one message, as in lesson 3, listing every key not yet sent, pending ones first, and records them sent together. For email, the keys of that message, sorted and joined, go in the Idempotency-Key header, which Resend remembers for 24 hours without sending twice. Telegram's Bot API documents no such key, so there the rare duplicate is a price you chose.
Where the state lives
Runs start on fresh machines, so the workflow commits alerts/state.json back. It needs permissions: contents: write; the checkout step leaves a token in place, so git push works; and a push with the workflow's own token starts no new runs. The workflow installs with npm ci --ignore-scripts, because plain npm ci runs the starter's prepare script, which switches on its git hooks, and the bot's git push would then run the whole pre-push gate, tests and a production build, on every run. The file holds ids, keys and dates, never prices: the repository is public, and nightly closes would be a copy of data you may not redistribute. If your default branch is protected and demands pull requests, the bot's push is refused and the run goes red: allow github-actions to bypass it, or ask your agent to keep the state on a branch of its own. Mock runs keep their own record in alerts/state.mock.json, which is gitignored, so the fixtures' fixed dates never reach the real one. Your local main falls behind a commit a day, so pull before you work.
State saves calls too, in two steps, and they share one model of the day. A trading date is the date in New York on a weekday; a weekend has none, so a weekend run (a manual one, since the schedule is weekdays only) prints no trading day and exits green for 0 calls; it never rolls back to Friday. On a weekday, a symbol whose last processed bar date is already today's trading date is skipped; if every symbol is, print nothing new since <date> and exit green for 0 calls. Otherwise fetch the rest, and if no bar is newer than the state's date (a holiday, or a mock run), print the same line and send nothing: that costs the fetch. Any newer bar is evaluated, oldest first, so a missed Monday is judged on Tuesday under Monday's key. Lesson 5 puts the trading-date rule into one tested function.
Retry what can succeed
| Answer | Meaning | The job |
|---|---|---|
| 402 | the day's calls are spent | stops; nothing until midnight GMT |
| 429 | over the per-minute limit | waits for Retry-After, retries once |
| 404 | no such ticker, still billed | no retry; names the rule; fails |
| 403 | the plan does not cover it | no retry |
| 5xx, timeout | upstream trouble | two retries, growing pause, then fails |
Instead of retrying a 402, add a second schedule: 20:30 New York is 00:30 UTC in summer and 01:30 in winter, after the reset, the same trading day, and free if the first run worked. Telegram's 429 carries a retry_after; same rule. Budget retries as calls.
Lesson 2's concurrency group keeps it to one run at a time; without it, two runs both send.
The prompt
Make the alert job idempotent. Plan first and list the failure cases you will test.
- alerts/state.json: per symbol, the last processed bar date; per key "<rule id>:<bar date>", status pending or sent and the date sent. No prices. Mock runs read and write alerts/state.mock.json instead, added to .gitignore, so fixture dates never reach the real state.
- One message per run, as before, listing every key not yet sent, pending ones first. Mark all of them pending, send, mark them sent together. For email, the Idempotency-Key header is those keys, sorted and joined.
- Trading date: the New York date on a weekday, none on a weekend. On a weekend, print "no trading day" and exit 0 with no calls. On a weekday, skip symbols whose last processed bar date is already today's trading date; if none is left, print "nothing new since <date>" and exit 0 with no calls. Otherwise fetch the rest, and if no bar is newer than the state's date, print the same line and send nothing. Evaluate every newer bar, oldest first.
- src/lib/alerts/retry.ts, sleep passed in and no clock read: 402 stops non-zero; 429 waits for Retry-After and retries once; 403 and 404 never retry and name the rule; 5xx and timeouts retry twice with a growing pause.
- Workflow: permissions contents: write; a second schedule at 30 20 * * 1-5 in America/New_York; install with npm ci --ignore-scripts, so the repository's git hooks are not switched on for the bot; after the alert step, a step with if: always() that commits alerts/state.json as github-actions[bot] when it changed, and pushes.
- Tests: two runs on the same data send once; a failed send goes out next run; a 402 is not retried; a missed day gets its own key; a Saturday run fetches nothing.
What the agent should do. New state.ts and retry.ts in src/lib/alerts, a test file, a line in .gitignore, four workflow changes. Check the state step: it must run when the alert step failed, because a half-finished run's record is what stops the next run repeating it.
Check it yourself
npm testpasses, with the four new cases.npm run alert:localin mock mode writesalerts/state.mock.json,git statusdoes not list it, andalerts/state.jsonis unchanged. Runnpm run alert:locala second time: it saysnothing new since 2026-10-30and sends nothing. Its price line still counts your symbols, because the fixtures' newest bar is older than today and the run has to fetch to find that out; the0 callsshortcut is for live runs.
The rest runs on GitHub, so commit, push the branch, open a pull request and merge it:
git status # the files you expect, and alerts/state.mock.json is not listed, and no .env file
git add -A
git commit -m "feat(alert): state, one send per crossing, catch-up, and a retry policy per status"
- Run the workflow twice. The second log says
nothing newand0 calls; one message arrives. git pull, thengit log --oneline -3 -- alerts/state.jsonshows the bot's commits.alerts/state.jsonholds ids, keys and dates, and not one price.- Set
TELEGRAM_CHAT_IDto a wrong number, delete one symbol's processed date in the state file, push and run: red. Restore the chat id and run again: the message arrives once.
Break it on purpose
Delete the concurrency block, clear one processed date, and press Run workflow twice quickly. Two messages arrive for one crossing. Put the block back.
Compare with ours
git fetch upstream, then git diff upstream/ref/runs-without-you/4.
Our version, on branch ref/runs-without-you/4
- run: npm ci --ignore-scripts
# ... the Alert step, as before ...
- name: Save state
if: always()
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add alerts/state.json
git diff --cached --quiet || git commit -m "chore(alert): state after run"
git push
--ignore-scripts keeps the starter's git hooks out of the bot's push; the bot identity is the one the checkout action's README uses; retry.ts is the table above as one loop.
Try it now
Checkpoint: the job can now run twice without harm.
- The commit you made for the checks is merged, and the bot's state commits follow it:
git fetch origin
git log --oneline -5 origin/main
- Write in
PLAN.mdwhich failure your channel accepts: a rare duplicate, or none. - Take the lesson check. It gives you a status code and asks whether to retry, wait or stop.