---
title: "Declare replica placement and spread leaders across racks"
description: "Tell monedula-gitops that a broker placement constraint decides replication, and keep each topic's preferred leaders spread across the racks you list."
url: https://monedula.dev/flock/docs/gitops/how-to/spread-leaders-across-racks/
---

On Confluent Server with a default placement constraint, such as a 2.5 data center layout, the constraint decides how many replicas a topic has and where they sit. It also puts the preferred leader of every partition in the rack the constraint lists first. `replicaPlacement` stops monedula-gitops from sending a replication factor to such a cluster, and `leaderDistribution` spreads the preferred leaders across the racks you name.

## Before you start

- monedula-gitops 1.2.0 or later; 1.3.0 for a constraint declared as JSON and for `rebalance-leaders`.
- Confluent Server brokers that set `confluent.log.placement.constraints` and `broker.rack`. In KRaft the controllers set the constraint too.
- For leader distribution, a principal with `Alter` on the `Cluster` resource.

## Steps

### 1. Declare the placement constraint

```yaml
apiVersion: gitops.monedula.dev/v1alpha1
kind: KafkaCluster
metadata:
  name: prod-mrc
spec:
  bootstrapServers: kafka-dc1.example.com:9092,kafka-dc2.example.com:9092
  defaults:
    replicaPlacement:
      constraints: BrokerDefault
```

`BrokerDefault` leaves the constraint to the brokers. From 1.3.0, `constraints` also takes the Confluent placement constraint itself, as JSON:

```yaml
    replicaPlacement:
      constraints: '{"version":1,"replicas":[{"count":2,"constraints":{"rack":"dc1"}},{"count":2,"constraints":{"rack":"dc2"}}]}'
```

monedula-gitops then sets it as `confluent.placement.constraints` on every `KafkaTopic` of the cluster that does not set its own, so the topics it creates get that placement. It does not change the brokers' own default, and mirror topics get no constraint. `validate` checks the constraint, and every rack in `leaderDistribution.racks` must be the rack of one of its replica groups. The CRD checks only the length of the value, so in the operator a constraint that cannot be used shows as `ValidationFailed` on each `KafkaTopic` of the cluster.

With either form, monedula-gitops never sends a replication factor to the cluster, because an explicit replication factor bypasses the constraint:

- `defaults.replicationFactor` on the same cluster is a validation error.
- `spec.replicationFactor` on a `KafkaTopic` or `KafkaMirrorTopic` of the cluster is a validation error. In the operator the resource reports `ValidationFailed` and is not reconciled until the field is removed.
- `import cluster` leaves the replication factor out of the manifests it writes.

### 2. List the racks that share leadership

```yaml
    replicaPlacement:
      constraints: BrokerDefault
      leaderDistribution:
        racks: [dc1, dc2]
        settleTime: 30m
```

- **`racks`** are `broker.rack` values, at least two and all distinct. Leave out a rack that holds only observers or a tiebreaker.
- **`settleTime`** (default `30m`) is used by the operator only, see step 5. It takes the units `ns`, `us`, `ms`, `s`, `m` and `h`, as in `45m` or `1h30m`; zero is written `0s`.

A topic is balanced when the number of preferred leaders per listed rack differs by at most one. To balance it, monedula-gitops reorders the replicas within a partition and runs a preferred leader election. It never changes which brokers hold a partition, so no data moves. Observers keep their position and never become leaders.

### 3. Check the racks and the permission with doctor

```bash
monedula-gitops doctor --cluster-config-file ./clusters/prod-mrc.yaml
```

The [`leader-distribution` check](/flock/docs/gitops/how-to/check-connectivity-with-doctor/) fails when a listed rack has no broker or the principal may not `Alter` the cluster. The `replica-placement` check fails when a rack has fewer brokers than a constraint declared as JSON asks of it.

### 4. Apply

`apply` spreads the leaders of each topic it creates or adds partitions to, after the changes themselves, and prints one line per topic:

```text
leader distribution: topic orders: corrected 3 partition(s) (dc1=3 dc2=3)
```

The line reads `balanced`, `corrected`, `skipped` with a reason, `deferred` when the topic has a reassignment in flight, or `failed`. A skip or a failure here does not change the exit code of `apply`.

`diff`, `verify` and `apply` report any other declared topic with skewed leaders as the finding `LeaderDistributionSkewed`, with the count per rack and the number of partitions to flip. The finding is informational: it changes no exit code, and these commands do not correct such a topic. When the cluster-wide reads for this report fail, the report is skipped with a warning.

### 5. Let the operator keep the leaders spread

The operator checks every `KafkaTopic` of the cluster at each [resync](/flock/docs/gitops/how-to/configure-the-operator/#reconciliation) and corrects a skew when all of these hold:

- The skew has lasted `settleTime`. A reassignment in flight on the topic restarts that time, so Self-Balancing Clusters finishes first.
- The topic's [reconciliation mode](/flock/docs/gitops/concepts/drift-and-reconciliation/) is `Enforce` and its `Ready` condition is `True`.
- Fewer than three corrections of the topic lie within the last 24 hours.

When the preferred leaders are balanced but a partition is led by another replica, the operator runs the election at once, one attempt per resync.

The `LeaderDistribution` condition carries the result. It never changes `Ready`, and a failure in this step never fails the topic's reconcile.

| Reason | Status | Meaning |
| --- | --- | --- |
| `Balanced` | `True` | The preferred leaders are spread. |
| `Corrected` | `True` | This pass reordered replicas and ran the election. |
| `Skewed` | `False` | Waiting for `settleTime` or for a reassignment to finish, or the topic is not in `Enforce` mode or not `Ready`. |
| `Contested` | `False` | Three corrections lie within 24 hours, so something else keeps moving the leaders. Correction resumes when one of them is older than 24 hours, or when `racks` or `settleTime` change. |
| `Failed` | `False` | A read, the reorder or the election failed. The message names the cause. |
| `Skipped` | `Unknown` | The topic does not qualify; the message gives one of the reasons below. |

`status.leaderDistribution` holds the preferred leaders and current leaders per rack, the time the skew was first seen and the times of the corrections.

## Correct topics that already exist

From 1.3.0, `rebalance-leaders` runs the same reorder and election for every declared `KafkaTopic` of the cluster that exists:

```bash
monedula-gitops rebalance-leaders -f ./topics --cluster-config-file ./clusters/prod-mrc.yaml --dry-run
```

```text
leader distribution: topic orders: would correct 3 partition(s) (dc1=6 dc2=0)
leader distribution: 1 would be corrected, 0 balanced, 0 skipped, 0 deferred, 0 failed
```

Without `--dry-run` the line reads `corrected`, as in `apply`. `--topic`, which can be repeated, limits the run to the named topics. A topic that opted out, is not in `Enforce` mode or does not exist yet is skipped, and a topic with a reassignment in flight is deferred until you run the command again. The command exits 2 when a topic fails; the [command reference](/flock/docs/gitops/reference/cli/rebalance-leaders/) lists its flags.

## Change the constraint of an existing topic

From 1.3.0, a constraint that differs in meaning from the live topic's is the operation `UpdateReplicaPlacement`, for the declared constraint and for a topic's own `confluent.placement.constraints`. The form in which the broker returns a constraint is not a difference. The operation is [gated](/flock/docs/gitops/concepts/safety-gates/) like a partition increase; before 1.3.0 a topic's own constraint changed as an ordinary config key.

- **No replicas move.** Existing partitions keep their layout and new partitions follow the constraint. `verify` exits 0 afterwards, because it compares the constraint and not where the replicas are. Moving replicas is left to Confluent's rebalancing tools.
- **Leader distribution** skips the topic as `LayoutDoesNotMatchConstraint` until its partitions match the new constraint.
- **With a partition increase** in the same `apply`, the constraint is set first, so the new partitions follow it.
- **In the operator**, a topic whose change waits for approval is not `Ready`, so its leaders are not corrected either. Changing the declared constraint does this to every existing topic of the cluster until each has the annotation, which also approves partition increases.
- **Removing the declaration**, or going back to `BrokerDefault`, leaves the constraint on the topics that have it.

## Topics that are skipped

| Reason | Cause |
| --- | --- |
| `NoPlacementConstraint` | The topic has no `confluent.placement.constraints`; it was created with an explicit replication factor. |
| `InvalidPlacementConstraint` | The topic's constraint cannot be read. |
| `LayoutDoesNotMatchConstraint` | A partition's replicas or observers are not what the constraint places, for example during a reassignment. |
| `ObserversNotReported` | The constraint lists observers but the broker does not report which replicas they are. |
| `NoReplicaInRack` | A partition has no replica that can lead in one of the listed racks. |
| `ReplicaBrokerOffline` | A replica sits on a broker that is not registered. |

## Opt a topic out

```yaml
kind: KafkaTopic
spec:
  leaderDistribution:
    enabled: false
```

The CLI and the operator then leave the topic's leaders alone, and the operator sets `LeaderDistribution` to `Skipped`.

## Related

- The [KafkaCluster reference](/flock/docs/gitops/reference/resources/kafka-cluster/) lists the `replicaPlacement` fields, and the [KafkaTopic reference](/flock/docs/gitops/reference/resources/kafka-topic/) the `leaderDistribution` status.
- [Least-privilege connecting principal](/flock/docs/gitops/reference/connecting-principal-acls/) lists the other grants a topic pipeline needs.
- Runnable versions: [scenarios/27-leader-distribution](https://github.com/monedula-dev/monedula-gitops/tree/main/scenarios/27-leader-distribution), [28-leader-distribution-observers](https://github.com/monedula-dev/monedula-gitops/tree/main/scenarios/28-leader-distribution-observers) [29-leader-skew-report](https://github.com/monedula-dev/monedula-gitops/tree/main/scenarios/29-leader-skew-report), [30-rebalance-leaders](https://github.com/monedula-dev/monedula-gitops/tree/main/scenarios/30-rebalance-leaders) and [31-declared-placement](https://github.com/monedula-dev/monedula-gitops/tree/main/scenarios/31-declared-placement), each on a four-broker Confluent Server cluster with two racks.