Metadata-Version: 2.4
Name: kafka-reassign-planner
Version: 0.1.0
Summary: Plan balanced, batched Kafka partition reassignments that move as little data as possible.
Author: Narayana Vemburaj
License-Expression: MIT
Project-URL: Homepage, https://github.com/narayana006/kafka-reassign-planner
Project-URL: Source, https://github.com/narayana006/kafka-reassign-planner
Project-URL: Issues, https://github.com/narayana006/kafka-reassign-planner/issues
Project-URL: Changelog, https://github.com/narayana006/kafka-reassign-planner/releases
Keywords: kafka,apache-kafka,partition-reassignment,rebalance,capacity-planning,rack-awareness,operations,sre
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: System Administrators
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Distributed Computing
Classifier: Topic :: System :: Systems Administration
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

# kafka-reassign-planner

Plan a Kafka partition reassignment that keeps every replica it can where it already is, then hands you standard reassignment JSON in reviewable batches.

**Status:** working first version. Planning for adding brokers, removing brokers and rebalancing works from files (reassignment JSON or `kafka-topics --describe` output), with rack awareness, batching, a suggested throttle and a duration estimate. Reading the assignment live from a cluster (`--bootstrap`) is not built yet. The tool never talks to a cluster and never executes anything.

## Why

`kafka-reassign-partitions --generate` builds a new assignment from scratch and ignores where the data is today, so adding two brokers can shuffle most of the cluster. This tool starts from the current assignment and moves a replica only when it has to: because its broker is going away, because its partition is badly spread over racks, or because its broker holds more than its share.

## Install

```bash
pip install kafka-reassign-planner
```

Python 3.10 or newer, no dependencies.

## Quick start

The `examples/` directory holds a 6-broker cluster (33 partitions, 87 replicas) in three availability zones. Add brokers 7, 8 and 9:

```bash
kafka-reassign-planner \
  --assignment examples/current-assignment.json \
  --sizes examples/log-dirs.json \
  --racks examples/racks.json \
  --add-brokers 7-9 --batch-size 10 --out plan.json
```

```text
Brokers: 1,2,3,4,5,6 -> 1,2,3,4,5,6,7,8,9
Partitions: 33 (87 replicas)
Changed partitions: 14 (27 replica move(s), 0 leader-order only)
Data to copy: 718.3 GB
Round-robin from scratch would need: 57 replica moves, 2712.6 GB

Replicas per broker:
  broker    1   2   3   4   5   6   7   8   9
  before   15  14  13  14  15  16   0   0   0
  after    10  10  10  10  10  10   9   9   9
Preferred leaders per broker:
  broker    1   2   3   4   5   6   7   8   9
  before    5   5   5   6   6   6   0   0   0
  after     4   4   4   4   4   4   3   3   3

Batch 1/2: 10 partition(s), 20 replica move(s), 608.2 GB to copy
  busiest broker 6: 258.8 GB; suggested throttle 72000000 B/s (72 MB/s); estimated duration at least 1h 00m
  written to plan-01.json
Batch 2/2: 4 partition(s), 7 replica move(s), 110.1 GB to copy
  busiest broker 8: 46.4 GB; suggested throttle 13000000 B/s (13 MB/s); estimated duration at least 1h 00m
  written to plan-02.json
Rollback (current assignment of every changed partition) written to plan-rollback.json

Review the files, then run each batch yourself and wait for it to finish, e.g.:
  kafka-reassign-partitions --bootstrap-server $BOOTSTRAP --reassignment-json-file plan-01.json --execute --throttle 72000000
  kafka-reassign-partitions --bootstrap-server $BOOTSTRAP --reassignment-json-file plan-01.json --verify
```

Each batch file is the document `kafka-reassign-partitions --reassignment-json-file` expects, one partition per line. `plan-02.json` from the run above:

```json
{"version":1,"partitions":[
  {"topic":"payments","partition":2,"replicas":[7,8,9]},
  {"topic":"payments","partition":3,"replicas":[8,6,7]},
  {"topic":"payments","partition":4,"replicas":[6,1,8]},
  {"topic":"payments","partition":5,"replicas":[1,2,9]}
]}
```

Other scenarios, using the `kafka-topics --describe` text as input:

```bash
# drain broker 6 before decommissioning it
kafka-reassign-planner --assignment examples/topics-describe.txt --remove-brokers 6 --out drain.json

# level the existing brokers, with a throttle you chose yourself
kafka-reassign-planner --assignment examples/topics-describe.txt \
  --sizes examples/log-dirs.json --rebalance --throttle 30000000
```

Without `--out` the tool prints the summary and writes nothing.

## Inputs

| Option | What it takes |
| --- | --- |
| `--assignment FILE` | Required. One of: the reassignment JSON format (`{"version":1,"partitions":[{"topic":"t","partition":0,"replicas":[1,2,3]}]}`), the whole output of `kafka-reassign-partitions --generate` (the "Current partition replica assignment" block is used), or the text of `kafka-topics --describe`. `-` reads stdin. |
| `--sizes FILE` | Optional. The JSON printed by `kafka-log-dirs --describe` (the two status lines before the JSON are skipped; the largest non-future replica of each partition counts), or CSV lines `topic,partition,size_bytes`. |
| `--racks FILE` | Optional. A JSON object of broker id to rack: `{"1": "az-a", "2": "az-b"}`. This is this tool's own small format; it must cover every broker that remains in the cluster. |
| `--brokers IDS` | Optional. The full list of live brokers. By default the brokers are those that appear in the assignment, so list them here if a broker currently holds no replicas. |

Getting the inputs from a cluster:

```bash
kafka-topics --bootstrap-server $BOOTSTRAP --describe > describe.txt
kafka-log-dirs --bootstrap-server $BOOTSTRAP --describe > log-dirs.json
```

## What to change

- `--add-brokers 7,8` or `--add-brokers 7-9`: include new brokers and give them their share.
- `--remove-brokers 3`: move everything off the listed brokers.
- `--rebalance`: keep the broker set, only level it.

Add and remove can be combined to replace brokers in one plan.

## How the plan is built

1. **Evacuate.** Every replica on a broker that is leaving is given to the least loaded remaining broker (in the least used rack for that partition). The new broker takes the same position in the replica list.
2. **Fix rack spread** (only with `--racks`). A partition is considered well spread when its replica counts per rack differ by at most one across all racks. Partitions that are not are repaired by moving a replica (a follower when possible) out of the most used rack.
3. **Balance replica counts.** A replica moves from the fullest broker to the emptiest until every broker holds either the floor or the ceiling of the average. A move is only allowed if it does not worsen the partition's rack spread. When sizes are known the smallest eligible partition is moved; ties are broken to spread each topic and to leave leaders alone.
4. **Balance preferred leaders.** The first broker in a replica list is the preferred leader. Lists are reordered (no data is copied) until preferred-leader counts are level. Skip this with `--keep-leaders`.

Without racks, step 3 uses the smallest number of replica moves that can reach that balance; the test suite checks this against the theoretical minimum on random clusters.

A reorder only changes the *preferred* leader. Leadership actually moves when a preferred leader election runs (`kafka-leader-election --election-type preferred`, or automatically when `auto.leader.rebalance.enable` is on).

## Batches, throttle and duration

Changed partitions are split, in topic and partition order, into batches of at most `--batch-size` partitions (default 50) and, with `--batch-bytes`, at most that many bytes to copy. Each batch is a complete reassignment file, so you can stop between batches. A `-rollback` file with the current replicas of every changed partition is written next to them.

With `--sizes`, each batch gets a throttle and an estimate:

- The busiest broker of a batch is the one with the most bytes to receive as a new replica or to send as a leader. The sender is assumed to be the first replica of the current list.
- The suggested throttle is `busiest bytes / --target-hours` (default 1 hour), rounded up to a whole MB/s, never below `--min-throttle` (default 10 MB/s) and never above `--max-throttle` if you set one. Pass `--throttle` to use your own value instead.
- The duration is `busiest bytes / throttle`. It is a lower bound: it ignores data produced during the move, disk and network limits below the throttle, and other load.

The value is meant for `kafka-reassign-partitions --execute --throttle`, which is in bytes per second. Set it above the rate at which the moved partitions are being written, otherwise the new replicas never catch up. Run `--verify` after each batch finishes; that is also what removes the throttle.

## Features

- [x] Plans for adding, removing or rebalancing brokers
- [x] Minimises the amount of data moved
- [x] Rack-aware placement
- [x] Suggested throttle and estimated duration
- [x] Splits large plans into batches
- [x] Outputs standard reassignment JSON; it does not execute it

## Roadmap

Not built yet:

- [ ] Read the current assignment and sizes directly from a cluster (`--bootstrap`)
- [ ] Balance disk usage, not only replica counts
- [ ] Per-topic balance guarantees

## Limitations

- Input comes from files only. There is no `--bootstrap` option yet.
- Balance means replica count and preferred-leader count per broker. Disk usage is not balanced; because small partitions are moved first, new brokers tend to receive the smaller partitions.
- Each topic is spread across brokers only as a tie-breaker, not as a guarantee.
- If racks have different numbers of brokers, or a rack has too few brokers for an even spread, perfect balance may be impossible. The tool then prints a `WARNING` with the counts it reached instead of failing.
- With racks, replicas are balanced by single moves only; the result is not proven minimal in that case.
- The replication factor is never changed, and `log_dirs` entries (JBOD placement) are ignored on input and not written.
- The "round-robin from scratch" comparison uses Kafka's rack-unaware round-robin scheme with a fixed starting broker. The real `--generate` picks a random start, so its exact number differs from run to run.
- The plans have been checked by tests, not yet against a live cluster. Review the JSON before executing it.

## Development

```bash
pip install -e ".[test]"
pytest
```

The tests are mostly property checks over a few hundred random clusters: replication factor preserved, no broker twice in a replica set, nothing left on removed brokers, replica and leader counts within one, rack spread respected, and never more movement than the round-robin baseline.

## Contributing

Issues and pull requests are welcome, especially assignments where the plan is worse than you expected (attach the input files with topic names changed if needed).

Built and maintained by [Narayana Vemburaj](https://github.com/narayana006).

## License

[MIT](LICENSE)
