Build a Log Structuring Pipeline with LLM-Generated Parsers
Machine LearningModel answerLast updated
Design a scalable system that transforms unstructured log lines into structured JSON using LLM-generated regex parsers cached for high-volume processing.
You need to build a production system that converts raw, unstructured log messages from diverse sources into structured JSON records. The logs come in many different formats with varying schemas.
Your system should handle situations like these:
Web server log:
192.168.1.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 1024 "http://example.com/start.html" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"
Should produce:
{
"src_ip": "192.168.1.1",
"time": "10/Oct/2023:13:55:36 +0000",
"http_method": "GET",
"path": "/index.html",
"protocol": "HTTP/1.1",
"response_code": 200,
"duration": 1024,
"url": "http://example.com/start.html",
"userAgent": "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"
}
Application error log:
[Tue Oct 10 13:55:36 2023] [error] [pid 12345] [client 192.168.1.1:12345] File does not exist: /var/www/html/favicon.ico
Should produce a different schema with fields like timestamp, level, pid, client_ip, client_port, and error_message.
Design the complete system covering:
- Overall architecture and data flow
- How to identify and handle different log formats
- Extraction approach and when to use LLMs versus other techniques
- Schema discovery and field naming consistency
- Validation and quality assurance
- Scaling to high throughput
- Reliability and failure handling
- Monitoring and operational concerns
- Privacy and security considerations
Hints
Hint 1
Calling an LLM for every log line at scale would be prohibitively expensive and slow—think about how to keep LLMs off the critical path
Hint 2
Most production logs follow a small number of repeating patterns; exploit this property
Hint 3
Deterministic parsers like regex are orders of magnitude faster than LLM calls once you have them
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Log Structuring Pipeline
Core Insight
The key realization is that calling an LLM per log line is economically and operationally infeasible at scale. At 500K events/second with ~150 tokens per line, you'd process 75M tokens/second—costing millions daily and adding unacceptable latency.
The solution: use LLMs to synthesize fast, deterministic parsers that handle the hot path, invoking the LLM only to create new parsers for previously unseen formats.
Requirements Clarification
Start by establishing scope:
Functional:
- Accept raw log text from multiple sources with unknown or changing formats
- Output structured JSON with consistent, typed fields
- Never discard raw data—unparsed lines pass through with metadata
- Support schema evolution as log formats change
Scale assumptions:
- ~500K events/second throughput (~150 MB/s, 13 TB/day)
- Sub-5ms added latency per event acceptable
- Log formats follow power-law distribution: 1,000-5,000 templates cover 99%+ of volume
- Dozens of new formats appear daily
Architecture Overview
┌─────────┐ ┌──────────────┐ ┌─────────────┐ ┌────────┐
│ Ingest │────>│ Fingerprint │────>│ Parser │────>│ Output │
│ │ │ & Route │ │ Execution │ │ │
└─────────┘ └──────────────┘ └─────────────┘ └────────┘
│ │
│ (miss) │
v v
┌────────────────┐ ┌──────────────┐
│ Parser │ │ Validation │
│ Synthesis │ │ & Enrichment │
│ (LLM-based) │ └──────────────┘
└────────────────┘
Hot Path (Microsecond Latency)
-
Pre-filtering: Try built-in parsers for standard formats (Apache logs, syslog, JSON, CEF, key=value). These are zero-cost and high-accuracy.
-
Template fingerprinting: Normalize the log line by replacing variable data (IPs, timestamps, numbers, UUIDs, hex strings) with placeholders, then hash. Example:
192.168.1.1 - - [10/Oct/2023:13:55:36]becomes<IP> - - [<TIMESTAMP>]→ hashabc123... -
Parser lookup: Check in-memory cache for compiled parser matching this fingerprint. Cache hit rate should exceed 99% in steady state.
-
Execute parser: Run the cached regex (microseconds) and extract named groups.
-
Validate & normalize: Type-check extracted values, map to canonical field names, emit structured event with metadata (
_template_id,_parser_version,_status).
Cold Path (Async, LLM-Involved)
When a fingerprint misses the cache:
-
Immediate passthrough: Emit the raw line with
_status=unparsedso no data is lost. -
Sample collection: Enqueue the line for parser synthesis, deduplicating by fingerprint. Collect 20-50 diverse examples of this template.
-
LLM synthesis: Send examples to LLM with a structured prompt:
- Provide the log samples
- Include canonical field vocabulary (based on standards like ECS or OCSF)
- Request: regex pattern with named capture groups, field types, timestamp format
- Use structured output (JSON schema or function calling) to constrain the response
-
Validation harness: Test the candidate parser against held-out samples:
- Compilation and ReDoS safety (use RE2 or timeout protection)
- Coverage: matches 99%+ of samples
- Grounding: extracted values are exact substrings from input
- Type validity: IPs parse, integers in range, timestamps parse, HTTP codes 100-599
- Schema consistency across samples
-
Shadow deployment: Run new parser alongside any existing version, collect metrics, then promote to active after stability period.
Schema Management
Per-template schemas: Each log format gets its own schema. The web server log and error log examples naturally produce different structures.
Field normalization: Map source-specific names to canonical vocabulary:
- Store original field names:
time,client_ip - Add normalized fields:
@timestamp(ISO 8601 UTC),source.ip(ECS standard) - Prevents collision while enabling cross-source querying
Semantic validation: Watch for mislabeling. In the web server example, the fourth numeric field is response bytes, not duration. Mitigate through:
- Recognizing well-known formats explicitly
- Providing field descriptions to the LLM
- Human review for high-volume templates
Semi-structured handling: Many logs have structured prefixes and free-text suffixes (e.g., error messages with file paths). Extract structured parts, capture remainder as message field, optionally extract sub-fields if consistent.
Extraction Strategy (Ordered by Cost)
- Known format parsers (free, deterministic)
- Cached LLM-generated parsers (microseconds)
- Generic heuristics (JSON detection, key=value splitting)
- Online LLM extraction (rate-limited, for rare high-value events like security alerts)
- Raw passthrough (always succeeds)
Validation & Quality Assurance
Candidate parser validation:
- Regex compiles and is ReDoS-safe
- Achieves 99%+ match rate on samples
- Extracted values are grounded in input text
- Types validate correctly
- Schema stable across diverse samples
Runtime validation:
- Type and range checks on every parsed field
- Mark events with validation failures as
_status=partialbut still emit - Track parse success rate per template
Human-in-the-loop:
- Flag new templates serving high volume for review
- Provide UI for approving, editing, or rejecting generated parsers
- Allow manual regex overrides
Scaling & Reliability
Stateless workers:
- Hold parser registry in local memory (tens of MB)
- Update via pub/sub when new parsers activate
- Scale horizontally, partition by source or hash
LLM service isolation:
- Async queue with fingerprint-based deduplication
- Batch processing, exponential backoff retries
- Circuit breaker and fallback to simpler model
- Per-tenant token budgets and rate limits
No critical dependency:
- LLM outage only delays new parser creation
- Existing parsers continue working
- Unparsed lines still flow through with raw data intact
Cost control:
- Single LLM call per template, amortized over millions of events
- At 1,000 templates/day × 5,000 tokens/call = 5M tokens/day (dollars, not millions)
- Optional: use small fine-tuned models for faster, cheaper synthesis
Monitoring & Operations
Metrics to track:
- Parser cache hit rate (target: >99%)
- Parse success rate per source/template
- Validation failure rate by field and type
- LLM synthesis latency and cost
- Template churn rate (new formats appearing)
Alerting on:
- Sudden spike in cache misses (format change detected)
- Drop in match rate for active parser (drift)
- LLM service degradation
- Validation failure rate increase
Drift handling:
- Automatic re-synthesis when existing parser match rate drops
- Keep previous version active during transition
- Version-controlled parser registry with rollback capability
Privacy & Security
Sensitive data:
- Never send full logs to external LLM APIs by default
- Use anonymized samples or self-hosted models for synthesis
- Redact PII patterns before LLM processing when possible
Parser safety:
- Regex timeout enforcement to prevent ReDoS attacks
- Validate extracted data doesn't execute code (if used in downstream systems)
- Audit trail for all parser changes
Access control:
- Parser approval workflow for production deployment
- Separate parser synthesis from parsing execution privileges
Common Pitfalls
- Per-event LLM calls: Fails on cost and latency
- Ignoring the power law: Not caching parsers wastes the fact that most logs repeat
- Losing raw data: Always preserve original on parse failure
- Schema conflicts: Need field naming standards across sources
- No validation: Generated parsers may hallucinate or extract incorrectly
- Tight coupling: Making LLM availability critical for data flow
This architecture achieves deterministic, microsecond parsing for 99%+ of events while leveraging LLMs intelligently for the long tail, balancing cost, reliability, and adaptability.