Skip to main content

Logging Platform

1. Executive Summary​

A logging platform collects, indexes, stores, and queries semi-structured log events from distributed services at terabytes per day scale. Principal-level design covers ingest pipelines, indexing strategies, hot/warm/cold tiering, schema-on-read vs schema-on-write, sampling and filtering, and compliance retention with cost control.

This chapter designs an ELK/Splunk-class platform ingesting 5 TB/day with search p99 under 5 s for common filters and 30-day hot retention. Structured logging, partition by time, and explicit behavior during index hotspot incidents are core interview topics.

2. Why This Topic Matters​

Logs remain the primary debugging artifact despite metrics and traces. Architects must explain:

  • Centralized vs sidecar collection.
  • Index design—what to index vs store only.
  • Cardinality in log fields (similar to metrics).
  • Cost of full-text index on everything.
  • PII and compliance (GDPR delete).

Poor logging design causes runaway storage bills, slow incident response, and compliance violations. Review Observability Fundamentals and Metrics Platform.

3. Problems Being Solved​

ProblemSolution
Distributed log collectionAgents + forwarders
High ingest volumeBuffered pipelines; Kafka
Fast searchInverted index; time partitioning
Retention policiesILM hot/warm/cold/delete
Structured queriesJSON parsing; field mapping
Security / complianceRBAC; audit; PII scrubbing
Cost controlSampling; tiered storage
Correlationtrace_id injection

4. Assumptions and System Model​

Functional:

  • Ingest JSON or text logs with metadata (service, env, level, trace_id).
  • Search: full-text + field filters; time range required.
  • Dashboards and saved searches.
  • Export to S3 for archive; rehydrate for investigations.
  • Per-tenant isolation in SaaS mode.

Non-functional:

  • Ingest 5 TB/day (50K events/sec average).
  • Hot search retention 30 days; archive 1 year.
  • Search p99 < 5 s for indexed fields over 24h range.
  • Ingest availability 99.9%.
  • At-least-once delivery acceptable with dedup optional.
AssumptionImplication
Time-range queries dominantPartition indexes by day
Most logs never queriedCold tier cheap storage
Structured fields keyParse at ingest
Full-text expensiveLimit analyzed fields
Compliance deleteDocument IDs for erasure

5. Essential Terminology​

TermDefinition
Log shipperAgent forwarding logs (Fluent Bit, Filebeat)
Ingest pipelineParse, enrich, drop processors
IndexSearchable collection (e.g., logs-2026.07.25)
ShardLucene sub-index partition
ILMIndex Lifecycle Management
Hot/warm/coldStorage tiers by access frequency
Inverted indexTerm → document mapping
Schema-on-readParse at query time
Bloated indexToo many analyzed fields
Trace correlationtrace_id links logs to traces
SamplingStore subset at ingest

6. Core Mechanism​

6.1 Architecture​

Figure 1: Agents buffer to Kafka; ingest pipeline parses and indexes; ILM moves cold data to object store.

6.2 APIs​

POST /_bulk (Elasticsearch bulk index)

GET /logs-*/_search
{ "query": { "bool": { "filter": [
{ "range": { "@timestamp": { "gte": "now-1h" }}},
{ "term": { "service": "payment" }},
{ "match": { "message": "timeout" }}
]}}}

POST /_ilm/policy/logs-policy
DELETE /_delete_by_query (GDPR erasure)

6.3 Data Model​

Log document:

{
"@timestamp": "2026-07-25T10:00:00Z",
"level": "ERROR",
"service": "payment",
"env": "prod",
"trace_id": "abc123",
"message": "charge failed",
"user_id_hash": "sha256...",
"duration_ms": 450
}

Index naming: logs-{env}-{yyyy.MM.dd} — enables time-based ILM.

Mapping:

  • Keyword: service, level, trace_id (exact match, aggregations).
  • Text: message (full-text, optionally disabled subfields).
  • Numeric: duration_ms (range queries).

6.4 Deep Dives​

Ingest pipeline:

  1. Kafka consumer batch (1000 docs or 5 MB).
  2. Grok/JSON parse; drop DEBUG in prod if policy.
  3. PII scrubber masks email, credit card patterns.
  4. Enrich with K8s metadata (pod, namespace).
  5. Bulk index to today's index shard.

Index and shard sizing:

  • Target shard 20–50 GB.
  • 5 TB/day ÷ 50 GB ≈ 100 shards/day—use index-per-day not per-hour unless extreme.
  • Forcemerge warm indices; read-only after day closes.

Figure 2: Buffered ingest decouples burst logging from index pressure.

Hot/warm/cold ILM:

PhaseAgeStorageActions
Hot0–7dSSDActive writes
Warm7–30dHDDShrink replicas
Cold30–365dS3 snapshotSearchable snapshot
Delete>365d—Compliance

Figure 3: Index lifecycle reduces cost as logs age.

Query optimization:

  • Always filter @timestamp first (prunes shards).
  • Use keyword filters before match on message.
  • Saved searches with index pattern logs-prod-* not *.

Sampling for high-volume debug:

  • Head-based: keep 10% of DEBUG logs.
  • Tail-based: keep all ERROR; sample INFO.
  • Never sample security audit logs.

7. Step-by-Step Walkthrough​

  1. On-call filters service:payment AND level:ERROR last 1h.
  2. Query hits 3 daily indices; 200 ms response.
  3. Click trace_id → jump to tracing platform.

7.2 Ingest spike​

  1. Buggy deploy logs 100× normal volume.
  2. Kafka absorbs burst; consumer lag grows.
  3. Autoscale ingest workers; lag clears in 10 min.
  4. Post-incident: rate limit log line per request.

7.3 GDPR delete​

  1. User requests erasure.
  2. _delete_by_query on user_id_hash across indices.
  3. Force merge; verify zero hits; audit log deletion job.

7.5 Security incident log investigation​

  1. SOC searches event:auth_failure AND user_id_hash:abc last 7d.
  2. Query spans 7 daily indices—shard pruning via time filter.
  3. Results exported to case ticket; chain of custody documented.
  4. Original logs immutable in WORM audit cluster if regulated.

7.6 Log sampling for high-volume debug​

  1. Service logs 50K DEBUG lines/sec per pod—unsustainable.
  2. Head sample 1% DEBUG; 100% WARN+.
  3. Dynamic upsample: if ERROR rate > threshold, capture 100% DEBUG for 5 min window.
  4. Balances cost vs debuggability during incidents.

7B. OpenSearch Cluster Sizing Heuristic​

Daily ingest: 5 TB
Retention hot: 30 days → 150 TB raw
Replica factor: 1 → 300 TB disk (with overhead)
Shard target: 40 GB → 3750 shards total → ~125 shards/day
Nodes: 30 data nodes × 12 TB NVMe with headroom

Validate with vendor sizing calculator—heuristic for interview whiteboard only.

10A. Query DSL Performance Patterns​

Fast:

{ "bool": { "filter": [
{ "range": { "@timestamp": { "gte": "now-1h" }}},
{ "term": { "service.keyword": "payment" }},
{ "term": { "level.keyword": "ERROR" }}
]}}

Slow: wildcard on message, no time filter, script filters on hot path.

Train developers via slow query log review weekly.

PhaseKey decisions
Requirements5TB/day, 30d hot, field search
ScaleKafka buffer; daily indices
APIsbulk index; search DSL
DataJSON mapping; ILM policy
Deep divesPII scrub; tiering

8. Invariants and Guarantees​

PropertyGuarantee
At-least-once ingestPossible duplicates; idempotent doc IDs optional
Time orderingPer-shard approximate; use timestamp field
RetentionILM deletes after policy
RBACIndex-level access per team
ImmutabilityLogs append-only; corrections via new events

9. Failure Scenarios​

ScenarioMitigation
Search cluster redReplica shards; cross-AZ
Kafka lag unboundedScale consumers; drop DEBUG emergency
Mapping explosionLimit dynamic fields; reject
Hot shardRollover alias; split index
Disk fullILM force; expand or delete
PII leak in logsScrub pipeline; block deploy

10. Performance Characteristics​

50K events/sec × 2 KB avg = 100 MB/sec ingest
5 TB/day raw; 30% index overhead ≈ 1.5 TB/day index hot
Query: filter on keyword + time → ms; full-text GB → seconds
Bulk batch 5–15 MB optimal for Elasticsearch

11. Scalability Limits​

LimitMitigation
Field cardinalityLimit dynamic mapping
Shard count explosionDaily indices not hourly
Expensive aggregationsPrecompute via metrics
Cross-cluster searchCCS or federated query
Log volumeSampling; log level policy

12. Operational Considerations​

  • Metrics: ingest rate, Kafka lag, JVM heap, query latency, disk %.
  • Alerts: cluster red; lag > 1h; failed bulk reject rate.
  • Runbooks: emergency index close; increase refresh interval.
  • Index template versioning in Git.

13. Security Considerations​

  • TLS ingest; mTLS for agents.
  • RBAC: team A cannot query team B indices.
  • PII scrubbing mandatory; secrets never logged (CI lint).
  • Audit admin searches.
  • Immutable audit log index separate from app logs.

14. Cost Considerations​

Storage dominates—ILM to S3 saves 80% vs all-SSD. Reduce volume: structured logs, appropriate levels, sampling. Managed OpenSearch vs self-hosted ops tradeoff. Chargeback per GB ingested per team.

15. Production Implementations​

SystemNotes
Elasticsearch / OpenSearchDominant OSS stack
SplunkEnterprise leader; proprietary
LokiLabel-indexed; cheaper at scale for K8s
Datadog LogsSaaS integrated
Fluent BitLightweight shipper

16. Alternatives and Tradeoffs​

ApproachProsCons
Full-text index (ES)Flexible searchExpensive
Label-only (Loki)Lower costWeak full-text
S3 + AthenaCheapest archiveSlow interactive
Schema-on-readFlexible ingestSlow queries
Kafka onlyDurable bufferNot searchable alone
stdout onlySimpleNo central search

16A. Structured Logging Standard (Org-Wide)​

Required fields on every production log line:

{
"@timestamp": "ISO8601",
"level": "INFO|WARN|ERROR",
"service": "payment",
"env": "prod",
"trace_id": "hex",
"span_id": "hex",
"message": "human readable",
"error": { "type": "", "stack": "" }
}

Optional: user_id_hash, tenant_id, request_id. Forbidden: raw email, PAN, password, OAuth tokens. Lint in CI with sample log fixture tests.

16B. Log Volume Reduction Levers​

LeverTypical savings
INFO default vs DEBUG50–90%
Sample DEBUG 1%Additional on remainder
Drop health-check logs at ingest5–15%
Aggregate access logs to metrics30–50% access log volume

Principal sponsors quarterly log budget review with top 10 volume services—engineering managers accountable.

| "grep scale" | Need distributed index | | "JSON any shape OK" | Mapping explosions hurt | | "Logs replace metrics" | Different cost model | | "Real-time means no buffer" | Kafka protects index |

Legal requests may require preserving logs matching complex queries across years of cold storage. Architecture provides: legal hold flag on index pattern preventing ILM delete; export API to WORM storage; chain-of-custody metadata on export job. Engineering does not interpret law—workflow hands forensic package to legal team with documented integrity hashes (SHA-256 of export manifest). Retention extension overrides default delete—monitor storage cost of holds quarterly.

18. Principal Architect Perspective​

  • Logging standard per org—required fields: trace_id, service, level.
  • Default log level INFO in prod; DEBUG gated.
  • PII policy in code review—not just pipeline afterthought.
  • ILM day-one—retrofit is painful.
  • Link logs to metrics and traces—observability triad.

19. Architecture Review Exercise​

Scenario: Single index logs-all 500 shards 2 TB; queries timeout.

Review: Daily indices; reduce shards; ILM; mandatory time filter in UI.

20. Whiteboard Explanation​

"Apps log structured JSON to stdout; Fluent Bit ships to Kafka for buffering. Ingest workers parse, scrub PII, enrich metadata, and bulk index into daily time-partitioned indices. Keyword fields indexed for filters; message full-text with care. ILM rolls hot SSD indices to warm HDD then S3 snapshots. Queries always time-bound; trace_id links to tracing. RBAC per team index pattern. Sampling and log-level policies control volume."

21. Interview Questions​

  1. Design logging for 5 TB/day. — Signals: Kafka, daily indices, ILM. Red flags: single DB.
  2. Elasticsearch vs Loki? — Signals: full-text vs label-only cost.
  3. Index design? — Signals: daily partition; keyword vs text.
  4. Handle ingest spike? — Signals: Kafka buffer; scale consumers.
  5. PII in logs? — Signals: scrub pipeline; hash user IDs.
  6. GDPR delete? — Signals: delete_by_query; audit.
  7. Shard sizing? — Signals: 20–50 GB target.
  8. Slow queries? — Signals: time filter; keyword first.
  9. At-least-once duplicates? — Signals: doc ID dedup optional.
  10. Cold archive search? — Signals: searchable snapshot.
  11. Correlation with traces? — Signals: trace_id field.
  12. Cost reduction? — Signals: sampling, ILM, log level.
  13. Mapping explosion? — Signals: disable dynamic; limit fields.
  14. Security audit logs? — Signals: separate index; no sampling.

21B. Extended Interview Question Deep Dives​

Q15 (Principal): GDPR erasure request across 400 daily indices—SLA 30 days.

Strong signals: _delete_by_query with user_id_hash; track job ID; verify zero hits; legal hold exception path; audit deletion certificate. Cost: expensive search—maintain secondary index on user_id_hash if frequent.

Q16 (Principal): Developer wants raw TCP syslog from 10K legacy devices.

Strong signals: Syslog gateway normalizing to JSON; Kafka buffer; rate limit per device; separate low-trust index with short retention. Security: unauthenticated syslog is spoofing risk—VPN or mTLS.

  1. Multi-region aggregation. — Cross-cluster search latency.
  2. Log-based metrics (ELK aggregations). — Prefer metrics platform instead.

22A. Production Low-Level Design (Interview + Game Day)​

Logging platform LLD: ingest agents → broker → indexers; separate hot query from cold object tiers.

Context diagram​

Step-by-step flow:

StepAction
1–2Edge buffer; backpressure
3–5Parse, index hot, archive cold
6Query planner picks tier

Production stack​

LayerChoiceRole
ShipFluent Bit / OTelDisk buffer
BusKafkaDecouple spikes
ParseStream processorsJSON / grok
HotOpenSearch / ClickHouseRecent N days
ColdParquet on S3Cheap retain
ACLTenant + fieldPII redaction

API + schema​

POST /v1/ingest (internal)
GET /v1/query?q=&from=&to=&tenant=
POST /v1/saved_searches
Index designGuidance
Shard by time + tenantAvoid mega-shards
Field capsDrop high-cardinality explode
ILMHot → warm → delete/archive

Happy-path sequence​

Failure — ingest flood​

Observability + SLO​

SLIIdea
End-to-end lagp99 < X min
Ingest durabilityAck after Kafka
Query availabilityHot tier SLO
Drop rateOnly under declared shed

22B. Game Day Playbooks​

Catalog​

IDDrillInjectSignal
GD-1Debug flood20× INFOLag + shed
GD-2Hot cluster redNode lossReplica promote
GD-3Mapping explosionNew field stormField cap
GD-4PII unredactedCanary SSNPipeline deny
GD-5Kafka fullDiskBlock producers
GD-6Query of deathUnbounded regexTimeout / cost gate

GD-1 — Debug flood (detailed)​

GD-3 — Mapping explosion (detailed)​

Pass criteria: cluster heap stable; tenant isolated; field cap enforced.

23. Strong Answer Example​

Question: "How to design indices for 5 TB/day?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—time+tenant sharding + ILM + cardinality control, not one giant daily index.

Figure A: PRACTICE map — walk the board in this order.


Student interview script (PRACTICE)​

P — Problem framing​

"5 TB/day will melt a naive single index. Design ingest → Kafka → indexers with time-based indices, tenant isolation, hot/warm/cold ILM, and field/cardinality caps. Query recent data hot; archive to object storage."

R — Requirements​

TypeRequirement
FRSearch last 7–14d hot; longer cold
NFRKeep up with 5 TB/day + spikes
SafetyTenant ACL; PII redact
CostILM delete/archive

A — Assumptions​

AssumptionWhy
Structured JSON dominantMapping control
Kafka bufferAbsorb spikes
Not all fields queriedDrop / flatten

C — Capacity​

5 TB/day ≈ 60 MB/s average; peak 5–10×
Shard size target 20–50 GB
Partitions ≥ indexer parallelism
Retention hot 7d → cold Parquet

T — Topology​

I — Invariants​

  1. No unbounded dynamic fields.
  2. Tenant cannot starve cluster (quotas).
  3. Ack durability at Kafka before agent drops.
  4. Audit logs not sampled away.

C — Constraints​

ConstraintResponse
Mapping stormField cap / flatten
Query of deathTimeout + cost limits
Multi-tenant noisySeparate indices / clusters

E — Evolution​

Single cluster → tiered storage → columnar hot (ClickHouse) → lakehouse query federation.


Closing line (interview)​

"For 5 TB/day: Kafka buffer, time/tenant-sharded indices, field caps, ILM to cold object storage, quotas so one tenant cannot melt the cluster."

Scoring signals​

StrongWeak
Time+tenant indices + ILMOne giant index
Cardinality capsIndex every JSON key
Kafka backpressureSync HTTP to ES only
Hot/cold splitKeep 1y hot

Compact outline (if time-boxed to 2 minutes)​

"For 5 TB/day: Kafka buffer, time/tenant-sharded indices, field caps, ILM to cold object storage, quotas so one tenant cannot melt the cluster."

24. Weak Answer Example​

Weak: "SSH to each server and grep logs."

Red flags: No centralization, no scale, no retention, no compliance.

25. Hands-On Exercise​

  1. Deploy Fluent Bit → Elasticsearch with JSON parse.
  2. Create ILM policy hot-warm-delete.
  3. Benchmark query with vs without time filter.
  4. Implement PII regex scrub in ingest pipeline.
  5. Extension: Kafka lag alert and consumer autoscale rule.

25A. Extended Hands-On Lab​

  1. Restore searchable snapshot from S3; measure query latency vs hot index.
  2. Run _delete_by_query dry-run mode; estimate affected docs before execute.
  3. Inject mapping conflict; observe strict dynamic mapping rejection.
  4. Principal lab: Define org JSON log schema with JSON Schema validation in CI.

25B. Production Readiness Review Questions​

  • Can ingest continue if search cluster yellow?
  • Is PII scrubber tested with adversarial payloads?
  • Are audit logs tamper-evident?
  • What is max acceptable Kafka lag before dropping DEBUG at source?

Logging platform incidents overlap with security incidents—runbooks must cover both.

  1. Keyword vs text mapping?
  2. Three ILM phases?
  3. Why Kafka before index?

27. Flashcards​

FrontBack
ILMAutomated index lifecycle phases
Log shipperAgent forwarding to central pipeline
Bulk APIBatch document indexing
Keyword fieldExact match and aggregations
Searchable snapshotS3-backed cold index
MappingSchema defining field types
Kafka bufferDecouples burst from index
PII scrubberRemoves sensitive data at ingest
trace_idCorrelates logs with traces
ForcemergeReduces segments in warm index

28. Cheat Sheet​

REQUIREMENTS: central search, 5TB/day, 30d hot, compliance
SCALE: Kafka buffer; daily indices; bulk ingest
APIs: bulk index; search DSL; ILM policy
DATA: JSON logs; keyword+text mapping
ARCH: agent → Kafka → pipeline → ES → S3
DEEP: ILM tiers; PII scrub; query optimization
RELIABILITY: replicas; at-least-once; lag monitoring
SECURITY: RBAC; audit index; no secrets in logs
OPS: disk %; kafka lag; mapping limits

17A. Failure Scenario Drill​

Engineer sets "index.mapping.total_fields.limit": 50000 to silence errors—mapping explodes from dynamic JSON keys; cluster yellow for weeks; search unusable. Mitigation: disable dynamic mapping prod; schema registry for log fields; reject unknown fields at ingest. Mapping discipline equals metrics cardinality discipline.

18.1 OpenSearch vs Loki Decision Matrix​

RequirementPrefer
Full-text message searchOpenSearch/ES
K8s label-only filterLoki
30d interactive + 1y archiveES ILM + S3
Cost < $0.10/GB/day ingestLoki or S3+Athena

19A. Extended Review Scenario​

Scenario B: Security team needs tamper-proof audit logs in same index as app DEBUG logs—attacker with app creds could delete audit entries if shared cluster admin.

Review: Separate cluster/account for audit; WORM bucket; break-glass access only.

21A. Additional Interview Questions​

  1. Structured logging standard? — Signals: required fields service, trace_id, level; JSON only. Red flags: printf debugging in prod.
  2. Rehydrate from S3 snapshot cost? — Signals: minutes to hours; chargeback to investigating team.

28A. Principal Interview Deep Dive​

Ingest pipeline processor order​

  1. Parse JSON
  2. Drop DEBUG (if policy)
  3. PII scrub
  4. Enrich k8s metadata
  5. Route to index

Scrub before index—indexed PII is compliance failure even if later deleted.

Query guardrails in UI​

  • Mandatory time range default 15m
  • Reject wildcard leading *search* without filter
  • Max result window 10K

Cost attribution​

Chargeback label team on every log line—FinOps visibility drives volume reduction more than ops nagging.

28B. Extended BOE Walkthrough​

Interviewer: "5 TB/day logs, 30 day hot search."

Strong candidate:

"5 TB/day × 30 = 150 TB hot before ILM—plan shard count and node disk.

Kafka buffer mandatory—100 MB/sec sustained ingest.

Daily indices logs-prod-yyyy.MM.dd; 30 shards × 50 GB target.

ILM to S3 snapshot day 31; delete year 1.

PII scrub at ingest. Correlate trace_id to Metrics Platform.

Never grep production servers at this scale."

30. References​

  • Elasticsearch documentation — index lifecycle and mappings (official).
  • Grafana Loki design doc — label-based logging alternative.
  • Kleppmann, DDIA — batch and stream processing for logs.

Distinction: Elasticsearch architecture well-documented; exact shard counts are deployment-specific.

30A. Further Reading Paths​

Ingest pipeline often fed by Kafka-like Event Platform. Security logs may require Security Architecture Fundamentals retention policies.

30B. Index Template Version Control​

Store index templates in Git:

{
"index_patterns": ["logs-prod-*"],
"settings": { "number_of_shards": 30, "index.lifecycle.name": "logs-policy" },
"mappings": { "dynamic": "strict", "properties": { ... } }
}

CI applies template before deploy; prevents mapping drift across environments.

30D. Principal Architecture Review Checklist​

  • Kafka buffer between agents and index—no direct burst to search cluster
  • Daily index pattern with ILM policy applied in all environments
  • Dynamic mapping disabled or strict in production indices
  • PII scrubbing in pipeline before index—spot-check weekly samples
  • Mandatory time filter in search UI and API gateway
  • Audit logs on separate cluster or WORM storage
  • Slow query log reviewed; top 10 queries optimized monthly
  • Ingest sampling policy documented for DEBUG volume

Logging at scale is an indexing and governance problem—volume reduction beats bigger cluster after ~2 TB/day for most orgs.

30F. Closing Principal Note​

Logging remains the definitive artifact for "what exactly happened to request X?"—metrics tell you that error rate spiked; logs tell you which dependency timed out.

30G. OpenTelemetry Logs Bridge​

OTel log signal export to same pipeline as app JSON enables trace-log correlation without custom instrumentation per framework. Standardize on OTel SDK where possible—reduces vendor lock-in to Elasticsearch vs Loki vs SaaS backend choice made independently of instrumentation.

30H. Dual-Write Anti-Pattern Warning​

Teams sometimes log AND metric the same event at high volume—duplicate cost. Prefer metric for aggregates (error rate) and log for exemplar traces (single error detail). Exception: security audit events may require both immutable log and metric counter for alerting—document explicitly in security architecture review. On-call runbooks should link from Alertmanager annotations directly to saved Kibana/OpenSearch searches with prefilled time range and service filter.