# Logic behind Rebalancing of primary and replicas

**URL:** <https://discuss.elastic.co/t/logic-behind-rebalancing-of-primary-and-replicas/24649>\
**Category:** Elasticsearch\
**Created:** [June 30, 2015, 5:37pm UTC](https://discuss.elastic.co/t/logic-behind-rebalancing-of-primary-and-replicas/24649 "2015-06-30T17:37:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bbhatia](https://avatars.discourse-cdn.com/v4/letter/b/71c47a/32.png) [@bbhatia](https://discuss.elastic.co/u/bbhatia)\
**Post date:** [June 30, 2015, 5:37pm UTC](https://discuss.elastic.co/t/logic-behind-rebalancing-of-primary-and-replicas/24649/1 "2015-06-30T17:37:19Z")

</div>

I have been playing around with my ES cluster. Especially bringing down nodes randomly. I observe when I add the nodes back the primary and replica shards are rebalanced in some manner, I can't find the logic as in how that rebalance is made.

1. One scenario, I observed out of 5, 4 primary shards were on a single node and all replicas spread evenly across rest of the nodes.
2. Other scenario, when I added a node back, I saw primary shards were relocated, and not replica shards. I also observed that since these were primary shards, no other node/shard was promoted a primary. This would mean the writes would fail while this is happening since write can only happen in primary shard.

Whats the logic behind moving primary and replica shards across?

---

<div class="post-metadata">

**Author:** ![Jason\_Wee](https://avatars.discourse-cdn.com/v4/letter/j/7ea924/32.png) [@Jason\_Wee](https://discuss.elastic.co/u/Jason_Wee)\
**Post date:** [July 1, 2015, 11:13am UTC](https://discuss.elastic.co/t/logic-behind-rebalancing-of-primary-and-replicas/24649/2 "2015-07-01T11:13:44Z")

</div>

start with the interface contract [https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/ShardsAllocator.java](https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/ShardsAllocator.java) then see the concrete class that implement this interface... should give you a good start 😄

hth

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 6, 2017, 12:04am UTC](https://discuss.elastic.co/t/logic-behind-rebalancing-of-primary-and-replicas/24649/3 "2017-07-06T00:04:19Z")

</div>


