Elasticsearch bulk indexing timeout during continuous ML training loop

Problem

During a continuous machine‑learning (ML) training loop, feature vectors are streamed from a preprocessing pipeline and indexed into an Elasticsearch cluster using the _bulk API. Intermittently the bulk request fails with timeout errors, resulting in partial writes and missing documents. The downstream training job stalls because it cannot retrieve a complete snapshot of the feature data.

Symptoms and Impact

  • Log entries similar to:
    2026-11-22T14:03:12.345Z ERROR bulk_processor[ml-ingest] - Bulk indexing failed: timed_out=true, took_millis=30000, items=[{index:{_index:features,_id:12345,status:429}}]
  • Elasticsearch response payload contains "status":429 or "status":503 for many items.
  • Training pipeline receives BulkWriteException and retries indefinitely, causing CPU spikes.
  • Cluster health occasionally flips to yellow due to shard relocation triggered by node pressure.
  • Data snapshots used for model validation are incomplete, leading to degraded model performance.

Root Cause

The timeout originates from a combination of resource saturation and mis‑aligned bulk‑ingest parameters:

  1. Thread‑pool queue saturation – The write thread pool on each data node is configured with size=8 and queue_size=200. The continuous ML loop generates bulk requests faster than the pool can process, causing the queue to fill and Elasticsearch to reject new bulk items with 429 Too Many Requests.
  2. Refresh interval contention – The default index.refresh_interval=1s forces a segment refresh after every second. With high bulk throughput this creates frequent I/O bursts, increasing merge activity and causing the write thread pool to stall.
  3. Circuit breaker limits – The ingest circuit breaker is set to 70% of the JVM heap. When the bulk payload (average 5 MB) exceeds the limit, Elasticsearch aborts the request and returns a timeout.
  4. Network latency spikes – The ML workers run in a separate VPC and occasionally experience 150 ms+ round‑trip latency, which pushes the bulk request close to the client‑side timeout of 30 s.

Because the failure is intermittent, the symptom appears as a random timeout rather than a deterministic error, making it hard to reproduce without load.

Debug

Below is a systematic investigation workflow that reproduces the failure and isolates the cause.

1. Capture bulk request failures

# Example curl request with verbose output
curl -s -w "\n%{http_code}\n" -XPOST "http://es-prod:9200/_bulk?timeout=30s" \
  -H "Content-Type: application/x-ndjson" \
  --data-binary @bulk_payload.ndjson -v

Typical output when the timeout occurs:


...
> POST /_bulk?timeout=30s HTTP/1.1
> Content-Type: application/x-ndjson
> Content-Length: 5242880
>
< HTTP/1.1 429 Too Many Requests
< Content-Type: application/json
< Content-Length: 1234
{
  "took":30000,
  "errors":true,
  "items":[
    {"index":{"_index":"features","_id":"12345","status":429,"error":{"type":"es_rejected_execution_exception","reason":"rejected execution of org.elasticsearch.action.bulk.BulkRequest$1"}}},
    ...
  ]
}
429

2. Inspect thread‑pool statistics

curl -s http://es-prod:9200/_cat/thread_pool/write?v&h=node_name,active,queue,rejected,completed

Sample output during the incident:

node-1 8 210 12 15000
node-2 7 198 9 14820

The queue column exceeding the configured queue_size (200) confirms saturation.

3. Review index refresh and merge activity

curl -s http://es-prod:9200/_stats?human&filter_path=indices.features.total.refresh,total.refresh_time,total.refresh_total,total.merge.total

Output snippet:

{
  "indices" : {
    "features" : {
      "total" : {
        "refresh" : 10234,
        "refresh_time_in_millis" : "12,345,678",
        "merge" : {
          "total" : 543,
          "total_time_in_millis" : "9,876,543"
        }
      }
    }
  }
}

High refresh counts (≈10 k per minute) indicate the 1 s interval is too aggressive for the ingest rate.

4. Check circuit breaker status

curl -s http://es-prod:9200/_nodes/stats/breaker?human

Sample excerpt:

"ingest": {
  "limit_size_in_bytes": "5.6gb",
  "estimated_size_in_bytes": "4.2gb",
  "overhead": 1.0,
  "tripped": 7
}

Multiple trips correlate with bulk failures.

5. Verify network latency

# From an ML worker node
ping -c 5 es-prod

Typical ping times:

64 bytes from 10.0.2.15: icmp_seq=1 ttl=64 time=28.3 ms
...
64 bytes from 10.0.2.15: icmp_seq=5 ttl=64 time=152.7 ms

Spikes above 100 ms line up with the bulk timeout windows.

Solution

The fix consists of three coordinated changes: increase write capacity, relax index refresh, and adjust circuit‑breaker limits. All changes are applied via the Elasticsearch REST API to avoid a full cluster restart.

1. Enlarge the write thread‑pool

Before:

# /etc/elasticsearch/elasticsearch.yml
thread_pool.write.size: 8
thread_pool.write.queue_size: 200

After (increase size to 16 and queue to 500):

# /etc/elasticsearch/elasticsearch.yml
thread_pool.write.size: 16
thread_pool.write.queue_size: 500

Apply with a rolling restart or via the dynamic settings API:

curl -XPUT "http://es-prod:9200/_cluster/settings" -H "Content-Type: application/json" -d '
{
  "persistent": {
    "thread_pool.write.size": 16,
    "thread_pool.write.queue_size": 500
  }
}'

2. Reduce refresh pressure

Before:

# Index template
{
  "index": {
    "refresh_interval": "1s"
  }
}

After (set to 30s and enable refresh_interval override during bulk):

# Update index settings
curl -XPUT "http://es-prod:9200/features/_settings" -H "Content-Type: application/json" -d '
{
  "index": {
    "refresh_interval": "30s",
    "translog.flush_threshold_size": "512mb"
  }
}'

In the bulk client code, disable automatic refresh for each request:

# Python Elasticsearch client example
from elasticsearch import Elasticsearch, helpers

es = Elasticsearch(["http://es-prod:9200"])

def bulk_index(docs):
    actions = ({
        "_op_type": "index",
        "_index": "features",
        "_id": doc["id"],
        "_source": doc
    } for doc in docs)

    # Disable refresh on bulk
    helpers.bulk(es, actions, request_timeout=60, refresh=False)

3. Raise ingest circuit‑breaker limit

Before:

# /etc/elasticsearch/elasticsearch.yml
indices.breaker.ingest.limit: 70%

After (increase to 85% and add a safety margin):

# Dynamic update
curl -XPUT "http://es-prod:9200/_cluster/settings" -H "Content-Type: application/json" -d '
{
  "persistent": {
    "indices.breaker.ingest.limit": "85%"
  }
}'

4. Adjust client‑side timeout and enable back‑pressure

Increase the bulk timeout to 60 seconds and implement exponential back‑off:

# Java High Level Rest Client snippet
BulkProcessor bulkProcessor = BulkProcessor.builder(
    client,
    new BulkProcessor.Listener() { … })
    .setBulkActions(5000)
    .setBulkSize(new ByteSizeValue(10, ByteSizeUnit.MB))
    .setFlushInterval(TimeValue.timeValueSeconds(10))
    .setConcurrentRequests(4)
    .setBackoffPolicy(BackoffPolicy.exponentialBackoff(TimeValue.timeValueSeconds(1), 5))
    .setBulkRequestTimeout(TimeValue.timeValueSeconds(60))
    .build();

Verify

After applying the changes, perform the following checks:

  1. Run a sustained bulk load test (e.g., 10 k documents per second) for 10 minutes and confirm no 429 or timeout responses.
  2. Re‑run the thread‑pool stats command; the queue column should stay well below the new limit (e.g., queue < 100).
  3. Confirm refresh_interval is now 30s and that _cat/indices?v shows a stable docs.count increase without sudden drops.
  4. Check circuit‑breaker trips: "tripped": 0 over the test period.
  5. Validate the ML training loop completes a full snapshot without stalling; monitor the training job logs for the absence of BulkWriteException.

Prevent

Implement the following guardrails to avoid recurrence:

  • Monitoring: Create Grafana panels for thread_pool.write.queue, indices.breaker.ingest.tripped, and cluster.health.status. Alert when queue > 80% of queue_size or breaker trips exceed 1 per hour.
  • Rate limiting: Add a token‑bucket limiter in the preprocessing pipeline to cap the bulk request rate to max_bulk_rate = (write_threads * 2) * avg_bulk_size.
  • Dynamic refresh control: Use the refresh=false flag for all bulk indexing during training, and schedule a manual POST /features/_refresh after each training epoch.
  • Capacity planning: Periodically run _nodes/stats?filter_path=indices.docs.count,process.cpu.percent,os.mem.total_in_bytes,os.mem.used_in_bytes to ensure heap usage stays below 70% and CPU below 75% during peak ingest.
  • Testing: Include a bulk‑ingest stress test in the CI pipeline that simulates the production ingest rate and verifies no timeouts.

Related Topic Hub: Data Infrastructure Troubleshooting Hub

FAQ

  1. Why do bulk timeouts only appear after a few hours of training?
    The write thread‑pool queue gradually fills as the training loop ramps up. Once the queue exceeds its limit, Elasticsearch starts rejecting requests, which manifests as timeouts after the system has been under load for a while.
  2. Can increasing the JVM heap solve the issue?
    A larger heap may postpone circuit‑breaker trips but does not address the underlying write‑thread saturation or refresh contention. Proper thread‑pool sizing and refresh tuning are more effective.
  3. Is disabling refresh_interval safe for search queries that need near‑real‑time data?
    During the training phase, downstream consumers read data only after an epoch completes, so a 30 s or manual refresh is sufficient. For real‑time dashboards, use a separate index with a shorter refresh interval.
  4. What is the recommended bulk size for this workload?
    Empirically, 5–10 MB per bulk request (≈5 k documents) maximizes throughput without overwhelming the ingest pipeline. Adjust setBulkSize and setBulkActions accordingly.
  5. How do I know if network latency is still a factor after the fix?
    Continuously monitor client.transport.connect_timeout and client.transport.max_retry_timeout metrics. If latency spikes persist, consider colocating the ML workers in the same VPC or using an internal load balancer.