Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: check service health every five minutes

Richie McIlroyf4eb55da7a3c
diff --git a/apps/status/README.md b/apps/status/README.md
index c504834a6..cdc493e47 100644
--- a/apps/status/README.md
+++ b/apps/status/README.md
@@ -7,8 +7,8 @@ An independent Next.js app for `status.cap.so`. It reuses the current landing pa
1. Import this repository into a **separate Vercel project**, with root directory **`apps/status`**, framework **Next.js**, and build command **`bun run build`**. Keep access to the repository root enabled so Vercel uses the existing Bun workspace and lockfile. Use Bun 1.4.0. Do not attach the main site’s environment variables.
2. Attach a dedicated Upstash Redis database through the Vercel Marketplace. Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` on the production environment. Keep preview data in a separate database, or leave preview storage unconfigured.
3. Set a random `CRON_SECRET` of at least 32 bytes on production. Vercel sends it as the cron’s Bearer token. Do not prefix any of these variables with `NEXT_PUBLIC_`.
-4. Configure the production service URLs below. Deploy on a plan supporting **one-minute cron jobs** (Vercel Pro or higher), then add `status.cap.so` to this project and point its DNS at Vercel. The page starts with honest “no data” states until checks run.
-5. Verify the first `/api/cron/check` invocation succeeds in the Vercel logs and `/api/status` contains current observations for every configured service. Set an **external dead-man monitor** to alert when `/api/status` has an old `checkedAt` (over 180 seconds), returns non-200, or cannot be reached. This detects a failed scheduler, Redis, or the status deployment itself.
+4. Configure the production service URLs below. Deploy on a plan supporting **five-minute cron jobs** (Vercel Pro or higher), then add `status.cap.so` to this project and point its DNS at Vercel. The page starts with honest “no data” states until checks run.
+5. Verify the first `/api/cron/check` invocation succeeds in the Vercel logs and `/api/status` contains current observations for every configured service. Set an **external dead-man monitor** to alert when `/api/status` has an old `checkedAt` (over 15 minutes), returns non-200, or cannot be reached. This detects a failed scheduler, Redis, or the status deployment itself.
No production deployment, DNS changes, external monitors, or storage resources are created by this PR.
@@ -31,12 +31,12 @@ These are availability checks, not end-to-end recording/upload/playback tests. A
## Monitoring and persistence
-- Vercel cron runs once per minute **only on production**. `/api/cron/check` rejects unauthenticated calls. Preview deployments cannot run the collector.
-- Six lightweight probes run concurrently, each with an eight-second deadline. Healthy responses over three seconds are degraded. An unhealthy probe is retried once immediately. At most 12 requests per minute reach Cap, independent of page traffic. HEAD probes do not download recordings; GET probes use only small health JSON.
-- A 55-second Redis lease prevents overlapping collectors. The function deadline is 50 seconds. Saving observations and releasing the lease is one atomic Lua operation conditional on lease ownership. A crashed collector’s lease expires. Duplicate invocations in the same UTC minute do not double-count.
-- A first confirmed unhealthy sample shows degraded/unknown status. Two consecutive unhealthy samples open an incident; two consecutive successful samples close it. After a monitoring gap, consecutive counters reset. An unobserved gap never resolves an incident.
+- Vercel cron runs every five minutes **only on production**. `/api/cron/check` rejects unauthenticated calls. Preview deployments cannot run the collector.
+- Six lightweight probes run concurrently, each with an eight-second deadline. Healthy responses over three seconds are degraded. An unhealthy probe is retried once immediately. Normally 72 requests per hour reach Cap; retries can increase that to 144 per hour, independent of page traffic. HEAD probes do not download recordings; GET probes use only small health JSON.
+- A 55-second Redis lease prevents overlapping collectors. The function deadline is 50 seconds. Saving observations and releasing the lease is one atomic Lua operation conditional on lease ownership. A crashed collector’s lease expires. Duplicate invocations in the same five-minute UTC interval do not double-count.
+- A first confirmed unhealthy sample shows degraded/unknown status. Two consecutive unhealthy samples open an incident, typically 5–10 minutes after a failure begins; two consecutive successful samples close it. After a monitoring gap, consecutive counters reset. An unobserved gap never resolves an incident.
- Redis stores 90 UTC calendar days of daily observed success/degradation/failure counts and all ongoing incidents and up to 500 recently resolved incidents. Empty days remain empty. Uptime is successful observed checks divided by all observed checks; it is not a promise about unobserved time. Hover, focus, or tap a day to see the sample count.
-- Visitors read only `/api/status`, cached at the CDN for 30 seconds. The visible page refreshes once a minute and stops polling in hidden tabs. It independently marks observations older than three minutes unknown. Storage failures show monitoring unavailable; they never fabricate healthy data. No service URLs, health payloads, or credentials appear in the public snapshot.
+- Visitors read only `/api/status`, cached at the CDN for 30 seconds. The visible page refreshes once a minute and stops polling in hidden tabs. It independently marks observations older than 15 minutes unknown. Storage failures show monitoring unavailable; they never fabricate healthy data. No service URLs, health payloads, or credentials appear in the public snapshot.
The status page and its scheduler share Vercel. The independent dead-man monitor is needed to notify operators of a Vercel-wide outage. This version records automatic incidents; notifications and manually written incident updates are outside its scope.
diff --git a/apps/status/app/api/cron/check/route.ts b/apps/status/app/api/cron/check/route.ts
index 92e555003..88ab8e32e 100644
--- a/apps/status/app/api/cron/check/route.ts
+++ b/apps/status/app/api/cron/check/route.ts
@@ -1,7 +1,7 @@
import { randomUUID, timingSafeEqual } from "node:crypto";
import { probe } from "../../../../lib/probe";
import { SERVICES, serviceUrl } from "../../../../lib/services";
-import { applyResult } from "../../../../lib/state";
+import { applyResult, CHECK_INTERVAL_MS } from "../../../../lib/state";
import {
COMMIT_SCRIPT,
getRedis,
@@ -38,10 +38,10 @@ export async function GET(request: Request) {
const now = Date.now();
if (
state.checkedAt &&
- Math.floor(Date.parse(state.checkedAt) / 60_000) >=
- Math.floor(now / 60_000)
+ Math.floor(Date.parse(state.checkedAt) / CHECK_INTERVAL_MS) >=
+ Math.floor(now / CHECK_INTERVAL_MS)
) {
- return Response.json({ skipped: "Minute already sampled" });
+ return Response.json({ skipped: "Check interval already sampled" });
}
const results = await Promise.all(
SERVICES.map(async (service) => {
diff --git a/apps/status/components/status-page.tsx b/apps/status/components/status-page.tsx
index c52773c46..5b193e3da 100644
--- a/apps/status/components/status-page.tsx
+++ b/apps/status/components/status-page.tsx
@@ -221,7 +221,7 @@ export function StatusPage() {
</span>
{secondsAgo !== null && fresh
? `Updated ${secondsAgo < 60 ? "just now" : `${Math.floor(secondsAgo / 60)}m ago`}`
- : "Updates every minute"}
+ : "Checks every 5 minutes"}
</div>
</div>
<section
@@ -357,8 +357,8 @@ export function StatusPage() {
How we keep an eye on things <span aria-hidden="true">+</span>
</summary>
<p>
- Lightweight checks run every minute, independently of this page.
- We retry an unhealthy response before recording it, confirm
+ Lightweight checks run every five minutes, independently of this
+ page. We retry an unhealthy response before recording it, confirm
incidents across two checks, and confirm recovery twice. Grey bars
mean no data; gaps are never counted as uptime. Percentages
describe successful observed checks, not unmonitored time. Select
diff --git a/apps/status/lib/state.ts b/apps/status/lib/state.ts
index 02cb8a744..810c8dc87 100644
--- a/apps/status/lib/state.ts
+++ b/apps/status/lib/state.ts
@@ -8,7 +8,8 @@ import type {
Snapshot,
} from "./types";
-export const STALE_AFTER_MS = 180_000;
+export const CHECK_INTERVAL_MS = 5 * 60_000;
+export const STALE_AFTER_MS = 3 * CHECK_INTERVAL_MS;
export const HISTORY_DAYS = 90;
const DAY_MS = 86_400_000;
@@ -79,8 +80,8 @@ export function applyResult(
}
if (
previous.checkedAt &&
- Math.floor(Date.parse(previous.checkedAt) / 60_000) >=
- Math.floor(now / 60_000)
+ Math.floor(Date.parse(previous.checkedAt) / CHECK_INTERVAL_MS) >=
+ Math.floor(now / CHECK_INTERVAL_MS)
)
return;
if (isStale(previous.checkedAt, now)) {
diff --git a/apps/status/tests/routes.test.ts b/apps/status/tests/routes.test.ts
index 781cc61c2..a7230101a 100644
--- a/apps/status/tests/routes.test.ts
+++ b/apps/status/tests/routes.test.ts
@@ -1,8 +1,10 @@
-import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+import { afterAll, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { GET as collect } from "../app/api/cron/check/route";
import { GET as readStatus } from "../app/api/status/route";
import { SERVICES } from "../lib/services";
+import { CHECK_INTERVAL_MS, emptyState } from "../lib/state";
import { LOCK_KEY, STATE_KEY } from "../lib/store";
+import deployment from "../vercel.json";
const values = new Map<string, string>();
const realFetch = globalThis.fetch;
@@ -134,11 +136,36 @@ describe("scheduler → storage → public API", () => {
expect(response.headers.get("cache-control")).toContain("s-maxage=30");
expect(probeCalls).toBe(6);
expect(await (await collect(authorizedRequest())).json()).toEqual({
- skipped: "Minute already sampled",
+ skipped: "Check interval already sampled",
});
expect(probeCalls).toBe(6);
});
+ test("limits collection to the configured five-minute interval", async () => {
+ expect(deployment.crons[0].schedule).toBe("*/5 * * * *");
+ const start =
+ Math.floor(Date.now() / CHECK_INTERVAL_MS) * CHECK_INTERVAL_MS;
+ values.set(
+ STATE_KEY,
+ JSON.stringify({
+ ...emptyState(),
+ checkedAt: new Date(start).toISOString(),
+ }),
+ );
+ const clock = spyOn(Date, "now").mockReturnValue(start + 2 * 60_000);
+ try {
+ expect(await (await collect(authorizedRequest())).json()).toEqual({
+ skipped: "Check interval already sampled",
+ });
+ expect(probeCalls).toBe(0);
+ clock.mockReturnValue(start + CHECK_INTERVAL_MS);
+ expect((await collect(authorizedRequest())).status).toBe(200);
+ expect(probeCalls).toBe(6);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
test("overlapping invocations perform a single collection", async () => {
const responses = await Promise.all([
collect(authorizedRequest()),
diff --git a/apps/status/tests/state.test.ts b/apps/status/tests/state.test.ts
index 37fbbd436..17f980c3d 100644
--- a/apps/status/tests/state.test.ts
+++ b/apps/status/tests/state.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
import {
applyResult,
availability,
+ CHECK_INTERVAL_MS,
dates,
emptyState,
isStale,
@@ -27,22 +28,22 @@ describe("monitor state", () => {
test("confirms an incident and recovery over two consecutive samples", () => {
const state = emptyState();
applyResult(state, "website", good, start);
- applyResult(state, "website", bad, start + 60_000);
+ applyResult(state, "website", bad, start + CHECK_INTERVAL_MS);
expect(state.services.website.status).toBe("degraded");
expect(state.incidents).toHaveLength(0);
- applyResult(state, "website", bad, start + 120_000);
+ applyResult(state, "website", bad, start + 2 * CHECK_INTERVAL_MS);
expect(state.services.website.status).toBe("outage");
expect(state.incidents).toHaveLength(1);
expect(state.incidents[0].startedAt).toBe(
- new Date(start + 60_000).toISOString(),
+ new Date(start + CHECK_INTERVAL_MS).toISOString(),
);
- applyResult(state, "website", good, start + 180_000);
+ applyResult(state, "website", good, start + 3 * CHECK_INTERVAL_MS);
expect(state.services.website.status).toBe("outage");
expect(state.incidents[0].resolvedAt).toBeNull();
- applyResult(state, "website", good, start + 240_000);
+ applyResult(state, "website", good, start + 4 * CHECK_INTERVAL_MS);
expect(state.services.website.status).toBe("operational");
expect(state.incidents[0].resolvedAt).toBe(
- new Date(start + 240_000).toISOString(),
+ new Date(start + 4 * CHECK_INTERVAL_MS).toISOString(),
);
expect(state.incidents).toHaveLength(1);
});
@@ -50,8 +51,8 @@ describe("monitor state", () => {
test("ignores duplicate and out-of-order samples", () => {
const state = emptyState();
applyResult(state, "website", good, start);
- applyResult(state, "website", bad, start + 1_000);
- applyResult(state, "website", bad, start - 60_000);
+ applyResult(state, "website", bad, start + CHECK_INTERVAL_MS - 1);
+ applyResult(state, "website", bad, start - CHECK_INTERVAL_MS);
expect(state.services.website.days[0].operational).toBe(1);
expect(state.services.website.days[0].outage).toBe(0);
expect(state.services.website.status).toBe("operational");
@@ -68,8 +69,11 @@ describe("monitor state", () => {
test("marks old observations unknown without erasing the incident or history", () => {
const state = emptyState();
applyResult(state, "website", bad, start);
- applyResult(state, "website", bad, start + 60_000);
- const snapshot = publicSnapshot(state, start + 60_000 + STALE_AFTER_MS + 1);
+ applyResult(state, "website", bad, start + CHECK_INTERVAL_MS);
+ const snapshot = publicSnapshot(
+ state,
+ start + CHECK_INTERVAL_MS + STALE_AFTER_MS + 1,
+ );
expect(snapshot.services[0].status).toBe("unknown");
expect(snapshot.incidents[0].resolvedAt).toBeNull();
expect(availability(snapshot.services[0].days)).toBe(0);
diff --git a/apps/status/vercel.json b/apps/status/vercel.json
index 16e7ae2cd..ec0f9ec25 100644
--- a/apps/status/vercel.json
+++ b/apps/status/vercel.json
@@ -2,5 +2,5 @@
"$schema": "https://openapi.vercel.sh/vercel.json",
"framework": "nextjs",
"buildCommand": "bun run build",
- "crons": [{ "path": "/api/cron/check", "schedule": "* * * * *" }]
+ "crons": [{ "path": "/api/cron/check", "schedule": "*/5 * * * *" }]
}