Architecture

Building a Distributed Full-Text Search System with Elasticsearch and Go: Sharding, Routing, and Fault Tolerance

Ruslan Ismailov Published 18 min read
B

Introduction: Why Build Distributed Search with Go + Elasticsearch in 2026

Full-text search has long ceased to be an "optional feature" — it is a critical component of most SaaS platforms, marketplaces, and enterprise applications. In 2026, Elasticsearch remains the de facto standard for distributed search: a mature ecosystem, rich query DSL, and built-in replication and horizontal scaling mechanisms. Go has firmly established itself in the highload backend stack: minimal overhead, high concurrency, and strict typing make it an excellent choice for the layer that manages the search cluster.

Key challenges when building such a system:

  • Proper sharding: choosing the wrong number of shards leads to performance degradation or an inability to scale without reindexing.
  • Request routing: without custom routing, queries hit all shards, creating scatter-gather overhead.
  • Fault tolerance: network partitions, split-brain scenarios, and slow nodes require well-designed client-side logic.
  • Multi-tenancy: data isolation and even load distribution across tenants.

In this article, we will cover each of these aspects with concrete Go code examples and Elasticsearch configurations.

Solution Architecture

Component Roles and Cluster Topology

Recommended topology for a mid-scale production cluster (50–200 million documents):

  • Dedicated master nodes (3 nodes) — cluster state management only, no data. An odd number eliminates split-brain.
  • Data nodes (6–12 nodes) — shard storage and search query execution. Support hot/warm/cold tiers when using ILM.
  • Coordinating nodes (2–4 nodes) — accept requests from Go clients, aggregate results from all shards. Reduce load on data nodes.
  • Go Search Gateway — a Go service implementing routing business logic, circuit breaking, rate limiting, and authentication.

The Go Search Gateway communicates exclusively with coordinating nodes over HTTP/1.1 (or HTTP/2 via the transport layer of the official client). Coordinating nodes hide shard placement details from the client and perform scatter-gather themselves.

Custom Routing in the Overall Architecture

Custom routing guarantees that documents belonging to the same tenant or the same time partition land on the same shard. This turns scatter-gather into a targeted query: instead of polling all shards, Elasticsearch goes directly to the relevant one.

Sharding Configuration

Choosing the Number of Shards

Elastic's rule of thumb: one shard holds 10–50 GB of data, with the optimum around 20–30 GB. For a 300 GB index, 10–15 primary shards is a reasonable choice. The number of replicas depends on availability requirements: with 1 replica, losing a node does not cause data loss; with 2 replicas, two nodes can be lost simultaneously.

Important: the number of primary shards is fixed at index creation time. Changing it without a full reindex is not possible (the split/shrink API allows proportional changes, but this is an expensive operation).

Segmentation by Tenant and Date

Two strategies are used for multi-tenant systems:

  • Index per tenant — each tenant gets its own index. Data isolation is maximum, but with thousands of tenants the metadata management overhead becomes significant (recommended limit: up to 1,000 indices per cluster).
  • Shared index with custom routing — all tenants share one index, but documents are routed by tenant_id. Scales to millions of tenants, but requires an explicit filter in every query.

Creating an index with explicit sharding configuration:

PUT /documents
{
  "settings": {
    "number_of_shards": 12,
    "number_of_replicas": 1,
    "routing.allocation.include.tier_preference": "data_hot",
    "index.routing_partition_size": 3
  },
  "mappings": {
    "_routing": {
      "required": true
    },
    "properties": {
      "tenant_id": { "type": "keyword" },
      "content":   { "type": "text", "analyzer": "english" },
      "created_at":{ "type": "date" },
      "title":     { "type": "text" }
    }
  }
}

The index.routing_partition_size: 3 parameter means that documents with the same routing key will be distributed across 3 of the 12 shards — this reduces the risk of a hot shard when tenant data is unevenly distributed.

Rebalancing and ILM

Index Lifecycle Management allows you to automatically move "old" indices to warm/cold nodes and delete them on a schedule. For time-partitioned data (logs, events), use the rollover API together with ILM:

PUT _ilm/policy/search_logs_policy
{
  "policy": {
    "phases": {
      "hot":  { "actions": { "rollover": { "max_size": "30gb", "max_age": "7d" } } },
      "warm": { "min_age": "7d",  "actions": { "shrink": { "number_of_shards": 2 }, "allocate": { "require": { "data": "warm" } } } },
      "cold": { "min_age": "30d", "actions": { "freeze": {} } },
      "delete":{ "min_age": "90d", "actions": { "delete": {} } }
    }
  }
}

Go Client for Elasticsearch

Official Client and Its Capabilities

The official client github.com/elastic/go-elasticsearch/v8 is the recommended choice for Go in 2026. It is type-safe (TypedClient), supports all Elasticsearch 8.x APIs, and includes built-in retry logic.

Client Initialization with Connection Pool and Retry

package search

import (
	"crypto/tls"
	"net/http"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
)

func NewESClient(addresses []string, username, password string) (*elasticsearch.Client, error) {
	transport := &http.Transport{
		MaxIdleConnsPerHost:   64,
		ResponseHeaderTimeout: 5 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: false, // always false in prod
		},
	}

	cfg := elasticsearch.Config{
		Addresses: addresses, // coordinating nodes
		Username:  username,
		Password:  password,

		// Retry on network errors and 5xx (except 429 — rate limiting is handled separately)
		RetryOnStatus:        []int{502, 503, 504},
		MaxRetries:           3,
		RetryBackoff: func(i int) time.Duration {
			// Exponential backoff: 100ms, 200ms, 400ms
			return time.Duration(100*(1<

The Elasticsearch Go client does not use a connection pool in the classical sense — it operates on top of the standard http.Transport, which manages keep-alive connections. The MaxIdleConnsPerHost: 64 parameter allows up to 64 idle connections per coordinating node, giving 192 ready connections across 3 nodes without a TCP handshake.

Request Routing

Routing Key and Targeted Queries

Custom routing is the key optimization tool for search in multi-tenant systems. When indexing a document, the routing parameter is passed, and Elasticsearch guarantees placement of the document on a specific shard (or group of shards when routing_partition_size > 1). During search, the same routing key directs the request only to the relevant shards.

package search

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/elastic/go-elasticsearch/v8/esapi"
)

type Document struct {
	TenantID  string `json:"tenant_id"`
	Title     string `json:"title"`
	Content   string `json:"content"`
	CreatedAt string `json:"created_at"`
}

// IndexDocument indexes a document with routing by tenant_id.
func IndexDocument(ctx context.Context, es *elasticsearch.Client, docID string, doc Document) error {
	body, err := json.Marshal(doc)
	if err != nil {
		return fmt.Errorf("marshal document: %w", err)
	}

	req := esapi.IndexRequest{
		Index:      "documents",
		DocumentID: docID,
		Routing:    doc.TenantID, // <-- custom routing key
		Body:       bytes.NewReader(body),
		Refresh:    "false", // async refresh for performance
	}

	res, err := req.Do(ctx, es)
	if err != nil {
		return fmt.Errorf("index request: %w", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return fmt.Errorf("elasticsearch error: %s", res.String())
	}
	return nil
}

// SearchDocuments performs a search with routing (only against the tenant's shards).
func SearchDocuments(ctx context.Context, es *elasticsearch.Client, tenantID, query string) (*SearchResult, error) {
	queryBody := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": map[string]interface{}{
					"match": map[string]interface{}{
						"content": query,
					},
				},
				"filter": map[string]interface{}{
					"term": map[string]interface{}{
						"tenant_id": tenantID,
					},
				},
			},
		},
		"size": 20,
	}

	body, _ := json.Marshal(queryBody)

	res, err := es.Search(
		es.Search.WithContext(ctx),
		es.Search.WithIndex("documents"),
		es.Search.WithRouting(tenantID), // targeted query — only the required shards
		es.Search.WithBody(bytes.NewReader(body)),
		es.Search.WithPreference("_local"), // prefer local replicas
	)
	if err != nil {
		return nil, fmt.Errorf("search request: %w", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return nil, fmt.Errorf("search error: %s", res.String())
	}

	var result SearchResult
	if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
		return nil, fmt.Errorf("decode response: %w", err)
	}
	return &result, nil
}

Shard Allocation Awareness

To improve fault tolerance, configure shard allocation awareness by rack or availability zone. This ensures that a primary shard and its replica never end up on the same physical server:

# In elasticsearch.yml on each node
node.attr.rack: rack-1   # or rack-2, rack-3

# In cluster settings
PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.awareness.attributes": "rack",
    "cluster.routing.allocation.awareness.force.rack.values": "rack-1,rack-2,rack-3"
  }
}

The _local value in WithPreference directs search requests to replicas located on the same node as the coordinating node, minimizing the network round-trip within the cluster.

Fault Tolerance

Circuit Breaker in Go

The built-in retry logic of the Elasticsearch client handles transient failures but does not protect against cascading failures. A circuit breaker at the Go service level allows fast error returns without waiting for a timeout when the cluster is overloaded or unavailable.

package breaker

import (
	"errors"
	"sync"
	"time"
)

type State int

const (
	StateClosed   State = iota // normal operation
	StateOpen                   // all requests are blocked
	StateHalfOpen              // probe request
)

var ErrCircuitOpen = errors.New("circuit breaker is open")

type CircuitBreaker struct {
	mu            sync.Mutex
	state         State
	failures      int
	maxFailures   int
	lastFailure   time.Time
	recoveryDelay time.Duration
}

func New(maxFailures int, recoveryDelay time.Duration) *CircuitBreaker {
	return &CircuitBreaker{
		maxFailures:   maxFailures,
		recoveryDelay: recoveryDelay,
	}
}

func (cb *CircuitBreaker) Allow() error {
	cb.mu.Lock()
	defer cb.mu.Unlock()

	switch cb.state {
	case StateOpen:
		if time.Since(cb.lastFailure) > cb.recoveryDelay {
			cb.state = StateHalfOpen
			return nil
		}
		return ErrCircuitOpen
	case StateHalfOpen:
		return nil
	default:
		return nil
	}
}

func (cb *CircuitBreaker) RecordSuccess() {
	cb.mu.Lock()
	defer cb.mu.Unlock()
	cb.failures = 0
	cb.state = StateClosed
}

func (cb *CircuitBreaker) RecordFailure() {
	cb.mu.Lock()
	defer cb.mu.Unlock()
	cb.failures++
	cb.lastFailure = time.Now()
	if cb.failures >= cb.maxFailures {
		cb.state = StateOpen
	}
}

In production, it is recommended to use the battle-tested github.com/sony/gobreaker library, which supports sliding windows, half-open state with a configurable number of probes, and thread-safe counters.

Failover Strategies and Health Monitoring

The Go service should periodically check cluster health and remove unavailable nodes from the pool:

package health

import (
	"context"
	"log"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
)

func MonitorCluster(ctx context.Context, es *elasticsearch.Client, interval time.Duration) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			res, err := es.Cluster.Health(
				es.Cluster.Health.WithContext(ctx),
				es.Cluster.Health.WithTimeout("3s"),
			)
			if err != nil {
				log.Printf("[ERROR] cluster health check failed: %v", err)
				continue
			}
			defer res.Body.Close()

			if res.IsError() {
				log.Printf("[WARN] cluster health returned: %s", res.Status())
			} else {
				// Parse status and send to metrics (Prometheus)
				log.Printf("[INFO] cluster health: %s", res.Status())
			}
		}
	}
}

Metrics to monitor in Prometheus: number of active shards, relocating shards (indicator of rebalancing), unassigned shards (indicator of data loss), query latency p99, rejected threads in thread pool.

Practical Example: Bulk Indexing and Search with Routing

Bulk Indexing via the Bulk API

The Bulk API is the primary tool for high-performance indexing. Optimal batch size: 5–15 MB of uncompressed data or 500–5,000 documents (depending on document size). Exceeding 15 MB yields no throughput gain and increases latency.

package indexer

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/elastic/go-elasticsearch/v8"
)

type BulkIndexer struct {
	es        *elasticsearch.Client
	indexName string
	batchSize int
}

func NewBulkIndexer(es *elasticsearch.Client, index string, batchSize int) *BulkIndexer {
	return &BulkIndexer{es: es, indexName: index, batchSize: batchSize}
}

func (bi *BulkIndexer) IndexBatch(ctx context.Context, docs []Document) error {
	var buf bytes.Buffer

	for _, doc := range docs {
		// Action line with routing
		meta := map[string]interface{}{
			"index": map[string]interface{}{
				"_index":   bi.indexName,
				"_id":      doc.ID,
				"routing": doc.TenantID,
			},
		}
		metaLine, _ := json.Marshal(meta)
		buf.Write(metaLine)
		buf.WriteByte('\n')

		// Document line
		docLine, _ := json.Marshal(doc)
		buf.Write(docLine)
		buf.WriteByte('\n')
	}

	res, err := bi.es.Bulk(
		bytes.NewReader(buf.Bytes()),
		bi.es.Bulk.WithContext(ctx),
		bi.es.Bulk.WithIndex(bi.indexName),
		bi.es.Bulk.WithRefresh("false"),
	)
	if err != nil {
		return fmt.Errorf("bulk request: %w", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return fmt.Errorf("bulk error: %s", res.String())
	}

	// Check for errors at the individual document level
	var bulkResponse struct {
		Errors bool `json:"errors"`
		Items  []map[string]map[string]interface{} `json:"items"`
	}
	if err := json.NewDecoder(res.Body).Decode(&bulkResponse); err != nil {
		return fmt.Errorf("decode bulk response: %w", err)
	}
	if bulkResponse.Errors {
		var failed []string
		for _, item := range bulkResponse.Items {
			if idx, ok := item["index"]; ok {
				if status, ok := idx["status"].(float64); ok && status >= 400 {
					failed = append(failed, fmt.Sprintf("%v", idx["_id"]))
				}
			}
		}
		return fmt.Errorf("bulk partial failure, failed IDs: %s", strings.Join(failed, ", "))
	}
	return nil
}

Performance and Benchmarks

Real-World Numbers

Based on typical production configurations (cluster of 6 data nodes, 16 vCPU / 64 GB RAM each, NVMe SSD, index of 150 million documents, average document size 2 KB):

  • Bulk indexing without routing: ~80,000–100,000 docs/s with a batch of 1,000 documents and 8 parallel goroutines.
  • Bulk indexing with custom routing: ~75,000–95,000 docs/s (slight reduction due to routing hash computation).
  • Targeted search query (with routing): p50 = 8 ms, p99 = 45 ms — the query hits 1–3 of the 12 shards.
  • Scatter-gather search (without routing): p50 = 35 ms, p99 = 180 ms — the query fans out across all 12 shards.

Thus, custom routing delivers a 4–5× latency improvement at p99 for search. This is especially critical at high RPS, where scatter-gather creates significant fan-out on data nodes.

Key Performance Settings

  • index.refresh_interval: 30s — increasing the refresh interval reduces CPU load during intensive indexing.
  • index.translog.durability: async — asynchronous translog fsync increases throughput at the cost of a small risk of data loss on a sudden node failure.
  • indices.memory.index_buffer_size: 20% — increasing the indexing buffer (default is 10%) speeds up bulk operations.
  • Thread pool tuning: thread_pool.write.queue_size: 1000 prevents rejected requests during short-lived load spikes.

Summary and Recommendations

Building a distributed full-text search system with Go and Elasticsearch requires attention to detail at every layer of the stack. Key recommendations:

  1. Design sharding up front. Changing the number of primary shards after index creation is a costly operation. Use routing_partition_size to balance hot shards in multi-tenant scenarios.
  2. Use custom routing wherever a natural partition key exists — tenant ID, category, region. A 4–5× latency gain at p99 is well worth the added complexity.
  3. Separate coordinating and data nodes in production. This reduces the risk of OOM on data nodes during heavy aggregations and simplifies scaling.
  4. Implement a circuit breaker at the Go service level. The client's built-in retry logic does not protect against cascading failures under systemic overload.
  5. Monitor unassigned shards and thread pool rejections as early warning indicators — they appear before latency starts to degrade.
  6. Optimize bulk indexing: batch size 5–15 MB, 4–8 parallel goroutines, refresh_interval: 30s during bulk loads.

The combination of Go and Elasticsearch in 2026 remains one of the most performant and operationally mature solutions for building distributed search. Go provides predictable latency and minimal overhead; Elasticsearch offers a time-tested distributed model. Applying custom routing and proper sharding correctly allows you to build systems that scale linearly to hundreds of millions of documents without performance degradation.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →