Issue
I am building a discord bot on cloudflare workers for setting reminders. I am using the interactions webhook api using discord's cloudflare template. I have one route for receiving interactions which sets the reminder data to a db (probably KV). I have another route that reads from the db at the specified time and reminds the user. How do I run the second route at the user specified time?
I have thought of using a cron job that runs every minute and checks the db but there's two problems:
- It would incur a lot of useless requests when there are no reminders in db
- (less important) Seconds precision is not possible
Solution
This is a great use case for Durable Objects, and in particular, Durable Objects alarms.
You'd design your worker to forward all requests to a singleton Durable Object. In the DO, you can track your state using DO storage, which is faster and cheaper than Workers KV. When you need to schedule an event at a precise time in the future, you'd set an alarm on the DO. This causes the DO to wake up at that time and invoke the alarm handler, where you can do whatever you need.
Note that a single object can only have one alarm at a time. So you'd always set the alarm for the earliest event. In the alarm handler, you set a new alarm for the next event. Etc.
If this service is intended to be for multiple users, you'd probably want to create a separate Durable Object for each user. That way, you can scale to millions of users with no trouble, and you can cleanly separate each user's data. Durable Objects are designed to be fine-grained so there's no problem with creating lots of them.
Answered By - Kenton Varda Answer Checked By - Marilyn (WPSolving Volunteer)