The first ELK cluster I ran died in week three. The disk filled up, Elasticsearch flipped into read-only mode, Logstash piled up 40GB of queued logs, Kibana showed nothing, and the on-call engineer couldn't find the error that was paging them. Classic. The cluster had 30 days of retention configured on paper, but no ILM policy actually deleting old indices, and the index template was creating a new field for every unique error message-billions of fields, billions of disk bytes. ELK is a powerful stack and a powerful way to ruin your week if you don't understand it.
This article is the guide I wish I'd had: how to size a cluster, how to structure logs at the source, how to write Logstash pipelines that don't melt your CPU, how to configure index lifecycle management so data actually ages out, and how to avoid the cardinality traps that quietly bankrupt your storage. We'll use the modern Elastic Stack (8.x) with security on by default, because that's what you should be deploying in 2024 and beyond.
Why ELK Over Loki, Datadog, or Splunk
Let me be honest about the trade-offs:
| Tool | Architecture | Cost model | Sweet spot | Weakness |
|---|---|---|---|---|
| ELK (Elasticsearch) | Indexed full-text + structured | Free OSS / paid Cloud | Search-heavy log analysis, SIEM | Heavy on disk and RAM; complex to operate |
| Grafana Loki | Append-only, indexed by labels | Free OSS / paid Cloud | "Prometheus for logs"; cheap storage | Weak full-text search; queries are slower |
| Datadog Logs | Agent → Datadog | Per-GB ingest + retention | "I want one bill and zero ops" | Gets expensive fast; vendor lock-in |
| Splunk | Indexed | Per-GB ingest (expensive) | Enterprise SIEM, complex search | Very expensive; legacy UX |
| OpenSearch | Fork of Elasticsearch | Free Apache 2.0 | Elasticsearch without Elastic license | Slightly behind Elastic features |
| Quickwit | Rust, columnar | Free OSS | Very high-volume, low-cost | Newer, smaller community |
I default to ELK when search quality matters and the team is willing to operate it. I default to Loki when the team is already on Prometheus and just wants to "see logs alongside metrics" cheaply. I tell teams with more money than time to use Datadog. Splunk is for organizations that have already standardized on it. OpenSearch is the right call if you're avoiding Elastic's license or want AWS's managed version.
Prerequisites
- 16GB+ RAM on the box you'll deploy to (32GB+ for production). Elasticsearch is a JVM beast; below 8GB you'll suffer.
- SSD storage, at least 100GB. HDDs make Elasticsearch unusably slow.
- Docker and Docker Compose for the demo. For production, dedicated VMs or managed Elastic Cloud.
- Basic familiarity with JSON, the command line, and what an inverted index is.
- Logs you actually want to ingest. We'll use a sample Nginx access log and a JSON application log.
Architecture: What's Actually Happening
CodeCopy
[apps] [nginx] [containers]
| | |
| stdout (JSON) | access.log | stdout
v v v
+--------------------------------------------------+
| Filebeat / Fluentbit |
| (tail files, parse, ship to Logstash or ES) |
+----------------------+------------------------------+
|
v
+--------------------------------------------------+
| Logstash (optional, for transformation) |
| - grok parse |
| - enrich (geoip, user-agent) |
| - mutate fields |
+----------------------+------------------------------+
|
v
+--------------------------------------------------+
| Elasticsearch cluster |
| - master nodes (3, small) |
| - data nodes (N, big) |
| - ingest nodes (optional, for pipelines) |
| - coordinating-only (optional, for Kibana) |
| indices: logs-nginx-2024.11.15 |
| logs-app-2024.11.15 |
| ILM: hot(7d) -> warm(14d) -> cold(60d) -> delete |
+----------------------+------------------------------+
|
v
+--------------------------------------------------+
| Kibana |
| - dashboards, saved searches, alerts |
| - KQL/Lucene query bar |
+--------------------------------------------------+
The four roles in an Elasticsearch cluster:
- Master nodes manage cluster state (which shards live where). 3 of them, small boxes, dedicated. Don't run data on master nodes.
- Data nodes hold shards and serve queries. Where you spend money.
- Ingest nodes run pipelines (grok, geoip) at index time. Often combined with data nodes for small clusters.
- Coordinating-only nodes take query requests, fan out to data nodes, merge results. Useful when you have many Kibana users hitting the cluster.
For dev/small prod, three nodes running all roles works. For real prod, separate them.
Installation: Docker Compose Stack
Here's a complete stack with security enabled. Elastic 8.x generates certificates and passwords on first boot.
YAMLCopy
yaml
docker-compose.yml
version: "3.8"
services:
es01:
image: docker.elastic.co/elasticsearch/elasticsearch:8.15.0
container_name: es01
environment:
- node.name=es01
- cluster.name=elk-cluster
- discovery.type=single-node
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms2g -Xmx2g"
- xpack.security.enabled=true
- xpack.security.enrollment.enabled=true
- xpack.security.http.ssl.enabled=false
- xpack.security.transport.ssl.enabled=false ulimits: memlock: { soft: -1, hard: -1 } volumes:
- es01_data:/usr/share/elasticsearch/data ports: ["9200:9200"]
kibana:
image: docker.elastic.co/kibana/kibana:8.15.0
container_name: kibana
environment:
- ELASTICSEARCH_HOSTS=http://es01:9200
- ELASTICSEARCH_USERNAME=kibana_system
- ELASTICSEARCH_PASSWORD=${KIBANA_PASSWORD} ports: ["5601:5601"] depends_on: [es01]
logstash:
image: docker.elastic.co/logstash/logstash:8.15.0
container_name: logstash
volumes:
- ./logstash/pipeline:/usr/share/logstash/pipeline:ro
- ./logstash/config/logstash.yml:/usr/share/logstash/config/logstash.yml:ro environment:
- ELASTIC_PASSWORD=${ELASTIC_PASSWORD} ports: ["5044:5044"] depends_on: [es01]
filebeat:
image: docker.elastic.co/beats/filebeat:8.15.0
container_name: filebeat
user: root
volumes:
- ./filebeat/filebeat.yml:/usr/share/filebeat/filebeat.yml:ro
- /var/log:/var/log:ro
- /var/lib/docker/containers:/var/lib/docker/containers:ro command: ["filebeat", "-e", "-strict.perms=false"] depends_on: [logstash]
volumes:
es01_data:
plaintext
Generate the elastic password and enroll Kibana:
BashCopy
shell
Reset elastic password
docker exec -it es01 bin/elasticsearch-reset-password -u elastic -i
Reset kibana_system password (set KIBANA_PASSWORD env var to match)
docker exec -it es01 bin/elasticsearch-reset-password -u kibana_system -i
Test
curl -u elastic:YOUR_PASSWORD http://localhost:9200/_cluster/health?pretty
markdown
For production, use multi-node Elasticsearch with TLS on transport and HTTP. The Elastic docs have a full docker-compose TLS example; copy it and don't try to roll your own PKI.
Cluster Design: Master, Data, and Shards
The single biggest decision in ELK is shard count. Get it wrong and your cluster is slow forever.
Rule of thumb: shard size should be 30-50GB. Below 10GB, you have too many shards (overhead). Above 50GB, search is slow and recovery during node failure is painful.
Number of primary shards = estimated_daily_volume_GB / 30, rounded up. For 50GB/day, that's 2 shards. For 500GB/day, that's 17. Use 1 replica for high availability (so 2x total shard count).
JSONCopy
json
// Index template for daily logs
PUT _index_template/logs
{
"index_patterns": ["logs-*"],
"template": {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"refresh_interval": "5s",
"index.lifecycle.name": "logs-policy"
},
"mappings": {
"dynamic": false,
"properties": {
"@timestamp": { "type": "date" },
"level": { "type": "keyword" },
"service": { "type": "keyword" },
"env": { "type": "keyword" },
"host": { "type": "keyword" },
"message": { "type": "text" },
"request_id": { "type": "keyword" },
"duration_ms": { "type": "long" },
"status": { "type": "integer" },
"path": { "type": "keyword" },
"user_id": { "type": "keyword" }
}
}
}
}
markdown
Three critical decisions in this template:
-
"dynamic": false- unknown fields are silently dropped. This is the most important production setting. Without it, a log line containing{"user_id": 123}followed by{"user_id": "abc"}triggers a mapping conflict (field can't be both integer and keyword). Withdynamic: false, you explicitly define fields; everything else goes into a catch-all or is dropped. If you must allow unknown fields, usedynamic: truewithdynamic_templatesto coerce them all to keyword, never text. -
keywordvstext-keywordis exact match, no analysis.textis full-text search, tokenized. Usekeywordfor fields you'll filter on (level, service, env). Usetextonly for the message body where you want to search "find me logs containing 'timeout'". Don't makeuser_ida text field-every unique value gets analyzed, you blow up your term dictionary. -
refresh_interval: 5s- default is 1s. Raising to 5s (or 30s for high-volume) reduces indexing pressure. Logs don't need to be searchable within 1 second; 5-30s is fine. -
No high-cardinality fields as
text. A field with 10 million unique values, mapped astext, becomes a 10-million-entry term dictionary. Cluster dies.
Index Lifecycle Management: Aging Out Data
Without ILM, your cluster fills up and dies. ILM automates the hot-warm-cold-delete progression.
JSONCopy
json
// Create ILM policy
PUT _ilm/policy/logs-policy
{
"policy": {
"phases": {
"hot": {
"actions": {
"rollover": {
"max_age": "1d",
"max_primary_shard_size": "30gb"
},
"set_priority": { "priority": 100 }
}
},
"warm": {
"min_age": "7d",
"actions": {
"shrink": { "number_of_shards": 1 },
"forcemerge": { "max_num_segments": 1 },
"set_priority": { "priority": 50 }
}
},
"cold": {
"min_age": "30d",
"actions": {
"set_priority": { "priority": 0 }
}
},
"delete": {
"min_age": "90d",
"actions": {
"delete": {}
}
}
}
}
}
markdown
What this does:
- Hot (0-7d): actively written to. Rollover to a new index when current one hits 30GB or 1 day. Set priority 100 (searched first).
- Warm (7-30d): read-only-ish. Shrink to 1 shard (saves overhead). Force-merge to 1 segment (saves disk, faster reads).
- Cold (30-90d): still searchable but slower. Move to cheaper storage (if you have tiered nodes).
- Delete (90d): gone.
For most log use cases, 30-90 days retention is plenty. Long-term log retention is rarely worth the cost-use S3 archival (Searchable Snapshots) if you really need it.
The bootstrapping step: your initial index needs the alias and write flag set so rollover works.
JSONCopy
http
// Bootstrap the first index
PUT logs-000001
{
"aliases": {
"logs-write": {
"is_write_index": true
}
}
}
markdown
Now Logstash writes to logs-write alias, which always points at the current write index. ILM handles rollover automatically.
Logstash Pipelines: Parsing Without Melting CPU
Logstash is the swiss army knife-and like all swiss army knives, it's slower than dedicated tools. Use it when you need transformation. Skip it (write directly from Filebeat to Elasticsearch) when you don't.
A real Nginx access log pipeline:
RubyCopy
conf
logstash/pipeline/nginx.conf
input {
beats {
port => 5044
}
}
filter {
if "nginx-access" in [tags] {
grok {
match => {
"message" => [
'%{IPORHOST:client_ip} - %{DATA:user} [%{HTTPDATE:timestamp}] "%{WORD:method} %{URIPATHPARAM:path} HTTP/%{NUMBER:http_version}" %{NUMBER:status} %{NUMBER:bytes} "%{DATA:referer}" "%{DATA:user_agent}" rt=%{NUMBER:request_time} uct=%{DATA:upstream_connect_time} urt=%{DATA:upstream_response_time}'
]
}
tag_on_failure => ["_grokparsefailure"]
overwrite => ["message"]
}
date {
match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"]
target => "@timestamp"
remove_field => ["timestamp"]
}
mutate {
convert => {
"status" => "integer"
"bytes" => "integer"
"request_time" => "float"
}
remove_field => ["user", "http_version"]
}
geoip {
source => "client_ip"
target => "geoip"
}
useragent {
source => "user_agent"
target => "ua"
}
}
}
output {
if "_grokparsefailure" in [tags] {
elasticsearch {
hosts => ["http://es01:9200"]
user => "elastic"
password => "${ELASTIC_PASSWORD}"
index => "nginx-parse-failures-%{+YYYY.MM.dd}"
}
} else {
elasticsearch {
hosts => ["http://es01:9200"]
user => "elastic"
password => "${ELASTIC_PASSWORD}"
index => "nginx-access-%{+YYYY.MM.dd}"
}
}
}
markdown
Key Logstash lessons, learned the painful way:
-
Grok is regex. A complex grok pattern can use 10x the CPU of a simple one. Test patterns with the Grok Debugger in Kibana before deploying. The
grokfilter hasbreak_on_match => true(default) which stops at the first matching pattern-put your most specific patterns first. -
overwrite => ["message"]removes the original raw message. Don't do this in production. Keep the raw message in a field for forensic debugging; parsed fields are for queries. -
Use
tag_on_failureto route parse failures to a separate index. If 5% of your logs don't match the pattern, you want to know and fix the pattern, not silently lose the data. - GeoIP and UserAgent are expensive. Only run them if you actually use the output. For an internal API, you don't need either.
-
Drop fields you don't need. Every field costs disk and memory. Use
mutate { remove_field => [...] }aggressively.
The fastest Logstash alternative: skip it entirely. Have your apps log structured JSON directly, ship via Filebeat to Elasticsearch. Logstash becomes optional. Modern best practice is structured logging at the source, not parsing at the pipeline.
Structured Logging at the Source
The right pattern: your applications emit JSON logs. Filebeat ships them. Elasticsearch indexes them. No Logstash needed.
PythonCopy
python
Python with structlog
import structlog
import logging
import sys
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
logger_factory=structlog.PrintLoggerFactory(file=sys.stdout),
cache_logger_on_first_use=True,
)
log = structlog.get_logger()
Bind request-scoped context
log = log.bind(request_id="abc-123", user_id="user-456", service="api")
log.info("request_completed", method="GET", path="/api/users/123",
status=200, duration_ms=42)
log.error("db_query_failed", query="SELECT * FROM users", error="timeout")
plaintext
Output (one JSON object per line):
JSONCopy
json
{"event":"request_completed","method":"GET","path":"/api/users/123","status":200,"duration_ms":42,"request_id":"abc-123","user_id":"user-456","service":"api","level":"info","timestamp":"2024-11-15T10:30:45.123Z"}
markdown
Why this matters:
- No parsing. Elasticsearch ingests JSON natively. No grok, no CPU tax.
- No information loss. Every field is structured from the start.
- Schema is consistent. Same field names across all logs.
-
You can correlate.
request_idlets you trace a request across multiple services in Kibana.
The cardinality rule still applies: don't log request_id or user_id as text fields. They go in the index template as keyword. If you need full-text search on a free-form error message, only the message/error field is text.
JSONCopy
json
// Index template for application logs (extends the logs template)
PUT _index_template/app-logs
{
"index_patterns": ["app-*"],
"template": {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"index.lifecycle.name": "logs-policy"
},
"mappings": {
"dynamic": false,
"properties": {
"@timestamp": { "type": "date" },
"level": { "type": "keyword" },
"service": { "type": "keyword" },
"env": { "type": "keyword" },
"host": { "type": "keyword" },
"request_id": { "type": "keyword" },
"user_id": { "type": "keyword" },
"event": { "type": "keyword" },
"method": { "type": "keyword" },
"path": { "type": "keyword" },
"status": { "type": "integer" },
"duration_ms": { "type": "long" },
"message": { "type": "text" },
"error": { "type": "text" },
"stack_trace": { "type": "text", "index": false }
}
}
}
}
markdown
The "index": false on stack_trace is a useful trick: the field is stored (so you can retrieve it in search results) but not indexed (so it doesn't bloat the term dictionary and you can't search on it). Stack traces are 90% of the bytes and 0% of the searches-index-off them.
Kibana: Queries, Dashboards, Alerts
Kibana's query bar supports both KQL (Kibana Query Language, simpler) and Lucene (more powerful, more verbose). Use KQL.
CodeCopy
plaintext
Find all 5xx errors in the API in the last hour
level: "error" and service: "api" and status >= 500
Find a specific request across services
request_id: "abc-123"
Full-text search for timeout errors
message: "timeout" or error: "timeout"
Combine: error logs mentioning database, excluding healthcheck
level: "error" and message: "database" and not path: "/healthz"
markdown
Saved searches are queries you name and reuse. Visualizations are charts built on saved searches. Dashboards are collections of visualizations.
A useful API dashboard layout:
- Top row: 4 metric panels - total requests, error count, error rate, p99 latency.
- Second row: time series of requests per minute (split by status code), latency percentile time series.
- Third row: top 10 error messages (data table), top 10 slowest endpoints (data table).
- Fourth row: log stream (last 100 ERROR-level logs in real time).
JSONCopy
json
// Example Kibana saved object: error count metric panel
{
"type": "visualization",
"attributes": {
"title": "Error count (last 1h)",
"visState": {
"type": "metric",
"params": { "fontSize": 60 },
"aggs": [
{ "id": "1", "type": "count", "params": {} }
]
},
"kibanaSavedObjectMeta": {
"searchSourceJSON": {
"query": { "query": "level: \"error\"", "language": "kuery" },
"filter": []
}
}
}
}
plaintext
Alerts via Kibana's Alerting framework (Stack features, free tier covers basics):
JSONCopy
json
// Alert: error rate above 5% for 5 minutes
POST /api/detection_engine/rules
{
"name": "API error rate > 5%",
"params": {
"aggType": "count",
"group": "top",
"termSize": 5,
"threshold": [5],
"timeWindowSize": 300,
"timeWindowUnit": "s",
"index": ["app-*"],
"aggField": "level"
},
"consumer": "alerts",
"rule_type_id": ".es-query",
"schedule": { "interval": "1m" },
"actions": [
{
"id": "slack-webhook",
"params": { "message": "Error rate above 5% on API" }
}
]
}
markdown
Set up alerts on: error rate, latency p99, log volume anomaly (sudden spike), specific error patterns (e.g., OutOfMemoryError). Don't alert on every error-alert on rate-of-change and absolute thresholds combined.
Performance Tuning: Heap, Shards, Refresh
Elasticsearch is a JVM app. Heap sizing rules:
- Half of available RAM, capped at 31GB. Above 31GB, JVM can't use compressed oops and performance degrades. Below 50% of RAM, you're wasting memory that the OS filesystem cache needs.
-
Set
-Xmsand-Xmxto the same value. Avoids heap resizing pauses. - Leave the rest of RAM for the OS filesystem cache. Elasticsearch is fast because Lucene relies heavily on OS-level page cache. Starve it and search is 10x slower.
YAMLCopy
plaintext
/etc/elasticsearch/jvm.options.d/heap.options
-Xms16g
-Xmx16g
markdown
For a 64GB box: 30GB heap (just under 31GB), 34GB for filesystem cache. For a 32GB box: 16GB heap, 16GB cache. For a 16GB box: 8GB heap, 8GB cache-barely enough for production.
Other tuning:
- Shard count: aim for 30-50GB per shard. Reindex if you got it wrong.
-
refresh_interval: 1s default is for near-real-time. For logs, 5-30s is fine and reduces indexing pressure. -
number_of_replicas: 1 for HA. 0 if you're trying to maximize write throughput on a single-node dev cluster. Never 0 in prod. -
Force-merge old indices:
POST logs-2024.10/_forcemerge?max_num_segments=1. Reduces segment count, speeds up search, saves disk. Run after an index is no longer being written to. -
Disable
_sourcefor fields you don't need: tradeoff-you can't reindex. Usually not worth it. -
Use
_field_namesand doc_values wisely: most fields have doc_values enabled by default; disabling saves disk but breaks aggregations.
Hot-Warm-Cold Architecture
For clusters with significant data, tier your nodes:
- Hot nodes: SSD, fast CPU, 64GB+ RAM. Hold current day's indices. Heavy write load.
- Warm nodes: HDD or slower SSD, less RAM. Hold last 30 days. Read-mostly.
- Cold nodes: Cheap storage, minimal RAM. Hold 30-90 days. Slow queries OK.
- Frozen tier (Elastic 7.12+): searchable snapshots in object storage. Costs pennies per GB. Slow queries but data is preserved.
ILM moves indices through these tiers automatically. Configure node attributes:
YAMLCopy
conf
elasticsearch.yml on hot node
node.roles: [data_hot]
node.attr.data: hot
On warm node
node.roles: [data_warm]
node.attr.data: warm
On cold node
node.roles: [data_cold]
plaintext
ILM allocate action moves shards to the right tier:
JSONCopy
json
"warm": {
"min_age": "7d",
"actions": {
"allocate": {
"include": { "data": "warm" }
},
"shrink": { "number_of_shards": 1 },
"forcemerge": { "max_num_segments": 1 }
}
}
markdown
Production Considerations
Scaling
- Add data nodes when disk usage crosses 70% or CPU sustains >70%.
- Shard count per node: keep under 20 shards per GB of heap. 30GB heap = 600 shards max. Beyond that, cluster state management becomes slow.
- For high write throughput: increase
number_of_shards(parallelism), userefresh_interval: 30s, batch index requests (bulk API).
Performance
- Use the
_bulkAPI for indexing. One bulk request of 1000 docs is 100x faster than 1000 single-doc index requests. - Tune batch size: 5-15MB per bulk request is the sweet spot.
- Use
op_type: createto skip version checks when you know documents are new. - Disable
_allfield (removed in 7.x but worth knowing). Usecopy_tofor specific combined fields.
Caching
- Elasticsearch has query cache, request cache, and shard request cache. All on by default. Don't disable.
- For repeated dashboards, the request cache returns the same result without re-executing the query.
- Cache is invalidated on index refresh. Raising
refresh_intervalincreases cache hit rate.
Security
- Enable security on day one. Elastic 8.x enables it by default. Don't disable.
- TLS on transport and HTTP. Use the elastic-certificates utility to generate certs.
-
Role-based access control. Don't use the
elasticsuperuser for apps. Create alogstash_writerrole with index-only permissions onlogs-*indices. Create akibana_readerrole for analysts. - API keys for app auth. Apps ship logs with an API key scoped to a specific role.
Monitoring
- Use Elastic Stack Monitoring (built-in, free). Ship metrics from your production cluster to a separate monitoring cluster.
- Watch:
cluster_status(yellow is OK during node failure; red means data is missing),jvm_heap_usage_percent(alert >85%),disk_usage_percent(alert >80%),search_latency(alert p99 >1s),indexing_latency(alert if sustained spike).
Logging
- Elasticsearch logs to
/usr/share/elasticsearch/logs/. Tailelasticsearch.logfor cluster events,elasticsearch_index_search_slowlog.jsonfor slow queries,elasticsearch_index_indexing_slowlog.jsonfor slow indexing. - Set slow log thresholds to catch expensive queries:
JSONCopy
json
PUT logs-*/_settings
{
"index.search.slowlog.threshold.query.warn": "2s",
"index.search.slowlog.threshold.query.info": "500ms",
"index.indexing.slowlog.threshold.index.warn": "1s"
}
Deployment
- Three master nodes minimum. One master = single point of failure.
- Use managed Elastic Cloud if you don't want to operate the cluster. It's not cheap but the ops cost of self-hosted ELK is significant.
- For self-hosted, use the Elastic Helm charts on Kubernetes. They handle rolling restarts, pod anti-affinity, and PVC management.
Common Mistakes
Mistake 1: Too many shards. 1000 small indices, each with 5 shards = 5000 shards. Cluster state becomes bloated, master node CPU spikes, recovery after node failure takes forever. Fix: shard size 30-50GB, consolidate small indices.
Mistake 2: Dynamic mapping on high-cardinality fields. A field like session_id with 10M unique values, mapped as text, blows up the term dictionary. Fix: dynamic: false or dynamic: strict, explicit keyword mapping for high-cardinality fields.
Mistake 3: No ILM policy. Disk fills up, cluster goes read-only, panic. Fix: ILM from day one, with delete phase.
Mistake 4: Running Logstash when you don't need it. Adds latency, CPU, and an extra failure point. Fix: structured logging at the source, Filebeat directly to ES.
Mistake 5: Heap > 31GB. Compressed oops disabled, performance degrades. Fix: cap at 30-31GB, give the rest to filesystem cache.
Mistake 6: One giant index for everything. A 1TB index is unrecoverable in any reasonable time. Fix: daily or weekly indices with rollover.
Mistake 7: Replica count 0 in production. One node failure = data loss. Fix: minimum 1 replica.
Mistake 8: Disabling security because it's annoying. Elasticsearch with no auth on the public internet gets ransomwared within hours. Fix: security on, TLS on, RBAC enforced.
Mistake 9: Using match_all queries in dashboards. Hits every shard, every document. Fix: time filter always, narrow queries.
Mistake 10: Not monitoring the monitoring tool. ELK goes down, you have no logs, you have no idea why. Fix: separate monitoring cluster, or external alerting on ELK health.
Troubleshooting Real Production Issues
Symptom: Cluster status red.
Some primary shards are unassigned. Usually because a data node is down. Check _cat/nodes?v and _cat/shards?v&h=index,shard,prirep,state,unassigned.reason. If a node is down, bring it back-shards will recover. If you've lost a node permanently, you may need to manually reassign replicas as primaries (data loss accepted).
Symptom: Cluster status yellow.
All primaries are assigned, but some replicas aren't. Usually normal during node restart or initial index creation. Should resolve in minutes. If it persists, you don't have enough data nodes to satisfy replica allocation.
Symptom: Indexing latency spikes.
Check _cat/thread_pool/write?v-is the write queue backing up? If yes, your cluster can't keep up. Options: add data nodes, reduce refresh_interval, batch more aggressively, reduce replicas (temporarily).
Symptom: Search latency spikes.
Check _cat/thread_pool/search?v. Run _cluster/pending_tasks to see if master is overloaded. Look at slow logs to find expensive queries. Often one bad query (e.g., match_all over 30 days) is killing the cluster.
Symptom: Heap usage at 90%+.
Out of memory coming. Check _nodes/stats/jvm-what's eating heap? Usually it's fielddata (unbounded by default for text fields) or too many shards. Disable fielddata on text fields. Reduce shard count.
Symptom: Disk filling up.
ILM not deleting. Check _ilm/explain/logs-write-is the policy attached? Are phases advancing? Sometimes ILM gets stuck; POST logs-*/_ilm/retry unsticks it.
Symptom: Kibana shows "Cannot reach Elasticsearch."
Check elasticsearch.log-is ES running? Check TLS-did the cert expire? Check kibana_system user password-did it get reset?
Symptom: Logstash pipeline is slow.
Look at Logstash's own metrics API: http://logstash:9600/_node/stats/pipelines. Check events_in, events_filtered, events_out. If events_in >> events_out, the filter is the bottleneck. Profile grok patterns. Consider switching to structured logging at source to skip grok entirely.
Symptom: Filebeat not shipping logs.
Check Filebeat's log. Verify the file path. Verify permissions (Filebeat needs read access to log files). Check the output config-can it reach Logstash/ES? Run filebeat test output.
Cost Considerations, Alternatives, Comparison
ELK is expensive to operate. Self-hosted, a 3-node cluster with 64GB RAM each costs roughly:
| Resource | Monthly cost (AWS, on-demand) |
|---|---|
| 3x r5.2xlarge (64GB RAM, 8 vCPU) | ~$1,500 |
| 3x 1TB gp3 EBS | ~$300 |
| Data transfer (variable) | ~$50-500 |
| Operations time (4-8 hours/month) | ~$1,000-2,000 equiv |
| Total | ~$2,500-4,000/month |
For comparison:
| Option | Cost model | Sweet spot |
|---|---|---|
| Self-hosted ELK | EC2 + ops time | High-volume, search-heavy, willing to operate |
| Elastic Cloud | $95+/node/month + storage | "I want ELK but not the ops" |
| AWS OpenSearch Service | $0.045/hour per instance + storage | AWS-native, slightly cheaper than Elastic Cloud |
| Grafana Loki | Free OSS / ~$0.10/GB ingest for Cloud | Cheapest; "Prometheus for logs" |
| Datadog Logs | $1.27/GB ingest + retention | One bill, zero ops |
| Splunk | $50-100+/GB ingest | Enterprise SIEM |
For most teams under 100GB/day of logs, Loki is significantly cheaper and the better choice if you don't need full-text search. For teams doing security analysis (SIEM), complex search across PB of logs, or already committed to ELK ecosystem, ELK is right. For teams that just want logs to show up next to metrics in Grafana without a separate cluster, Loki wins.
The cost trap in ELK: storage grows linearly with ingest, and old data rarely gets queried but you keep it because "we might need it." Set retention aggressively (30-90 days for most logs), use frozen tier or S3 archival for longer retention, and accept that some logs just don't matter.
Real-World Use Cases
Application log centralization. 50 microservices, each writing JSON logs to stdout. Filebeat on each host ships to Elasticsearch (no Logstash). Kibana dashboards per service. Request ID correlation across services. 30-day retention. ~50GB/day, 1.5TB total.
Nginx access log analysis. Filebeat tails /var/log/nginx/access.log, Logstash parses with grok, enriches with GeoIP and UserAgent. Kibana dashboard shows top URLs, status code distribution, traffic by country, slow requests. 90-day retention, 200GB/day, hot-warm-cold tiered.
Security information and event management (SIEM). Elastic Security (built into Kibana) ingests system logs, network flow data, authentication events. Pre-built detection rules for common attacks. Alerts on suspicious patterns. This is what Splunk does, at a fraction of the cost if you're already running ELK.
Audit log compliance. All user actions logged to a separate audit-* index pattern. WORM-style (write-once-read-many) enforcement via index blocks. 7-year retention via searchable snapshots to S3. Lower write volume but strict immutability requirements.
E-commerce search. Not logs-actual product search. Elasticsearch as the primary search engine for a product catalog. Per-field analyzers, faceted search, relevance tuning. This is the original use case for Elasticsearch and still one of the best.
Real-time log alerting. Lambda function logs → CloudWatch Logs subscription → Firehose → Elasticsearch. Alert on error rate spike via Kibana Alerting. PagerDuty integration. End-to-end latency under 2 minutes.
Log-based metrics. Use Elasticsearch transforms to derive metrics from logs (e.g., requests-per-minute by endpoint). Materialize to a metrics-* index, queryable in Kibana. Replaces Prometheus for some teams that want one tool.
Conclusion
ELK is a powerful stack and a powerful way to waste money if you don't understand it. The patterns in this article-explicit mappings, dynamic mapping off, ILM from day one, structured logging at the source, shard sizing at 30-50GB, heap at 50% of RAM capped at 31GB-are the ones that keep clusters alive past month three. Get these right and ELK becomes what it should be: the central nervous system of your observability stack.
The biggest mistake teams make with ELK is treating it as "logs go in, magic comes out." Logs go in, but the magic is in the engineering: the index templates, the ILM policies, the cardinality discipline, the structured logging at the source. Skip the engineering and you get a slow, expensive, unreliable cluster. Do the engineering and ELK is genuinely the best-in-class tool for log search and analysis.
If after all this you decide ELK is too much, that's a valid conclusion. Switch to Loki. It's simpler, cheaper, and probably good enough. But if you need full-text search, complex queries, or SIEM capabilities, ELK remains the right tool-and now you know how to run it without regretting the choice.
Originally published on Mango Developer.
Top comments (0)