ELK Stack Architecture: Elasticsearch, Logstash and Kibana at Scale

When your central logging system handles 50 GB a day, almost any architecture will work. When it handles 2 TB a day across 300 services and three regions, every shortcut you took comes back to haunt you. I have run the ELK stack through both extremes — as a single Elasticsearch node with a Logstash container tailing Docker JSON files, and as a 30-data-node cluster ingesting 80,000 events per second. The core components never changed: Elasticsearch for storage and search, Logstash for transformation, and Kibana for visualization. What changes at scale is how you decouple them, protect them from each other, and give each layer room to fail without taking the whole pipeline down. This article is the architecture I wish someone had handed me before my first large-scale rollout.

Why ELK Components Decouple Differently Under Heavy Log Volume

In my experience, the biggest misunderstanding about the elk stack is treating it as a single system. It is three distinct systems with different scaling characteristics and failure domains that happen to work well together. Elasticsearch is stateful, memory-intensive, and sensitive to heap pressure and disk I/O. Logstash is stateless but CPU-intensive, especially when you run Grok patterns or Ruby filters. Kibana is mostly stateless and light, but it becomes your bottleneck if you let every developer run unoptimized aggregations against cold data. If you co-locate them on the same hosts or let them share resource pools, a surge in ingest will starve search, and a heavy dashboard will starve ingest.

At scale, I always separate ingest from storage and search with a durable buffer. Direct Beats-to-Logstash-to-Elasticsearch works fine for moderate volume, but it provides no backpressure handling. If Elasticsearch pauses for a rolling upgrade or a merge throttle, Logstash blocks, and then your application hosts block. I've found that inserting Kafka or Redis between your shippers and Logstash is the cheapest insurance you can buy. Filebeat and other Beats are extremely lightweight shippers — their job is to tail files and forward with at-least-once delivery, not to parse. Let them do that and nothing more. Logstash should then consume from the buffer at its own pace, scale horizontally when the queue depth grows, and retry without data loss.

The Ingest Path I Use in Production

For most clusters I build now, the path looks like this: Filebeat / Fluent Bit on the host or as a DaemonSet -> Kafka topic (3-5 partitions per Logstash consumer group) -> Logstash indexed pipeline -> Elasticsearch data nodes. This lets me scale each tier independently. If you are just starting, a simpler Redis buffer is acceptable, but Kafka gives you replay, which has saved me more than once when a bad Grok pattern corrupted a day of parsing and we needed to reprocess from the raw topic. For context on shaping your payload before it ever hits this pipeline, see Structured Logging: JSON Format, Context Fields and Log Aggregation — getting your application to emit structured JSON upfront removes half the work Logstash would otherwise have to do.

Component Primary Responsibility Scaling Unit When It Becomes the Bottleneck
Beats (Filebeat, Metricbeat) Lightweight shipping, backpressure-aware tailing DaemonSet / host agent Rarely; usually when multiline or JSON decoding is pushed to the Beat instead of Logstash
Kafka / Buffer Layer Durable queue, replay, decoupling Broker count and partitions Undersized partitions or retention too low to survive a downstream outage
Logstash Parsing, enrichment, filtering Pipeline workers and horizontal instances Expensive Grok, DNS lookups, or Ruby filters without persistent queues enabled
Elasticsearch Indexing, storage, search and aggregation Data nodes, shards, and hot-warm tiers Heap pressure, too many shards, or slow disks during merges
Kibana Visualization, alerting, access control Instances behind a load balancer Unbounded time ranges or high-cardinality aggregations over cold indices

Sizing Elasticsearch Nodes: Roles, Shards and Heap Boundaries at Scale

Elasticsearch is where most ELK projects fail at scale, and almost always for the same reasons: too many small shards, heap set incorrectly, or all nodes configured as master-eligible data nodes. Starting with version 7+, dedicated node roles are not optional at scale — they are a requirement. In a cluster that will exceed 10 nodes or 5 TB of retained data, I separate roles explicitly. Three dedicated master nodes (small, stable, 2-4 GB heap, no data), a set of hot data nodes for recent indices, and optionally warm nodes for older data. I also run at least two dedicated ingest nodes if I use ingest pipelines, or two coordinating-only nodes to front Kibana queries so that data nodes are not interrupted by aggregation coordination.

Master, Data and Coordinating Role Separation

Master nodes need stable CPU and low GC pauses, not large heap. Data nodes need fast disks and the right heap-to-RAM ratio. I've found that giving any single JVM more than 31 GB of heap is counterproductive because you lose compressed ordinary object pointers, and the garbage collector pauses become brutal. The rule I follow is 50% of RAM for heap, capped at 26-30 GB, and never let the OS have less than 50% for filesystem cache. That filesystem cache is what actually serves Lucene segments. If you give Elasticsearch 64 GB RAM and allocate 31 GB+ heap, you starve the page cache and query performance collapses even though indexing looks fine. For deployments on Kubernetes, the Kubernetes Documentation on StatefulSets is the right reference for how to run these roles with stable identities and persistent volumes.

Shard Count and Heap Pressure Are Related

Every shard is a Lucene index with its own segments, file handles, and heap overhead. In my experience, the most common production outage is not disk full, but cluster state bloat from 10,000+ shards. Each shard costs roughly 20-50 MB of heap on the master just to track cluster state, plus additional overhead on data nodes. A good target is to keep shards between 10 GB and 50 GB in size. For time-series logs, that usually means one primary shard per daily index for volumes under 50 GB/day, scaled to more primaries only when a single shard cannot keep up with indexing throughput. Avoid the default of one replica for system indices and one replica for log indices at a minimum — but don't create five primaries because you think more primaries equals more parallelism. It equals more overhead unless your ingest truly saturates a single shard's indexing thread pool.

# /etc/elasticsearch/elasticsearch.yml - example hot data node
cluster.name: logging-prod
node.name: es-hot-03
node.roles: [ data_hot, data_content ]
path.data: /data/hot1,/data/hot2
path.logs: /var/log/elasticsearch
bootstrap.memory_lock: true
network.host: _site_
discovery.seed_hosts: ["es-master-01:9300","es-master-02:9300","es-master-03:9300"]
cluster.initial_master_nodes: ["es-master-01","es-master-02","es-master-03"]
xpack.security.enabled: true
xpack.monitoring.collection.enabled: true
# Heap is set via jvm.options, not here: -Xms30g -Xmx30g
# Ensure vm.max_map_count >= 262144 and no swap

Disk choice matters more than people expect. I have moved clusters from 8 TB HDD warm nodes to 4 TB NVMe hot nodes and seen indexing latency drop by 60% and query latency by half. Elasticsearch merges segments constantly. On slow disks, merges queue up, indexing thread pools reject, and Logstash starts seeing 429s. Monitor indexing_pressure and thread_pool.write.rejected. If those counters climb, you do not need more Logstash workers — you need faster disks or fewer shards competing for I/O on the same node.

Building Resilient Logstash Pipelines That Don't Lose Data

Logstash gets a reputation for being slow and memory-hungry, but in my experience that reputation comes from misconfigured pipelines, not from Logstash itself. The defaults are conservative for a laptop, not for a production pipeline processing 30,000 events per second. The three settings I tune first on every deployment are pipeline workers, batch size, and persistent queues. Without persistent queues, a Logstash restart drops whatever is in memory. With them enabled and properly sized on fast local disk, Logstash can survive an Elasticsearch outage of 30-60 minutes and replay without loss.

I also split pipelines by responsibility. A single pipeline that does syslog parsing, JSON decoding, GeoIP, and Elasticsearch output becomes impossible to reason about and impossible to scale selectively. Instead, I run multiple pipelines in pipelines.yml — for example, one pipeline for pre-processing and routing, one for application JSON logs, and one for noisy system logs with a lower worker count. This isolates a bad regex in one pipeline from blocking the others. And I avoid Grok wherever a dissect or json filter will do. Grok is powerful but expensive; a single unanchored Grok pattern with excessive backtracking can drive CPU to 100% and stall the entire pipeline.

# /etc/logstash/pipelines.yml
- pipeline.id: beats-kafka-input
  queue.type: persisted
  queue.max_bytes: 4gb
  path.queue: /var/lib/logstash/queue-input
  config.string: |
    input { kafka { bootstrap_servers => "kafka-01:9092,kafka-02:9092" topics => ["logs-raw"] group_id => "logstash-prod" consumer_threads => 4 } }
    output { pipeline { send_to => [app_logs, infra_logs] } }

- pipeline.id: app_logs
  queue.type: persisted
  pipeline.workers: 8
  pipeline.batch.size: 250
  pipeline.batch.delay: 50
  config.string: |
    input { pipeline { address => app_logs } }
    filter {
      json { source => "message" tag_on_failure => ["_jsonparsefailure"] }
      if "_jsonparsefailure" in [tags] {
        dissect { mapping => { "message" => "%{timestamp} %{level} %{msg}" } }
      }
      mutate { remove_field => ["beat","agent","ecs"] }
      date { match => ["timestamp", "ISO8601"] target => "@timestamp" }
    }
    output { elasticsearch { hosts => ["https://es-hot-01:9200"] index => "app-logs-%{+YYYY.MM.dd}" ilm_enabled => false } }

- pipeline.id: infra_logs
  queue.type: persisted
  pipeline.workers: 2
  config.string: |
    input { pipeline { address => infra_logs } }
    filter { dissect { mapping => { "message" => "%{ts} %{host} %{program}[%{pid}]: %{logmsg}" } } }
    output { elasticsearch { hosts => ["https://es-hot-01:9200"] index => "infra-logs-%{+YYYY.MM.dd}" } }

Monitoring Logstash as a Production Service

Treat Logstash like any other application: expose its monitoring API and alert on it. I scrape Logstash metrics with Metricbeat or Prometheus exporter and watch three signals: pipeline throughput (events per second), queue depth, and dead letter queue count. A growing persistent queue depth that never drains means Elasticsearch cannot keep up, not that Logstash is slow. A rising DLQ count means your Elasticsearch mapping is rejecting documents — typically because a field flipped from integer to string or a date parse failed. Pair this visibility with Prometheus and Alertmanager: Complete Setup for Production Monitoring so you get paged when queue depth exceeds your replay window, not when the disk is already full.

One more practical detail: run Logstash with LS_JAVA_OPTS="-Xms4g -Xmx4g" and keep pipeline workers at roughly 1x to 1.5x CPU cores. Over-provisioning workers on a 4-core instance creates context switching without more throughput. I have benchmarked the same pipeline at 4, 8, and 16 workers on an 8-core host — throughput peaked at 8 workers, and latency degraded at 16.

Index Lifecycle Management and Hot-Warm-Cold Data Tiering at Scale

Without lifecycle management, your hot Elasticsearch nodes will fill up, your heap will grow, and you will be deleting indices manually at 2 AM. Index Lifecycle Management (ILM) is not optional once you retain more than seven days of logs. The pattern I use everywhere is rollover based on size and age, not just daily indices. A daily index works when your volume is predictable, but when a service suddenly logs 10x due to a debug flag left on, a daily index for that day becomes a 300 GB shard that will never merge efficiently. Rollover at 40-50 GB or 1 day, whichever comes first, keeps shards in the sweet spot regardless of spikes.

The hot-warm-cold model maps directly to hardware and cost. Hot nodes are fast NVMe, warm nodes are larger, cheaper SSD or spinning disk, and cold or frozen tiers can be searchable snapshots on S3. In my experience, 90% of Kibana queries hit the last 3 days of data. Keeping 7 days on hot and 30 days on warm, then moving to searchable snapshots, reduces hot storage cost by 60% while keeping dashboards snappy. For compliance and retention planning beyond performance, I align ILM phases with the policy described in Log Rotation and Retention: Storage Optimization and Compliance Requirements so that engineering, security, and legal agree on how long we keep what.

PUT _ilm/policy/logs-app-policy
{
  "policy": {
    "phases": {
      "hot": {
        "actions": {
          "rollover": { "max_size": "45gb", "max_age": "1d" },
          "set_priority": { "priority": 100 }
        }
      },
      "warm": {
        "min_age": "7d",
        "actions": {
          "shrink": { "number_of_shards": 1 },
          "forcemerge": { "max_num_segments": 1 },
          "allocate": { "require": { "data": "warm" } },
          "set_priority": { "priority": 50 }
        }
      },
      "cold": {
        "min_age": "30d",
        "actions": {
          "searchable_snapshot": { "snapshot_repository": "s3-snapshots" },
          "allocate": { "require": { "data": "cold" } },
          "set_priority": { "priority": 0 }
        }
      },
      "delete": {
        "min_age": "90d",
        "actions": { "delete": {} }
      }
    }
  }
}

PUT _index_template/app-logs
{
  "index_patterns": ["app-logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 1,
      "number_of_replicas": 1,
      "index.lifecycle.name": "logs-app-policy",
      "index.lifecycle.rollover_alias": "app-logs"
    }
  }
}

Mappings and Field Explosion

The other ILM-adjacent problem is mapping explosion. Elasticsearch will happily create a new field for every distinct JSON key it sees if dynamic mapping is left on. I have seen a single misbehaving service that logged HTTP headers as top-level fields create 4,000 fields in one index and push the cluster state over 50 MB. That slows down every cluster state update. My default is to disable dynamic mapping for application logs or set dynamic: strict and explicitly define allowed fields, with dynamic_templates to map unknown strings as keyword with ignore_above: 256. Flattened or object fields with index: false are useful for high-cardinality metadata you need to store but never aggregate on.

Securing and Tuning Kibana for Multi-Team Observability

Kibana is the part your developers actually touch, so its usability determines whether the ELK stack is adopted or bypassed. Two things matter most here: performance and access control. On performance, I tune Kibana before I blame Elasticsearch. Common fixes include setting elasticsearch.requestTimeout and elasticsearch.shardTimeout sensibly, enabling query caching, and educating teams to avoid searching * over 90 days with a wildcard leading query. In Kibana spaces, I create a separate space per team with its own index patterns — app-logs-team-a-* — so that a team cannot accidentally query cold indices they do not need, which protects the cluster from expensive cross-tier searches.

Security at scale means integrating with your identity provider and using document- and field-level security. X-Pack security with RBAC lets you give team A read access only to indices matching app-logs-team-a-* and hide fields like user.pii entirely. I also put Kibana behind an authenticating reverse proxy and enable audit logging. I've found that anonymous Kibana access inevitably leads to someone leaving a dashboard auto-refreshing every 5 seconds over a 30-day range, which generates a load equivalent to a sustained DDoS from inside your own network. Saved objects, alerts, and dashboard permissions should be versioned and applied via the Kibana Saved Objects API, not clicked into place manually.

Practical Kibana Hardening I Apply Every Time

First, run at least two Kibana instances behind a load balancer with health checks on /api/status. Second, set xpack.encryptedSavedObjects.encryptionKey and store it in a secret manager — without it, alert rules and connectors will not survive restarts. Third, limit the maximum buckets for aggregations. A single visualization that tries to aggregate 100,000 terms will OOM Kibana and put pressure on Elasticsearch coordinating nodes. I set search.max_buckets: 10000 in Elasticsearch and data.search.aggs.shardDelay thresholds in Kibana to fail fast rather than hang.

Failure Modes I Watch For When ELK Runs on Kubernetes

Many teams now run ELK on Kubernetes, which adds orchestration benefits but also new failure modes. Elasticsearch is a StatefulSet, not a Deployment — it needs stable network identity and persistent volumes that survive rescheduling. Logstash and Kibana can be Deployments, but they still need proper resource limits. The Kubernetes Documentation on resource management is essential here; I set explicit requests and limits for heap and non-heap memory separately, because the JVM will happily exceed a container limit if you only set heap and ignore direct memory and file handles.

The Docker logging layer is another hidden constraint. If your nodes use the json-file logging driver, unmanaged log files will fill the node disk before Elasticsearch does. I always configure Docker's json-file options with max-size and max-file or switch to journald for systemd hosts. The Docker Documentation covers the per-driver options — review it before you deploy Filebeat, because Filebeat tracking offsets on a log file that Docker rotated away will cause duplicate or missing events. In Kubernetes, I prefer reading from /var/log/containers with Filebeat's add_kubernetes_metadata processor so that every log line is enriched with pod, namespace, and labels at the edge, which lets Logstash avoid expensive Kubernetes API lookups.

Finally, plan for upgrades and chaos. Elasticsearch rolling upgrades require shard allocation awareness and cluster.routing.allocation.enable: primaries during the restart, or you will trigger a massive rebalance that saturates the network. Logstash upgrades should drain the persistent queue first. And Kibana upgrades should be blue-green if you have alert rules — a half-upgraded Kibana instance can execute alerts twice. I schedule a quarterly game day where we kill a hot data node, fill the Kafka buffer, and verify that dashboards still render from warm nodes and that no logs are lost end-to-end. If that test does not pass, the architecture is not truly at scale yet.

Frequently Asked Questions

How many Elasticsearch shards do I need for a high-volume logging cluster?

Start with one primary shard per index and use ILM rollover at 40-50 GB rather than pre-creating many primaries. Aim for shard sizes between 10 GB and 50 GB. On a cluster retaining 30 days at 1 TB per day, that typically results in 600-900 shards total including replicas, which keeps master heap under pressure. Only increase primaries when a single shard cannot sustain your indexing throughput — usually above 15,000-20,000 docs per second per shard depending on document size and mapping complexity.

Should I use Logstash or run Elasticsearch ingest pipelines instead?

Use both for what they are good at. I use Logstash when I need branching logic, persistent queues, buffering against Elasticsearch outages, or heavy transformations like GeoIP and multiline aggregation. I use Elasticsearch ingest pipelines for lightweight, index-time enrichment that benefits from running close to the data node, such as adding a timestamp or removing a field. In my experience, pushing all parsing to ingest pipelines makes Elasticsearch data nodes CPU-bound during peak ingest, so keep expensive Grok and Ruby processing in Logstash.

How do I prevent Kibana from slowing down Elasticsearch?

Isolate workloads with coordinating-only nodes for Kibana, use Kibana Spaces with narrow index patterns, and enforce time-range limits via proxy or RBAC. Set search timeouts and max buckets, encourage users to filter on indexed keyword fields instead of full-text wildcards, and move older data to warm or searchable snapshots so that broad queries do not hit hot nodes. Monitoring Kibana's own request latency and Elasticsearch's search thread pool rejections will tell you quickly when a dashboard is too expensive.

Can I run the entire ELK stack on Kubernetes without a separate Kafka buffer?

Yes for moderate volumes, but I do not recommend it beyond roughly 10,000 events per second or when you require guaranteed replay. On Kubernetes, you can run Filebeat as a DaemonSet shipping directly to Logstash, but without a durable buffer a rolling restart of Elasticsearch or Logstash will cause backpressure and potential loss if persistent queues fill. If you must avoid Kafka, at least enable Logstash persistent queues on fast persistent volumes and size them to cover your longest expected Elasticsearch maintenance window.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation