A monitoring tool has a strange job. Everything else in your stack is allowed to fail, and this one thing has to notice. If it misses a failure, nobody finds out until a customer does.
That's why I picked it. I'm a frontend engineer by trade, and I wanted one project that would force me through every backend problem I usually get to avoid: queues, retries, races between workers, token rotation, outbound requests to URLs I don't control, and data that grows every thirty seconds forever.
The result is Pulse. This post is my project file for it. It covers what Pulse does, how I organized it, how each module works under the hood, and the parts I'm not happy with yet.
The source is on GitHub.
What Pulse does#
Pulse watches two kinds of things.
HTTP monitors. You give it a URL, a method, an interval and an expected status code. A worker calls that URL on schedule and records whether it was up, slow or down. You can send custom headers and a request body, and mark headers as secret so they're encrypted at rest.
Webhook endpoints. Some systems don't have a URL you can poll. Stripe and GitHub push events to you. For those, Pulse gives you an ingest URL and an expected interval. If nothing arrives within that window, the webhook is marked silent.
When something stays broken, Pulse opens an incident and sends alerts. Here is the full feature list:
| Area | What you get |
|---|---|
| Monitors | Interval checks, latency chart, last 50 checks, pause and resume, failure threshold, custom headers and body |
| Webhooks | Ingest endpoint per source, event inspector, silence detection |
| Incidents | Open, acknowledged, resolved, with who did what and when |
| Alerts | Email, Slack, Microsoft Teams, Discord, PagerDuty, Opsgenie, signed webhooks |
| Services | Group monitors and webhooks into what your users actually depend on |
| Status page | A public page with 90 day uptime bars and active incidents |
| Reports | Uptime, SLA status, mean time to acknowledge and resolve, CSV export |
| Team | Owner, admin, member and viewer roles, invites, ownership transfer |
| Live updates | Every open tab updates within a second, no refresh needed |
How it looks#
I chose a dark theme with a single lime accent. A monitoring tool spends most of its life open on a second screen, and dark pages are easier on the eyes at 2am. Color only appears when it means something: green is up, amber is degraded, red is down.





The stack, and why#
| Layer | Choice | Why |
|---|---|---|
| Runtime | Node 26 running TypeScript directly | No build step for the backend. node src/server.ts just works |
| HTTP | Express 5 | Boring, well known, and async errors finally reach the error handler |
| Database | PostgreSQL with Drizzle | Constraints do the hard work. Drizzle keeps queries typed without hiding SQL |
| Queues | BullMQ on Redis | Retries, backoff and job deduplication without writing any of it myself |
| Frontend | React 19, TanStack Router and Query | Typed routes, and server state that refetches itself |
| Contracts | zod, shared between both apps | One schema validates the request on the server and types the client |
| Tests | Vitest and Playwright | 292 backend tests and 90 end to end tests in a real browser |
| Shipping | Docker, Caddy, GitHub Actions | One image, two targets, and a deploy script for a single EC2 machine |
I deliberately skipped anything clever. There are no decorators, no dependency injection container, and no generic repository base class. I wanted every file to make sense to someone opening it for the first time, and that someone was usually me a week later.
How the code is organized#
It's a pnpm monorepo with two apps and two shared packages.
pulse/ apps/ api/ Express API and the BullMQ worker src/ modules/ one folder per feature models/ Drizzle tables jobs/ queues, schedulers, processors lib/ small helpers (cache, errors, outbound http) security/ tokens, passwords, encryption web/ React app src/ features/ one folder per feature, mirrors the API routes/ TanStack file routes packages/ contracts/ zod schemas, endpoint map, roles and permissions ui/ shared components e2e/ Playwright tests against the real stack deploy/ compose file, Caddy config, deploy scripts
Every backend module has the same four layers. Once you've read one, you can read them all.
The piece that holds it together is packages/contracts. Each endpoint is declared once, with its method, path, required permission and schemas:
transitionIncident: defineEndpoint({ method: "POST", path: "/incidents/:id/:transition", access: "incident:manage", response: incidentSchema, }), report: defineEndpoint({ method: "GET", path: "/reports", access: "monitor:read", query: reportQuerySchema, response: reportSchema, }),
The API reads this map to register the route, enforce the permission and validate the query. The web app reads the same map to build a typed client. If I rename a field in reportSchema, both apps fail to compile until I fix them. That one file has saved me from more bugs than any test.
The big picture#
The most important decision here is that the API and the worker are separate processes.
The API answers requests from people. The worker runs checks, sends alerts and cleans up old data. If a slow target API ties up fifty check jobs, the dashboard stays fast because those jobs aren't competing with HTTP requests for the same event loop. And if the API restarts during a deploy, scheduled checks keep running.
They talk through two channels, Postgres for state and Redis for everything that moves: job queues, cache, rate limit counters and a pub/sub channel for live updates.
Module by module#
Checks: from schedule to result#
This is the heart of Pulse, and it's where most of the interesting bugs lived.
Every few seconds a scheduler asks Postgres which monitors are due and queues a job for each:
export const dispatchDueChecks = async () => { const dueMonitors = await findDueMonitors(); const now = Date.now(); await checksQueue.addBulk( dueMonitors.map((monitor) => ({ name: "run-check", data: { monitorId: monitor.id }, opts: { jobId: `check-${monitor.id}-${Math.floor(now / (monitor.intervalSeconds * 1000))}`, }, })), ); };
Look at the jobId. It's built from the monitor and the current time slot. If the scheduler runs twice in the same slot, which happens during deploys or when two workers are alive, BullMQ sees the same id and ignores the duplicate. I didn't need a lock. I needed a name that two copies of the same job would agree on.
The worker then fetches the URL and saves everything in one transaction:
export const saveCheckResult = (monitorId: string, measurement: CheckMeasurement) => db.transaction(async (tx) => { const checkedAt = new Date(); const [checked] = await tx .update(monitors) .set({ status: measurement.outcome, lastCheckedAt: checkedAt, consecutiveFailures: measurement.outcome === "up" ? 0 : sql`${monitors.consecutiveFailures} + 1`, }) .where(and(eq(monitors.id, monitorId), eq(monitors.isPaused, false))) .returning({ id: monitors.id }); if (!checked) { return undefined; } await tx.insert(checkResults).values({ monitorId, checkedAt, ...measurement }); await tx .insert(monitorDailyStats) .values({ monitorId, day: checkedAt.toISOString().slice(0, 10), checkCount: 1 /* ... */ }) .onConflictDoUpdate({ target: [monitorDailyStats.monitorId, monitorDailyStats.day], set: { checkCount: sql`${monitorDailyStats.checkCount} + 1` /* ... */ }, }); });
Three details here took me a while to get right.
First, consecutiveFailures + 1 happens in SQL, not in JavaScript. If I read the count, added one in Node and wrote it back, two overlapping checks could both read 1 and both write 2. Letting Postgres do the arithmetic makes that race impossible.
Second, the where includes isPaused = false. If someone pauses a monitor while its check is in flight, the update matches zero rows, the function returns early, and the stale result never lands.
Third, the daily rollup is upserted in the same transaction. Reports never scan raw checks. Raw checks are deleted after 30 days, and daily rows stay for 400. A 90 day report reads 90 rows per monitor instead of a quarter of a million.
Incidents: one active incident per source, enforced by Postgres#
A single failed check doesn't open an incident. Networks blip. Each monitor has a failure threshold, two by default, and only a confirmed failure counts.
The tricky rule is "never open two incidents for the same monitor". My first version checked for an open incident and then inserted one. That's a classic race. Two workers can both see "no incident" and both insert.
The fix was to stop asking and let the database decide. There's a partial unique index on incidents.source_id that only applies while the status isn't resolved, and the insert simply does nothing if it would break it:
const [incident] = await tx .insert(incidents) .values(values) .onConflictDoNothing({ target: incidents.sourceId, where: sql`${incidents.status} <> 'resolved'`, }) .returning({ id: incidents.id });
If incident comes back empty, someone else already opened it, and I skip the alerts. No lock, no retry loop. The same pattern shows up for acknowledging. The update only matches rows in an allowed starting state, and coalesce keeps the first person who acknowledged, even if two people click at once:
.set({ status: rule.to, acknowledgedAt: sql`coalesce(${incidents.acknowledgedAt}, now())`, acknowledgedById: sql`coalesce(${incidents.acknowledgedById}, ${actor.id})`, }) .where(and(eq(incidents.id, id), inArray(incidents.status, [...rule.from])))
This became the rule for the whole codebase. Write the condition into the query, and let the number of rows that changed tell you what happened.
Alerts: retries without spam#
When an incident opens, Pulse queues one job per alert channel. Each job gets five attempts with exponential backoff starting at five seconds, and every attempt is written to an alert_deliveries table so you can see in the UI why a message didn't arrive.
Retries cause their own problem. If PagerDuty accepts the request but the response times out, the retry sends the alert again. For PagerDuty and Opsgenie I pass the incident id as dedup_key and alias. They treat repeat deliveries as the same alert, and the resolve message closes the right one.
Outgoing webhooks are signed with an HMAC secret per channel, the same way Stripe signs its webhooks to you, so the receiver can prove the request came from Pulse.
Webhooks: monitoring silence#
Webhook monitoring flips the usual model. There's nothing to call. You can only notice that something stopped arriving.
Every event that hits /hooks/:slug updates lastReceivedAt. A scheduled job looks for webhooks whose last event is older than their expected interval and marks them silent, which opens an incident through the same path as a failing monitor.
The status page needed one more piece. Monitors have daily check counts for the uptime bars, but webhooks don't have checks. So for services made only of webhooks, I derive uptime from incident time instead: how much of each day was covered by a critical incident, counted from the day the webhook was created.
const overlapSeconds = (fromMs: number, toMs: number, start: Date, end: Date) => Math.max(0, Math.min(toMs, end.getTime()) - Math.max(fromMs, start.getTime())) / 1000; export const webhookDailyCounts = (webhooks, outages, now) => { const firstDayMs = Date.parse(historyStartDay(now)); return Array.from({ length: UPTIME_HISTORY_DAYS }, (_, index) => { const dayStart = firstDayMs + index * DAY_MS; const dayEnd = Math.min(dayStart + DAY_MS, now.getTime()); const observed = webhooks.reduce( (total, webhook) => total + overlapSeconds(dayStart, dayEnd, webhook.createdAt, now), 0); const down = outages.reduce( (total, outage) => total + overlapSeconds(dayStart, dayEnd, outage.startedAt, outage.resolvedAt ?? now), 0); return { day: toIsoDay(new Date(dayStart)), checkCount: Math.round(observed), downCount: Math.round(down) }; }).filter((row) => row.checkCount > 0); };
It returns the same shape as the monitor counts, seconds instead of checks, so the function that draws the bars didn't change at all.
Live updates: notify, then refetch#
I used Server-Sent Events instead of WebSockets. Updates only flow one way, from server to browser, and SSE is plain HTTP. It reconnects by itself and passes through proxies without special handling.
The events are deliberately tiny. They say what changed, never the new data:
{ "type": "monitor.checked", "id": "5f1c..." }
The browser maps each event type to the React Query keys it affects, waits a moment to batch a burst of events, then refetches only those queries:
const keysByType: Record<ChangeEventType, (id: string) => QueryKey[]> = { "monitor.checked": (id) => [monitors.lists(), monitors.detail(id), dashboard, services], "incident.updated": (id) => [incidents.lists(), incidents.detail(id), dashboard, services], "webhook.event": (id) => [webhooks.lists(), webhooks.detail(id), dashboard], "service.updated": () => [services, monitors.all, webhooks.all], };
Sending only ids means I never had to worry about pushing data to someone who isn't allowed to see it. The refetch goes through the normal API, with the normal permission checks.
Auth: refresh tokens that notice theft#
Access tokens live for fifteen minutes. Refresh tokens live in an httpOnly cookie and are rotated on every use. Each one belongs to a family that starts at sign-in.
if (session.revokedAt) { logger.warn({ userId: session.userId }, "Refresh token reuse detected, revoking session family"); await revokeSessionFamily(session.familyId); return null; }
A legitimate browser never sends an old token, because it always received the new one. So an old token showing up means two parties hold the same family. Pulse can't tell which one is the attacker, so it ends both sessions. The real user signs in again, and the attacker can't.
Around that sit the less glamorous pieces. Passwords use Argon2id. Email verification and password reset tokens are single use and stored hashed. Login is rate limited per IP address and email. A password reset signs out every device and unlinks Google and GitHub, so a takeover can't survive a reset.
Outbound requests: don't let users point Pulse at your own network#
A monitoring tool makes HTTP requests to URLs that users type. Without care, someone could add http://169.254.169.254/ and read cloud credentials from inside your server. This is called SSRF.
Checking the hostname isn't enough. A domain can resolve to a public IP when you check it and a private one when you connect. So Pulse checks the address at connect time, inside the DNS lookup that undici uses for the actual socket:
resolve(hostname, (error, addresses) => { const allowed = addresses.filter(({ address }) => policy.isAllowedAddress(address)); const [first] = allowed; if (!first) { callback(blocked(), []); return; } callback(null, first.address, first.family); });
Redirects are followed by hand, up to a limit, and each hop goes through the same check. Response bodies are capped in size. Secret request headers are encrypted with AES-256-GCM before they touch the database, with a version prefix so the key can be rotated later.
Errors: let constraints speak#
I didn't want "check if the email exists, then insert" code anywhere. It's slow, it's racy, and the database already knows the answer. Instead every insert just runs, and a small map turns constraint names into friendly errors:
const errorsByConstraint: Record<string, () => AppError> = { users_email_unique: () => conflict("Email already in use", { email: ["An account with this email already exists"] }), users_single_owner: () => conflict("This workspace already has an owner"), invitations_one_pending_per_email: () => conflict("Already invited", { email: ["An invitation is already pending for this email"] }), services_name_unique: () => conflict("Service name already in use", { name: ["A service with this name already exists"] }), };
The field-level messages flow straight into the form on the frontend, under the right input.
Reports: math on daily rows#
Reports compute uptime, SLA status, average latency, incident counts, mean time to acknowledge, mean time to resolve and estimated downtime for any range up to 400 days back. Because the daily rollup already exists, a report is a handful of grouped queries over small tables. The CSV export runs the same function and writes rows instead of JSON.
The data model#
A few constraints in this schema carry real business rules:
- A partial unique index allows only one owner in the workspace.
- Another one allows only one pending invite per email.
- Opsgenie channels must have a region, and no other channel type may have one. That's a check constraint, not an
ifstatement. - Deleting a service sets
service_idto null on its monitors instead of deleting them.
How I wrote it#
A few rules I held myself to, and why.
No comments. If code needed a comment, I renamed things until it didn't. isConfirmedFailure explains itself in a way // check threshold never will.
No abstraction until the third copy. Every module has its own repository functions, written out. Some look similar. They also change for different reasons, and keeping them apart meant I never broke monitors by fixing webhooks.
No N+1 queries. Lists load their related rows in one grouped query and stitch them together with Map.groupBy, never a query inside a loop.
Test against the real thing. The backend tests run against a real Postgres and Redis, not mocks. The Playwright suite starts the whole stack, signs in as each role, clicks through every feature and reads the emails Pulse sends from a file. When a test says "an incident opens after two failed checks", it waits for two real failed checks.
Ship it like it's real. One Dockerfile builds both the API and the web app as separate targets. Caddy terminates TLS and has buffering turned off so SSE flows. GitHub Actions runs lint, typecheck, unit and end to end tests on every push. There's a deploy workflow for a single EC2 machine that's switched off until I decide to pay for one.
What's missing#
I'd rather be honest about this list than pretend Pulse is finished.
- Single region. Every check runs from one place. If that machine's network has a bad minute, every monitor looks down at once. Real monitors check from several regions and only alert when most agree.
- One workspace. There's no multi-tenancy. Each install is one team.
- No maintenance windows. You can pause a monitor, but you can't schedule "ignore this between 2 and 3am on Sunday".
- HTTP only. No TCP, DNS, ping or SSL expiry checks yet.
- No on-call schedules. Pulse alerts channels, not people on a rota. For now that's what the PagerDuty integration is for.
What I'd improve#
- Region-aware checks. Run a worker per region, tag each result with where it came from, and confirm failures across regions before opening an incident.
- Partition check results by day. Deleting old rows works at this scale. At ten times the monitors, dropping a daily partition would be far cheaper than deleting millions of rows.
- A proper status page subscription. Visitors should be able to get an email when a service they care about goes down.
- Smarter thresholds. Alert when latency is unusual for this endpoint, not when it crosses a fixed number.
Future scope#
The part I'm most excited about is turning incidents into a timeline. Right now an incident knows when it opened, who acknowledged it and when it resolved. I'd like it to collect the failing checks, the alerts sent, the notes people add and the deploy that happened right before it, then generate a short write-up when it closes. That's the document every team writes by hand after an outage, and Pulse already holds most of the facts.
What I took away#
Before this project, "backend" meant writing an endpoint that read from a table. Pulse taught me that the real work is everything between the requests: two copies of the same job, a click that lands during a check, a token used twice, a URL that resolves differently the second time.
Almost every one of those problems had the same answer. Don't read, decide and write in separate steps. Put the rule in the database, write one conditional statement, and trust the result it gives back.
If you want to dig in, the code is on GitHub. The README walks through running the whole thing locally: start Postgres and Redis with Docker, seed the demo data, run pnpm dev.