Blog

Designing Agent Investigations for Trillion-Scale API Logs

avatarDatabendLabsNov 24, 2026View Markdown
Designing Agent Investigations for Trillion-Scale API Logs

The HTTP 200 Blind Spot: Why Valid Credentials Aren't Enough

Security incidents disclosed in October—including unauthorized internal credential use at Fireworks and attackers abusing admin tokens and cloud keys at Zeabur—highlight a recurring detection problem: what do you check when a request carries a valid credential, passes authentication, and returns

HTTP 200
?

In a microservice architecture, the answer rarely lives in one place:

  • API logs tell you which workload called which endpoint.

  • Deployment records tell you where that workload came from and how it was shipped.

  • Approval tickets tell you whether a sensitive action—like a fund transfer or bulk export—was actually authorized.

Inspecting any single log source in isolation misses the causal chain. We wanted an AI Agent to automate this cross-system triage for security engineers: following leads across tables, aligning calls and deployments on a single timeline, and packaging the raw evidence for human review.

The catch is scale. If your logging pipeline is projected to hit a trillion rows per month, letting an Agent query raw JSON tables directly breaks down fast. On a small Databend Cloud warehouse, scanning 100 million raw logs took roughly 5 seconds. Worse, investigative agents iterate—tweaking filters, checking historical baselines, and pulling back large payloads that quickly blow up the model's context window.

Instead of pointing an LLM at raw logs, we flipped the workflow: pre-aggregate and score risk inside the lakehouse first, then let the Agent drill down only where the risk score points. All results below come from an in-database synthetic dataset covering normal business peaks, manual hotfixes, and an injected attack.

Shrinking the Search Space: Stream Cleaning and Windowed Features

Our pipeline runs in four stages: incremental cleaning on ingestion, 10-minute feature aggregation per workload, business-context risk scoring, and Agent-led evidence retrieval (with humans approving any containment actions).

1. Preserving Raw Payloads Without Rigid Schemas

Microservice log schemas drift constantly as teams ship new fields. To avoid brittle ingestion pipelines, our landing table

sec.raw_api_logs
stores request and response payloads in
VARIANT
columns, alongside
event_time
and
log_id
for raw evidence lookup. Clustering by
event_time
lets time-bounded queries prune irrelevant blocks early:

CREATE DATABASE IF NOT EXISTS sec;
CREATE TABLE sec.raw_api_logs (
event_time TIMESTAMP,
log_id STRING,
req VARIANT,
resp VARIANT
) CLUSTER BY (event_time);

(Note: SQL snippets here illustrate the core pipeline logic rather than full production scripts; you will still need to wire up log shipping, business-field mappings, and access controls.)

2. Incremental Flattening With Streams and Tasks

Querying

VARIANT
paths repeatedly during detection is wasteful. To offload high-frequency queries, we flatten core fields—caller workload, credentials, target endpoints, HTTP status—into a structured event table (
api_events
).

We pair an append-only

Stream
(
APPEND_ONLY = true
) to track only newly ingested rows with a scheduled
Task
running every minute. Whenever
STREAM_STATUS
detects unconsumed rows, the Task extracts the structured columns and advances the stream offset upon commit:

CREATE TABLE sec.api_events_demo (
event_time TIMESTAMP,
log_id STRING,
caller_workload STRING,
http_status INT
);
CREATE STREAM sec.raw_api_logs_s
ON TABLE sec.raw_api_logs APPEND_ONLY = true;

CREATE TASK sec_clean_demo
WAREHOUSE = 'default'
SCHEDULE = 1 MINUTE
WHEN STREAM_STATUS('sec.raw_api_logs_s') = true
AS
INSERT INTO sec.api_events_demo
SELECT event_time, log_id,
req['caller']['workload']::STRING,
resp['status']::INT
FROM sec.raw_api_logs_s;

ALTER TASK sec_clean_demo RESUME;

Tasks are created in a suspended state by default, so you must run

RESUME
to activate scheduling (and
ALTER TASK sec_clean_demo SUSPEND
to pause it after testing).

3. Decoupling Compute From Request Volume

Even on a flattened event table, scanning every row for every detection rule scales linearly with traffic. To break that coupling, we aggregate events into

workload_features
—one row per workload per 10-minute window—capturing call counts, sensitive operations, and trace
log_id
s.

This bounds downstream compute by workload count rather than request volume. With 1,000 active workloads across 144 ten-minute windows per day, the feature table tops out at 144,000 rows per day, even if traffic spikes 10x inside a window. Every 10 minutes, a scheduled job recomputes the last two complete windows and updates the table via

MERGE
so late-arriving logs and approvals are folded in (anything older than the two-window lookback still requires a separate backfill).

Adding Business Context: Baselines, Approvals, and Dynamic Table Scoring

Traffic spikes can be legitimate business peaks, and manual deployments can be routine hotfixes. To separate anomalies from noise, we join

workload_features
with approval tickets (matching operation type, amount, and target account), deployment/credential logs, and each service's 30-day sensitive-call baseline into a risk table (
workload_risk
).

We materialize this join as a Dynamic Table, explicitly triggered by a downstream Task (

REFRESH DYNAMIC TABLE
) right after feature aggregation finishes. Because source changes don't auto-trigger updates, this incurs a full query recompute on each refresh—a tradeoff that works only because inputs are already compressed to the feature layer and window-level latency is acceptable.

For our initial validation, we configured six additive scoring rules:

Detection RuleScore
High-risk operation lacks valid approval, or parameters mismatch the ticket+40
Preset high-risk operation observed (e.g., grant, role assignment, bulk export)+30
Sensitive calls present despite zero occurrences in the service's 30-day baseline+20
Manually deployed workload subsequently calls a sensitive service+20
Deployment credential appears on a new host matching configured time conditions+20
Sensitive call volume exceeds 3x historical peak and meets minimum count threshold+10

Scores dictate triage priority, while the triggered

reasons
persist alongside the score so engineers know immediately whether to audit an approval ticket or trace a deployment.

In our test dataset:

  • A 2x traffic peak on sensitive endpoints where every call matched an approval scored 0.

  • A manual hotfix from a known developer host with no sensitive calls scored 0.

  • The injected attack triggered the first five rules and scored 130.

In production, these weights still need domain calibration—for instance, a service that routinely grants permissions shouldn't automatically accrue +30 points on every call.

Anatomy of an Investigation: Tracing an Injection Attack in 24 Rows

We connected the AI Agent to Databend Cloud via mcp-databend using a dedicated warehouse and a strict read-only role scoped to three objects: the risk table, a unified timeline view, and a raw evidence view. Log text is treated strictly as untrusted data; containment actions like isolating workloads or rotating credentials remain human-in-the-loop.

In our November 9 test run, the Agent investigated the incident in four drill-down steps, returning 24 rows in total:

  1. Triage high-risk workloads (1 row): The Agent queried
    sec.workload_risk
    for the past hour and surfaced
    sync-helper-7f9c
    with a risk score of 130, along with
    deploy_host = laptop-99
    and initial evidence IDs:
-- Prerequisite: create and refresh the complete workload_risk table.
SELECT window_start, caller_workload, risk_score,
reasons, deploy_host, evidence
FROM sec.workload_risk
WHERE window_start >= now() - INTERVAL 1 HOUR
AND window_start < now()
AND risk_score > 0
ORDER BY risk_score DESC
LIMIT 20;

(For live triage,

now()
filters the current hour; reproducing the November 9 test requires swapping in that fixed timestamp window.)

  1. Reconstruct the unified timeline (15 rows): Filtering the two-hour timeline view by workload, host (
    laptop-99
    ), and deployment credential returned 15 events that exposed the full attack chain:
TimeRecorded Activity
08:50Deployment credential
cred-deploy-0
used on known runner
ci-runner-1
10:02Same credential used from an unfamiliar host (
laptop-99
)
10:02:30
laptop-99
bypasses the CI/CD pipeline to deploy a new workload
10:04+New workload uses
svc-core
to call transfer APIs, assign roles, and run bulk exports

All 12 sensitive API calls returned

HTTP 200
. Only by aligning API logs with deployment and approval records on one timeline did the link between the unknown host, bypassed pipeline, and unapproved operations become obvious.

  1. Check blast radius (6 rows): Querying all callers of

    svc-core
    over the 24-hour window returned 6 workloads—5 known services plus
    sync-helper-7f9c
    . Because feature-level evidence and credential arrays have length caps, a summary alone can't rule out other anomalies; wider time-range and raw checks are still required for full blast-radius confirmation.

  2. Verify raw payloads (2 rows): Using two

    log_id
    s and exact timestamps, the Agent pulled the original JSON payloads to verify operation parameters for human sign-off.

Returning 1, 15, 6, and 2 rows respectively kept the LLM's context lean—though the database still does the underlying scan work, making data layout and filter selectivity critical.

Benchmark Results and Testing Boundaries

We validated the end-to-end pipeline on a small Databend Cloud warehouse using 100 million request logs (~570 bytes/row) spanning 24 hours across 200 services and 1,000 workloads, ingested sequentially in 10-minute batches alongside approval, deployment, and credential records.

We also extended the feature table to 30 days (4.32 million rows) to benchmark baseline refreshes, and loaded two 10-minute windows totaling ~460 million rows (matching the average density of 1 trillion rows/month) to test high-density investigation queries.

Pipeline Stage / QueryMeasured Result
Incremental cleaning~31.5s for 100M rows at once; ~1s per 10-min batch (~690K rows)
Feature aggregation~0.6s to recompute two windows (~1.39M rows); ~6.3s to backfill 100M rows (1 day)
Dynamic Table risk refresh~2s over 30 days of features (4.32M rows)
High-density workload queryRead 1 of 1,421 data blocks
Raw payload lookupPruned 563 blocks → 48 by time → 2 via Bloom index

Assuming a 30-day month, 1 trillion rows/month averages ~33.3 billion rows/day (~390K rows/sec). Linearly extrapolating our backfill throughput, recomputing two 10-minute windows (~460M rows) would take roughly 30 seconds. That gives a reasonable starting point for capacity planning, but it still needs validation under continuous ingestion and concurrent agent queries.

What we didn't test: We did not run a full-month, 1-trillion-row end-to-end stress test. Synthetic logs were generated in-database (excluding external ingestion overhead), and

RECLUSTER
costs were not measured separately. As a result, we are reporting per-stage measurements only—not making production cost or compute commitments. Still, the architectural takeaway holds: higher request volumes increase cleaning and aggregation work, while baseline and risk compute stay flat as long as workload count and window granularity remain stable.

Production Gotchas: Clustering Depth, Index Selectivity, and Point-in-Time Joins

Most of the hard problems happened before the Agent ran a single query:

  • Ingestion order dictates clustering depth: When we bulk-loaded 24 hours of logs in one shot,

    raw_api_logs
    hit an average clustering depth of 464 because data blocks spanned wide time ranges, crippling time pruning. Switching to sequential 10-minute batches dropped clustering depth to 3.5. Always backfill historical data in time-ordered batches and verify clustering health.

  • Few returned rows ≠ small scan: Bloom indexes work great when a suspicious workload appears in only a handful of blocks. For high-frequency workloads present in nearly every block, you must narrow query windows to 10–20 minutes or paginate—otherwise a

    LIMIT 20
    query can still trigger a heavy scan.

  • Incomplete baselines create false positives: When our feature table held only 1 day of history, 300 rows were falsely flagged (+20 points) for lacking baseline sensitive calls. Backfilling the full 30 days eliminated those false positives. Treat baseline coverage as a mandatory pre-launch check and design separate cold-start rules for brand-new services.

  • Point-in-time joins and late data: Our prototype joined the latest deployment record per workload. In production, you need a point-in-time join (the most recent valid deployment before the API call) so newer releases don't retroactively skew past investigations. Similarly, late-arriving logs and updated approval tickets need automated backfill—otherwise "missing approval" just means "data hasn't landed yet."

Where to Start: Building Your First Verifiable Investigation Loop

If you want to adopt this pattern in your own stack, start small and keep the feedback loop tight:

  1. Pick one bounded workflow: Start with a single high-signal scenario—such as bulk-export auditing or tracking sensitive calls after manual deployments—and verify that you can reliably join API logs, approval tickets, and deployment records on shared workload, credential, and ticket IDs.

  2. Test anomalies alongside noisy normal traffic: Include both known attack patterns and legitimate edge cases (traffic spikes, routine hotfixes) in your first validation run so you can audit every scoring rule's business justification and raw-log traceability.

  3. Guardrail the Agent at the tool layer: Read-only roles and isolated warehouses are necessary, but not sufficient. Enforce strict time-window caps,

    LIMIT
    s, and query timeouts inside the MCP/tool layer, and mask sensitive payload fields in the evidence views exposed to the Agent.

  4. Capacity-test with realistic distributions: Factor in external ingestion overhead, late-data backfills, and concurrent triage queries. Run one end-to-end drill on a real alert—verifying every Agent claim maps back to raw evidence—before onboarding more microservices.

Share this post

Subscribe to our newsletter

Stay informed on feature releases, product roadmap, support, and cloud offerings!