Centralized Logging with Fluent Bit and Fluentd: Collection, Parsing and Routing

Centralized logging sounds simple until you run it at scale across a few hundred nodes. You start with tailing a few log files, then you inherit JSON logs from fifteen microservices, multiline Java stack traces that refuse to parse, and a compliance team asking why container logs disappeared during a node rollover. After running Fluent Bit and Fluentd together in production for the last three years — across both Kubernetes and mixed VM workloads — I've settled on a split architecture that keeps collection lightweight and aggregation resilient. Fluent Bit handles the edge, Fluentd handles the heavy lifting in the middle, and everything in between is about careful parsing, tagging, and buffered routing. This article walks through the exact patterns I use to build that pipeline without losing logs or drowning your backends.

Why Fluent Bit at the Edge and Fluentd at the Core Still Wins

In my experience, the most common mistake teams make is choosing one or the other for every role. Fluentd is written in Ruby with a rich plugin ecosystem of over 1000 plugins, but its memory footprint of 40-80 MB per instance adds up fast when you run it as a DaemonSet on 200 nodes. Fluent Bit, written in C, idles around 5-15 MB and uses a fraction of the CPU for tailing and basic filtering. That difference matters when you are competing for resources with application pods.

I deploy Fluent Bit everywhere logs are generated and Fluentd only where logs are aggregated. This is not just about resource efficiency. Fluent Bit's architecture is designed for high-throughput, low-latency collection with limited transformation. Fluentd's strength is complex routing, buffering to disk, and reliable delivery with retries and acknowledgments. If you push complex Ruby filters or extensive buffering logic to the edge, you increase the blast radius of a bad config. Keep the edge dumb, fast, and stateless; keep the aggregator smart, persistent, and stateful.

Compared to running Logstash on every node — a pattern I moved away from in 2021 — the Fluent Bit + Fluentd combination is far more stable during log bursts. Logstash's JVM startup time and heap requirements made node autoscaling painful. The alternative of shipping directly from Fluent Bit to Elasticsearch or S3 can work for small clusters, but you lose the ability to fan-out, enrich, and dead-letter without deploying that logic to every node. The two-tier model gives you a single choke point to control.

If you are evaluating the broader ecosystem, it helps to understand how this pipeline fits versus a full ELK Stack Architecture: Elasticsearch, Logstash and Kibana at Scale. I often run Fluent Bit/Fluentd in front of Elasticsearch precisely to replace Logstash at the edge while keeping Kibana for search.

When to Break the Rule

There are two cases where I run Fluentd at the edge. First, when I need a plugin that only exists for Fluentd, such as certain legacy enterprise SIEM outputs or custom Ruby parsers for proprietary binary logs. Second, on dedicated Windows nodes where Fluent Bit's Windows support has historically lagged. Otherwise, Fluent Bit is the default DaemonSet.

Mapping Log Flow Topology: DaemonSets, Sidecars, and Forward Aggregation

The physical topology determines your failure modes. For Kubernetes, the standard is a Fluent Bit DaemonSet that mounts /var/log and /var/lib/docker/containers or /var/log/pods depending on your container runtime. As described in the Kubernetes Documentation on logging architecture, Kubernetes itself does not provide a native log aggregation layer, so you must choose how node-level logs are collected. I avoid sidecar log shippers unless the application writes logs to a file inside the container that is not exposed via stdout. In my experience, sidecars double your shipper count, complicate resource limits, and make upgrades tedious.

My canonical production topology looks like this: Fluent Bit DaemonSet -> Fluentd StatefulSet (3 replicas behind a headless Service) -> Multiple backends (OpenSearch, S3 for cold storage, Loki). Fluent Bit uses the forward output to send to Fluentd over TLS. Fluentd exposes the forward input with shared keys and TLS mutual auth. This decouples the edge from the destination. If OpenSearch goes down for maintenance, Fluent Bit never knows — it keeps forwarding to Fluentd, and Fluentd buffers to disk.

For VMs outside Kubernetes, I install Fluent Bit as a systemd service with the same configuration management (Ansible or Terraform) I use for the DaemonSet ConfigMap. This keeps parsing logic identical. I manage both via the Terraform Documentation using the kubernetes_config_map resource and cloud-init templates so the config does not drift. One detail I learned the hard way: always set a dedicated node pool or taint for your Fluentd aggregators. If you schedule them on general worker nodes, a noisy neighbor can starve the buffer flush and cause backpressure to propagate to Fluent Bit.

Network and Security Baseline

Fluent Bit to Fluentd traffic should be TLS-encrypted and authenticated. I generate a shared key per environment and rotate it via Sealed Secrets. I also set Require_ack_response true on the forward output so Fluent Bit knows if Fluentd is overwhelmed. Without ack, you risk silent drops during rollouts. For cross-region forwarding, I place a local Fluentd aggregator in each region and let the aggregators forward to a central S3 bucket rather than having every edge agent cross the WAN.

Collection to Parsing: Turning Raw Text into Structured Events in Fluent Bit

Collection is where logs are won or lost. The two inputs you will use 90% of the time are tail and systemd. For Kubernetes, the tail input with DB and DB.Sync is critical. Without a persistent DB file, Fluent Bit will re-read entire files or skip them after a restart. I store the DB on a hostPath volume at /var/log/flb-storage and mount it into the DaemonSet.

[INPUT]
    Name              tail
    Path              /var/log/containers/*.log
    DB                /var/log/flb-storage/flb_kube.db
    DB.Sync           Full
    Tag               kube.*
    Parser            docker
    Refresh_Interval  5
    Skip_Long_Lines   On
    Mem_Buf_Limit     10MB
    Storage.Type      filesystem

[FILTER]
    Name              kubernetes
    Match             kube.*
    Kube_URL          https://kubernetes.default.svc:443
    Kube_Tag_Prefix   kube.var.log.containers.
    Merge_Log         On
    Merge_Log_Key     log_processed
    Keep_Log          Off
    K8S-Logging.Parser On
    K8S-Logging.Exclude On
    Annotations       Off

That Storage.Type filesystem line is non-negotiable in production. In-memory buffering looks fine until a Fluentd rollout takes 3 minutes and your node generates 50 MB of logs. With filesystem storage, Fluent Bit will spool to disk and retry. I've found that setting Mem_Buf_Limit per input prevents one noisy pod from OOMing the agent. Set it to 5-10 MB for tail inputs and 2 MB for systemd.

Parsing is the next bottleneck. Do not parse application JSON in Fluentd if you can do it at the edge with Fluent Bit's filter parser. It reduces load on the aggregator and keeps the tag space clean. The pattern I use is: collect raw, add Kubernetes metadata, then try to parse the log field as JSON. If parsing fails, keep the raw message.

[FILTER]
    Name              parser
    Match             kube.*
    Key_Name          log
    Parser            json
    Reserve_Data      On
    Preserve_Key      On

[PARSER]
    Name              json
    Format            json
    Time_Key          time
    Time_Format       %Y-%m-%dT%H:%M:%S.%L
    Time_Keep         On

[PARSER]
    Name              multiline_java
    Format            regex
    Regex             /^(?

For Structured Logging: JSON Format, Context Fields and Log Aggregation, this parser approach is essential. If your applications still emit plain text, push them to emit JSON with consistent fields: timestamp, level, msg, trace_id, service. In my experience, trying to regex-parse unstructured logs at scale is a losing battle. I enforce JSON at the application code review stage and use Fluent Bit's modify filter to add default fields like cluster and environment if developers forget.

Handling Multiline Correctly

Java, Python tracebacks, and Go stack traces will break your pipeline if you ingest them line-by-line. Fluent Bit's multiline.parser with Docker mode or CRI mode must match your runtime. For containerd, use cri, for Docker use docker. I define a custom multiline parser for Java and apply it via annotation fluentbit.io/parser: multiline_java on pods that need it, then enable autoMultiline off and control it explicitly. Automatic multiline detection is convenient but it misidentifies JSON logs that contain newlines.

The Fluentd Aggregation Tier: Buffering, Routing, and Output Reliability

Fluentd aggregators are where reliability is engineered. Every output should have file-based buffering with explicit retry and overflow behavior. Memory-only buffers are fast until the downstream is down for 10 minutes and you lose everything in RAM. I use the @type file buffer for all production outputs, with separate buffer paths per output to avoid one slow destination blocking others.

<match kube.**>
  @type copy
  <store>
    @type elasticsearch
    host opensearch.example.internal
    port 9200
    logstash_format true
    logstash_prefix k8s-app
    <buffer tag, time>
      @type file
      path /var/log/fluentd-buffers/es.k8s-app
      timekey 1m
      timekey_wait 30s
      chunk_limit_size 8MB
      queue_limit_length 256
      flush_interval 5s
      flush_thread_count 4
      retry_forever true
      retry_max_interval 30s
      overflow_action block
    </buffer>
  </store>
  <store>
    @type s3
    s3_bucket central-logs-archive-prod
    path logs/%Y/%m/%d/
    time_slice_format %Y%m%d%H
    <buffer time>
      @type file
      path /var/log/fluentd-buffers/s3.k8s-app
      timekey 10m
      timekey_wait 5m
      chunk_limit_size 16MB
      flush_at_shutdown true
    </buffer>
  </store>
</match>

<match fluent.**>
  @type null
</match>

Note the overflow_action block — this applies backpressure to the input rather than dropping chunks. The alternative drop_oldest_chunk will silently lose data. With block, Fluent Bit will see slower acks and spool locally, which is the correct behavior. I size the buffer volumes at 50-100 GB per Fluentd pod on SSDs. On one incident where OpenSearch had a 45-minute outage, each aggregator buffered ~18 GB and drained it in 12 minutes after recovery without loss.

I run Fluentd as a StatefulSet with 3 pods, not a Deployment. StatefulSet gives stable storage and network identity, which matters for buffer files. I mount a PVC per pod and set podManagementPolicy: Parallel to avoid slow rollouts blocking log flow. Resource requests I use in production: 1 CPU, 2 Gi RAM requests, 2 CPU / 4 Gi limits, with Java heap for the Elasticsearch plugin tuned to 1g. Monitor buffer queue length via the fluentd_status_buffer_queue_length Prometheus metric — if it grows monotonically, your output is slower than input.

Capability Fluent Bit (Edge Agent) Fluentd (Aggregator)
Language / Footprint C, 5-15 MB RAM, very low CPU Ruby, 40-80 MB RAM, higher CPU with complex filters
Plugins Available ~150 core plugins, covers common inputs/outputs 1000+ plugins, extensive enterprise integrations
Buffering Filesystem spool (new) + Mem limit, at-most-once by default File buffers, retry_forever, ack, at-least-once delivery
Parsing / Filtering Fast regex, JSON, Lua; limited Ruby Full Ruby, record_transformer, complex rewrite
Ideal Role Collection on every node, lightweight parsing Central aggregation, routing, enrichment, fan-out
Throughput per Instance 100k+ events/sec with minimal filtering 20-40k events/sec with multiple outputs and buffers

Isolating Tenants and Environments with Tag Routing and Rewrite Rules

As soon as you have more than one team or environment on the same cluster, tag routing becomes security and cost control. I use a strict tag schema at the edge: kube.{namespace}.{pod}.{container} via Fluent Bit, then rewrite at the Fluentd layer into env.{prod|staging}.team.{name}.app.{service}. This lets me route based on labels without exposing raw tags to outputs.

The workhorse is record_modifier and rewrite_tag_filter. I pull namespace and labels from the Kubernetes filter metadata and create canonical fields. One pattern I rely on heavily is routing by namespace prefix: anything in payments-* goes to a PCI-compliant S3 bucket with 7-year retention, while dev-* goes to a 30-day bucket with cheaper storage.

Label-based routing also prevents noisy tenants from polluting shared indices. In OpenSearch I create isolated indices per team (k8s-payments-prod-* vs k8s-frontend-prod-*) and use Fluentd's elasticsearch_dynamic index naming from record fields. This keeps index mappings stable and avoids field explosion — a real problem when one team sends 2000 dynamic fields and breaks the mapping for everyone. I've found that capping dynamic fields and dropping or hashing unknown keys before indexing saves hours of debugging.

Don't forget to handle dead letters. I define a final <match **> that catches anything not routed and sends it to S3 with an unrouted prefix, plus a <match fluent.**> for internal Fluentd logs. Without that catch-all, mis-tagged logs vanish with no trace. For retention and legal requirements, link this routing to your policy — see Log Rotation and Retention: Storage Optimization and Compliance Requirements for sizing those S3 lifecycles and index rollovers.

Example Rewrite for Environment Isolation

I add a Fluentd filter that reads kubernetes.namespace_name and sets env and team fields, then re-tags. This keeps the original tag for debugging but routes on the enriched tag. I also strip sensitive fields like authorization or cookie at this layer before any output sees them — doing it at the edge is too late if you have multiple aggregator replicas and inconsistent configs.

Hardening Throughput and Observability Before Production Breaks

A logging pipeline that isn't monitored is a time bomb. I instrument both tiers with Prometheus metrics. Fluent Bit exposes /api/v1/metrics/prometheus and Fluentd has fluent-plugin-prometheus. Key signals I alert on: Fluent Bit storage_chunks and storage_chunks_bytes growing, Fluentd buffer_queue_length > 20 for 10 minutes, buffer_total_queued_size > 80% of limit, and output retry_count increasing. Pair these metrics with Prometheus and Alertmanager: Complete Setup for Production Monitoring to route pipeline alerts to the platform team, not the app team.

Throughput tuning starts with measuring. On a 3-node Fluentd aggregation layer, I sustained 85k events/sec with JSON parsing at the edge and simple routing. Moving JSON parsing to Fluentd dropped that to ~45k and doubled CPU. Multiline parsing is the most expensive operation — I benchmarked a 30% throughput hit when enabling Java multiline on all containers, so I now enable it only on namespaces that need it via annotation selectors.

Two hardening details that have saved me during incidents. First, set Flush_Interval in Fluent Bit to 1s and flush_interval in Fluentd buffers to 5s. Longer intervals increase latency and make it look like logs are missing when they are just buffered. Second, enable health_check on the forward output and set livenessProbe on Fluentd that checks buffer directory writability and output connectivity. I've seen Fluentd pods report Running while their PVC was ReadOnly due to a storage issue — the pipeline blocked for 20 minutes before anyone noticed.

Finally, test failure modes. Kill an aggregator pod during load, fill the disk, revoke the downstream credentials, and send a burst of 10x normal traffic. Document what happens to backpressure. In my load tests, the correct behavior is: Fluent Bit filesystem buffer fills, then throttles tail reading, then Kubernetes log files rotate. You will lose logs if your log rotation deletes files before Fluent Bit tails them. Mitigate this by increasing log rotation size to 50 MB with 10 files and setting Fluent Bit storage.pause_on_chunks_overlimit On so it pauses ingestion rather than dropping.

Frequently Asked Questions

Should I use Fluent Bit alone without a Fluentd aggregation layer?

For small clusters under 20 nodes with a single destination like CloudWatch or S3, Fluent Bit alone is often enough and simpler to operate. I recommend adding Fluentd when you need to fan-out to multiple backends, add strict multi-tenant routing, buffer reliably to disk for hours, or use enterprise plugins that only exist for Fluentd. If you run directly from Fluent Bit to OpenSearch or Elasticsearch, you shift retry and buffering complexity to every DaemonSet pod, which makes upgrades and credentials rotation harder.

How do I prevent log loss during Fluent Bit or Fluentd restarts?

Use filesystem storage on both tiers. In Fluent Bit, set Storage.Type filesystem and mount a hostPath or emptyDir with sizeLimit for the DB and spool, plus DB.Sync Full so offsets are persisted. In Fluentd, use file buffers with retry_forever and flush_at_shutdown. Also configure your container runtime log rotation to keep at least 50 MB x 5 files so logs are not deleted before the shipper reads them. Test by rolling the DaemonSet and checking for gaps in sequence numbers.

How do I handle multiline logs like Java stack traces without breaking JSON logs?

Do not enable global auto-multiline. Instead, define explicit multiline parsers for the runtimes you support and enable them per-pod via annotations or per-namespace filters. Keep JSON parsing as a separate filter that runs after Kubernetes metadata enrichment. If a log line fails JSON parsing, preserve the raw message in a fallback field. This way JSON microservices are not penalized by multiline logic, and Java services get correct aggregation.

What is the biggest performance pitfall in this pipeline?

Parsing and filtering at the wrong layer. Doing heavy regex, multiline, and Ruby transformations in Fluentd halves throughput and increases aggregator CPU. Pushing complex routing and large disk buffers to Fluent Bit increases its footprint and couples edge agents to backend details. Keep parsing lightweight and early in Fluent Bit, and keep buffering, enrichment, and fan-out in Fluentd. Benchmark with your real log samples — synthetic benchmarks hide multiline and JSON costs.

Related Articles

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