LLM-Assisted Structured Log Parsing Pipeline

Medium · ML System Design · Software Engineer · Technical Screen

Prompt

Architect a production log-processing system that pairs an LLM with deterministic parsing logic to turn diverse, unstandardized text log lines into typed JSON records. Incoming feeds span many services and appliances whose output schemas differ substantially from one source to another.

For instance, given an HTTP gateway log record:

203.0.113.42 - svc-checkout [14/Mar/2026:08:21:09 +0000] "POST /v2/orders HTTP/2.0" 201 48 "https://shop.acme.io/cart" "curl/8.6.0"

the pipeline should emit structured attributes such as:

{
  "client_ip": "203.0.113.42",
  "auth_user": "svc-checkout",
  "received_at": "14/Mar/2026:08:21:09 +0000",
  "method": "POST",
  "route": "/v2/orders",
  "http_version": "HTTP/2.0",
  "status": 201,
  "latency_ms": 48,
  "referrer": "https://shop.acme.io/cart",
  "agent": "curl/8.6.0"
}

Meanwhile, a background daemon warning line from another service:

2026-03-14 08:21:11 WARN [worker 4812] [peer 198.51.100.77:5432] Upstream timeout waiting for /srv/cache/session.db

should yield a format-appropriate schema with fields like logged_at, severity, worker_pid, peer_ip, peer_port, and detail.

Scope & Expectations

  • System architecture and hot/cold data flow: Separating high-throughput event ingestion from LLM-assisted schema discovery and parser synthesis so cost and latency remain low at scale.
  • Schema inference, extraction, and validation: Discovering distinct log templates, inferring typed field schemas, extracting grounded values, and automatically verifying candidate rules before rollout.
  • Reliability, throughput, and security: Handling peak ingestion volumes, parser regressions, LLM outages, PII redaction, and untrusted user strings safely without dropping events.
  • Quality evaluation and observability: Measuring extraction accuracy offline, testing parser changes safely, and monitoring live parse health and schema drift.

Step-by-step walkthrough

  1. Clarify requirements and make the core architectural decision

    Functional requirements

    • Heterogeneous log ingestion: Accept raw log lines from diverse sources (files, agents, cloud APIs, network appliances) whose formats we may never have seen before.
    • Format-specific structured output: Emit one JSON object per log event whose field names and types fit that format (for example, client_ip, method, status, latency_ms for an HTTP gateway log versus logged_at, severity, worker_pid, peer_ip, peer_port, detail for a daemon warning log).
    • Lossless raw preservation: Always keep the original raw text (_raw) alongside parsed fields so no data is ever lost if a parser is missing or imperfect.
    • Human-in-the-loop governance: Allow engineers to inspect, rename, approve, or roll back inferred schemas, and re-parse historical logs when a parser improves.

    Non-functional requirements (planning assumptions)

    • Throughput: ~1 TB/day of raw logs per large deployment, with traffic spikes at 3x the daily average.
    • Low latency: Single-digit milliseconds per event inside the pipeline because parsed logs feed real-time security and outage alerts.
    • Zero data loss: Never drop or block an event because parsing failed or the LLM is unavailable.
    • Privacy and security: Logs contain PII (personally identifiable information, such as emails and IP addresses), credentials, and attacker-controlled strings, so data leaving the customer boundary must be redacted and sanitized.
    • Predictable cost: Parsing cost per GB must stay tiny and roughly flat as log volume grows.

    The core decision: invoke the LLM once per format, never once per line

    Production logs are overwhelmingly repetitive: billions of lines come from a few thousand printf or logger statements in source code. Figuring out the structure and field names of a brand-new log format requires language understanding, which happens rarely on the cold path (the asynchronous background workflow triggered only when an unknown format appears). Extracting substrings from millions of matching lines is mechanical work on the hot path (the real-time, per-event processing path every log line travels through). Therefore, the LLM writes deterministic parsers, and the pipeline runs those parsers in compiled code:

    Cold path (rare, async, ~200x/day):
      sample lines --> redact PII --> LLM synthesizes parser --> sandbox validates --> parser registry
    
    Hot path (every event, ~175,000 lines/s peak, zero LLM calls):
      raw log line --> route to compiled parser --> regex extract --> cast types --> structured JSON
    
  2. Estimate scale, latency, and LLM cost

    Let's run back-of-the-envelope numbers to verify why per-line LLM calls fail and per-format synthesis easily fits our budget.

    Traffic volume (assumed for one large enterprise deployment)
      Daily volume:             1 TB/day = 1,000,000,000,000 bytes/day
      Average log line size:    ~200 bytes
      Total lines per day:      1,000,000,000,000 / 200 = 5,000,000,000 (5 billion lines/day)
      Average ingestion rate:   5,000,000,000 / 86,400 s = ~58,000 lines/s
      Peak ingestion rate (3x): ~175,000 lines/s
    
    Option A: Call an LLM on every log line (naive approach)
      Tokens per call:          ~60 (raw line) + ~400 (prompt + schema rules) + ~100 (JSON output)
                                = ~560 tokens/line
      Tokens per day:           5,000,000,000 x 560 = 2.8 trillion tokens/day
      Daily model cost:         Even on a tiny model at $0.10 per 1M tokens -> ~$280,000/day (~$102M/year)
      Latency & concurrency:    ~300 ms per LLM call x 175,000 lines/s = ~52,500 concurrent GPU calls
      Verdict:                  Completely unviable on cost, latency, and value-hallucination risk.
    
    Option B: Call an LLM once per new or changed format (our design)
      Active log formats:       ~20,000 distinct templates across all services
      New/changed formats/day:  ~200/day (new microservices or software deploys altering log lines)
      Tokens per format job:    20 sample lines (~1,200) + prompt & field dictionary (~2,500) + output (~600)
                                = ~4,300 tokens; up to 3 validation retries -> ~13,000 tokens worst case
      Tokens per day:           200 x 13,000 = ~2.6 million tokens/day (~1,000,000x fewer than Option A!)
      Daily model cost:         Even on a frontier model at $5.00 per 1M tokens -> ~$13/day
    
    Deterministic hot-path CPU and memory
      Regex extract + typing:   ~10 microseconds (us) per line
                                175,000 lines/s x 10 us = ~1.75 CPU cores at peak
      Full worker pipeline:     ~50 us per line (framing, routing, regex, JSON serialization, network I/O)
                                175,000 lines/s x 50 us = ~8.75 CPU cores at peak (~18 cores with 2x headroom)
      In-memory parser cache:   20,000 compiled parsers x ~2 KB each = ~40 MB RAM per worker
    

    Three design conclusions jump right out of this math:

    • The registry fits entirely in worker RAM (~40 MB), so workers never make a network call per log line.
    • Deterministic parsing takes a handful of CPU cores to process 1 TB/day at sub-millisecond latency.
    • Because the LLM runs ~200 times a day asynchronously, we can afford a strong reasoning model with multi-step validation retries without hurting latency or budget.
  3. Define the API and data model

    Data plane interface (in-process worker library)

    The data plane (the subsystem that processes live log events) runs as an embedded library inside each stream-processing worker rather than a remote microservice, because a 1 ms network hop per line would be 100x slower than the 10-microsecond parse itself:

    parse_event(raw_line: bytes, meta: {tenant_id, source_id, sourcetype, host}) ->
    {
      "fields": { "client_ip": "203.0.113.42", "status": 201, "latency_ms": 48, ... },
      "_raw": "203.0.113.42 - svc-checkout [14/Mar/2026:08:21:09 +0000] ...",
      "_time": "2026-03-14T08:21:09Z",
      "_parser": "p_http_gateway@v3",
      "_parse_status": "parsed" | "provisional" | "unparsed"
    }
    

    Control plane REST API

    The control plane (the low-QPS administrative service that manages parser lifecycles, human reviews, and backfills) exposes standard HTTP endpoints:

    GET  /v1/parsers?source_id=...                  List parsers with status, live match rate, and volume
    GET  /v1/parsers/{parser_id}                    Fetch pattern, field map, validation report, and samples
    POST /v1/parsers/{parser_id}/approve            Promote a provisional parser to approved
    POST /v1/parsers/{parser_id}/rollback           Revert source routing to the previous parser version
    PUT  /v1/parsers/{parser_id}/field-map          Apply human field renames or type overrides
    POST /v1/reparse                                Re-process archived raw logs for {source_id, time_range}
    

    Core metadata tables

    parsers           (parser_id, version, tenant_id, source_selector, kind, grok_pattern,
                       compiled_re2, required_literals, field_map_json, status,
                       validation_metrics_json, created_by, approved_by, created_at)
    templates         (template_id, tenant_id, source_id, masked_signature, line_count,
                       active_parser_id, first_seen_at, last_seen_at)
    template_samples  (template_id, redacted_lines[], held_out_hashes[], expires_at)
    inference_jobs    (job_id, template_id, attempt_count, status, model_id, prompt_version,
                       token_usage, last_error, updated_at)
    canonical_fields  (canonical_name, value_type, description, known_aliases[])
    

    Every parser is immutable and versioned: editing a pattern or renaming a field writes v4 rather than overwriting v3. That guarantees every historical event's _parser tag points to the exact rule that produced it, and rolling back a bad parser is an instant pointer flip. To collect representative examples without storing millions of lines, each unmatched template uses reservoir sampling (a single-pass randomized algorithm that maintains a fixed-size uniform sample — here 120 lines — from an unbounded stream), expiring stored samples after 7 days.

  4. High-level architecture and end-to-end data flow

      Log Sources (files, syslog, agents, cloud streams)
         |
         v
      +----------------------- PIPELINE WORKER (Hot Path, ~50 us/line) -----------------------+
      | 1. Event Breaker  --> 2. Format Detector --> 3. Parser Router --> 4. RE2 Extract      |
      |    (joins multi-        (JSON? key=val?       (source_id cache     + Type Normalizer  |
      |     line stack           RFC syslog?           + literal filter)   (int, UTC time,    |
      |     traces)              or free-text)                             nulls, IP split)   |
      +--------------------------------------|------------------------------------------------+
         | all events (structured + _raw)    | unmatched free-text lines only
         v                                   v
      Downstream Sinks (SIEM, Search)    5. Drain Template Miner (clusters lines by token shape)
      + Cheap Object-Store Raw Archive       |
                                             | once template hits 120 samples (or 1 hour timeout)
                                             v
                                         6. Redactor + Deduplicated Inference Queue (1 job/template)
                                             |
                                             v
                                         7. LLM Parser Synthesizer <---> 8. Validator Sandbox
                                            (20 diverse samples +          (RE2 compile, 100 held-out
                                             canonical dictionary)          lines, cross-match, <=3 tries)
                                             |
                                             v
                                         9. Parser Registry ("provisional") <--> Human Review UI
                                             |
                                             v
                                        10. Canary Push to Worker Memory Caches (1% -> 10% -> 100%)
    

    Let's trace what happens step by step when a developer deploys a brand-new microservice emitting an unseen log format:

    1. Zero-drop fallback (seconds 0–60): No parser matches the new lines yet. Workers emit them immediately with _raw intact and _parse_status = "unparsed", so logs remain searchable by full-text grep and nothing is delayed.
    2. Template clustering and sampling: Unmatched lines flow to the template miner, which groups structurally identical lines into one template_id. Once the template collects 120 lines (20 diverse lines for the LLM prompt + 100 held-out lines kept secret from the LLM to test generalization), exactly one job enters the inference queue. Low-volume templates that do not reach 120 lines within 1 hour trigger a job with whatever samples they have, flagged for mandatory human review.
    3. Synthesis, validation, and provisional rollout (minutes 1–3): The LLM generates a parser; the sandbox tests it on the 100 held-out lines. Once it passes, it is saved as provisional and pushed to workers. Subsequent lines immediately gain structured JSON fields with _parse_status = "provisional".
    4. Approval and optional backfill: For high-volume or security-critical sources, an engineer reviews field names in the UI and clicks Approve (_parse_status = "parsed"). If needed, POST /v1/reparse replays the first few minutes of unparsed lines from the object-store raw archive.
  5. Deep dive 1: Template mining and fast hot-path routing

    Step 1: Cheap deterministic detection before template mining

    Many logs are already structured: valid JSON objects, key=value pairs, CSV rows, or standard RFC 5424 syslog headers. A lightweight prefix/character check handles these directly in compiled code without regex synthesis. Only free-text formats (or unstandardized field names that need canonical mapping) require template mining and the LLM.

    Step 2: Grouping free-text lines with Drain template mining

    How do we realize that 50,000 error lines belong to the same log statement before we have a parser? We use Drain template mining (a fast, fixed-depth parse-tree clustering algorithm that groups log lines first by token count, then by their leading static tokens, merging variable positions into wildcards). Crucially, our tokenizer treats quoted strings ("...") and bracketed blocks ([...]) as single structural units so a 6-word user-agent and a 12-word user-agent do not split into separate templates:

    Raw line A:  2026-03-14 08:21:11 WARN [worker 4812] [peer 198.51.100.77:5432] Upstream timeout waiting for /srv/cache/session.db
    Raw line B:  2026-03-14 08:21:14 WARN [worker 4890] [peer 198.51.100.19:5432] Upstream timeout waiting for /srv/cache/profile.db
    
    After masking obvious primitives (timestamps, IPs, numbers, file paths) & comparing tokens:
    Inferred template:  <TS> WARN [worker <NUM>] [peer <IP>:<NUM>] Upstream timeout waiting for <PATH>
    

    Step 3: Separating the log envelope from the inner message

    Notice a subtle trap in the second sample log: 2026-03-14 ... WARN [worker 4812] [peer 198.51.100.77:5432] Upstream timeout waiting for /srv/cache/session.db and 2026-03-14 ... WARN [worker 4812] [peer 198.51.100.77:5432] TLS handshake rejected by peer have different trailing text, yet they share the exact same log envelope (logged_at, severity, worker_pid, peer_ip, peer_port, detail). If we generated one LLM parser per trailing message, every new warning string in an application's code would trigger an LLM call! Instead, we split parsing into two layers:

    • Format (envelope) parser (LLM-generated): Extracts structured header fields and captures the remaining free-text body as detail.
    • Sub-message template lookup (Drain lookup-only mode): Runs Drain in read-only mode on detail to attach message_template = "Upstream timeout waiting for <*>" and message_params = ["/srv/cache/session.db"] in a few microseconds, enabling GROUP BY message_template dashboards with zero extra LLM calls.

    Step 4: Microsecond routing on the hot path

    A worker holding 20,000 parsers cannot test 20,000 regular expressions on every line. We narrow candidates in four fast stages:

    1. Scope by source_id: Most log sources emit only 1 to 10 formats, immediately pruning 20,000 parsers down to a handful.
    2. One-slot "last matched" cache: Logs arrive in bursts from the same logger; testing the parser that matched the previous line from that source_id hits on the first try >90% of the time.
    3. Literal substring prefilter: Each parser stores required constant substrings (such as "[worker " or " HTTP/"). A fast byte scan (memmem) rejects non-matching candidates in nanoseconds.
    4. Single-pass multi-regex fallback: For multiplex sources (like a shared Kubernetes stdout collector with hundreds of formats), we compile that source's patterns into an RE2 Set (a combined finite-state automaton that identifies which regular expressions match an input string in a single linear scan), then run capture-group extraction only on the winning pattern.
  6. Deep dive 2: LLM parser synthesis and automated sandbox validation

    Why the LLM outputs Grok patterns instead of raw JSON or unrestricted regexes

    Instead of asking the LLM to parse lines directly or write fragile raw regular expressions from scratch, we ask it to assemble Grok patterns (named, pre-tested regex building blocks such as %{IPV4}, %{HTTPDATE}, and %{INT}) and map each extracted field to a canonical schema (a shared organization-wide field dictionary modeled on OpenTelemetry or Elastic Common Schema, so every parser maps client IPs to source.ip alongside the source-specific name).

    The LLM runs at temperature = 0 with constrained JSON-schema decoding. Here is what it produces for the HTTP gateway log sample, followed by how our compiler expands both sample formats into RE2 (a deterministic finite-automaton regular-expression engine that guarantees O(line_length) matching time and eliminates catastrophic backtracking, a vulnerability where ambiguous nested quantifiers cause standard regex engines to hang a CPU core for minutes on a crafted line):

    {
      "format_name": "http_gateway_access",
      "pattern": "%{IPORHOST:client_ip} %{NOTSPACE} %{NOTSPACE:auth_user} \\[%{HTTPDATE:received_at}\\] \"%{WORD:method} %{NOTSPACE:route} %{DATA:http_version}\" %{INT:status} %{INT_OR_DASH:latency_ms} \"%{DATA:referrer}\" \"%{DATA:agent}\"",
      "fields": [
        {"group": "client_ip", "canonical": "source.ip", "type": "ip"},
        {"group": "auth_user", "canonical": "user.name", "type": "string"},
        {"group": "received_at", "canonical": "event.original_time", "type": "timestamp", "format": "%d/%b/%Y:%H:%M:%S %z"},
        {"group": "method", "canonical": "http.request.method", "type": "string"},
        {"group": "route", "canonical": "url.path", "type": "string"},
        {"group": "http_version", "canonical": "network.protocol_version", "type": "string"},
        {"group": "status", "canonical": "http.response.status_code", "type": "int"},
        {"group": "latency_ms", "canonical": "event.duration_ms", "type": "int"},
        {"group": "referrer", "canonical": "http.request.referrer", "type": "string"},
        {"group": "agent", "canonical": "user_agent.original", "type": "string"}
      ]
    }
    

    Notice that unmapped placeholder tokens (-) use unnamed building blocks (%{NOTSPACE}), so the compiled pattern only creates named capture groups for fields we actually want in the output JSON:

    import re
    
    # Compiled pattern for Sample 1 (HTTP gateway log); unnamed '-' uses \S+ without (?P<...>)
    GATEWAY_PATTERN = re.compile(
        r'^(?P<client_ip>\S+) \S+ (?P<auth_user>\S+) \[(?P<received_at>[^\]]+)\] '
        r'"(?P<method>[A-Z]+) (?P<route>\S+) (?P<http_version>[^"]+)" '
        r'(?P<status>\d{3}) (?P<latency_ms>\d+|-) '
        r'"(?P<referrer>[^"]*)" "(?P<agent>[^"]*)"$'
    )
    
    # Compiled pattern for Sample 2 (daemon log); splits peer IP and port into distinct fields
    DAEMON_PATTERN = re.compile(
        r'^(?P<logged_at>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (?P<severity>\w+) '
        r'\[worker (?P<worker_pid>\d+)\] '
        r'\[peer (?P<peer_ip>[0-9a-fA-F:.]+):(?P<peer_port>\d+)\] '
        r'(?P<detail>.*)$'
    )
    

    Because regex capture groups can only slice characters that literally exist inside the input line, extracted values are grounded by construction: the LLM could misname a field, but it can never hallucinate an IP address or status code that was not in the log.

    Six-gate automated validator sandbox and self-repair loop

    We treat every LLM output as untrusted code until it passes six deterministic checks on the unredacted held-out lines inside the secure boundary:

    Validation Gate     Pass Requirement                                     What It Catches
    ------------------  ---------------------------------------------------  -------------------------------------
    1. RE2 Compile      Compiles cleanly in RE2; latency < 50 us/line        Syntax errors, slow regex constructs
    2. Held-out Recall  Matches >= 99% of the 100 unseen lines in template   Overfitted patterns matching only the
                                                                             20 prompt lines (e.g., IPv4-only)
    3. Cross-Match      Matches <= 0.1% of lines from OTHER templates        Lazy catch-all patterns like ^(?P<m>.*)$
    4. Type Validity    100% of matched values parse as declared type        "-" failing int cast, bad date format
    5. Field Coverage   Every declared field is non-empty in >= 95% of hits  Dead or misaligned capture groups
    6. Vocabulary       Canonical names exist in canonical_fields table      Invented or inconsistent field names
    

    If any gate fails, the validator sends the exact error message and up to 5 failing sample lines (redacted) back to the LLM for a self-repair loop capped at 3 attempts. If attempt 3 still fails, the job moves to a human engineering queue while raw logs continue flowing uninterrupted as unparsed.

  7. Deep dive 3: Semantic field naming, type normalization, and schema evolution

    Handling ambiguous field semantics (the 48 trap in the HTTP gateway log)

    Look closely at 48 right after 201 in our first sample log: in a stock NCSA Combined Log Format, that seventh column records response payload bytes, whereas custom gateway configs often log request latency in milliseconds there (matching our expected "latency_ms": 48). Looking at "201 48" in isolation, neither a human nor an LLM can be 100% sure whether 48 means bytes or milliseconds! Our workflow resolves this cleanly:

    1. Metadata context in the prompt: Pass source tags (sourcetype, agent config snippets, log file path) to the LLM, and have the model output a per-field confidence (high | medium | low) plus reasoning.
    2. Known-format precedence: Standard vendor formats (stock Nginx, Envoy, AWS VPC Flow Logs) use curated, human-verified schemas rather than fresh LLM guesses.
    3. Provisional status + persistent overrides: Low-confidence field names (like latency_ms vs. bytes) flag the parser for human review while serving data immediately as provisional. When a reviewer confirms or renames a field via PUT /field-map, that override is saved per source_id so future re-inferences never overwrite human corrections.

    Deterministic type casting and timestamp normalization

    • Numbers and null sentinels: Cast "201" -> 201 and "4812" -> 4812. Convert sentinel placeholders like "-" to null (never 0, which would corrupt p50 latency or byte-count averages).
    • Timestamps and missing time zones: Preserve the original timestamp field (received_at or logged_at) and populate a normalized UTC _time in ISO-8601. The HTTP gateway log (14/Mar/2026:08:21:09 +0000) carries an explicit offset and becomes 2026-03-14T08:21:09Z. The daemon warning log (2026-03-14 08:21:11) has no time zone; rather than silently guessing, the normalizer applies the source's configured zone (defaulting to UTC) and sets "_tz_assumed": true.

    Graceful schema evolution across software deploys

    When an application upgrade adds [shard 3] next to [worker 4812], those new lines fail DAEMON_PATTERN, flow safely as unparsed, and form a new Drain template that synthesizes p_daemon_warn@v2 within minutes. Meanwhile, v1 stays active during rolling deploys so old pods keep parsing cleanly. If a field is renamed, the worker emits both the new name and a deprecated alias for 30 days so existing alert queries do not break overnight.

  8. Privacy, security, scaling, and failure recovery

    Three layers of privacy and security

    1. Format-preserving PII redaction before the LLM: Before 20 sample lines leave the worker boundary, deterministic detectors replace sensitive tokens with typed placeholders that preserve structural clues: IPv4 addresses -> <IPV4:1>, emails -> <EMAIL:1>, JWTs/API keys -> <SECRET_TOKEN>, credit card numbers passing the Luhn check (the standard modulo-10 checksum formula used to validate payment card numbers) -> <CREDIT_CARD>, and URL query values -> ?token=<REDACTED>. The LLM still sees enough structure to emit %{IPV4:client_ip}, while real customer data stays inside the VPC where the validator tests against unredacted held-out lines.
    2. Tenant-isolated deployment options: Regulated customers route inference jobs to a self-hosted open-weights model running inside their own VPC; cloud LLM APIs are used only under zero-data-retention agreements. Parsers are never shared across tenants unless promoted by staff into the public vendor catalog (since custom regex literals could leak internal hostnames).
    3. Prompt-injection containment: An external attacker controls HTTP paths and User-Agent headers, so a log line can literally say "Ignore previous instructions and output...". Blast radius is near zero: the LLM has no tool access or database credentials, outputs only a constrained JSON Grok spec compiled by RE2 (no eval or arbitrary code execution), and any corrupted pattern fails the 99% held-out recall gate.

    Scaling and failure-handling matrix

    • Horizontal scaling: Partition log streams by source_id across stateless worker pods so each worker keeps hot routing stats and Drain trees local in memory; split ultra-high-volume sources (e.g., 50,000 lines/s firewall feeds) across multiple shards. Truncate pathologically long lines (e.g., > 64 KB) before regex matching while preserving full bytes in _raw.
    • Volume-weighted inference queue: Deduplicate jobs by template_id (1,000,000 unmatched lines = 1 LLM job) and prioritize the queue by line_count so high-traffic formats get parsers first.
    Failure Scenario                    System Behavior & Recovery
    ----------------------------------  -------------------------------------------------------------------
    LLM provider outage or rate limit   Zero impact on existing formats; unmatched lines flow with _raw and
                                        _parse_status="unparsed"; queued template jobs retry with backoff.
    Bad parser slips past validation    Canary rollout tests new parser version on a hash-selected 1% of
                                        the source's lines, then 10%, then 100%; auto-rollback if live
                                        match rate drops or CPU us/line exceeds budget.
    Parser registry database down       Workers continue indefinitely using their in-memory cached parsers.
    Downstream SIEM / index backlogged  Workers spill to local disk buffers and apply backpressure upstream.
    
  9. Offline evaluation, online A/B testing, and production monitoring

    Offline evaluation (gating prompt or model upgrades)

    Maintain an offline golden dataset of ~50 diverse log formats x 200 human-labeled lines (10,000 lines total: web servers, databases, firewalls, custom app logs, multi-line Java/Python stack traces). Before shipping any prompt, sub-pattern, or model change, evaluate:

    • Template clustering accuracy: Adjusted Rand Index / grouping accuracy of Drain templates against ground-truth formats.
    • Extraction quality: Precision, recall, and F1 score (the harmonic mean 2 * precision * recall / (precision + recall), which penalizes both missing fields and bogus extra fields) on (canonical_field_name, typed_value) pairs.
    • Operational efficiency: First-attempt sandbox pass rate, average tokens per successful parser, and historical human reviewer edit rate (fraction of fields renamed before approval).

    Online A/B testing

    Randomize at the template_id level (never per log line, so one format gets one consistent parser): hash each newly discovered template_id 50/50 between the control generator and candidate generator. Track zero-edit human approval rate as the primary metric, with first-week live match rate and worker CPU microseconds/line as guardrails. At ~200 new templates/day (~100/day per arm), a 14-day test collects ~1,400 templates per arm — enough statistical power (80% power at 5% significance) to detect a ~5 percentage-point improvement over a 70% baseline approval rate.

    Production monitoring and continuous quality audits

    • Per-source parse coverage: Alert when % unparsed jumps on an established source (indicating a breaking log-format change from a new deploy).
    • Template explosion: Alert if a single source creates >50 templates/hour (indicating an unmasked random ID like a custom request hash needs a token-masking rule).
    • Hot-path SLOs: Track worker p99 parse latency, CPU microseconds per parser ID, and end-to-end ingestion lag.
    • Daily offline audit: Sample 100 parsed (redacted _raw, output JSON) pairs per day from top sources and score them asynchronously with a separate LLM judge + human spot-check to catch silent semantic drift (like bytes mislabeled as latency_ms) at negligible cost.

Intuition & how it works

Think of the LLM in this system like a master toolmaker who builds a custom metal stamp once per cookie shape, rather than a baker hand-carving five billion cookies one by one with a pocketknife. Raw logs look chaotic across services, yet within any single service almost all lines come from a small number of printf or logger statements in code. Our system separates the slow, intelligent job of understanding a new log format (done once in the background by an LLM that writes a deterministic parser) from the fast, mechanical job of extracting fields from millions of lines (done in compiled code in ~10 microseconds per line).

Why do the obvious approaches fail? Calling an LLM directly on every log line at 1 TB/day (~5 billion lines/day, peaking at ~175,000 lines/s) would consume roughly 2.8 trillion tokens per day (~$280,000/day even on a cheap model), add hundreds of milliseconds of delay to real-time alerts, and risk hallucinations (the model inventing plausible-looking IP addresses or status codes that do not exist in the raw text). Conversely, asking engineers to hand-write regular expressions (text-matching patterns) for 20,000 constantly evolving microservice log formats falls behind every time a team ships a new release.

Here is how 4 raw log lines flow through our two-path workflow step by step:

1. Raw lines arrive at a pipeline worker:
   Line 1 (known HTTP gateway format):
     203.0.113.42 - svc-checkout [14/Mar/2026:08:21:09 +0000] "POST /v2/orders HTTP/2.0" 201 48 ...
     -> Matches cached parser p_http_gateway@v1 in ~10 us (zero LLM calls!)
     -> Emits {"client_ip": "203.0.113.42", "method": "POST", "status": 201, "latency_ms": 48, ...}

   Lines 2..121 (brand-new daemon warning format, unseen before):
     2026-03-14 08:21:11 WARN [worker 4812] [peer 198.51.100.77:5432] Upstream timeout waiting for /srv/cache/session.db
     -> No parser matches yet; emitted immediately with "_raw" and "_parse_status": "unparsed" (zero data loss).

2. Drain template miner (a tree-based log clustering algorithm) groups Lines 2..121 into ONE template:
     <TS> WARN [worker <NUM>] [peer <IP>:<NUM>] Upstream timeout waiting for <PATH>

3. Redactor masks sensitive values (<IPV4:1>) on 20 diverse lines and sends ONE async job to the LLM:
     -> LLM returns a Grok pattern (reusable named regex building blocks) + canonical field types.
     -> Sandbox compiles to RE2 (a linear-time regex engine) and verifies >=99% recall on 100 unseen lines.

4. Compiled parser p_daemon_warn@v1 pushes to worker RAM caches:
     -> Line 122+ parses in ~10 us into {"logged_at": "...", "severity": "WARN", "worker_pid": 4812,
        "peer_ip": "198.51.100.77", "peer_port": 5432, "detail": "..."}!

Key trade-offs

  • LLM per format (cold path) vs. LLM per line (hot path). Synthesizing a parser once per format cuts token usage by ~1,000,000x (~2.6M vs. ~2.8T tokens/day), runs in microseconds per line, and makes value hallucination impossible because regex capture groups can only slice characters present in the log line. The trade-off is extra control-plane machinery (template mining, sandbox validation, versioned registry) and a brief window (1–3 minutes for busy sources, up to 1 hour for rare ones) where a brand-new format flows as unparsed raw text.
  • Vetted Grok building blocks compiled to RE2 vs. unrestricted LLM regexes. Restricting the LLM to tested macros (%{IPV4}, %{HTTPDATE}, %{INT}) compiled into RE2 (a regular-expression engine guaranteed to run in O(line_length) time without catastrophic backtracking, where nested quantifiers stall a CPU on crafted input) eliminates syntax bugs and denial-of-service risks. The trade-off is that unusual custom formats occasionally need an engineer to register a new macro.
  • Provisional auto-rollout + human review vs. blocking until human approval. Rolling validated parsers out immediately as provisional gives engineers structured fields within minutes of a deploy, while requiring human sign-off on high-volume sources catches subtle semantic mistakes (such as confusing response bytes with request latency_ms). Blocking all formats on human approval would create multi-day parsing backlogs.
  • Envelope parser + Drain message templates vs. one LLM parser per distinct message. Extracting the log header (logged_at, severity, worker_pid, peer_ip, detail) with one LLM parser and clustering detail variations with lookup-only Drain keeps parser count proportional to logger formats (~20,000) rather than every unique warning sentence in application code.
  • Dual field naming (source name + canonical name) vs. single schema. Preserving source-native names (client_ip, agent) avoids surprising service owners, while mapping to a canonical schema (a standard cross-system vocabulary such as OpenTelemetry or Elastic Common Schema, e.g., source.ip) lets security analysts write one query across every firewall and web server.
  • PII-redacted prompts + VPC models vs. sending raw logs to cloud APIs. Masking IPs, emails, and tokens into typed placeholders (<IPV4:1>, <EMAIL:1>) before prompting protects customer secrets while keeping enough structural hints for regex generation, though extreme redaction can slightly reduce semantic naming hints.

Common mistakes

  • Putting an LLM on the synchronous per-line hot path, without calculating that 5 billion lines/day means trillions of tokens, hundreds of thousands of dollars per day, and unworkable alerting latency.
  • Having the LLM emit parsed JSON values directly instead of an executable rule, which allows the model to silently invent or alter numbers, timestamps, and IP addresses.
  • Validating the generated regex only on the 20 lines shown in the prompt, missing overfitted patterns (like hardcoding 203.0.113. or IPv4-only character classes) that fail on unseen traffic.
  • Forgetting a cross-match check against other templates, allowing a lazy catch-all regex like ^(?P<detail>.*)$ to score 100% recall while swallowing every format from that source.
  • Executing LLM-generated regexes in a backtracking engine (like default Python re, Java, or PCRE without guards), where one attacker-crafted User-Agent header can trigger catastrophic backtracking and freeze worker threads.
  • Dropping or queueing unparseable log lines, instead of immediately forwarding every event with _raw and _parse_status = "unparsed" so live incident response never goes blind.
  • Silent type and timezone coercion, such as turning a gateway's "-" placeholder into integer 0 (skewing latency/size metrics) or assuming timezone-less timestamps are UTC without flagging _tz_assumed: true.
  • Sending unredacted raw logs to external LLM APIs, leaking customer PII/secrets and ignoring prompt injection (malicious instructions planted inside HTTP paths or User-Agent strings).

Follow-up questions

  • How does the pipeline behave during a rolling deployment that alters the log format of a busy service? Lines from updated pods fail the existing v1 parser and immediately flow downstream with _raw and _parse_status = "unparsed", while old pods continue matching v1 with zero disruption. Within a minute on a busy service, the Drain template miner collects 120 unmatched lines of the new shape, queues one high-priority LLM synthesis job, validates v2 against 100 held-out lines, and rolls v2 out through a 1% -> 10% -> 100% canary (gradual traffic ramp with automatic rollback on regressions). Both v1 and v2 remain active side by side until old pods drain, and the few minutes of unparsed events can be backfilled from the raw archive via POST /v1/reparse.
  • How would you support multi-line log records like Java or Python exception stack traces? Before format detection or regex extraction, each source passes through a stateful event breaker that buffers incoming lines and identifies event boundaries using a fast start-of-event pattern (typically anchored on a leading timestamp) while appending indented continuation lines (at ..., Caused by:, Traceback) up to a strict byte cap (e.g., 64 KB) and flush timeout (e.g., 500 ms). If a source's multi-line framing is unknown, the LLM can synthesize the start-of-event regex from raw multi-line chunks on the cold path, validated by checking that split chunks cleanly match the envelope parser. The envelope parser then extracts top-level metadata (logged_at, severity, exception_type) and keeps the full stack trace string in one field.
  • At what point does fine-tuning a compact open-weights model beat calling a large hosted LLM? At launch, calling a frontier LLM ~200 times a day costs only ~10–20 USD/day and gives superior zero-shot field naming, saving expensive human review time. Once the platform accumulates 5,000–10,000 human-approved (redacted samples -> Grok pattern + canonical field map) pairs across diverse formats, that registry history forms a clean supervised fine-tuning dataset. A fine-tuned 7B–8B model can then be deployed entirely inside air-gapped or regulated customer VPCs once it matches the frontier model's field-level F1 score and human edit rate on the offline golden dataset.

Follow-up questions

Similar questions

More Cribl interview questions

All 1 Cribl questions →