Design ElasticSearch (scaling, fault tolerance, Lucene ignorance)

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2024-04-24

Problem Statement

Design a horizontally scalable, fault-tolerant search and analytics system that supports full-text search, aggregations, and near real-time indexing over JSON documents. You must not rely on Lucene specifics; assume a pluggable Index Engine that exposes generic inverted-index and columnar-store capabilities.


🔶 Functional Requirements


1.Document Ingestion
•CRUD on JSON documents (index/upsert, get, delete, _bulk).
•Schema management: dynamic mapping with type inference; explicit mappings supported.
•Multi-index, aliases, routing keys, and index templates.
2.Search & Query
•Boolean queries, term/prefix/wildcard, range queries, phrase/proximity.
•Relevance ranking (BM25-like) with scoring/explain.
•Faceting/aggregations (terms, range, histogram, top-k, percentiles).
•Pagination & sorting, highlight snippets.
3.Near Real-Time (NRT)
•Index refresh interval (configurable) with read-your-refresh semantics.
•Optional write durability before refresh via commit/log flush.
4.Cluster & Multi-tenancy
•Multiple indexes, replicas per shard, cross-cluster search (optional).
•Role-based access, index-level and field-level security (coarse-grained is fine).
5.Observability & Ops
•Health/status APIs, metrics (QPS, p50/p95 latency, indexing throughput).
•Snapshots/restore, rolling upgrades, hot-warm-cold tiering, ILM (index lifecycle mgmt).


🔶 Non-Functional Requirements


•Scalability: Billions of docs; TB-scale per cluster. Linear scale in shards/replicas.
•Availability: Survive single node failures without downtime; RPO≈0, RTO<1 min.
•Latency: P50 < 50–100 ms for search; indexing p99 commit/ack < 200 ms (network dependent).
•Durability: No acknowledged write loss (write-ahead log + quorum ack).
•Consistency: Tunable: ONE | QUORUM | ALL for writes/reads (primary/replica semantics).
•Security: TLS in transit, access tokens/API keys, basic auth/OIDC pluggable.


🔶 Constraints & Assumptions


•Commodity hardware; nodes can join/leave at any time.
•Documents are immutable per version; updates = new version + old version tombstone.
•No reliance on Lucene classes; Index Engine provides:
•add(doc), delete(docId), commit(), refresh(), search(query), stats().
•Segment management abstracted behind engine.


🔶 High-Level Components (Lucene-agnostic)


1.Gateway / REST API
•Endpoints: /index/_doc, /_bulk, /_search, /_mget, /_delete_by_query, /indices/*, /_cluster/*.
2.Coordinator Node
•Parses queries, rewrites/optimizes, scatter-gather to shards, merges results, circuit-breakers.
3.Data Node
•Hosts Primary/Replica Shards.
•Shard Service: apply writes, maintain WAL, handle refresh/flush.
•Index Engine Adapter: bridges shard service ↔ pluggable engine.
4.Cluster Manager (Control Plane)
•Membership, shard assignment, leader election, cluster state dissemination.
5.Routing & Sharding
•Hash-based routing by _id or custom key → (index, shard).
•Rebalancer for shard movement, throttled.
6.Replication & Durability
•Write path: client → coordinator → primary shard → parallel replicas.
•WAL per shard; fsync policy configurable; ack policy (primary only vs quorum).
7.Search Fan-Out
•Coordinator sends query to all relevant shards (or a shard subset for DFS/scroll).
•Top-k merge (heap) and aggregation reduce (tree/streaming combine).
8.Index Lifecycle / Tiering
•Hot (fast SSD), Warm (cheaper), Cold (object store snapshot).
9.Snapshot & Restore
•Incremental, chunked to blob store (S3/GCS/HDFS).
10.Monitoring
•Metrics, tracing hooks, slow-query/index logs, autoscaling signals.


🔶 Data Model & Storage


•Index → logical namespace; Shard → physical partition (N primary, R replicas).
•Document (JSON), Mapping (field types & analyzers), Settings (shards/replicas, refresh).
•WAL/Commit Log per shard for durability.
•Segments/columnar layout hidden by engine; expose refresh()/commit() semantics only.


🔶 Core Algorithms & Flows (overview)


•Write (Index/Update/Delete):
1.Coordinator hashes routing key → target primary shard.
2.Primary appends to WAL, applies change to engine, optionally refreshes.
3.Replicates to R replicas; ack based on write consistency.
•Search:
4.Coordinator builds execution plan; scatter to shard copies (prefer local primaries or least loaded).
5.Each shard returns top-k heap + partial aggs.
6.Coordinator merges heaps (k-way) and reduces aggs; returns results.
•Rebalance/Failure:
•Cluster Manager detects failure (heartbeats). Promote replica → primary; reassign new replica; replay WAL if needed.


🔶 APIs (examples)


•PUT /{index} (settings, mappings), DELETE /{index}
•POST /{index}/_doc/{id} (write), POST /{index}/_bulk
•POST /{index}/_search (DSL: query + aggs)
•GET /_cluster/health, GET /_cat/indices, POST /_snapshot/*


🔶 Fault-Tolerance Scenarios to Handle


•Node crash during write → WAL replay on recovery; idempotent replication via operation IDs.
•Network partition → split-brain prevention via quorum/term-based primary election.
•Disk full / hot shard → backpressure, admission control, autoscaling hooks.
•Stale reads → versioning + read-from-primary when cSTRONG.


🔶 Capacity & Scaling Guidelines (what to reason about)


•Shard sizing (10–50 GB hot shards), segment counts, refresh interval trade-offs.
•Read heavy vs write heavy workloads → replicas for reads, refresh throttling for writes.
•Cache layers: query cache, filter bitset cache, fielddata/doc values memory budgets.


🔶 Evaluation Metrics


•Indexing throughput (docs/sec), search QPS, tail latency (p95/p99), refresh lag.
•Cluster recovery time, data rebalancing impact, snapshot/restore speed.
•Cost per TB and per 1k QPS.


🔶 Optional Extensions


•Cross-cluster search/replication.
•Vector similarity (ANN) as a pluggable engine.
•Per-tenant isolation (resource quotas, circuit breakers).
•Schema evolution & reindexing service.


👉 Deliverables


•Component diagram with write/search paths.
•Shard/replica placement and failover strategy.
•API contracts (request/response) and DSL outline.
•Consistency model choices and refresh/commit policies.
•Sizing & capacity plan + operational runbooks (backup, upgrades, hotfixes).


Solution

Comments