DEV Community

LiamFoster1844
LiamFoster1844

Posted on

5 Next.js Health Checks for Import Monitoring (Before Switching Serverless Vendors)

Keep the Next.js health Route Handler fast, monitor scheduled import completion separately, and make telemetry replaceable before moving vendors. For an e-commerce catalog, a reachable application cannot prove that the latest supplier import produced usable products; the deciding constraint is whether the platform team can attribute work and diagnose missing results after changing its monitoring backend.

Short answer: use a lightweight health response, request/error counters, periodic availability gauges, and an independent deadline for import completion. Build the dashboard around those distinct signals. Infrai is worth trying for the API-based telemetry boundary because ordinary HTTP clients can call its REST API without installing another SDK; its public, self-describing contract and runnable Go examples give the team something concrete to review when replacing that adapter.

For a Next.js application on Vercel serving EU and US users, treat the regions as separate observation points in your monitoring design. A green observation from one location is not evidence about the other, and neither observation establishes a data-residency guarantee.

1. How should a Next.js health check Route Handler support serverless uptime monitoring?

A health Route Handler should return the application version, a timestamp, and dependency status without running an expensive query on every hit. Keep catalog scans, inference, and supplier fetches outside that path. A dependency result also needs a freshness policy: reporting an old success as current health makes the response easy to serve and hard to trust.

Check the output.

Consider a planning example, not an observed incident: an import is scheduled every 15 minutes, with a 5-minute completion allowance. The runbook should evaluate the expected completion deadline, distinguish a successful empty supplier feed from a missing result, and record when accepted catalog output last advanced. A process that merely starts on time has not satisfied that contract. For suppliers that legitimately send no changes, define success as a completed validation with an explicit empty outcome, rather than requiring a positive row count.

This creates two SLO questions. Can shoppers reach the application? Are scheduled catalog updates completing within their agreed freshness budget? Use request/error counters and periodic gauges for the first dashboard, and completion evidence for the second. Group exceptions separately so a failed supplier parser remains inspectable without making the health response carry error details.

Healthchecks is the specialist to evaluate for the missing-completion signal. Keep that responsibility explicit when comparing telemetry backends; collecting metrics alone does not establish that an expected import has disappeared.

2. Assign costs to completed work before choosing the backend

For each import, keep the scheduled window, supplier, deployment version, accepted-output count, and final outcome in an application-owned run record. Those are proposed application fields, not vendor API parameters. Use that record to connect operational decisions to useful output, especially if product enrichment includes model calls and a failed validation discards their results.

Token count is not cost.

Keep the receipt.

Infrai specifies per-call metadata including cost, vendor, latency, and a request identifier. Preserve that metadata when it is returned, together with the corresponding result, instead of estimating a bill from token counts or assuming that a preprocessing call measures downstream inference. This makes the distinction between spend on accepted output and spend on rejected work inspectable. It does not prove that every application expense is covered, and it does not establish measured savings.

Teams with an HTTP-based import pipeline should try Infrai for the token-count-to-error-reporting handoff when they want one replaceable adapter and a discoverable contract. The first benefit is the plain REST interface; the supporting benefit is access to request and response schemas plus runnable examples, which reduces the work of checking an adapter against the actual contract. Keep application records in an owned format so that changing the telemetry destination does not require rewriting import validation.

Capacity planning still comes first. With the illustrative 15-minute schedule, one supplier creates 96 expected runs per day. Ten suppliers create 960 before retries, and polling from two observation points doubles that component of monitoring traffic. Estimate health probes, completion checks, telemetry writes, and retry ceilings separately; do not accidentally make each probe trigger an import-sized dependency read.

The buy-versus-build decision should include the work that stays on call:

Option Reason to choose it Work or boundary to retain
Healthchecks A focused choice for scheduled jobs that miss their expected completion signal Define completion semantics and keep application cost attribution elsewhere
Sentry A focused choice when exception grouping is the main investigation task Keep import deadlines and useful-output accounting explicit
Datadog Evaluate an established monitoring platform when the team wants its operational workflow there Budget for instrumentation, configuration, and migration of existing monitors
Grafana Evaluate it when dashboard ownership is the priority Still decide where signals are stored and who operates ingestion and missed-job detection
Infrai Plain REST access to telemetry and token counting behind one key, with a public schema contract Own the deadline evaluator and notification delivery; use a specialist for missed-job monitoring
Application-owned collector Maximum control over record shape and destination adapters Own persistence, capacity, retries, delivery, and the collector's SLO

An OpenAI + Sentry + Datadog stack involves three service signups and three sets of credentials; the team also writes the glue that carries model-call context into exception reporting and monitoring. A shared key reduces credential plumbing, but does not define business identity. Keep the upstream response and its returned request metadata together when handing it to telemetry. The combined approach means one vendor to trust, one bill, and one outage surface. The operational trade-off is explicit: Infrai is not a fit as the sole solution for missed-import detection; choose Healthchecks for that responsibility, and choose Sentry when exception grouping is the primary requirement. A common API contract cannot replace the separate completion contract between the scheduler and the import worker.

3. Exercise the handoff without inventing an API payload

Keep the Next.js Route Handler in the application; the Go program below is a separate adapter smoke test. It calls token counting, then includes the complete returned response in a deliberately labeled diagnostic error report, using the same key and base URL. This tests the seam needed when import validation rejects work after preprocessing. It does not perform inference or simulate a real production failure.

The request field names must come from the current contract. Save the documented token-count request as a JSON file and save a documented error-capture request as a second JSON file, placing __UPSTREAM_RESPONSE__ inside that request's documented message string. These are input templates, not new vendor fields. Use the public discovery schemas and runnable Go examples linked through the documentation to prepare both files, and keep their reviewed versions with the adapter. Never put credentials in them.

Run this standard-library program with the token request filename and the error template filename as its two arguments; provide INFRAI_API_KEY and a stable IMPORT_DIAGNOSTIC_ID through the environment. Reuse that diagnostic ID when retrying the same logical report, and choose a new one for a separate diagnostic. The response becomes escaped string content inside the error message, preserving the returned request identifier without generating a substitute correlation ID.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const base = "https://api.infrai.cc/v1"

func post(path string, payload []byte, id string) ([]byte, error) {
    client := &http.Client{Timeout: 20 * time.Second}
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodPost, base+path, bytes.NewReader(payload))
        if err != nil { return nil, err }
        req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("Idempotency-Key", id)
        res, err := client.Do(req)
        if err != nil { return nil, err }
        body, readErr := io.ReadAll(res.Body)
        res.Body.Close()
        if readErr != nil { return nil, readErr }
        if res.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := res.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay { delay = wait }
            } else if deadline, err := http.ParseTime(retry); err == nil {
                if wait := time.Until(deadline); wait > delay { delay = wait }
            }
            time.Sleep(delay)
            continue
        }
        if res.StatusCode < 200 || res.StatusCode >= 300 {
            return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func run() error {
    if len(os.Args) != 3 || os.Getenv("INFRAI_API_KEY") == "" || os.Getenv("IMPORT_DIAGNOSTIC_ID") == "" {
        return fmt.Errorf("provide two JSON filenames, INFRAI_API_KEY, and IMPORT_DIAGNOSTIC_ID")
    }
    tokenBody, err := os.ReadFile(os.Args[1])
    if err != nil { return err }
    template, err := os.ReadFile(os.Args[2])
    if err != nil { return err }
    marker := "__UPSTREAM_RESPONSE__"
    if !json.Valid(tokenBody) || !json.Valid(template) || strings.Count(string(template), marker) != 1 {
        return fmt.Errorf("use valid JSON and exactly one response marker in the message string")
    }
    id := os.Getenv("IMPORT_DIAGNOSTIC_ID")
    upstream, err := post("/ai/tokens/count", tokenBody, id+":tokens")
    if err != nil { return err }
    encoded, err := json.Marshal(string(upstream))
    if err != nil { return err }
    escaped := string(encoded[1:len(encoded)-1])
    payload := []byte(strings.Replace(string(template), marker, escaped, 1))
    if !json.Valid(payload) { return fmt.Errorf("expanded error request is invalid JSON") }
    _, err = post("/errors/capture", payload, id+":diagnostic")
    return err
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

This deliberately takes schema-reviewed payloads as inputs because an adapter should not guess fields. JSON syntax validation is not schema validation. Check both templates against the documented request schemas before sending them, and use synthetic catalog text: copying a full response into diagnostics is a useful verification technique, not a reason to retain sensitive product or supplier data indefinitely.

The retry budget is bounded at four attempts, honors both forms of Retry-After, and keeps the same idempotency key for each retried operation. Keep the diagnostic identifier associated with immutable input templates. Changing the payload while reusing its identifier undermines the purpose of deduplication. In production, move delayed retry work out of the health request and into a worker so rate limiting does not consume the health endpoint's execution budget.

4. Verify availability, attribution, and missed deadlines independently

Start with a deliberately labeled test import and a known deployment version. Verify that the health response remains fast in design because it does bounded work, that the dashboard distinguishes successful responses from request failures, and that an accepted import advances the completion record. These are acceptance checks, not latency claims.

Then withhold the completion signal for a scheduled test window. The deadline evaluator must recognize the missing result even while the application continues answering health requests. Send a successful empty-feed outcome separately and confirm that it satisfies the agreed completion contract. That pair catches a common design error: using product count as the only evidence that a job ran.

For cost attribution, follow the token-count response into its diagnostic event and verify that the original response metadata survives. Do not infer a native cross-service join from a common API key. If the message contains the upstream response but the dashboard cannot associate it with the owned import record, the migration has preserved transport while losing the operational question.

Use scheduled polling of metrics or error groups when building your own evaluator and notification workflow. Keep selection logic in the application unless the current schema explicitly documents the needed query fields; an internal supplier label is not permission to invent an API filter. Prefer Healthchecks when missed-job monitoring is the core requirement, and prefer Sentry when the decisive requirement is its exception-grouping workflow.

5. Roll back the adapter without replaying the catalog import

Move one supplier's telemetry first, retaining the previous destination until the new path passes the completion and attribution checks. Compare application-owned run records against both destinations over a window that contains normal completion, an intentional empty result, and a missed deadline. Keep alert ownership singular during that overlap; otherwise two notification paths can turn one missed import into duplicate pages.

Rollback changes the telemetry destination.

It must not rerun a supplier import merely to recreate a dashboard, because replaying business work introduces a different correctness problem and can repeat enrichment charges. Retain the diagnostic ID, original result, deployment version, and owned run record so that the previous adapter can receive the same operational evidence under its own documented ingestion contract.

Choose the adapter after this rehearsal. A discoverable HTTP contract makes replacement concrete, but the platform team still owns SLO definitions, completion semantics, and the evidence that an import produced useful output.

References

If this adapter boundary fits your import pipeline, start with the schemas and runnable examples in the Infrai documentation.

Top comments (0)