> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# ON CLUSTER queries fail after replacing a failed replica

> After a replica is lost and replaced, ON CLUSTER queries time out or fail on the new host. Update the cluster definition, recreate the tables on the new host and drop the lost replica.

An [`ON CLUSTER`](https://clickhouse.com/docs/reference/statements/distributed-ddl) query is written to a queue in ClickHouse Keeper together with the list of hosts that the cluster definition contains at that moment. Each of these hosts executes the query, and the server that received it waits for all of them. After a replica of a self-managed cluster is lost and replaced, this causes two different failures:

* While the lost host is still in the cluster definition, every `ON CLUSTER` query waits for it and ends with `TIMEOUT_EXCEEDED`.
* The replacement host starts without databases and tables, and the queue does not create them for it. `ON CLUSTER` queries that touch existing tables then fail on this host.

To fix both, update the cluster definition on all servers, recreate the schema on the new host, and drop the lost replica from the replicated tables.

The examples use the cluster `my_cluster` with one shard, the lost host `host-3` with the replica name `replica_3`, and its replacement `host-4`.

## The query times out

```sql theme={null}
ALTER TABLE db.events ON CLUSTER my_cluster ADD COLUMN level String;
```

```text theme={null}
Code: 159. DB::Exception: Distributed DDL task /clickhouse/task_queue/ddl/query-0000000042 is not finished on 1 of 3 hosts (0 of them are currently executing the task, 0 are inactive). They are going to execute the query in background. Was waiting for ... seconds, which is longer than distributed_ddl_task_timeout. (TIMEOUT_EXCEEDED)
```

The hosts that are up have executed the query. Only the wait failed: the server waited [`distributed_ddl_task_timeout`](https://clickhouse.com/docs/reference/settings/session-settings/distributed-ddl#distributed_ddl_task_timeout) seconds (180 by default) for a host that will never answer.

Remove the lost host from `remote_servers` in the configuration of every server, or replace it with the new host. Cluster definitions are reloaded without a restart, and all servers must have the same one. Check the result on each server:

```sql theme={null}
SELECT cluster, shard_num, replica_num, host_name, port
FROM system.clusters
WHERE cluster = 'my_cluster'
ORDER BY shard_num, replica_num;
```

If you have to run `ON CLUSTER` queries before the configuration is fixed, change [`distributed_ddl_output_mode`](https://clickhouse.com/docs/reference/settings/session-settings/distributed-ddl#distributed_ddl_output_mode) for the session. With `null_status_on_timeout` the query returns a `NULL` status for the unfinished host instead of an exception, and with `throw_only_active` it does not wait for hosts that are offline.

## The query fails on the replacement host

Once the new host is part of the cluster definition, the same `ALTER TABLE ... ON CLUSTER` query reaches it and fails there, because the host has no such database or table yet:

```text theme={null}
Code: 81. DB::Exception: There was an error on [host-4:9000]: Code: 81. DB::Exception: Database db does not exist. (UNKNOWN_DATABASE) ...
```

The other hosts have executed the query. The queue of `ON CLUSTER` queries does not bring a new host up to date, because every entry is addressed to the hosts that were in the cluster definition when the query was issued:

* A replacement with a new host name is not listed in the existing entries and skips them.
* A replacement that reuses the host name and port of the lost host executes only the entries that the lost host did not finish and that are still in the queue. Entries are removed when they are older than `task_max_lifetime` (7 days by default) or when the queue holds more than `max_tasks_in_queue` entries (1000 by default), see [`distributed_ddl`](https://clickhouse.com/docs/reference/settings/server-settings/settings/distributed-ddl#distributed_ddl).

In both cases the databases and tables that existed before the failure are missing on the new host. Create them there with the same statements, without `ON CLUSTER`. Take the definitions from a healthy replica with `SHOW CREATE TABLE`. For a `ReplicatedMergeTree` table:

* Use the same path in ClickHouse Keeper as the other replicas and a replica name that is not registered for this table. If the engine arguments contain the `{shard}` and `{replica}` macros, define the macros in the configuration of the new host and keep the statement unchanged.
* If the path contains the `{uuid}` macro, the table must have the same UUID on all replicas. `SHOW CREATE TABLE db.events SETTINGS show_table_uuid_in_table_create_query_if_not_nil = 1` prints the definition with its `UUID` clause.

After the `CREATE TABLE`, the new replica copies the data from the other replicas by itself.

If the new host keeps the replica name of the lost one, the `CREATE TABLE` fails as long as the lost replica is registered:

```text theme={null}
Code: 253. DB::Exception: Replica /clickhouse/tables/01/db/events/replicas/replica_3 already exists. (REPLICA_ALREADY_EXISTS)
```

Either drop the lost replica first, as described in the next section, or restore the replica under its old name as described in [How to restore a replica after storage failure](https://clickhouse.com/docs/resources/support-center/knowledge-base/troubleshooting/restore-replica-after-storage-failure.md) and [Recovery after complete data loss](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/replication.md#recovery-after-complete-data-loss).

## Drop the lost replica

The lost replica is still registered in ClickHouse Keeper for every replicated table. On a healthy replica, `system.replicas` shows it as inactive:

```sql theme={null}
SELECT database, table, replica_name, replica_is_active
FROM system.replicas
WHERE database = 'db';
```

In the `replica_is_active` map the lost replica has the value `0`. Remove it with [`SYSTEM DROP REPLICA`](https://clickhouse.com/docs/reference/statements/system#drop-replica), run on a healthy replica:

```sql theme={null}
SYSTEM DROP REPLICA 'replica_3' FROM TABLE db.events;
```

`SYSTEM DROP REPLICA 'replica_3' FROM DATABASE db` does the same for all replicated tables of a database, and without a `FROM` clause for all replicated tables of the server. The statement works on an attached table, removes only an inactive replica, and never touches local data.

## Entries left in the queue

The queries that were issued while the host was down stay in the queue as unfinished for that host. [`system.distributed_ddl_queue`](https://clickhouse.com/docs/reference/system-tables/distributed_ddl_queue) lists them:

```sql theme={null}
SELECT entry, host, port, status, exception_code, query
FROM system.distributed_ddl_queue
WHERE status != 'Finished'
ORDER BY entry, host;
```

A host that never executed an entry has the status `Inactive`. These rows need no cleanup: the other hosts do not wait for them, and the entries are removed automatically as described above.

## If a host does not get past a queue entry

A host works through the queue in order. If its DDL worker fails on an entry with an unexpected error, it writes `Unexpected error (N times in a row), will try to restart main thread` to the server log, waits and starts again, so the entries after that one are not executed on this host and `ON CLUSTER` queries time out there. The preceding `DDLWorker` messages (`Checking task query-...`) show the entry.

1. Fix the cause named in the error message if you can.
2. Since ClickHouse 26.2, [`SYSTEM RESET DDL WORKER`](https://clickhouse.com/docs/reference/statements/system#reset-ddl-worker) makes the worker of a host forget its state and read the queue again.
3. As the last resort, if an entry can never be processed, remove it from ClickHouse Keeper with [`clickhouse-keeper-client`](https://clickhouse.com/docs/concepts/features/tools-and-utilities/clickhouse-keeper-client):

```bash theme={null}
clickhouse-keeper-client -h localhost -p 9181 -q "rmr '/clickhouse/task_queue/ddl/query-0000000042'"
```

> [!WARNING]
>
> A removed entry is gone for every host. Hosts that have not executed it yet will never execute it, so first check in `system.distributed_ddl_queue` which hosts are unfinished, and afterwards run the statement of the entry on those hosts yourself if it is still needed.

## Related pages

* [Distributed DDL queries (`ON CLUSTER`)](https://clickhouse.com/docs/reference/statements/distributed-ddl)
* [Data replication](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/replication.md)
* [How to restore a replica after storage failure](https://clickhouse.com/docs/resources/support-center/knowledge-base/troubleshooting/restore-replica-after-storage-failure.md)
