Discuss your project

Blog

A free uptime monitor on a Cloudflare Worker, with Telegram alerts

Mher Poghosyan · 29 November 2026 · 8 min read

We run n8n and a few other internal services on one machine with Docker Compose, published through Cloudflare Tunnel, with an encrypted offsite backup to Cloudflare R2 every night (how we set that up). That raises two questions we want answered without looking: is the machine still serving, and did last night’s backup actually arrive?

A monitor on the same machine dies with it, so the check has to run somewhere else. Paid uptime services do this well, but for a handful of checks we wanted something free, described in Terraform next to the rest of our infrastructure, and able to check one thing a ping cannot: the age of a backup.

The result is a Cloudflare Worker of about a hundred lines. A cron trigger runs it every 5 minutes, KV keeps its state between runs, an R2 binding lets it see the backup bucket, and a Telegram bot delivers the alerts.

What it checks

Sites. Each site must answer 200 and contain an expected piece of text. When we built the monitor, the list held two small placeholder sites served from that machine through tunnels. If such a page comes back correct, the machine, Docker, the container, cloudflared and the tunnel all work: one request checks the whole chain.

Three details make the check honest:

Backup freshness. restic writes one small file per snapshot under snapshots/ in its repository. The Worker lists that prefix through the R2 binding and takes the newest upload time. Our backup runs at 04:15, so the threshold is 26 hours: a missed night triggers an alert, a slow one does not. The Worker never reads the encrypted contents, so it needs no restic password, and the binding replaces S3 keys.

The code

Simplified, but this is the structure we run:

export default {
  async scheduled(controller, env, ctx) {
    ctx.waitUntil(run(env));
  },
  async fetch() {
    return new Response("Not found", { status: 404 }); // no public endpoint
  },
};

async function run(env) {
  const cfg = JSON.parse(env.CONFIG);
  const results = await Promise.all([...cfg.sites.map(checkSite), checkBackup(env, cfg.backup)]);
  for (const r of results) await handle(env, cfg, r);
}

async function checkSite(site) {
  try {
    const res = await fetch(`${site.url}?monitor=${Date.now()}`, {
      redirect: "manual",
      signal: AbortSignal.timeout(15000),
    });
    const body = await res.text();
    if (res.status !== 200) return { name: site.name, ok: false, detail: `HTTP ${res.status}` };
    if (site.expect && !body.includes(site.expect))
      return { name: site.name, ok: false, detail: "expected text not found" };
    return { name: site.name, ok: true };
  } catch (e) {
    const detail = e.name === "TimeoutError" ? "no answer in 15 s" : e.message;
    return { name: site.name, ok: false, detail };
  }
}

async function checkBackup(env, b) {
  let newest = 0;
  let cursor;
  do {
    const page = await env.BACKUPS.list({ prefix: b.prefix, cursor, limit: 1000 });
    for (const o of page.objects) newest = Math.max(newest, o.uploaded.getTime());
    cursor = page.truncated ? page.cursor : undefined;
  } while (cursor);
  if (!newest) return { name: b.name, ok: false, detail: "no snapshots in R2" };
  const hours = (Date.now() - newest) / 3600000;
  if (hours > b.max_age_hours)
    return { name: b.name, ok: false, detail: `last snapshot ${Math.round(hours)} h ago` };
  return { name: b.name, ok: true };
}

The real backup check also has a try/catch, so an R2 error becomes a failed check, not a crashed run.

Alerts without spam

A monitor that sends a message every 5 minutes during an outage gets muted on day one. Ours keeps a small state record per check in KV and follows four rules:

  1. Two failures in a row before the first alert. A single failed request (a network blip, a container restart) wakes nobody. With a 5-minute interval, the alert arrives 5 to 10 minutes after a real outage starts.
  2. One alert per incident, then a reminder every 6 hours while it lasts.
  3. A recovery message with the duration, but only if an alert went out. A blip that never alerted stays silent when it ends too.
  4. Write to KV only when the state changes. A healthy run writes nothing. The free KV plan allows 1,000 writes a day; writing three checks on every run would use 864 of them.
async function handle(env, cfg, r) {
  const key = `state:${r.name}`;
  const prev = (await env.STATE.get(key, "json")) ?? { ok: true, fails: 0 };
  const now = Date.now();
  let next;

  if (r.ok) {
    if (!prev.ok && prev.alerted) {
      await notify(env, `✅ ${r.name}: OK again, the outage lasted ${duration(now - prev.since)}`);
    }
    next = { ok: true, fails: 0 };
  } else {
    next = prev.ok
      ? { ok: false, fails: 1, since: now, alerted: false, alertedAt: null }
      : { ...prev, fails: prev.fails + 1 };
    next.detail = r.detail;
    if (!next.alerted && next.fails >= cfg.fail_threshold) {
      await notify(env, `❌ ${r.name}: ${r.detail}`);
      next.alerted = true;
      next.alertedAt = now;
    } else if (next.alerted && now - next.alertedAt >= cfg.remind_hours * 3600000) {
      await notify(env, `⏰ ${r.name}: still failing after ${duration(now - next.since)}: ${r.detail}`);
      next.alertedAt = now;
    }
  }
  if (JSON.stringify(next) !== JSON.stringify(prev)) await env.STATE.put(key, JSON.stringify(next));
}

notify() is one POST to the Telegram Bot API’s sendMessage, with the host name in front of the text; if Telegram refuses, the error goes to console.error. duration() turns milliseconds into “25 min” or “3 h 10 min”.

The Terraform side

The Worker, its KV namespace and its schedule live in one small module. Everything the code needs arrives through bindings, including the checks as one JSON value, so adding a site changes the stack inputs, not the code:

resource "cloudflare_workers_kv_namespace" "state" {
  account_id = var.account_id
  title      = "${var.name}-state"
}

resource "cloudflare_workers_script" "this" {
  account_id         = var.account_id
  script_name        = var.name
  main_module        = "worker.js"
  content            = file("${path.module}/worker.js")
  compatibility_date = "2026-10-01"

  bindings = [
    { type = "kv_namespace", name = "STATE", namespace_id = cloudflare_workers_kv_namespace.state.id },
    { type = "r2_bucket", name = "BACKUPS", bucket_name = var.backup.bucket, jurisdiction = "eu" },
    { type = "secret_text", name = "TELEGRAM_BOT_TOKEN", text = var.telegram_bot_token },
    { type = "plain_text", name = "TELEGRAM_CHAT_ID", text = var.telegram_chat_id },
    { type = "plain_text", name = "HOST_NAME", text = var.name },
    {
      type = "plain_text"
      name = "CONFIG"
      text = jsonencode({ sites = var.sites, backup = var.backup, fail_threshold = 2, remind_hours = 6 })
    },
  ]
}

# No public *.workers.dev address: the Worker only runs on schedule.
resource "cloudflare_workers_script_subdomain" "this" {
  account_id       = var.account_id
  script_name      = cloudflare_workers_script.this.script_name
  enabled          = false
  previews_enabled = false
}

resource "cloudflare_workers_cron_trigger" "this" {
  account_id  = var.account_id
  script_name = cloudflare_workers_script.this.script_name
  schedules   = [{ cron = "*/5 * * * *" }]
}

The stack passes the checks: a list of { name, url, expect } for the sites, and for the backup the bucket, the restic/snapshots/ prefix and max_age_hours = 26.

Three details that matter when you deploy it:

Workers Logs are on in the script’s observability settings: a few days of run logs, free. We tested the whole thing the honest way: stopped the site container and waited for the message.

What it deliberately does not do

Its limits next to a paid monitor

For internal services it is enough. For a customer-facing product it is not:

A check proves only what it tests

One lesson came from our own history: on 29 November kubmeta.com moved from a placeholder on our machine to Cloudflare Pages. We updated the expected text to the new page title in the same commit, and the check stayed green. But it no longer proves anything about the machine: it now tests Cloudflare Pages. The other placeholder site had been retired earlier.

The machine is still covered, but slowly: if it is down at night, no snapshot arrives, and the backup check alerts once the newest snapshot is more than 26 hours old. If a site check is your heartbeat for a server, keep at least one endpoint that this server actually serves, and re-read the monitor config every time a service moves.

If you build one

For a few internal services, this costs nothing and catches the failures that matter: the server is gone, or the backup stopped. For systems your customers depend on, start with a paid monitor and keep a check like this for what it cannot see, such as backup age. Need help with either? Let’s talk.

#cloudflare#monitoring#devops#serverless