Detecting Attacks in Traces
local graph
Chapter 13 — Detecting Attacks in Traces
Section titled “Chapter 13 — Detecting Attacks in Traces”In the previous chapter, we put you in the on-call seat to debug a complex checkout degradation. We built a repeatable, evidence-driven workflow: detect with alerts, investigate with traces, diagnose with metrics, and correlate with logs. That identical framework is the foundation of security observability.
Traditionally, security monitoring and performance debugging have lived in separate silos. Security teams stare at Security Information and Event Management (SIEM) dashboards full of firewall logs, while platform engineers pore over Jaeger traces and Prometheus metrics looking for latency spikes.
But to an engineer running production services, an attack on your infrastructure is fundamentally just an anomalous request journey. The tools you use to find performance bottlenecks are the exact same tools that surface security breaches. A credential stuffing attack is just an anomalous spike in failed authentication spans. A targeted data exfiltration attempt is just a trail of unusually large database responses. A distributed denial-of-service (DDoS) attack is just resource saturation bubbling up as backpressure across your async runtimes.
In this chapter, we are not introducing new tools or complex security platforms. We are going to apply the confident, evidence-driven incident response workflow from Chapter 12 to a new domain. We will leverage the exact same tracing instrumentation and OpenTelemetry infrastructure we have built to read traces not just for speed, but for safety.
What this chapter covers:
- How to map canonical request paths to identify skipped or repeated architectural hops
- How to detect authentication abuse patterns like credential stuffing using failed spans
- How to spot data exfiltration attempts using anomalous database payload sizes
- How to deploy DDoS indicator metrics and investigate complex resource exhaustion attacks
- How to implement application-level load shedding to mitigate DoS at the runtime layer
- How to configure OpenTelemetry Collector tail-sampling to cost-effectively retain security traces
Detecting Anomalies in the Request Journey
Section titled “Detecting Anomalies in the Request Journey”Before we can use traces to detect attacks, we need to define what an “anomaly” actually is.
In observability, an anomaly is a deviation from an established baseline or expected pattern. When you investigated performance in Chapter 9, a latency anomaly meant 5 seconds instead of 50 milliseconds. The system did what it was supposed to do, it just did it slowly.
A security anomaly, however, is often structural or behavioral. The attacker is not just making the system slow, they are forcing the system to behave in ways it was never designed to. They are accessing internal endpoints directly, repeatedly triggering expensive logic, or extracting massive amounts of data. These actions change the literal shape, topology, and metadata of the trace hierarchy.
To spot a structural anomaly, you first need a solid baseline of what “normal” looks like.
Defining the Baseline: The Normal Journey
Section titled “Defining the Baseline: The Normal Journey”As we saw in Chapter 3, a canonical checkout request follows a highly predictable, well-defined topological path. Every time a legitimate user checks out, the trace waterfall in Jaeger looks roughly like this:

Generated ASCII Image
Figure 13.1 – The baseline checkout journey: a properly-rooted trace from the OtelMart gateway through Orders and Inventory to PostgreSQL
This is our baseline. We expect a checkout trace to have this specific parent-child structure.
Recognizing the Deviations: The Abnormal Journey
Section titled “Recognizing the Deviations: The Abnormal Journey”An abnormal journey breaks that expected structure. When an attacker probes or exploits your system, their actions produce traces that look alien compared to the baseline. These security anomalies typically fall into three highly visible categories:
- Skipped Hops (Topological Anomalies) A trace begins deep within your internal network rather than starting at the
Generated ASCII Image - Repeated Hops (Behavioral Anomalies) A single request at the gateway spawns an unusually high number of backend requests. While this could be a performance bug (like the N+1 database query problem we fixed in Chapter 11), in a security context, it often indicates an attacker brute-forcing an endpoint or triggering an expensive application loop to exhaust resources.
Detecting which IP is behind the attack is straightforward: when your tail-sampling policy flags a suspicious trace, the observability platform captures the full request metadata. Your security team can pivot from the anomalous trace (
trace_id,timestamps,user_id, resource IDs accessed) directly into your Web Application Firewall (WAF) logs or your cloud provider’s network telemetry (e.g., Azure Application Gateway, Google Cloud Armor) to identify and block the source IP. This way, your application’s observability pipeline stays free of raw IP PII — the application layer provides behavioral signals, and the network layer handles the blocking. IPs are detected, not stored: Your traces never log raw IP addresses. Instead, when an attack is detected (flagged by the tail-sampling policy), the security team correlates thetrace_idand timestamp with WAF or network logs to find the offending IP. This separation of concerns keeps your observability clean while enabling rapid response. - Unusual Patterns (Attribute Anomalies) The shape of the trace looks topologically correct, but the metadata is deeply suspicious. For instance, the HTTP request might exhibit an
http.request.header.user_agentthat rotates wildly every second. Alternatively, a database span that usually returns one or two items might suddenly show adb.response.returned_rowsattribute skyrocketing to 50,000. By configuring our observability pipeline to flag these specific structural and metadata anomalies, we transform standard performance telemetry into an active security detection system. This gives us deep, application-level security visibility out-of-the-box, complementing your perimeter WAF without the need to inject heavy, invasive security SDKs into your Rust services. We will explore exactly how to instrument and act on these volumetric anomalies in the Data Exfiltration Detection section below.
How real production apps actually do it: The modern industry standard is to converge performance and security telemetry into a single pipeline. Major observability platforms ingest standard OpenTelemetry distributed traces and route them directly through specialized threat detection engines. In real production environments, your application relies on these traces for deep application-layer threat detection, acting as the perfect complement to your perimeter defenses (like WAFs) and OS-level monitoring (like eBPF agents).
Authentication Abuse Detection
Section titled “Authentication Abuse Detection”Let’s put our evidence-driven incident workflow into practice. Imagine your PagerDuty goes off: the OtelMart gateway is reporting a 15% spike in HTTP 401 Unauthorized responses.
In a traditional setup, one without distributed tracing, you would look at a generic Prometheus metrics dashboard and verify that errors are indeed elevated. But why? Is a newly deployed frontend bug sending expired tokens? Is a single user aggressively forgetting their password? Or is an attacker running a distributed credential stuffing botnet? Without a high cardinality context, you are just guessing.
With OpenTelemetry, we replace guessing with evidence. We want to actively instrument our Gateway to emit rich security telemetry that answers why the authentication failed and who is attempting it, without ever logging sensitive passwords or PII.
Let’s look at the complete security_audit_middleware implemented in the OtelMart gateway. This middleware wraps the entire request workflow in a dedicated auth.attempt span, actively tracking the outcome.
pub async fn security_audit_middleware(request: Request, next: Next) -> Response { // 1. (IP hashing logic omitted for brevity)
// 2. Create a dedicated security span with empty evaluation fields, let security_span = info_span!( "auth.attempt", otelmart.security.event.type = "authentication", otelmart.client.address.hash = %ip_hash, otelmart.auth.success = tracing::field::Empty, );
async move { // Run the downstream Axum request handlers let response = next.run(request).await;
// 3. Record the failure outcome on the span if response.status() == 401 { // Unauthorized Span::current().record("otelmart.auth.success", false);
// 4. Emit an explicit event for immediate SIEM alerts tracing::warn!(event = "otelmart.security.auth_failed", "Authentication failed"); }
// ... (record success cases omitted) ... response } .instrument(security_span) .await}The OtelAxumLayer already records the HTTP 401 status code via the http.response.status_code attribute. Note that per OTel HTTP semantic conventions, only 5xx server errors set otel.status_code = ERROR; a 401 leaves the span status as UNSET. This is exactly why otelmart.auth.success is a necessary custom attribute: it provides a clean, explicit key that the OpenTelemetry Collector’s tail-sampling and routing processors can target without fragile logic based on HTTP status codes, which may not carry the ERROR signal. We namespace it under otelmart.* because it is a custom application attribute, not part of the OpenTelemetry semantic conventions. This is the same namespacing pattern we have used throughout the book for application-specific telemetry.
Let’s look at why this specific middleware design is so powerful for active security detection:
- Centralized Threat Attributes: By explicitly recording
otelmart.auth.success = falseon the root security span, we create a deterministic detection rule. A SOC (Security Operations Center) dashboard or an OpenTelemetry Collector can immediately trigger an alert the moment a singleotelmart.client.address.hashgenerates an anomalous cluster of failedauth.attemptspans. - Request Scope: By wrapping the downstream Axum execution (
next.run(request).await) with.instrument(security_span), every downstream span within this authentication request (for example, a user-lookup query) is parented under theauth.attemptspan. Note that if credential stuffing succeeds, subsequent authenticated requests (checkout, order creation) produce separate traces — they are not automatically children of the originalauth.attemptspan. Those traces are still correlated through the sharedotelmart.auth.user.idattribute, which you can use to trace the blast radius across multiple traces in Jaeger.
The Dual-Signal Strategy: Bridging Performance and Security
Section titled “The Dual-Signal Strategy: Bridging Performance and Security”Notice how our middleware emits two distinct signals the moment an authentication attempt fails. This is a deliberate architectural pattern designed to satisfy both the engineers debugging the system and the security tools protecting it, all from a single instrumentation point:
- Strategic Context (
Span::record): By attachingotelmart.auth.success = falsedirectly onto the active trace, we empower the on-call engineer workflow. If you get paged for elevated 401 errors, you do not have to guess why. You open Jaeger, group the traces byotelmart.client.address.hash, and instantly visualize whether 50 distinct users are legitimately mistyping passwords, or if a single hashed IP is firing rapid-fire requests, proving a malicious bot is actively attacking the login endpoint. - Tactical Alerts (
tracing::warn!): By explicitly firing aotelmart.security.auth_failedlog event, we satisfy dedicated security workflows. Instead of overwhelming security dashboards with millions of verbose performance traces, the OpenTelemetry Collector can easily filter out these specificwarn!logs and route them directly to a SIEM to trigger an immediate, automated block.
By enriching standard performance traces with this dual-signal approach, we break down the conventional silos between performance debugging and security monitoring. A single, elegant Rust middleware protects the system while providing irrefutable, high-cardinality evidence to whoever is on call.
Data Exfiltration Detection
Section titled “Data Exfiltration Detection”In the previous section, we defended the public gateway (Hop 1). But breaches are not always stopped at the front door. If an attacker bypasses authentication, exploits a SQL injection (SQLi) vulnerability, or finds a broken access control architecture, their next target is usually deep within your internal network (Hop 3 or beyond).
Their ultimate goal? Data Exfiltration
What is Data Exfiltration and Why Does it Matter?
Section titled “What is Data Exfiltration and Why Does it Matter?”Data exfiltration is the unauthorized extraction of sensitive information from your system. Rather than bringing your servers down to disrupt service, the attacker stealthily and exfiltrates your users’ personal data, payment details, or proprietary intellectual property.
The business impact of exfiltration is catastrophic. Unlike a temporary performance outage, a data breach permanently erodes user trust and often triggers massive compliance fines (such as GDPR or HIPAA penalties).
To pull off this crime, the attacker must compel your database to return orders of magnitude more data than a standard user workflow requires. A legitimate user fetching their own user profile triggers a database query that returns exactly one row. An attacker executing a SQL injection to dump the entire user table forces the database to return more rows than usual. This sheer volumetric difference is the key to detecting them.
Detection via Distributed Traces
Section titled “Detection via Distributed Traces”We established above that a sudden, massive spike in the number of returned rows is the definitive fingerprint of an exfiltration attempt. But how do we actually surface that fingerprint so an on-call engineer or a security dashboard can see it?
If you followed the database instrumentation guide in Chapter 5, your SQLx queries are already emitting connection spans. However, standard observability pipelines are optimized for performance. They tell us that a database query was successfully executed in 12ms. They do not inherently record how much data was extracted during those 12ms. To weaponize our backend queries for security, we must explicitly instrument them to track payload volumes.
Let’s look at the list_inventory function in our Inventory service. We use the standard OpenTelemetry semantic attribute db.response.returned_rows to attach this volumetric data directly to the active span.
#[instrument( name = "SELECT inventory", skip(pool), fields( db.system.name = "postgresql", // 1. WHAT: Pre-allocate the OTel security field db.response.returned_rows = tracing::field::Empty, ))]pub async fn list_inventory(/* ... args omitted ... */) -> Result<Vec<ProductInventory>, sqlx::Error> { // Execute the dynamic database query let inventory = query_builder.build_query_as().fetch_all(pool).await?;
// 2. HOW: Explicitly record the result size onto the active span Span::current().record("db.response.returned_rows", inventory.len());
Ok(inventory)}This architectural pattern is incredibly resilient to evasion. An attacker exploiting a SQL injection (such as passing 1=1 to dump a table) may successfully bypass database access controls, but they do not control your application’s tracing pipeline. They cannot prevent the list_inventory function from accurately measuring its own vector length and securely stamping that true volume onto the active span before the data is ever serialized back to the client.
Furthermore, by adhering to the OpenTelemetry semantic convention db.response.returned_rows rather than inventing a custom attribute (like my_app.db.size), we ensure interoperability across observability platforms.
db.response.returned_rows is currently classified as experimental in the OTel semantic conventions and requires the semconv_experimental feature flag in the Rust opentelemetry‑semantic‑conventions crate. Its schema may still evolve. You can use it today with that caveat, or define your own otelmart.db.response.returned_rows custom attribute if you prefer a stable name.
While a massive SQL dump is a highly visible example, it is ultimately just one of many ways an attacker might attempt to steal data. By systematically designing your tracing pipeline to capture these necessary context and volume signals across all your persistence layers, you provide your incident responders with the high-fidelity evidence they need to proactively detect anomalies and prevent catastrophic breaches.
Rapid Mitigation
Section titled “Rapid Mitigation”When a volumetric alert triggers, the resulting incident response is highly targeted. Because the anomaly is embedded in a distributed trace rather than in an isolated database log, responding engineers use the Trace ID to follow the attack backward from the database up to the gateway.
Consider the investigation flow. The alert fires: ” db.response.returned_rows exceeded threshold of 100 on span SELECT inventory.” The on-call engineer opens Jaeger, searches by the Trace ID attached to the alert, and sees the full waterfall:

Generated ASCII Image
Figure 13.3 – A data exfiltration trace with db.response.returned_rows = 47,832 flagged on the SELECT inventory span, alongside the gateway’s user ID and hashed client address
The trace tells the complete story without ambiguity. The SELECT inventory span returned 47,832 rows instead of the expected 1-5. The request originated from otelmart.auth.user.id = "user_847" at IP hash a3f8c2.... The engineer now has the exact session to revoke, the exact endpoint to patch, and the exact IP hash to block. No log correlation is required. No guesswork about which user or which endpoint was involved. The distributed trace provides the full attack narrative in a single view.
The response playbook is direct: revoke the session token for user_847, deploy a temporary rate limit on the /checkout endpoint for the offending IP hash, and file an urgent fix for the query that allowed unbounded result sets.
The Limits of Application Telemetry: Keep in mind that OpenTelemetry distributed tracing only monitors data exfiltration that flows through your instrumented application layer. If an attacker bypasses your API entirely, such as by compromising native database credentials or gaining direct SSH access to your Postgres cluster, your application telemetry will be blind to the extraction. Out-of-band monitoring (like raw database query logs or VPC flow logs) is still required for true defense-in-depth.
Suspicious Access Patterns (IDOR & BOLA)
Section titled “Suspicious Access Patterns (IDOR & BOLA)”A massive volumetric database dump is a highly destructive attack, but it is often noisy and easily caught by the db.response.returned_rows threshold we just configured. A stealthier, far more common data theft technique is Insecure Direct Object Reference (IDOR), often referred to in modern API security as Broken Object Level Authorization (BOLA).
In a BOLA attack, the adversary does not try to dump an entire table in a single payload. Instead, they authenticate legally, receive a valid session token, and then systematically iterate through resource IDs they do not own. For example, a malicious script might sequentially call GET /api/orders/100, GET /api/orders/101, GET /api/orders/102, patiently harvesting single records one by one.
Because each database query returns exactly one row, our returned_rows volumetric anomaly alarm will remain completely silent.
Detecting the Scraping Loop
Section titled “Detecting the Scraping Loop”To catch BOLA and unauthorized scraping loops, we must shift our forensic focus from query volume to access frequency per identity.
This is where the “single pane of glass” power of OpenTelemetry shines. Remember the otelmart.client.address.hash and otelmart.auth.user.id attributes we injected at our API Gateway during the authentication phase? Distributed context propagation carries the trace and span IDs across service boundaries — span attributes themselves do not automatically appear on child or sibling spans. However, because all spans in a request share the same trace_id, your observability platform can join them by querying db.operation.name = "SELECT" spans on the orders collection, then pivot by trace_id to find the gateway span carrying otelmart.auth.user.id. This trace-level correlation is what enables identity-based scraping detection.
Configuring the BOLA Alert
Section titled “Configuring the BOLA Alert”A mature security team configures an entirely different alert targeting this specific vector: “Alert if any single otelmart.auth.user.id (correlated via shared trace_id) initiates more than 100 unique db.operation.name = \"SELECT\" spans against the orders collection within a 60-second window, AND the db.response.returned_rows is strictly equal to 1.”
The resource.id concept (e.g., the accessed order ID) mentioned in detection rule summaries is not automatically instrumented by SQLx or OtelAxumLayer. To enable per-resource correlation, explicitly record it as a span attribute in your handler or query span: Span::current().record("db.query.parameter.order_id", order_id). The db.operation.name attribute follows the stable OTel DB semantic conventions; the older db.operation name was deprecated and replaced.
This highly specific correlation isolates the exact behavioral fingerprint of an iterative IDOR script. When the alert fires, the responding engineer can pivot directly into the distributed trace, identify the malicious otelmart.auth.user.id driving the loop, and revoke the compromised session token before the attacker can harvest the entire dataset.
DoS Detection
Section titled “DoS Detection”What is a Denial of Service (DoS) Attack?
Section titled “What is a Denial of Service (DoS) Attack?”A Denial of Service (DoS) attack occurs when an attacker intentionally overwhelms your server with a massive flood of junk traffic, exhausting your CPU, database, or network connections so that legitimate users cannot get through.
Both authentication abuse and data exfiltration can usually be identified by looking at a single, isolated trace. For example, you might see an Inventory span suddenly return 50,000 rows. A DoS attack, however, is a system-wide anomaly. A single malicious request in a DoS attack often looks perfectly identical to a normal user’s request. It is the sheer aggregate volume that causes the system to fail.
Identifying the Exhaustion Fingerprint
Section titled “Identifying the Exhaustion Fingerprint”To effectively detect an application-layer DoS attack before it completely exhausts your infrastructure, you cannot rely solely on standard performance metrics such as CPU utilization or memory usage. By the time those metrics peak at 100%, your system is already in catastrophic failure. Instead, you need explicit OpenTelemetry signals that capture the signatures of the attack in its infancy.
In Rust, emitting these custom security metrics requires nothing more than the opentelemetry::metrics API in your gateway middleware. Instead of just recording basic performance, we actively track the localized request rate:
use opentelemetry::{global, KeyValue};
// Initialize this once in your application startuplet meter = global::meter("security.dos_monitor");let request_counter = meter.u64_counter("otelmart.security.requests").build();
// Inside your Axum middleware, increment the metric using the hashed IPrequest_counter.add(1, &[ KeyValue::new("otelmart.client.address.hash", ip_hash.clone())]);Observing a sudden aggregate spike in this otelmart.security.requests counter might just mean your application went viral. However, if you cross-reference that rate spike with geographic anomalies (like a sudden surge in ddos.requests.by_country from a region you do not typically serve) or connection exhaustion indicators (like ddos.connections.active showing a single IP holding hundreds of idle connections open simultaneously), you have found the definitive fingerprint of an attack. By correlating these diverse signals (volume, origin, and protocol behavior), you construct highly accurate, automated alerts that actively suppress the alert fatigue typically associated with raw threshold monitoring.
When Volume Is Not the Vector: Asymmetric Attacks
Section titled “When Volume Is Not the Vector: Asymmetric Attacks”Not all DoS attacks rely on brute-force volumetric floods. Some of the most devastating attacks are highly asymmetrical, requiring only a handful of malicious requests to completely toxify your routing layer.
Consider the notorious HTTP Request Smuggling attack. In one notable incident documented by Datadog, an attacker weaponized the HTTP specification itself by dispatching meticulously crafted OPTIONS requests containing chunked payloads but explicitly omitting the Content‑Length header. A misconfigured Layer 7 load balancer aggressively stripped the chunk encoding, violently confusing downstream proxy buffers. The malicious payload was left abandoned in the TCP buffer, only to be dynamically prepended to the next legitimate user’s request that shares that connection.
From an incident response perspective, the resulting chaos was baffling: innocent, authenticated users were suddenly receiving 400 Bad Request (Downstream Protocol Error) responses for entirely valid endpoints. The responding engineers did not diagnose this by digging through isolated text logs; they solved it using the exact same high-cardinality distributed tracing principles we discussed throughout this chapter.
First, they queried their traces to isolate the uncharacteristic spike in 400 errors, proving they were generated by the network proxies rather than the application backend. Next, they pivoted using GeoIP tags in their OpenTelemetry logs to discover that every broken transaction was immediately preceded by an anomalous OPTIONS request originating from a specific cloud provider’s IP block. Armed with this incontrovertible evidence, the team identified the exact blast radius and rapidly deployed a targeted block to stop the bleeding.
Mitigation and Good Practices
Section titled “Mitigation and Good Practices”Detecting the flood is only half the battle. When an alert fires, your architecture must be defensively engineered to survive the onslaught. A mature anti-DoS strategy relies on defense-in-depth:
- Edge Mitigation (The WAF): The absolute best place to stop a DoS attack is before it even hits your Rust server. When your OpenTelemetry metrics detect an IP flood, your observability platform should dynamically update your Web Application Firewall (WAF) to block the offenders at the network edge.
- Rate Limiting: For application-layer protection, use crates like
tower‑governorto enforce strict quotas on expensive endpoints (e.g., maximum 5 search queries per second per user). - Load Shedding: If the attack breaches the perimeter, your Rust application must intentionally drop excess traffic to protect its own thread pool and prevent a total crash.
Let’s look at how we implemented active load shedding in our API gateway to keep the system alive under attack.
Application-Level Mitigation: Load Shedding
Section titled “Application-Level Mitigation: Load Shedding”While network teams update Edge WAF rules, your Rust application code must protect itself. We look for signs of saturation and backpressure. In Chapter 10, we learned how to use Tokio Console to observe task queuing and executor starvation. But how do we surface this in Jaeger?
We can use the tower::limit::ConcurrencyLimitLayer to apply backpressure when our system is overwhelmed, and instrument the request path to emit security telemetry when saturation conditions appear.
Let’s condense the OtelMart gateway configuration to focus entirely on the load shedding mechanics:
// 1. Enforce a strict concurrency limit to protect server threads.// \`ConcurrencyLimitLayer\` alone only *queues* excess requests; it does not// shed them. To get immediate HTTP 503 responses when the limit is reached// we combine Tower's \`load_shed()\` (which converts excess requests into an// \`Overloaded\` error) with \`HandleErrorLayer\` (which converts that error// into an axum \`Response\`), all wired via \`ServiceBuilder\`.use tower::{ServiceBuilder, BoxError};use tower::load_shed::error::Overloaded;use axum::error_handling::HandleErrorLayer;
let app = Router::new() .layer( ServiceBuilder::new() .layer(HandleErrorLayer::new(|e: BoxError| async move { if e.is::<Overloaded>() { StatusCode::SERVICE_UNAVAILABLE // HTTP 503 } else { StatusCode::INTERNAL_SERVER_ERROR } })) .load_shed() .concurrency_limit(1000) ) .layer(axum::middleware::from_fn(track_load_shedding));
// 2. Observe saturation symptoms and emit a high-priority security signal#[instrument( skip(req, next), fields( // Pre-declare as Empty so the tail-sampling string_attribute policy can match it otelmart.security.event.type = tracing::field::Empty, ),)]async fn track_load_shedding(req: Request, next: Next) -> Response { let response = next.run(req).await;
if response.status() == StatusCode::SERVICE_UNAVAILABLE { // Record on the span (not a log event) so the OTel Collector // tail-sampling \`string_attribute\` policy can match this trace. Span::current().record("otelmart.security.event.type", "dos_protection"); tracing::warn!( event = "otelmart.security.load_shedding", "Concurrency limit reached, request dropped" ); }
response}By recording otelmart.security.event.type = "dos_protection" as a span attribute (initialized as Empty and recorded at detection time), the tail-sampling policy’s string_attribute matcher can now catch these traces and retain them at 100%. This ensures DoS events flow through to your SIEM for alerting and playbook execution. In practice, pair the concurrency limit with queue-wait or request-timeout telemetry so saturation remains visible even before 503s appear. A sudden spike in these signals, combined with a high request rate on Hop 1, provides a clear signature of an ongoing DoS attack traversing your infrastructure. Your automated mitigation workflows can then use these origin IPs to feed dynamic WAF rules (such as Google Cloud Armor edge policies or native Azure firewall features).
Best Practice: Test Through Simulations
Section titled “Best Practice: Test Through Simulations”You do not want to discover that your OpenTelemetry trace sampling policies or SIEM alert thresholds are misconfigured during an actual attack.
A critical best practice for Security Observability is to frequently run controlled DDoS attack simulations (using authorized cloud partners like BreakingPoint Cloud, Red Button, or RedWolf) against a staging environment. During these simulations, you should ensure:
- Diagnostic Metric Configuration: Validate that the platform-level network telemetry (e.g., cloud-specific tools natively routing
AllMetricsandallLogs) is properly exported and correlated with your internal application OpenTelemetry logs. - Alerting Rules & Action Groups: Confirm that conditions (e.g., an aggregation of an
Under DDoS attack or notmetric breaching a threshold value of1) successfully trigger your configured Action Groups to notify the on-call engineer. - Practicing the Playbook: Ensure the engineering team knows how to pivot from an alert notification into a Jaeger trace view, isolate the offending IPs, and deploy emergency traffic rules without dropping legitimate traffic.
Building Detection Rules
Section titled “Building Detection Rules”We now have four distinct security signals flowing through our traces:
otelmart.auth.success = false,indicating failed logins (Credential Stuffing).db.response.returned_rows > 100indicates abnormally large reads (Data Exfiltration).- High-frequency
resource.idaccess perotelmart.auth.user.idindicating scraping (BOLA). otelmart.security.event.type = "dos_protection"indicating system saturation (DoS).
How do we actually operationalize this? We certainly do not want engineers manually refreshing the Jaeger UI all day.
Tail Sampling for Security Retention
Section titled “Tail Sampling for Security Retention”The first operational challenge is cost. In a healthy production system, the vast majority of traces are normal. Storing every trace at full fidelity is expensive and wasteful. But dropping traces randomly risks discarding the one trace that contains evidence of an attack.
The solution is the OpenTelemetry Collector’s tail_sampling processor. Unlike head sampling (which makes a keep/drop decision at trace creation before any spans have been recorded), tail sampling waits until the trace is complete and then inspects the full span tree before deciding. This means the Collector can examine every attribute we instrumented throughout this chapter and make an informed retention decision.
Here is the tail_sampling processor configuration for our security-aware pipeline:
processors: batch: send_batch_size: 256 send_batch_max_size: 512 timeout: 5s tail_sampling: decision_wait: 10s # Wait 10s for all spans in a trace to arrive num_traces: 100000 # Buffer up to 100k concurrent traces expected_new_traces_per_sec: 1000 policies: # POLICY 1: Keep 100% of traces with authentication failures - name: security-auth-failures type: boolean_attribute boolean_attribute: { key: otelmart.auth.success, value: false }
# POLICY 2: Keep 100% of traces with massive Data Exfiltration - name: security-data-exfiltration type: numeric_attribute numeric_attribute: { key: db.response.returned_rows, min_value: 100 }
# POLICY 3: Keep 100% of traces hitting DoS limits - name: security-dos-dropped type: string_attribute string_attribute: { key: otelmart.security.event.type, values: ["dos_protection"] }
# POLICY 4: Keep 100% of traces with HTTP 5xx errors - name: server-errors type: numeric_attribute numeric_attribute: { key: http.response.status_code, min_value: 500 }
# BASELINE: Keep only 1% of normal healthy traffic - name: baseline-healthy-traffic type: probabilistic probabilistic: { sampling_percentage: 1 }The decision_wait parameter is critical. It controls how long the Collector span before evaluating the policies. If your checkout trace takes 3 seconds end-to-end, a decision_wait of 10 seconds gives the Collector enough time to receive every span in the trace before deciding whether to keep it. Setting this value too low risks evaluating an incomplete trace and missing the security attribute that would have triggered retention.
This configuration guarantees that if an anomaly occurs, the entire trace (from the frontend IP hash down to the deepest database query) is preserved and sent to your observability backend. Meanwhile, 99% of your normal, healthy traffic is dropped before it reaches storage, dramatically reducing your observability costs.
Summary: Security as an Observability Problem
Section titled “Summary: Security as an Observability Problem”In this chapter, we reframed application security as an observability problem. Rather than relying solely on perimeter-based Web Application Firewalls that are blind to business logic, we demonstrated how to detect sophisticated API threats from the inside out using OpenTelemetry.
We built four concrete detection capabilities on top of the same instrumentation infrastructure that has been running since Chapter 4. We tracked credential stuffing cascades at the gateway using otelmart.auth.success attributes and hashed IP grouping. We set volumetric thresholds on db.response.returned_rows to catch data exfiltration. We identified stealthy BOLA scraping loops by correlating otelmart.auth.user.id against high-frequency resource.id accesses. And we measured infrastructure saturation to detect Denial of Service attacks, capturing load-shedding events directly in our traces. Each detection capability required fewer than 20 lines of Rust middleware or handler code, because the hard work (context propagation, span parenting, attribute recording) was already in place.
We then operationalized these signals using the OpenTelemetry Collector’s tail-sampling processor. The four-policy configuration guarantees that every anomalous trace is preserved at full fidelity while 99% of healthy traffic is dropped before storage, keeping observability costs under control without sacrificing forensic coverage.
Application-layer telemetry has real limitations. Because OpenTelemetry operates at Layer 7, it cannot detect attacks that bypass the Rust application entirely (exploiting a zero-day in the native PostgreSQL engine, or obtaining direct SSH access to your infrastructure). Deep network layer attacks, such as TCP SYN floods, will exhaust the load balancer before they ever reach your Axum routes. For true defense-in-depth, application tracing must always be combined with infrastructure monitoring and packet-level inspection.
But within its scope, application telemetry provides something that perimeter tools cannot: visibility into business logic. The WAF can tell you that a request arrived. The trace shows that the request accessed 50,000 rows it should not have, using a session token issued 3 minutes ago, from an IP hash that has been hitting the login endpoint at 200 requests per minute. That level of context is what turns a vague security alert into an actionable incident response.
The ultimate goal of enriching traces with security context is not manual detection. It is automated remediation. As your tracing pipeline matures, these high-fidelity OpenTelemetry alerts can be wired directly into runbooks that dynamically update Edge WAF rules, temporarily lock compromised user accounts, or automatically scale up database read-replicas during an attack.
In the next chapter, we extend the same instrumentation discipline to a new kind of dependency: a third-party AI model with non-deterministic latency and token-based cost. The patterns are the same (instrument, measure, detect anomalies), but the failure modes are entirely different.