A background sync that only writes when something changes
How a scheduled Cloudflare job updates a Discord widget without wasting requests or giving up after errors.
My widget copies listening information to a Discord profile widget. It runs in the background on Cloudflare and wakes itself with an alarm. The goal is to stay current while sending as few writes as possible.
- Set a safety alarm
- Read the source
- Compare with last write
- Publish if different
- Schedule next run
Set the safety net first
Before doing any work, the job schedules a recovery alarm a minute ahead. If the run crashes partway, another one will still happen. A successful run then replaces that alarm with the normal interval.
Compare before writing
The outgoing data is turned into a string and compared with the last version that was published. If they are identical, nothing is sent. Most checks end here.
const signature = JSON.stringify(data);
if (signature !== previous.signature) {
await client.publish(data);
}
Slowing down when asked
When the service returns a retry delay, the job waits at least that long and also lengthens its normal interval, with an upper limit. Other errors wait five minutes. This avoids hammering a service that is already struggling.
No overlapping runs
If a tick arrives while the previous one is still working, it receives the same pending promise instead of starting a second run:
return (running ??= run().finally(() => {
running = null;
}));
Honest status
The job records when it last read the source and when it last wrote to Discord as separate times. If no check has happened well past the expected delay, the status is reported as stale instead of running. A failure to fetch lyrics is allowed to pass, because the rest of the widget is still useful without them.