Blog

2 lines, 1 document: Pairing Elasticsearch bulk actions in Logstash

Logstash holds the Elasticsearch credentials, masks the emails and gives each tenant its own index. The client never needs to know your cluster exists, and the repo runs on Docker Compose.

Check out the different ways to ingest data into Elasticsearch and dive into practical examples to try something new.

Elasticsearch is packed with new features to help you build the best search solutions for your use case. Start a free cloud trial or try Elastic on your local machine now.

  • An Elasticsearch bulk API request is two lines per document, and Logstash reads newline-delimited JSON (NDJSON) one line at a time, so an action line and its document arrive as separate events. The gateway in this blog post pairs them back up before anything gets indexed. On the way through, it masks emails and drops debug events, and it routes each tenant to its own index. This means a client that can only POST a bulk body to a URL never has to hold an Elasticsearch credential. It’s one config file and one ordered worker, and the repo runs on Docker Compose. It works for clients that speak raw _bulk, but apps built on an official Elasticsearch client will not.

Prerequisites

The repo was tested with Elasticsearch, Logstash, and Kibana 9.5.6.

What the Logstash bulk gateway needs to handle

We’ll build for the following situation:

  • A client sends _bulk requests to one URL and can't be modified.

  • A proxy or load balancer in front sets two headers on every request: X-Request-Id, which is unique per request, and X-Tenant-Id. It overwrites whatever the client sent, and clients can't reach Logstash directly.

  • Each tenant's data must go to its own index.

  • Emails must be masked, and debug events must be dropped.

  • Only Logstash holds the Elasticsearch credentials.

  • Kibana is there so you can see what was indexed.

Why not send bulk requests straight to Elasticsearch?

Often, you should. Elasticsearch ingest pipelines can mask fields and drop documents,  and they can set the index. If that's all you need, use one and skip Logstash.

Logstash earns its place when:

  • The client must not know that Elasticsearch exists, or it can't hold a credential.

  • You need to enrich events from outside Elasticsearch, like a database or an HTTP service.

  • You want to write the same data to more than one place, like Elasticsearch and Kafka.

  • You want one set of rules in front of several destinations.

How the Elasticsearch bulk API format works (NDJSON)

A bulk request is NDJSON, rather than a JSON array. Most operations take two lines: an action line that says what to do; and a source line with the document. A delete takes only the action line:

{ "index": { "_id": "1" } }
{ "order_id": "A-1001", "email": "jane.doe@example.com", "total": 42.5, "level": "info" }
{ "create": { "_id": "2" } }
{ "order_id": "A-1002", "email": "bob.smith@example.com", "total": 10, "level": "info" }
{ "index": { "_id": "3" } }
{ "order_id": "A-1003", "email": "debug@example.com", "total": 0, "level": "debug" }
{ "update": { "_id": "1" } }
{ "doc": { "total": 45.0, "email": "jane.doe@example.com" } }
{ "delete": { "_id": "2" } }

Each line has to be on its own line, not pretty-printed, and the body must end with a newline. When you send it, read the file as raw bytes. If a JSON library reserializes the body, you lose the newlines.

Why Logstash splits a bulk request into separate events

Point the Logstash http input at this body with the json_lines codec, and Logstash makes one event per line.

That split is the problem. After the action and source are separate events, nothing connects { "index": { "_id": "1" } } to the document that follows it. And if more than one worker handles events from the same request, they can be processed out of order, so a source line can end up with the wrong action.

So the pipeline has two jobs: 

  • Keep the events of one request together.

  • Handle them in order.

Building the Logstash bulk API gateway pipeline

The whole pipeline is one file, bulk-gateway.conf, in the repo.. In this post, we discuss each step in turn.

Configuring the Logstash http input for NDJSON

The http input picks its codec from the request's Content-Type, and the default mapping doesn’t split a bulk body into lines. This input block overrides that and normalizes what arrives:

input {
  http {
    port => 8080
    ecs_compatibility => disabled
    request_headers_target_field => "[@metadata][headers]"
    remote_host_target_field     => "[@metadata][remote_host]"
    codec => json_lines { decode_size_limit_bytes => 20971520 }
    additional_codecs => {}
  }
}
  • codec => json_lines makes line splitting the behavior for every request. Bulk clients send application/x-ndjson or application/json(or no content type at all), so the codec cannot depend on what the client declares.

  • additional_codecs => {} empties the default map. Without this, application/json would still route to the json codec, which treats the whole body as one document.

  • decode_size_limit_bytes => 20971520 caps a single line (meaning, one action or one document) at 20 MB.

  • ecs_compatibility => disabled stops the input from adding its own http, url, host, and user_agent fields to every event, where they could collide with the client’s own fields.

  • request_headers_target_field and remote_host_target_field move the request headers and the client address into [@metadata], which is where the next filter reads the tenant and request ID from.

Reading tenant and request ID from the headers

In Logstash, the above http input puts the request headers in metadata, under [@metadata][headers], because of the request_headers_target_field setting in the input block. It also lowercases the header names and turns dashes into underscores, so X-Request-Id arrives as x_request_id.

Two Ruby filters handle the header metadata. The first processor removes everything in metadata except what the input puts there, because a client can put its own @metadata key in a document and Logstash merges it into the event. The second reads x_request_id and x_tenant_id from [@metadata][headers]:

# keep only what the input put in metadata
ruby {
  code => '
    md = event.get("[@metadata]") || {}
    md.keys.each { |k| event.remove("[@metadata][#{k}]") unless %w[headers remote_host].include?(k) }
  '
}
ruby {
  code => '
    h = event.get("[@metadata][headers]") || {}
    req = h["x_request_id"]
    tenant = h["x_tenant_id"]
    if req.nil? || req.empty? || tenant.nil? || tenant.empty?
      event.tag("missing_headers")
      event.set("[@metadata][reject]", true)
    elsif tenant !~ /\A[a-z0-9_-]{1,64}\z/
      event.tag("invalid_tenant")
      event.set("[@metadata][reject]", true)
    else
      event.set("[@metadata][req_id]", req)
      event.set("[@metadata][tenant]", tenant)
    end
  '
}
# a client @timestamp that isn't ISO 8601: convert epoch milliseconds
if "_timestampparsefailure" in [tags] {
  ruby {
    code => '
      v = event.get("_@timestamp")
      v = Integer(v, 10) if v.is_a?(String) && v.match?(/\A\d+\z/)
      if v.is_a?(Integer)
        event.timestamp = LogStash::Timestamp.at(v / 1000.0)
        event.remove("_@timestamp")
        t = (event.get("tags") || []) - ["_timestampparsefailure"]
        t.empty? ? event.remove("tags") : event.set("tags", t)
      end
    '
  }
}

The filter tags the event missing_headers, if either header is missing, and invalid_tenant, if the tenant name isn't 1–64 lowercase letters, digits, dashes, or underscores, so a tenant like Acme/X is rejected. Both also set a reject flag in metadata, and that flag is what sends the event to stdout. Nothing flagged is written to the tenant's index, so bad input is visible and not quietly indexed. The tenant check matters because the tenant becomes part of an index name, and Elasticsearch answers an invalid name with a 400.

stdout is added there so rejects are easy to see. In a production setup, send them wherever suits you; for example, an Elasticsearch output to a separate rejected-documents index, a file, or a queue like Kafka, so you can fix them and resend. 

You could also use the Logstash dead letter queue input plugin to retry failed documents. Only the Elasticsearch output writes to it, for documents that Elasticsearch rejects with a 400 or 404, so it can't hold these pipeline rejects.

The last filter in the block deals with the client's @timestamp. Logstash keeps a valid International Organization for Standardization (ISO) 8601 value and tags anything else with _timestampparsefailure. Elasticsearch also accepts epoch milliseconds, so the filter converts those back. Any other value stays tagged and goes to stdout.

Pairing action and source lines with the aggregate filter

An action line is any event with a top-level index, create, update, or delete key that holds an object. The first Ruby filter below finds it and saves its operation and ID. The pipeline puts index, create, and update in a small queue for that tenant and request, using the aggregate filter, and drops the event. The next source line takes the oldest waiting action and picks up its operation and ID. A delete has no source line, so it skips the queue:

# find the action line, and remember its operation and ID
ruby {
  code => '
    %w[index create update delete].each do |k|
      if event.get(k).is_a?(Hash)
        event.set("[@metadata][is_action]", true)
        event.set("[@metadata][op]", k)
        event.set("[@metadata][op_id]", event.get("[#{k}][_id]"))
        break
      end
    end
  '
}
# delete has no source line: send it on if it has an _id
if [@metadata][op] == "delete" {
  if [@metadata][op_id] {
    mutate {
      add_field => {
        "[@metadata][action]" => "delete"
        "[@metadata][doc_id]" => "%{[@metadata][op_id]}"
      }
    }
  } else {
    mutate {
      add_tag   => ["missing_id"]
      add_field => { "[@metadata][reject]" => "true" }
    }
  }
}
# index, create, update: remember the action line, then drop it
aggregate {
  id => "queue_push"
  task_id => "%{[@metadata][tenant]}:%{[@metadata][req_id]}"
  code => '
    map["pending"] ||= []
    map["pending"] << {
      "op" => event.get("[@metadata][op]"),
      "id" => event.get("[@metadata][op_id]")
    }
  '
  timeout => 3600
  inactivity_timeout => 300
}
drop { }
# any other line is a source line: take the oldest waiting action
aggregate {
  id => "queue_pop"
  task_id => "%{[@metadata][tenant]}:%{[@metadata][req_id]}"
  code => '
    op = (map["pending"] || []).shift
    if op.nil?
      event.tag("orphan_source_line")
      event.set("[@metadata][reject]", true)
    elsif op["op"] == "update" && op["id"].nil?
      event.tag("missing_id")
      event.set("[@metadata][reject]", true)
    else
      event.set("[@metadata][action]", op["op"])
      event.set("[@metadata][doc_id]", op["id"]) if op["id"]
    end
  '
}

With this code, we should be aware of the following considerations:

  • Rejected lines. A source line with nothing waiting gets orphan_source_line, and an update or delete with no _id gets missing_id. Both are rejected; they go to stdout and aren’t indexed.

  • Lines without an _id. An index or create without an _id is accepted. Elasticsearch generates one.

  • Found by shape. A document with its own top-level field named index, create, update, or delete and holding an object would be mistaken for an action line.

  • The shift operation removes and returns the first item in the list, because events arrive in order.

  • Timeouts. They clean up queues that never finish, like a truncated request. inactivity_timeout => 300 clears a queue after 300 seconds without an event, and timeout => 3600 is a hard cap from its first event.

  • Why so long. If the output is waiting on Elasticsearch (for example, retrying after a 429 or a connection error), the worker can sit in the output between an action line and its source line, and a queue that expires in between turns the source line into an orphan. Within 30 seconds, a 50-second stall lost a document in a test. An open queue only costs memory.

  • Open queues. Finished requests keep their queue until the inactivity timeout, so aggregate_maps takes five to seven minutes to fall back to 0.

  • Queue key. It's the tenant plus the request ID, so two tenants that reuse a request ID can't mix queues. All timeout options live in the first aggregate filter, as the aggregate filter docs require.

Pairing only works if events are handled in order, and Logstash doesn't guarantee to preserve message ordering by default. Events in a batch (and whole batches) can be reordered. So the pipeline runs one worker with ordered processing, which the aggregate filter docs and the event ordering docs both specify. For example, processing financial transactions, where a debit has to be applied before the credit that follows it, is the classic case. The pipeline.ordered defaults to auto, which already turns ordering on with one worker. Setting it to true prevents Logstash from starting if someone raises the worker count later. Both settings are in logstash.yml in the repo and are described by the logstash.yml reference:

pipeline.workers: 1
pipeline.ordered: true

Masking emails, dropping events, and routing per tenant

Now that every event has its operation and ID, the rules are simple. An update source has to be exactly { "doc": { ... } }. The Elasticsearch output wraps updates itself, so the pipeline unwraps doc first. Without that, you'd store a nested doc field instead of updating the document. 

The script, upsert, doc_as_upsert, and the other update options aren't supported. The Elasticsearch output takes them as settings on the output itself, which apply to every event it sends, so it can't use the option that a client chose for one update. Passed through as plain fields, they'd end up in the document and do nothing. So the following code tags these updates unsupported_update and sends them to stdout instead. If you need them, send the updates straight to Elasticsearch.

if [@metadata][action] == "update" {
  ruby {
    code => '
      d = event.get("doc")
      extra = event.to_hash.keys - ["doc", "@timestamp", "@version"]
      if !d.is_a?(Hash) || !extra.empty?
        event.tag("unsupported_update")
        event.set("[@metadata][reject]", true)
      else
        event.remove("doc")
        ts = d.delete("@timestamp")
        d.each { |k, v| event.set(k, v) }
        if ts
          event.timestamp = ts.is_a?(Integer) ? LogStash::Timestamp.at(ts / 1000.0) : LogStash::Timestamp.parse_iso8601(ts.to_s)
          event.set("[@metadata][keep_timestamp]", true)
        end
      end
    '
  }
}
if [level] == "debug" { drop { } }
if [email] {
  mutate { gsub => ["email", "^(.)[^@]*@", "\1***@"] }
}
mutate { add_field => { "[@metadata][index]" => "orders-%{[@metadata][tenant]}" } }
mutate { remove_field => ["@version"] }
if [@metadata][action] == "update" and ![@metadata][keep_timestamp] {
  mutate { remove_field => ["@timestamp"] }
}

The index comes from the tenant header, not from the client. That way a client can't write into another tenant's index, even by accident, as long as your proxy sets X-Tenant-Id from an authenticated identity and clients can't reach Logstash directly. The http input processor has no authentication unless you set user and password, or Transport Layer Security (TLS) client certificates.

The email rule only masks a top-level email field (a string or list of strings) and keeps the domain, so it isn't full personally identifiable information (PII) redaction. Logstash adds @version and @timestamp to every event. The pipeline drops @version and keeps @timestamp on index and create, which the Kibana step uses. A valid @timestamp from the client wins. On an update, @timestamp is removed so it doesn't overwrite the original, unless the client sent a new one.

Configuring the Elasticsearch output with dynamic action and index

The last step is the Elasticsearch output. What's specific to this pipeline is that action and index aren’t fixed values, and neither is document_id. They're populated from the metadata collected from the earlier steps set for each event. An index or create without an _id goes to a second output with no document_id, so Elasticsearch generates one. Without that split, every ID-less document would be written with the literal text %{[@metadata][doc_id]} as its ID, and each one would overwrite the last. Anything that the pipeline flagged, like missing_headers or invalid_tenant, goes to stdout instead. The credentials live in Logstash, too, and the ${ENV_VALUES} values are environment variables that Logstash replaces at startup:

if [@metadata][reject] or "_jsonparsefailure" in [tags] or "_timestampparsefailure" in [tags] or "_rubyexception" in [tags] or "_tagsparsefailure" in [tags] {
  stdout { codec => rubydebug { metadata => true } }
} else if [@metadata][doc_id] {
  elasticsearch {
    hosts       => ["${ES_HOST}"]
    user        => "${ES_USER}"
    password    => "${ES_PASSWORD}"
    action      => "%{[@metadata][action]}"
    index       => "%{[@metadata][index]}"
    document_id => "%{[@metadata][doc_id]}"
  }
} else {
  elasticsearch {
    hosts    => ["${ES_HOST}"]
    user     => "${ES_USER}"
    password => "${ES_PASSWORD}"
    action   => "%{[@metadata][action]}"
    index    => "%{[@metadata][index]}"
  }
}

The output uses the Elasticsearch bulk API to send events in batches. So you take a bulk request apart, and the output builds a new one on the other side. In the next section, we cover what happens to a document that Elasticsearch rejects. 

Limitations of a Logstash bulk API gateway

Logstash acknowledges the request as soon as it accepts the body, so the client gets a 200 OK and never learns what Elasticsearch did with its documents. Here’s what happens to each outcome:

Elasticsearch response

What happens

400 or 404; for example, a mapping error

Goes to the dead letter queue, which is off by default in Logstash and enabled in the repo with dead_letter_queue.enable: true in logstash.yml

409, a version conflict

Logged and dropped

Any other error

Retried

Any outcome at all

The client already received a 200 OK and never learns the result

  • The failure store is a similar feature, but it only fits data streams, which take new documents through creation, so it doesn’t fit here.
  • Rejected input. A request without the headers, a bad tenant name, a timestamp that isn't ISO 8601 or epoch milliseconds, a tags field that's an object, and an update with a script or upsert all go to stdout and never to Elasticsearch. The client still receives a 200 OK response.

  • Crashes. Enable queue.type: persisted explicitly from the logstash.yml to use persistent queues (not enabled by default). The persistent queues keep events across a restart, but the pairing queues are in memory. After a crash, a replayed source line can arrive without its action line and be rejected as an orphan. In a kill -9 test (a simulated crash test), by setting queue.checkpoint.writes: 1, we lose every document of a request split across two batches. The default settings recover them, but nothing guarantees that, so treat the persistent queue as a help, not a guarantee.

  • One worker. Ordered processing means one CPU thread for the filters. If you need ordered processing across more than one CPU thread, run several independent pipelines and split the traffic by tenant at the proxy.

  • Ignored bulk features. Only the operation and _id values are used. The _index, routing, if_seq_no, if_primary_term, per-action pipeline, URL parameters, and index in the path are dropped.

  • Watch the queues. Logstash's monitoring API shows how many queues are open. Run curl localhost:9600/_node/stats/pipelines/main, and look at aggregate_maps, which falls back to 0 five to seven minutes after the last request. To see it in Kibana, connect Logstash with Elastic Agent or Metricbeat.

aggregate_maps counts the queue(s), one for each request from the last few minutes, so you can check the queues using the jq command:

# Request
curl -s localhost:9600/_node/stats/pipelines/main | jq '.pipelines.main.plugins.filters[] | select(.id=="queue_push") | {id, aggregate_maps}'
# Response
{
  "id": "queue_push",
  "aggregate_maps": 2 
}
  • Demo settings. The repo uses a simple password and no TLS, so it runs anywhere. For production, authenticate using an API key and TLS.

Running the Logstash bulk gateway with Docker Compose

Everything is in a repo. Along with Docker, you need curl and jq, as listed in the prerequisites.

git clone https://github.com/someshwaranM/logstash-bulk-gateway.git
cd logstash-bulk-gateway
docker compose up -d
./scripts/send.sh
./scripts/verify.sh

send.sh posts the sample body with the two headers. verify.sh checks the end state and should print six PASS lines:

  • Document 1 exists.

  • Document 1 has a total 45, so the update was applied.

  • Document 1 has the email masked.

  • Document 1 has no nested doc field.

  • Document 2 is gone, because it was created and then deleted.

  • Document 3 was never stored, because it was a debug event.

Then run ./scripts/edge-cases.sh. It sends problem requests that a real client can produce, and it prints 18 PASS lines. It covers the following cases:

  • A body sent as application/json

  • Documents without an _id

  • Documents with their own url, host, and tags fields

  • Client timestamps in different formats

  • An invalid tenant name

  • An update with a script

  • An update that keeps the original @timestamp

  • A mapping error that ends up in the dead letter queue 

After that, try a few things:

  • Send the same file as another tenant, with ./scripts/send.sh sample/bulk-acme.ndjson globex. You’ll get a second index, orders-globex.

  • Send a request without the headers. Look for missing_headers in the Logstash logs.

  • Set pipeline.workers: 2, and recreate the Logstash container. Compose says it started, but Logstash exits a few seconds later with an error, and the log explains why.

  • Send a request with the tenant Not/Valid. The client still gets OK back, and the events show up on stdout with an invalid_tenant tag.

To look at the documents, open Kibana at http://localhost:5601 and log in with the user elastic and the password changeme. In Discover, create a data view for orders-* with @timestamp as the time field. You'll see the documents with the emails masked, and no document for the debug event.

If port 8080 is busy on your machine, set the LOGSTASH_PORT environment variable first as outlined in the README.

Logstash as a bulk gateway

Bulk requests don't survive a trip through Logstash on their own. The json_lines codec splits them into single lines, and the link between an action and its source is gone. One small queue per request (plus an ordered worker) puts it back.

After that works, Logstash is a helpful gateway for a client that you can't change. It can mask and drop, and it can route, and it keeps the Elasticsearch credentials to itself.

But it isn’t the right answer for everything. For example, if:

  • An ingest pipeline does what you need, use that. 

  • You need to scale past one worker, split the traffic first. 

  • You can change the client, send the data straight to Elasticsearch. 

  • The client is built on an official Elasticsearch client, this gateway won't work for it.

Clone the repo, and send the sample. Break it on purpose. That's the fastest way to see why each piece is there.

Additional references

How helpful was this content?

Related Content

Reading the fine print: OCR and Markdown extraction, native in Elasticsearch

Reading the fine print: OCR and Markdown extraction, native in Elasticsearch

Tim Grein
GPU-accelerated vector indexing in Elasticsearch with NVIDIA cuVS: 138M vectors in under 10 minutes

GPU-accelerated vector indexing in Elasticsearch with NVIDIA cuVS: 138M vectors in under 10 minutes

Bao Tong
Agentic workflows in Elasticsearch: pause an AI agent for human approval, resume 72 hours later

Agentic workflows in Elasticsearch: pause an AI agent for human approval, resume 72 hours later

Alex Salgado
One field, one copy: How Elasticsearch columnar storage drops the inverted index

One field, one copy: How Elasticsearch columnar storage drops the inverted index

Martijn Van Groningen
Backfill time series data in Elasticsearch: Load months of historical metrics through the bulk API

Backfill time series data in Elasticsearch: Load months of historical metrics through the bulk API

Mary Gouseti

Ready to build state of the art search experiences?

Sufficiently advanced search isn’t achieved with the efforts of one. Elasticsearch is powered by data scientists, ML ops, engineers, and many more who are just as passionate about search as you are. Let’s connect and work together to build the magical search experience that will get you the results you want.