← All writing

Birthdays on a budget

My bot runs every five minutes with a fixed number of calls to Discord. On a busy day it ran out halfway through the birthdays, and wrote everyone down as done anyway. Some people never got their role.

·2 min read

My Discord bot does its background work in one run every five minutes: scheduled posts, timed roles, giveaways, reminders, birthdays. It runs on Cloudflare’s free plan, and Discord limits how fast a bot may call it. So each run has a budget: 46 calls to Discord, shared by every job, for every server.

Each job gets a slice. Birthdays get what’s left of theirs, often less than ten.

What a birthday costs

For one server on one day:

  • one post in the birthday channel, shared by everyone whose day it is
  • one extra post for anyone the staff wrote a personal message for
  • one call per person to give the birthday role

Three people with the role on is four or five calls. Fine. Until the budget for this run is already nearly spent.

The bug

The old code went like this:

  1. find everyone whose birthday it is and who isn’t written down as done this year
  2. send the posts, while there’s budget
  3. give the roles, while there’s budget
  4. write everyone down as done

Step 4 didn’t look at steps 2 and 3. If the calls ran out after the first role, the others were still marked done. The next run skipped them, because they were done. They never got the role. Someone with a personal message might never get their post.

There was a second way to go wrong. If Discord answered “slow down” in the middle, the run stopped before step 4, with nobody written down. Five minutes later the whole list ran again, and the people who were already wished got wished twice.

One job, two opposite failures: skipped on a busy day, doubled on a slow one.

The fix

Two changes.

Only take what this run can pay for. Before doing anything, count what each person costs and stop adding people when the budget is gone. The rest stay not-done and wait five minutes. A birthday wish five minutes late is fine. One that never comes is not.

Write each thing down as it goes out. The post is sent, then its people are marked. The role is given, then that person’s role is saved. If the run stops anywhere, what’s written down is exactly what happened.

The test

A server, two birthdays, a role, and a budget of two calls: room for one post and one role.

After the first run: one post, naming one person. That person has the role. One name written down.

After the second run: a second post for the other one, and their role.

After the third: nothing new. Once a year each.

The general shape

A job with a budget has to answer one question honestly: what did I actually finish? Marking the whole batch done at the end is a guess. It’s right when nothing goes wrong, which is exactly when nobody is checking.