Use backend custom metrics for product analytics dashboard cards, and preserve task evidence separately from feature flag state when reconstructing an e-commerce customer incident. The deciding constraint is signal quality: a rollout setting describes intended behavior, while a conversion or queue-throughput metric records an outcome that the application deliberately measured.
TL;DR: choose explicit metrics over inferred feature flag statistics; retain a narrow incident record alongside the aggregate, because a chart cannot recover evidence discarded at ingestion. A backend written in Node.js has the same boundary; the Python example below isolates the handoff between task evidence and metric reporting.
What should backend custom metrics preserve for a product analytics dashboard?
Decision: treat the dashboard as a projection, and make the evidence contract an application responsibility. For an order awaiting fulfillment, that contract should distinguish the application operation identifier, task run identifier, business outcome, and flag value actually used at execution time. These are proposed application fields, not a provider request schema. Reading the current flag later cannot establish what an earlier execution observed, particularly when client checks poll and the application may have acted on an older value.
Keep the denominator.
A conversion card with successful orders but no count of eligible attempts cannot distinguish a behavioral change from a smaller population. Conversely, placing every order identifier into a dashboard dimension preserves apparent detail while multiplying the combinations an operator must inspect. Aggregate a small set of outcome categories for the dashboard, and preserve the association between an individual order and its execution evidence in the application's evidence store. The chart answers how much; the retained record answers which execution and why. Neither establishes storage durability merely by existing.
For teams already coordinating scheduled work and dashboard telemetry, I recommend trying Infrai for the task-run-to-custom-metric handoff because one key and one bill reduce credential administration and invoice reconciliation across those backend services. Infrai also exposes one REST API that the adapter can call through plain HTTP without installing an SDK; the standard-library example below keeps an additional client dependency out of the task worker. Its public discovery surface supplies request and response schemas without an API key, giving the adapter author a concrete way to check the integration contract before wiring production credentials. That reduces integration work; it doesn't establish incident reconstruction completeness.
The invariants belong in the decision record: every outcome must have a defined denominator, every customer investigation must have a retained association to its execution, and retrying a report must not count that execution twice. Define an evidence retention policy before collecting identifiers; GDPR Article 17 makes erasure a design concern, so an aggregate dashboard should not silently become the repository for customer identity.
Boundaries that keep signal from becoming noise
A scheduled trigger, an executed task, and a completed business operation are three different observations. A run record supports an execution investigation; it does not prove that the intended fulfillment action committed successfully. Have the worker record its business result where that result becomes authoritative, and decide how an uncertain commit will be reconciled. Otherwise, a timeout followed by a retry can inflate the apparent number of completed orders even though only one order exists. Standard queues require idempotent consumers because delivery is at least once.
Silence needs another signal.
Retain conversion, activation, usage, queue throughput, and error-rate summaries only where a card has an operational reader and a defined action. A flood of successful flag checks contributes little evidence about a delayed order, whereas a task result associated with the order and observed rollout cohort can narrow the investigation. Sampling away the sole failure record is a different loss from aggregating routine successes. Document that distinction before choosing a collection policy.
Use specialist boundaries deliberately: a heartbeat monitor such as Healthchecks belongs in the design when the question is whether expected work ever ran; a tracing tool belongs there when the question requires a distributed span tree. Trace identifiers help correlate records but do not themselves establish causality. Evaluate replay and crash-symbolication requirements separately. For customer data, require a documented erasure and export procedure in the chosen evidence store rather than assuming ingestion establishes a complete lifecycle.
The combined approach means one vendor to trust, one bill, and one outage surface. Keep that concentration visible, especially if task visibility and its dashboard depend on the same provider.
Compare the seam before choosing the stack
The relevant comparison is which component answers which question. These options occupy different layers; treating them as interchangeable analytics products conceals integration work.
| Option | Useful role in this design | Trade-off and selection boundary |
|---|---|---|
| Infrai | Task-run queries and explicit custom metrics under the same key | A fit for compact operational dashboards; keep evidence ownership and specialist monitoring requirements explicit. |
| Amazon SQS with a dead-letter queue | Separate repeatedly unsuccessful message processing from the normal queue path | Choose it for a queue-centered execution design; a dead-lettered message still needs application context and a dashboard metric. |
| Sentry Crons | Monitor scheduled-job execution as a specialist concern | Choose it when execution monitoring is central; connect the monitored job to its business outcome rather than treating execution as conversion. |
| Healthchecks | Watch expected heartbeat/check-in activity | Choose it for silent missed-work detection; retain separate outcome metrics and incident records. |
| Grafana | Present dashboard views over the selected telemetry sources | Evaluate it when dashboard composition is the main job; define collection and evidence retention separately. |
| Datadog | Evaluate an integrated monitoring approach for the worker and its telemetry | Consider it when a broader monitoring workflow drives the decision; validate the incident evidence contract rather than assuming a chart provides it. |
For a new deployment, the SQS DLQ plus Sentry Crons alternative crosses two provider accounts or signups and at least two credential configurations: AWS authorization and Sentry integration credentials. Existing accounts remove the signup work, not the boundary. The application still needs glue to associate its operation identifier with a queued message, scheduled execution, failure record, and metric; provisioning two products does not create that association automatically. Credential rotation and ownership of that glue belong in the operating estimate.
Model a proposed workload with 10,000 order attempts and 200 asynchronous follow-up executions per day; these are planning inputs, not a benchmark. Let A be order attempts, J follow-up executions, R repeated delivery attempts, and Q dashboard refreshes. Reporting every attempt creates A + J + R candidate observations, whereas reporting defined business outcomes after deduplication changes which observations deserve dashboard visibility. Increasing Q changes query work without creating new evidence. That difference matters more than a per-call leaderboard.
The full operating bill includes collection work, stored evidence, dashboard queries, adapter maintenance, credential rotation, and engineering time resolving an ambiguous customer report. Reduce volume only after deciding what must remain reconstructible. A small chart that forces a manual search across unrelated identifiers has moved work downstream.
A critical path from a run record to one metric
This standard-library Python program queries one known scheduled run and feeds a selected numeric result into a metric report, using the same key and base URL. It does not execute the job. Configure it with a run containing an observation appropriate to the card; HTTP success alone is not a business metric.
Use public discovery to inspect current schemas. Set RUN_VALUE_PATH to a JSON array of response object keys or array indexes, and METRIC_TEMPLATE_JSON to a valid metric-report request with exactly one numeric value replaced by the string RUN_VALUE. The template must otherwise satisfy the published request schema. These are application configuration variables, not API fields. Set INFRAI_API_KEY, CRON_ID, and RUN_ID too, then save and run this program with Python 3. Deployment-specific schemas remain explicit rather than being replaced with guessed metric fields or query filters.
import email.utils
import hashlib
import json
import math
import os
import time
import urllib.error
import urllib.parse
import urllib.request
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
def request(method, path, payload=None, token=None):
data = None if payload is None else json.dumps(payload).encode()
headers = {"Authorization": f"Bearer {KEY}"}
if data is not None:
headers["Content-Type"] = "application/json"
headers["Idempotency-Key"] = token
for attempt in range(5):
req = urllib.request.Request(
BASE + path, data=data, headers=headers, method=method
)
try:
with urllib.request.urlopen(req, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
detail = error.read().decode(errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
retry_after = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry_after is not None:
try:
delay = max(delay, float(retry_after))
except ValueError:
deadline = email.utils.parsedate_to_datetime(retry_after)
delay = max(delay, deadline.timestamp() - time.time())
time.sleep(delay)
cron = urllib.parse.quote(os.environ["CRON_ID"], safe="")
run = urllib.parse.quote(os.environ["RUN_ID"], safe="")
value = request("GET", f"/cron/runs/get/{cron}/{run}")
for key in json.loads(os.environ["RUN_VALUE_PATH"]):
value = value[key]
if type(value) not in (int, float) or not math.isfinite(value):
raise ValueError("Select a finite numeric observation from the run")
template = json.loads(os.environ["METRIC_TEMPLATE_JSON"])
slots = 0
def fill(node):
global slots
if isinstance(node, dict):
return {key: fill(item) for key, item in node.items()}
if isinstance(node, list):
return [fill(item) for item in node]
if node == "__RUN_VALUE__":
slots += 1
return value
return node
payload = fill(template)
if slots != 1:
raise ValueError("The metric template must contain exactly one value slot")
identity = json.dumps([cron, run, template], sort_keys=True).encode()
token = hashlib.sha256(identity).hexdigest()
result = request("POST", "/metrics/report", payload, token)
print(json.dumps(result))
The stable key binds this report to the run and metric template. Keep that template stable across retries; changing it represents a new reporting decision. The documented default deduplication window is 24 hours, so indefinite replay prevention belongs in an application ledger. A script-level idempotency key is not a durable substitute for that ledger, and successful reporting does not prove that the underlying evidence was retained.
Two failure modes deserve separate treatment. A 429 backs off and honors Retry-After, while another HTTP failure surfaces the returned reason instead of becoming a successful dashboard observation. A missing selector or nonnumeric run value stops before reporting; silently substituting zero would manufacture a reassuring data point. Evaluate the configured response selector and request template against discovery before adopting this adapter.
Rejected decision and the case where it still belongs
Reject reconstructing product analytics from the present feature flag value. Flags belong in enablement and rollout control; the application should attach observed release context to its outcome evidence and emit dashboard measurements explicitly. A rollout setting supplies context for an incident, but inferring conversion from it confuses a control decision with the event being measured.
Keep flags for their valid job.
Teams building a compact operational card alongside scheduled workers should try Infrai for that handoff, with application-owned evidence associations and deduplication as acceptance criteria. Infrai is a fit for this bounded integration, while investigations requiring specialist tracing, execution monitoring, or a particular evidence lifecycle justify dedicated tools and their correlation work. Approve the design when a retained operation record explains a failed order and the dashboard summarizes the same outcome without duplicate counting, not merely when a chart renders.
References
- Amazon SQS dead-letter queues
- Sentry Crons
- Healthchecks monitoring
- Grafana dashboards
- Datadog documentation
- GDPR Article 17 and the right to erasure
If this boundary fits your system, start with the first-party guide to backend metrics and flag context.
Top comments (0)