How to Design a Metrics and Telemetry Collection Agent
A practical design for a telemetry collection agent covering signals, sampling, backpressure, PII redaction and AI agent traces, with a reference config.
4 Oct 2026·13 min read·General

Most telemetry problems start at the agent, not the backend. The dashboards stay green while the bill climbs, and the one trace you need during an incident was dropped two hops earlier because a buffer filled up and nobody had decided what should be thrown away first.
A metrics and telemetry collection agent is the small process that sits next to your workloads, gathers signals, shapes them and ships them on. It is easy to start and hard to get right. The hard parts are the ones nobody demos, like resource limits, backpressure, cardinality and redaction.
This guide walks through the design decisions in the order we would make them, with the numbers that justify each one and a reference config at the end. It also covers the extra signals you need once the workload you are watching is an AI agent.
What a telemetry collection agent actually does
The agent is the first tier of your observability pipeline. It runs on every host, node or job, close to the thing producing data, and it has four jobs.
Collect metrics from the host and runtime, and receive traces, logs and events from local applications.
Enrich every signal with identity, such as host, region, service, version and environment.
Protect the pipeline by bounding memory, buffering through outages and redacting sensitive fields.
Ship batches to a gateway or backend over a single, well-behaved connection.
What it should not do is heavy processing. Joins, tail-based sampling and expensive enrichment belong one tier up, where state can be shared across many agents. An agent that tries to be clever competes with the application for CPU, and the application always loses that argument in production.
Choose the deployment shape first
Where the agent runs decides most of its constraints. Three shapes cover almost every case.
Shape | Best for | Watch out for |
|---|---|---|
Host or node agent (one per VM or Kubernetes node) | Host metrics, container metrics, local OTLP endpoint | Noisy neighbours, so set hard resource limits |
Sidecar (one per workload) | Strict tenant isolation, per-service config | Overhead multiplies with pod count |
Gateway (a pooled tier behind the agents) | Tail-based sampling, routing, fan-out to several backends | A single point of failure unless you scale it horizontally |
Our default is a host agent feeding a gateway. The agent stays small and dumb, and the gateway holds the decisions that need a whole-system view. Short-lived workloads change this slightly. A serverless GPU job on Modal has no long-lived host to scrape, so it has to push its telemetry out before it exits, which means a local agent is replaced by an exporter flushing on shutdown.
Design the signal model before the code
Agree on what you collect before choosing how. Four signal types cover nearly everything, and each has a different cost profile.
Metrics are cheap per sample and expensive in cardinality. They answer "how much" and "how often".
Traces are expensive per request and the best tool for "where did the time go".
Logs are the highest volume and the least structured. Keep them structured or they become a storage bill.
Events are discrete facts such as a deploy, a policy block or a failed handoff. They are rare and valuable.
Then fix the resource attributes every signal must carry. At minimum that means service.name, service.version, deployment.environment and the host or pod identity. Without these, a signal cannot be joined to anything and you will rebuild the same context in every dashboard.
Cardinality is the budget you will actually blow
Volume is predictable. Cardinality is not. Take a fleet of 300 hosts, each emitting 800 active series at a 15 second interval.
Active series come to 300 x 800 = 240,000
Samples per second come to 240,000 / 15 = 16,000
Samples per day come to 16,000 x 86,400 = about 1.38 billion
That is manageable. Now one engineer adds a user_id label to a request metric that already covers 50 endpoints. With 10,000 active users that single metric becomes 50 x 10,000 = 500,000 series, or about 33,000 samples per second on its own. That one label has roughly tripled the load of the whole fleet.
The agent is the right place to defend against this. Drop or hash high-cardinality labels on the way out, enforce an allow-list of label keys for application metrics, and stretch the interval for low-value series. Moving a series from 15 seconds to 60 seconds cuts its sample volume to a quarter.
Push, pull or both
Both models earn a place, and the mistake is picking one for every source.
Pull (scrape) suits long-lived targets that expose an endpoint. The agent controls the schedule, and a failed scrape is itself a signal.
Push (OTLP) suits applications that already speak OpenTelemetry and short-lived jobs that cannot wait to be scraped.
A good agent exposes a local OTLP endpoint for applications and scrapes the host and any exporters itself. Bind the local endpoint to loopback or a node-local address so it is not reachable from the network.
Give the agent a resource budget it cannot exceed
The agent shares a machine with revenue-generating code. Treat its footprint as a hard limit, not a goal.
Cap memory with a limiter that starts refusing data before the process is killed, so you lose a few spans instead of the whole agent.
Cap CPU through the platform, with a limit that leaves headroom for bursts.
Bound every queue. An unbounded buffer is a slow-motion out-of-memory kill.
As a starting point for a host agent, we would budget in the low hundreds of MiB of memory and a small fraction of one core, then measure under real load before tightening. The point is that the number is written down and enforced, so a spike in telemetry degrades telemetry and nothing else.
Plan for backpressure and backend outages
Backends go away. Networks stall. The agent has to decide, in advance, what happens next.
Use this order of preference.
Batch and retry with exponential backoff for short interruptions.
Spill to disk with a persistent queue so a restart or a longer outage does not lose data.
Drop deliberately once the bounded queue is full, and drop the cheapest data first.
Priority matters here. Metrics that drive alerts and error traces should survive longer than debug logs and routine successful traces. Encode that as separate pipelines with separate queues, so a flood of logs cannot starve the alerting path.
Count the drops, too. A silent drop is the worst outcome because the dashboard looks healthy while the data is gone.
Sample in two stages
Sampling is where cost and usefulness trade off, and doing it in one place is a mistake.
At the agent, use cheap head-based decisions. Drop health checks, filter known noise and apply a modest probabilistic rate to routine traffic.
At the gateway, use tail-based sampling. It waits until a trace is complete, then keeps everything that failed, ran slow or cost a lot.
Here is what tail sampling buys. Say the gateway sees 2,000 traces per second and 3 percent of them are errors or slow, which is 60 per second. Keep all of those, plus 5 percent of the remaining 1,940, which is 97 per second. You retain about 157 traces per second, roughly 8 percent of volume, and you have kept every trace you would actually open during an incident.
One requirement catches teams out. Tail sampling needs every span of a trace on the same gateway instance, so the agent must route by trace ID rather than round-robin. This is the single most common reason tail sampling quietly misbehaves.
Redact before you ship
Telemetry carries more sensitive data than most teams expect. Query strings, headers, exception messages, prompts and tool arguments can all contain personal data, and once they leave the host they are expensive to recall.
Redact at the agent, because it is the last point you fully control.
Strip or hash known sensitive attribute keys such as authorization headers and cookies.
Apply pattern-based masking for values that look like card numbers or email addresses.
Set retention and access rules in the backend so what survives is not world-readable.
We weigh this heavily when scoring tools in the AI infrastructure and LLMOps category, because traces contain prompts and prompts contain customer data. The same logic applies to your own agent. Confirm redaction and retention before production traffic goes anywhere.
A reference agent configuration
The config below shows the shape using the OpenTelemetry Collector in agent mode. It receives local OTLP, scrapes host metrics, limits memory, redacts, batches, and ships through a persistent queue to a gateway. Treat the limits and the regex as starting points.
yaml
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:4317
http:
endpoint: 127.0.0.1:4318
hostmetrics:
collection_interval: 30s
scrapers:
cpu:
memory:
filesystem:
network:
extensions:
file_storage:
directory: /var/lib/otelcol/queue
processors:
memory_limiter:
check_interval: 1s
limit_mib: 200
spike_limit_mib: 50
resourcedetection:
detectors: [env, system]
redaction:
allow_all_keys: true
blocked_values:
- "[0-9]{13,16}"
batch:
timeout: 5s
send_batch_size: 512
exporters:
otlp/gateway:
endpoint: otel-gateway.internal:4317
sending_queue:
enabled: true
queue_size: 5000
storage: file_storage
retry_on_failure:
enabled: true
max_elapsed_time: 600s
service:
extensions: [file_storage]
pipelines:
metrics:
receivers: [otlp, hostmetrics]
processors: [memory_limiter, resourcedetection, batch]
exporters: [otlp/gateway]
traces:
receivers: [otlp]
processors: [memory_limiter, resourcedetection, redaction, batch]
exporters: [otlp/gateway]
logs:
receivers: [otlp]
processors: [memory_limiter, resourcedetection, redaction, batch]
exporters: [otlp/gateway]Three details are worth noticing. The memory limiter comes first in every pipeline so it can shed load before anything else allocates. The queue is backed by disk so a restart does not erase the buffer. And the receivers bind to loopback, so the agent is not an open door.
Extending the agent for AI agent workloads
Everything above works for services. An AI agent adds a failure mode that infrastructure metrics cannot see. A run can succeed technically, return fluent text and still be wrong, or loop quietly while every span reports healthy.
The numbers explain why. An agent that repeats a retrieval step six extra times against a 3,000-token context burns 18,000 extra input tokens, and each of those spans looks fine. Latency and error rate barely move. Cost does.
To catch this, extend the signal model with four things.
One trace per run. Treat each user request as a single trace with child spans for planning, model calls, tool calls and handoffs, and propagate trace context across every agent and tool boundary.
The GenAI semantic conventions. Use the shared names for operation, agent, model and token usage, such as
gen_ai.operation.name,gen_ai.agent.nameandgen_ai.usage.input_tokens. The OpenTelemetry GenAI attribute registry is the reference, and since it is still evolving, pin a version and change it deliberately.Task outcome, separate from span status. Record whether the task succeeded as its own attribute. A span can finish cleanly and the task can still have failed.
Evaluation scores on the run. Attach a score and the criterion behind it, so a number like 0.4 always says what it is measuring.
Then change the sampling rules at the gateway. Keep every run that failed, scored low, ran slow or cost more than a set multiple of the median for its task type. Sample the healthy runs lightly. A random sample of a healthy-looking agent mostly captures routine successes, which is exactly the data you need least.
The backend you pick shapes how you use this data. Whether you want a tracing-first or an evaluation-first view is the question we work through in LangSmith vs Braintrust. LangSmith's trace explorer is strongest when the problem is seeing what happened in production, while Braintrust fits teams that already know what good looks like and want a quality gate in CI. If you would rather capture at the network edge than in application code, a gateway-level option such as Helicone records model traffic without touching the agent.
Orchestration matters too. Durable checkpoints in LangGraph give you a replayable record of state, which pairs well with traces because you can compare what the graph held against what the spans show. We lay out how these layers fit together in the AI Agent Hub stack, where orchestration, observability, evaluation and compute each get their own layer.
A final boundary worth drawing. Infrastructure telemetry and product analytics answer different questions. Tools like PostHog tell you what users did, and your collection agent tells you what the system did. Keep the two pipelines separate, and join them on a shared identifier only when you need to.
Watch the watcher
At scale you need to monitor your monitoring. The agent exposes its own metrics, and four of them are the ones to alert on.
Spans, metrics and logs accepted by receivers
Items refused or dropped by the memory limiter and processors
Export failures and retries
Queue size against its capacity
Exact metric names vary slightly between collector versions, so check your build. The alert logic does not change. If dropped items rise or the queue sits near full, the pipeline is losing data and the dashboards downstream are lying to you.
Manage configuration centrally. With hundreds of agents you cannot edit files by hand, so ship config through your orchestrator, version it, and roll it out in stages. Inject the shared settings such as the gateway endpoint through environment variables, so applications stay free of telemetry plumbing.
A rollout order that works
Do not instrument everything on day one. This sequence keeps the first release small and the lessons cheap.
Deploy the agent to a single environment with host metrics only.
Add the local OTLP endpoint and migrate one service.
Turn on the persistent queue and test it by killing the gateway on purpose.
Add redaction and verify it with realistic payloads, not synthetic ones.
Add the gateway tier and tail-based sampling.
Extend to AI agent workloads with per-run traces and evaluation scores.
Build or adopt
For most teams the answer is to adopt the OpenTelemetry Collector and configure it, not to write an agent from scratch. It already handles batching, queues, retries, memory limiting and a large set of receivers, and it keeps you portable across backends. Write custom code only for sources it cannot reach, such as unusual embedded devices or proprietary protocols, and even then, write a receiver and keep the rest standard.
Questions
Frequently asked questions
What is a metrics and telemetry collection agent?
It is a lightweight process that runs next to your workloads, collects metrics, traces and logs, adds identifying context, and forwards them to a gateway or backend. Its job is to be reliable and cheap, so it bounds its own memory, buffers through outages and redacts sensitive data before anything leaves the host.
What is the difference between a collection agent and a gateway?
The agent runs on every host or node and does light work such as batching, enrichment and basic filtering. The gateway is a pooled tier that sees data from many agents, so it handles decisions that need a whole-system view, such as tail-based sampling, routing and fan-out to several backends.
Should metrics be pushed or pulled?
Use both. Scrape long-lived targets that expose an endpoint, because the agent controls the schedule and a failed scrape is a useful signal. Accept pushed OTLP from applications and short-lived jobs that cannot wait to be scraped.
How much CPU and memory should the agent use?
Set a hard limit and measure against real load. A host agent can usually run in the low hundreds of MiB of memory and a small fraction of one core. What matters most is that the limit is enforced, so a telemetry spike degrades telemetry and not the application.
How do I stop the agent from losing data during a backend outage?
Batch and retry for short interruptions, use a disk-backed persistent queue for longer ones, and drop deliberately once the bounded queue fills. Prioritise alerting metrics and error traces over debug logs, and alert on dropped items so a loss is never silent.
How do I collect telemetry from AI agents?
Treat each run as one trace, use the OpenTelemetry GenAI conventions for agent, model and token attributes, and record task success separately from span status. Attach evaluation scores to each run and configure tail-based sampling to keep failed, slow, expensive and low-scoring runs.
Should I write my own agent or use the OpenTelemetry Collector?
Adopt the Collector unless you have a source it cannot reach. It already covers batching, retries, queues and memory limiting, and it keeps your pipeline portable. If you need something custom, write a receiver and leave the rest standard.
Final verdict
Adopt the OpenTelemetry Collector, run it as a small host agent in front of a gateway, and design it around how it fails rather than how it behaves on a good day. A collection agent earns its keep during the incident, when a backend is down, a label explodes or a deploy doubles traffic. If it bounds its own memory, buffers to disk, drops the cheapest data first and redacts before shipping, the rest of your observability stack stays trustworthy.
If the workload you are watching is an AI agent, treat that as an extension of the same pipeline and not a second one. Add one trace per run, record task outcome separately from span status, attach an evaluation score, and let the gateway keep the runs that failed, scored low or cost too much. Those are the failures infrastructure metrics will never show you.
WebTechOS accepts no payment for coverage, placement or scores. Where a piece references pricing, it reflects published list rates at the date shown.
Keep reading
All insights →Designing Zero-Downtime Database Migration Frameworks
Design a zero-downtime database migration framework with expand and contract, safe backfills, lock budgets, sync, cutover gates and rollback.
Gorgias Alternatives for Small Ecommerce Teams in 2026
Compare the 7 best Gorgias alternatives for small ecommerce teams in 2026. Review pricing, AI automation, features, and support capabilities.
Is ChatGPT or Claude Worth Paying For? 2026 Pricing Breakdown
ChatGPT Plus and Claude Pro both cost $20. Compare Free, Go, Pro, Max and Ultra plans, usage limits and hidden costs to see which is worth paying for.
Best AI chatbot.com alternatives compared in 2026
Compare 7 AI chatbot alternatives for 2026 on resolution claims, pricing, channels and handoff. See where YourGPT, Intercom, Zendesk and Tidio fit.