Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 133 ยท Projects

Project: URL Monitoring Service

Build an uptime monitor in Node.js. Scheduled HTTP checks with timeouts, status history, uptime percentages and alerts that fire on state changes without flapping.

Every website goes down sometimes. The question is whether you hear about it from a monitoring tool or from an angry customer. An uptime monitor requests your URLs on a schedule, records what happened and tells you when a site goes down or comes back. Services such as UptimeRobot do exactly this, and the core is small enough to build in one lesson.

You will build a monitor with four parts: a checker that makes one HTTP request with a timeout and classifies the result, a history that keeps the last results per site and computes uptime, an alert rule that fires only when the state really changes (not on a single blip), and a scheduler that runs the checks. The checker and the scheduler are kept apart so you can test the alert logic with a fake clock and fake results, which is the only sane way to test "what happens after three failures in a row".

Plan

  1. check(url, { timeoutMs }) returns { ok, status, ms, error }. It never throws.
  2. History keeps a bounded list of results per target and reports uptime and average latency.
  3. AlertRule turns a stream of results into events: down after N failures in a row, up after the first success that follows.
  4. Monitor owns targets, schedules checks with a timer per target and emits events.

Stage 1: one check that never throws

A check has three outcomes: the server answered with a good status, the server answered with a bad status (500, 404), or nothing useful came back (refused connection, timeout). All three must become plain data, because the scheduler should not need try/catch around every call. We use fetch with AbortSignal.timeout, so a hung server cannot hold the check forever (abort signals).

Node.js The checker: ok, bad status, refused and timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what counts as "up": response.ok means a status from 200 to 299. A 500 is down from the customer's point of view even though the server is running, and a timeout is down even though it eventually answers. Real monitors let you configure the expected status or a text that must appear in the page; add expectStatus or expectText options as an exercise.

Checking from the same machine that runs your site proves little: if the whole server is down, so is the monitor. A real monitor runs somewhere else, ideally from more than one location. The code is the same, only the place you deploy it changes.

Stage 2: history and uptime

Keeping every result forever would grow without bound, so History stores the last limit results per target in an array and drops the oldest. Uptime is the share of successful checks, and average latency is taken over the successful ones only, so a timeout (which takes the whole timeout period) does not distort it.

Node.js Bounded history with uptime and latency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because the 7th result evicted the first, the summary covers six checks: four succeeded, so the uptime is 66.7%. A production monitor stores results in a database (see SQLite) and keeps daily rollups for long-term uptime, but the idea is the same: a bounded raw window plus summaries.

Stage 3: alerts that do not flap

If you alert on every failed check, one dropped packet wakes someone at 3 a.m. and a site that wobbles between up and down sends a flood of messages. The standard cure has two parts:

  • Confirm before alerting. A target is declared down only after failAfter consecutive failures (for example 3).
  • Alert on change, not on state. Send one down event when the state flips to down and one up event when it recovers. While it stays down, say nothing more.

This is a small state machine with the states up and down (plus unknown before the first result). It takes no clock and no network, so it is trivial to test.

Node.js AlertRule: confirm failures, alert on change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Follow the output: the isolated failure at 30 s and the pair at 90 and 120 s never reach three in a row, because the success at 60 s resets the counter. The third failure in the second streak (at 150 s) flips the state, so you get one down event, and the next two failures are silent. The first success after that gives the up event with downFor set. Tune failAfter and the check interval together: with a 30 s interval and failAfter: 3 you learn about an outage within 90 seconds.

Stage 4: the monitor and its scheduler

Now we join the pieces. The monitor schedules each target with its own interval. Two details matter:

  • Use setTimeout after each check, not setInterval. With setInterval, a slow check can overlap with the next one; scheduling the next run only after the current one finishes means a target is never checked twice at the same time.
  • Make the checker and the clock injectable. In tests you pass a fake check function that returns scripted results, so the whole monitor runs in milliseconds.

The monitor is an EventEmitter (events), so alert delivery (log, email, webhook) is just a listener.

Node.js The Monitor with a scripted checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The monitor reported one down and one up for the shop, and nothing at all for the blog. report() shows the final state and uptime over the eight checks each. The now function is injected too, so the "timestamps" here are ticks and the output never depends on the real clock.

Delivering an alert is a side effect that can fail too. When you connect down and up to email, Slack or an SMS gateway, catch errors in the listener and retry. A monitor that crashes while sending an alert, or a listener that throws inside emit, would be the worst kind of outage: a silent one. See Error Handling in Production.

Going live

To turn the pieces into a service, replace the fake checker with the real check from stage 1, load targets from a configuration file, and add the outputs:

  • A status page: GET /status returns monitor.report() as JSON (HTTP servers). It is cheap to cache.
  • Alert delivery: a down listener that posts to a webhook with fetch. Include the name, the reason and the time.
  • Persistence: write results to SQLite so history survives a restart, and load recent results at start so the alert state is not unknown after each deploy.
  • Graceful stop: on SIGTERM call monitor.stop() and let a running check finish (Graceful Shutdown).
  • Jitter: add a small random delay to each target's first check so a hundred targets do not all fire at the same second.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the checker return a result object instead of throwing when a request fails?

    Down sites are the expected case for a monitor. Turning every outcome into plain data means the caller handles all of them in the same way and one bad target cannot stop the loop.
  2. 2. What does AbortSignal.timeout(150) give you in the checker?

    Without a timeout a hung server would keep the check waiting forever and the target would never be reported as down.
  3. 3. A site fails once, succeeds, fails once, and so on. With failAfter: 3, how many down alerts fire?

    The counter only reaches 3 when three failures follow each other. This is what stops flapping from flooding you with alerts.
  4. 4. Why schedule the next check with setTimeout after the current one finishes instead of using setInterval?

    setInterval fires on a fixed beat whether or not the last check is done. Chaining setTimeout guarantees one check at a time per target.
  5. 5. Why are the checker and the clock injected into the Monitor?

    Injected dependencies let a test run an outage of ten minutes in a few milliseconds with fully predictable output.

Summary

  • A monitor is a checker, a bounded history, an alert rule and a scheduler. Keep them separate.
  • Turn every request outcome (good status, bad status, refused, timeout) into plain data; always use a timeout.
  • Alert on state changes after N consecutive failures, and send one up when the site recovers.
  • Chain setTimeout after each check so a target is never checked twice at once; inject the checker and the clock to test the logic without a network.
  • A real service adds persistence, a status endpoint, alert delivery with retries and graceful shutdown.

Next: Project: Real-Time Polling and Auction