Schedule icon
Request icon
Sleep icon
If icon
Fail icon
OutputValues icon
Log icon
SlackIncomingWebhook icon
Pause icon
Loop icon

Reclaim Deleted-Doc Disk in Cold Elasticsearch Indices with Force Merge

Find cold Elasticsearch indices wasting disk on deleted docs, expunge them with a gated force merge, then verify the space came back from _stats.

Categories
Infrastructure

In Elasticsearch a delete or an update does not remove a document. It marks the old one deleted inside its Lucene segment. That space comes back only when segments merge. An index that saw heavy updates or deletes and is no longer written to keeps those deleted docs and their small segments for as long as it exists, because background merges deprioritise a cold index. The disk stays spent and every search still walks the dead docs. This blueprint reads _stats, flags the indices whose deleted docs are a large share of what their segments still hold, then runs POST /<index>/_forcemerge?only_expunge_deletes=true behind a dry run and a human approval to compact just those segments, re-reads _stats and fails the run if the ratio did not come down.

This is segment compaction. It expunges documents that are already deleted. It removes no live data, so it is not a retention flow.

Safety

  • Never force merge an index that is still being written to. A force merge on a live write index rewrites its segments and new writes then land in fresh small segments that the merged ones no longer absorb cheaply, which is the Elasticsearch force-merge footgun. So an index is eligible only when it is provably cold: indexing.index_total did not move across a probe window, no indexing is in flight and (by default) it carries index.blocks.write or index.blocks.read_only, which is the state ILM itself sets before its own force-merge step. Everything else is refused, listed in the report and the Slack alert, never merged.
  • only_expunge_deletes=true is the safer force-merge variant. It rewrites only segments whose deletes are above index.merge.policy.expunge_deletes_allowed and it does not force the index into one giant segment, so it never creates the single huge segment that max_num_segments=1 leaves behind and that can never merge again. The flow uses this variant on purpose.
  • An index under a disk read-only block (index.blocks.read_only_allow_delete) is refused. Force merge needs temporary disk headroom, so running it while the cluster is low on disk makes the pressure worse.
  • max_merge_per_run refuses the pass when the eligible list is long, because force merge is heavy IO and a long list usually means the pattern is too wide for one run.

Findings

  • io.kestra.plugin.elasticsearch.Request reports task success on any HTTP status, so a 4xx is silent. Every read is gated on outputs.<id>.status. The force merge verdict comes from a re-read of _stats, never from a 200.
  • The same task deserializes the response body into a map, so a _cat endpoint with format=json fails the task on its JSON array. All counts here come from _stats, which is a JSON object.
  • The ratio is read from primaries, not total. A replica mirrors its primary, so total would count the same deleted docs once per copy and inflate the figure.
  • A force merge can return 200 and reclaim nothing. If expunge_deletes_allowed is set above the index's actual deleted ratio, no segment qualifies and the deletes stay. The re-read is what catches that, which is why the run fails on it rather than trusting the call.

How it works

  1. detect_cluster (io.kestra.plugin.elasticsearch.Request) reads GET _cluster/health for context and reachability.
  2. detect_stats_before reads GET {index_pattern}/_stats/docs,indexing for primary doc counts and the indexing counters. detect_settings reads the write blocks plus the hidden flag.
  3. probe_wait (io.kestra.plugin.core.flow.Sleep) waits write_probe_wait, then detect_stats_after takes the second sample.
  4. check_reads (io.kestra.plugin.core.flow.If) fails the run when any read did not return 200.
  5. plan (io.kestra.plugin.core.output.OutputValues) keeps the indices at or above min_deleted_pct holding at least min_total_docs, then marks each eligible only when it is not taking writes, has no disk block and has a write block unless require_write_block is off.
  6. summary splits the candidates into the eligible merge set and the refused set. report logs both with the reclaim they represent and the mode. alert_detected posts a Slack findings alert whenever anything is flagged, before any remediation decision.
  7. route acts only when an index is eligible, auto_remediate is true and dry_run is false. cap_gate then refuses unless the eligible count is at or under max_merge_per_run, logging the refusal and failing so the alert fires.
  8. approval_gate (io.kestra.plugin.core.flow.Pause) holds the run until a human resumes it with approved true. remediate_forcemerge (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) sends one POST {index}/_forcemerge?only_expunge_deletes=true per eligible index.
  9. settle waits verify_wait, then reverify_stats re-reads the doc counts. verify_result fails the run when any merged index is still at or above the threshold.
  10. The errors block posts a Slack alert on any failure. A disabled Schedule trigger runs the scan every night in report-only mode.

What you get

  • Disk back from indices that were paying for documents nobody can read.
  • A refusal to force merge any index still taking writes, so the force-merge footgun cannot happen through this flow.
  • A threshold in percent of held docs instead of a guess, with a floor so a tiny index is never flagged.
  • Proof the space came back, from a re-read of _stats, not from the merge call returning 200.
  • Slack on detection and Slack on failure, both through a secret.
  • Outputs to chain on: outputs.summary.values.merge_json holds the eligible indices, outputs.summary.values.refused_json the ones still taking writes, outputs.verify_plan.values.still_json whatever stayed over the threshold after a pass.

Who it's for

  • Platform and SRE teams whose Elasticsearch disk keeps climbing on indices that stopped taking writes weeks ago.
  • Anyone running time-based indices that get a bulk _update_by_query or _delete_by_query for a correction or a GDPR erasure, which leaves a pile of deleted docs behind.
  • Teams who want the ILM warm-phase force-merge step as a safe, approved, verified one-off against indices ILM is not managing.

Why orchestrate this with Kestra

Force merge is one call and easy to point at the wrong index, where it quietly harms a live index instead of helping a cold one. The value is the sequence around it: prove the index is cold, show it to a human, hold for approval, run the merge, then read the system again to decide whether the run passed. A flow records all of that against one execution id, with the read-only default, the write-safety gate and the Pause making a careless merge hard.

Tested end to end

Verified on Kestra 2.0.5 against Elasticsearch 8.15.3 with security disabled, on a single node. A cold index was created, filled, then had half its documents removed with _delete_by_query and was set index.blocks.write: true, which left it holding a high deleted ratio with no further writes. A second cold index was given a low deleted ratio to prove precision. A third index was kept under a steady write stream with a high deleted ratio, to prove the write-safety refusal. The clean, detect, dry-run, approved-remediation, declined-approval, refused-active-index, re-verify-fails and failure paths were all run. The flagged cold index went from a high deleted ratio to near zero, the low-ratio index was never touched, the actively written index was refused and reported rather than merged. Every count was confirmed with a direct call to the Elasticsearch _stats API and the segment count from _cat/segments, not read off the Kestra log. An index whose index.merge.policy.expunge_deletes_allowed was set above its deleted ratio made the re-verify step fail the run as designed, because the merge reclaimed nothing.

Prerequisites

  • A reachable Elasticsearch cluster. For a secured cluster, credentials allowed to read cluster health, index stats and index settings and to call _forcemerge.
  • A Slack incoming webhook for the findings and failure alerts.

Secrets

  • ELASTICSEARCH_USERNAME: username for basic auth, when the cluster has security enabled.
  • ELASTICSEARCH_PASSWORD: password for basic auth, when the cluster has security enabled.
  • SLACK_WEBHOOK_URL: Slack incoming webhook URL for alerts.

Inputs

  • elasticsearch_url: base URL of the cluster.
  • elasticsearch_username and elasticsearch_password: empty by default, so the secrets apply. Set both to any value on a cluster with security off.
  • index_pattern: index or pattern to inspect, * by default.
  • include_system_indices: set true to inspect dot-prefixed and hidden indices too.
  • min_deleted_pct: flag an index at or above this percent deleted of held docs. Keep it above the 10 percent expunge_deletes_allowed default.
  • min_total_docs: ignore an index holding fewer than this many docs.
  • require_write_block: when true an index must carry a write block to be eligible, the strongest proof it is cold.
  • write_probe_wait: gap between the two indexing samples that detects writes.
  • max_merge_per_run: the flow refuses to merge more than this many indices in one pass.
  • verify_wait: settle time before the re-read.
  • dry_run and auto_remediate: the two safety gates. A merge runs only when auto_remediate is true and dry_run is false, then only after the Pause is resumed with approved true.

Quick start

  1. Add the Slack webhook secret plus the Elasticsearch credentials if your cluster is secured.
  2. Set elasticsearch_url and run once with the defaults to see which cold indices are over the threshold and which are refused as still live.
  3. Set index.blocks.write: true on an index you have finished writing or set require_write_block to false if you want the write-activity probe to stand on its own.
  4. Run with auto_remediate true and dry_run false, then resume the Pause with approved true to compact the eligible indices.
  5. Set disabled: false on the nightly trigger to scan every night in report-only mode.

How to extend

  • Point index_pattern at one family such as logs-2024-* to scope a pass to indices you know are closed to writes.
  • Set require_write_block to false and raise write_probe_wait on a cluster where cold indices are not block-marked, so the activity probe alone decides.
  • Chain a flow off this flow's FAILED state to open a ticket when a merge reclaims nothing, since that points at a merge-policy setting rather than a one-off.
  • Add a step that sets index.blocks.write: true on an index before merging it, turning this into the full ILM warm-phase readonly-then-forcemerge sequence for indices ILM is not managing.

Links

This blueprint was created by zkasuran.

See How

New to Kestra?

Use blueprints to kickstart your first workflows.