Choose a hosted structured logging platform for a SaaS by whether its logs preserve one useful explanation of a failed checkout across retries, server actions, and background work. A pile of JSON is weak evidence if it cannot distinguish an abandoned purchase from a recoverable fulfillment attempt.
TL;DR: For a Next.js logistics SaaS, use structured app logs to connect checkout failures to subsequent job outcomes; choose Sentry or Axiom when the requirement extends into richer debugging workflows. Include Logtail in the comparison, and evaluate a hosted logs API when a common backend contract matters more than specialized investigation features. The decision axis is signal quality versus noise. Price doesn't establish that boundary.
Decision and invariants
This architecture decision record treats checkout as a workflow whose customer-visible outcome and asynchronous execution history can diverge. Consider an illustrative test fixture: checkout checkout_demo_41 produces three attempts to arrange fulfillment, two recoverable failures, and one terminal outcome. Those are proposed test inputs, not measured production results. Counting three error records as three failed purchases would corrupt the operational picture before any query language could help.
Preserve identity first.
The proposed application event contract uses workflow_id, attempt_id, stage, and outcome, with trace_id and span_id retained where instrumentation supplies them. These are application-owned fields, not vendor ingestion fields. Keep a stable workflow identity across retries and a distinct attempt identity for each execution. A terminal outcome must describe the business state the application actually committed; a timeout alone is insufficient evidence that a downstream operation failed.
From a storage architecture perspective, the important distinction is between an authoritative state transition and an observation of that transition: a log entry can help explain an order, but it should not become the mechanism that decides whether the order exists. The checkout's commit boundary belongs to its application data layer. Logging delivery belongs to a separate failure boundary, and the design needs an explicit policy for what happens when that delivery fails. This note chooses to surface delivery errors to the collection caller; the checkout team must decide how its collector buffers or escalates them without silently changing purchase semantics. An ingestion response, by itself, establishes neither a retention guarantee nor the durability of the underlying business transaction.
Which structured logging platform should a SaaS use for checkout logs?
An investigator should be able to explain the terminal checkout outcome without counting retries as new customers or reading every background attempt. The three-attempt fixture should yield one workflow narrative while retaining all three attempts for diagnosis. Authentication failures, API route logs, server action output, and background job output need consistent identities to contribute to that narrative.
Keep two failure modes separate. Duplicate amplification happens when retried delivery makes one observation appear several times. Silent omission happens when a job never executes and therefore emits no failure event. Deduplicating records can address the former; it cannot detect the latter. Scheduled work needs an independent expectation of completion, such as a heartbeat check, because an empty log stream is ambiguous. Healthchecks is a relevant companion to evaluate for that requirement.
Silence proves little.
Signal quality also depends on what stays out. Allowlist operational identifiers and bounded stage names rather than serializing customer addresses, payment details, authentication tokens, or entire order objects. GDPR Article 17 makes deletion behavior a selection concern, not a cleanup task to postpone. Require a documented remediation path before allowing personal data into any candidate, and establish what an ingestion acknowledgment means, how long evidence remains available, and how it can be retrieved after an incident.
Cardinality has a separate boundary. A workflow identifier helps reconstruct one purchase, but placing every unique identifier into a metric label creates a different scaling problem; Prometheus explicitly cautions about label cardinality. Keep detailed identity in event data and bounded dimensions in aggregate operational signals.
Options and their investigation boundaries
This is a selection table, not a benchmark. No throughput, latency, durability, or relative cost has been measured here. Use the same fixture and business-outcome definition for each trial.
| Candidate | Reason to include it | Checkout acceptance test | Boundary to establish |
|---|---|---|---|
| Sentry Logs | Relevant when logging is part of a broader application debugging decision. | Connect the failed checkout to the debugging context the team needs. | Verify the required debugging features and their relationship to logs; a log record alone doesn't establish them. |
| Axiom | A candidate when richer investigation workflows matter alongside structured app logs. | Separate terminal outcomes from repeated attempts without losing attempt history. | Test actual investigation queries instead of treating JSON ingestion as proof of fitness. |
| Logtail / Better Stack | A hosted logging alternative for the app-log workflow. | Find server and worker evidence using stable application identities. | Verify retention, deletion, acknowledgment, and notification requirements against its documentation. |
| Hosted backend API | Fits a team prioritizing a consistent contract across logging and background work. | Carry a job execution result into logging evidence using the same credentials and conventions. | Correlation identifiers do not establish a trace tree or a complete frontend debugging workflow. |
Infrai exposes 295 routes across 20 modules through one REST API and one API key, so adding logging alongside job operations can reuse a consistent contract instead of introducing another integration. Public, self-describing discovery provides a different workflow advantage: the team can inspect request schemas before wiring the checkout collector. Its fit here is centralized app evidence; embedded trace identifiers support correlation, while source map deobfuscation, crash symbolication, session replay, and distributed tracing queries belong in separate tooling. User-specific deletion and evidence-export requirements need explicit review before adoption.
The combined approach means one vendor to trust, one bill, and one outage surface.
The main trade-off is limited investigation scope: a hosted app-log collector is not suitable as the sole tool for frontend-heavy debugging. Prefer Sentry when that debugging workflow drives the decision, or evaluate Axiom when richer investigation is the priority. Require a separate notification and heartbeat design where timely detection is an acceptance criterion.
An SQS dead-letter queue plus Sentry Crons instead introduces two provider accounts for a new deployment, AWS and Sentry, and two credential contexts. The team writes the glue that propagates workflow identities, links queue failures to application events, and reconciles scheduled expectations with execution. Existing accounts reduce onboarding work; they don't remove that correlation responsibility. A dead letter and a missing scheduled execution are different observations.
Critical path: carry run evidence into the logging contract
The handoff below reads an existing cron run and submits its response as application logging evidence, using the same base URL and key for both calls. It doesn't schedule checkout work or acknowledge a queue message. Runs, dead letters, and captured errors are related investigation inputs, but this example demonstrates only the run-to-log seam; validate dead-letter retrieval separately rather than inferring it from this code.
Use Python 3. Set INFRAI_BASE_URL to the documented versioned API base. Load the full public discovery descriptors into RUN_CONTRACT_JSON and LOG_CONTRACT_JSON, selecting paths /v1/cron/runs/get/{id}/{run_id} and /v1/logs/ingest. Set CRON_ID and RUN_ID to an existing run. Set LOG_BODY_TEMPLATE_JSON to a valid ingestion body from its runnable example, placing the string __RUN_RESPONSE__ in the documented message field. These environment values configure the program; they aren't additional API fields.
This keeps the request shape explicit rather than guessing a batch wrapper. Paths come from discovery. The run response becomes text, so the code doesn't assume a nested response shape. Use a sanitized fixture.
import json
import os
import time
import uuid
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE = os.environ["INFRAI_BASE_URL"].rstrip("/")
KEY = os.environ["INFRAI_API_KEY"]
def request_json(contract, path, body=None):
data = None if body is None else json.dumps(body).encode("utf-8")
headers = {"Authorization": f"Bearer {KEY}"}
if data is not None:
headers["Content-Type"] = "application/json"
headers["Idempotency-Key"] = str(uuid.uuid4())
url = BASE + path.removeprefix("/v1")
for attempt in range(4):
req = Request(url, data=data, headers=headers, method=contract["method"])
try:
with urlopen(req, timeout=20) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected status: {response.status}")
raw = response.read()
return json.loads(raw) if raw else None
except HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
if exc.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
delay = float(2 ** attempt)
retry_after = exc.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
deadline = parsedate_to_datetime(retry_after)
delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
time.sleep(delay)
run_contract = json.loads(os.environ["RUN_CONTRACT_JSON"])
log_contract = json.loads(os.environ["LOG_CONTRACT_JSON"])
if run_contract["method"] != "GET" or log_contract["method"] != "POST":
raise ValueError("Select the run-read and log-ingest contracts")
if not log_contract.get("idempotent", False):
raise ValueError("Confirm write deduplication before enabling retries")
path = run_contract["path"]
for field, variable in (("id", "CRON_ID"), ("run_id", "RUN_ID")):
path = path.replace("{" + field + "}", quote(os.environ[variable], safe=""))
run_response = request_json(run_contract, path)
marker_count = 0
def attach(value):
global marker_count
if isinstance(value, dict):
return {key: attach(item) for key, item in value.items()}
if isinstance(value, list):
return [attach(item) for item in value]
if value == "__RUN_RESPONSE__":
marker_count += 1
return json.dumps(run_response, separators=(",", ":"))
return value
payload = attach(json.loads(os.environ["LOG_BODY_TEMPLATE_JSON"]))
if marker_count != 1:
raise ValueError("Use exactly one run-response marker")
request_json(log_contract, log_contract["path"], payload)
print("Run evidence submitted")
Every request has an explicit method, the key stays in an environment variable, and the write retains one idempotency key across its rate-limit retries. The code requires the write contract to declare idempotency before making that write. Four attempts bound retry count; a server-specified retry interval can still make collection take longer than the HTTP timeout. Response status and error bodies are surfaced to the caller rather than assumed successful.
HTTP 429 is the retry boundary here. Other errors stop collection.
There are two intentional limits. The generated key protects retries within this invocation; a durable collector must persist event identity across process restarts. Copying a full run response is appropriate only for the sanitized test fixture: production collection should project an allowlist of operational fields before submission. A log submission is evidence of a job observation, not proof that fulfillment committed.
Rejected option and its valid use case
Reject the proposal to log every exception at the same severity and treat error volume as failed-checkout volume. It confuses attempt history with customer impact, lets a noisy worker dominate the evidence, and cannot reveal a scheduled task that never ran.
Keep verbose attempt logging for a bounded diagnostic investigation where the team needs execution detail and can control the data collected. For routine operation, preserve that detail while making terminal workflow outcomes distinguishable. The acceptance test is concrete: the three-attempt fixture must remain three inspectable attempts and one explainable checkout outcome. Choose a platform only after recovering that distinction and documenting the delivery, retention, and remediation boundaries the design relies on.
References
- Sentry Logs: https://docs.sentry.io/product/explore/logs/
- Axiom documentation: https://axiom.co/docs
- Better Stack logging documentation: https://betterstack.com/docs/logs/
- Amazon SQS dead-letter queues: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html
- Sentry Crons: https://docs.sentry.io/product/crons/
- Healthchecks documentation: https://healthchecks.io/docs/
- Prometheus instrumentation practices: https://prometheus.io/docs/practices/instrumentation/
- GDPR Article 17: https://gdpr-info.eu/art-17-gdpr/
Top comments (0)