The post has been translated automatically. Original language: Russian
This is the third article in a series of materials on how to reanimate the monitoring system when Prometheus stops coping with the amount of data and load.
In the first part, we analyzed the root causes of problems and typical symptoms, in the second, we explored architectural options for scaling and unloading Prometheus.
The first part is here: https://astanahub.com/ru/blog/kak-spasti-monitoring-kogda-prometheus-zadykhaetsia-chast-1
The second part is here: https://astanahub.com/ru/blog/kak-spasti-monitoring-kogda-prometheus-zadykhaetsia-chast-2
Now it's time to move on to the practical stage — how to organize migration to long-term storage so as not to lose data and not disrupt alerts.
In this part, we will analyze the features of migration to Thanos, Cortex/Mimir and VictoriaMetrics — the three most common solutions that use a PromQL-compatible approach and combine well with Prometheus.
If you have already decided on the storage, the next task is to carefully plan the transfer, avoid downtime, and ensure that metrics and alerts work as reliably as before.
Thanos
The softest transition option
Thanos fits into the existing infrastructure without having to break the current Prometheus:
Prometheus continues to work as before.
A Thanos Sidecar is being raised nearby to upload two—hour TSDB blocks to object storage, for example, S3-compatible.
Historical blocks of the local TSDB also end up in the repository.
You can add a Thanos Querier, connect Grafana to it, and get a single global reading layer.
Prometheus remains the live data source, while Thanos takes over the long retention.
A practical nuance
From experience, if Grafana is connected to Thanos Querier, both long-term storage data and current metrics from Prometheus are visible. As a result, a separate datasource for Prometheus is no longer needed.
Where queries are not placed in variables, the replacement can be done through the export/import of dashboards.
Whether you will save two sources at the same time or switch to Thanos completely depends on your requirements.
Cortex / Mimir
Medium difficulty, but high flexibility
Moving to Cortex or Mimir usually looks like this:
Deploying a new storage cluster.
Setting up remote_write in Prometheus so that it sends metrics to the new storage.
Prometheus itself can be left as it is, used only for alerts, or to facilitate configuration by leaving a minimum of scrap targets.
It is not necessary to transfer old data — many companies choose the path of "accumulating a new story."
If you need the full story
For Cortex, there is a thanosconvert utility that can load Prometheus TSDB blocks into the Cortex object storage.
The process requires copying files and careful preparation, so it is not always used.
Often, the old Prometheus just keeps on living until its retention ceases to be important.
VictoriaMetrics
Moderate complexity, but simpler than Cortex/Mimir
The VM migration scenario looks something like this:
Deploying the VictoriaMetrics cluster.
Configuring Prometheus to send data via remote_write.
Optionally, we replace Prometheus with vmagent, which can scrape metrics and send them to the VM.
It is not necessary to transfer the history: you can wait until the VM accumulates its own retention, and leave the old Prometheus for a while.
How to transfer old data
VM provides a convenient vmctl tool that imports data from a Prometheus snapshot.
As an interim option, you can leave Prometheus only for alerts, and use the VM as the main storage.
The general rule of migration
Do not turn off Prometheus until you are sure that the new backend is fully synchronized and the alerts are working correctly.
Usually both systems work in parallel.: Prometheus continues to give away live metrics, and the new solution is to accumulate a long-term history.
Transferring dashboards and alerts
One of the advantages of Thanos, Cortex/Mimir, and VictoriaMetrics is that they all support PromQL. This means that:
Grafana
We are changing the datasource in Grafana to a new storage.
Most panels will continue to work without edits, as the names of the metrics and the query language are preserved.
It is important to consider:
external labels (external_labels);
tenant-ID in multiuser Cortex/Mimir systems.
It is best to temporarily keep two data sources in Grafana and test the panels in parallel.
Alerts and recording rules
As long as Prometheus is active, it can follow all the rules as before.
Most alerts use short intervals (up to an hour), so you can take your time transferring them.
If you want to transfer the rules:
Thanos provides the Ruler component.
Cortex/Mimir have HA-enabled ruler services.
You need to make sure that PromQL expressions are fully compatible, especially if non-standard functions were used.
Alertmanager does not need to be changed — it works on top of any source that provides alerts.
Transferring historical data
If access to the old history is critical, plan ahead.:
vmctl (VictoriaMetrics)
thanosconvert (Cortex)
uploading TSDB blocks to Thanos
But more often a simple strategy is chosen.:
“Starting from this date, we store data for a long time, we can leave Prometheus in the past."
How to avoid data loss during migration
1. Running in parallel
The new backend works together with Prometheus from a few hours to a full retention period. This allows you to:
check that the metric stream is coming in correctly;
make sure that there are no time interval gaps;
wait for the same history to accumulate in the new storage.
2. remote_write monitoring
Keep an eye on:
remote_write_pending_samples;
delays in sending;
possible connection errors.
When under high load, set up correctly:
batch sizes,
timeouts,
the network subsystem,
migration schedule (it is better to do it during a period of low traffic).
3. Carefully shut down Prometheus
If you decide to completely replace Prometheus:
make sure that all TSDB blocks are unloaded;
make sure that the data from the WAL has been sent and there are no "hanging" samples living only in RAM.
Even 1-2 minutes of raw data can lead to "dips" in the charts.
4. Backup
Make sure to take a snapshot before turning it off.:
in case of an error, you can upgrade Prometheus again.,
or import the data into a new storage.
Thanos, for example, allows you to connect snapshots as an additional Store source.
5. Testing on the stand
Before selling:
deploy the test stand,
check out scrape, sending metrics, dashboards, and alerts,
make sure that authentication, TLS, and multitenancy are working (if any).
This helps to identify any incompatibilities in advance.
Перед вами третья статья из серии материалов о том, как реанимировать систему мониторинга, когда Prometheus перестаёт справляться с объёмом данных и нагрузкой.
В первой части мы разобрали корневые причины проблем и типичные симптомы, во второй — изучили архитектурные варианты масштабирования и разгрузки Prometheus.
Первая часть находится здесь: https://astanahub.com/ru/blog/kak-spasti-monitoring-kogda-prometheus-zadykhaetsia-chast-1
Вторая часть находится здесь: https://astanahub.com/ru/blog/kak-spasti-monitoring-kogda-prometheus-zadykhaetsia-chast-2
Теперь пришло время перейти к практическому этапу — как организовать миграцию на долгосрочное хранилище так, чтобы не потерять данные и не нарушить работу алертов.
В этой части мы разберём особенности миграции в Thanos, Cortex/Mimir и VictoriaMetrics — три наиболее распространённых решения, которые используют совместимый с PromQL подход и хорошо комбинируются с Prometheus.
Если вы уже определились с хранилищем, следующая задача — аккуратно спланировать перенос, избежать простоев и гарантировать, что метрики и алерты будут работать так же надёжно, как раньше.
Thanos
Самый мягкий вариант перехода
Thanos вписывается в существующую инфраструктуру без необходимости ломать текущий Prometheus:
Prometheus продолжает работать как раньше.
Рядом поднимается Thanos Sidecar для выгрузки двухчасовых блоков TSDB в объектное хранилище — например, S3-совместимое.
Исторические блоки локального TSDB также попадают в хранилище.
Можно добавить Thanos Querier, подключить Grafana к нему и получить единый глобальный слой чтения.
Prometheus остаётся источником живых данных, а Thanos берёт на себя длинный retention.
Практический нюанс
По опыту, если Grafana подключена к Thanos Querier, то видны как данные длинного хранения, так и актуальные метрики из Prometheus. В результате отдельный datasource для Prometheus перестаёт быть нужным.
Где запросы не вынесены в переменные — замену можно сделать через экспорт/импорт дашбордов.
Будете ли вы сохранять два источника одновременно или полностью перейти на Thanos — зависит от ваших требований.
Cortex / Mimir
Средняя сложность, но высокая гибкость
Переезд в Cortex или Mimir обычно выглядит так:
Разворачиваем новый кластер хранения.
Настраиваем remote_write в Prometheus, чтобы он отправлял метрики в новое хранилище.
Сам Prometheus можно оставить как есть, использовать его только для алертов или облегчить конфигурацию, оставив минимум scrape-таргетов.
Старые данные переносить не обязательно — многие компании выбирают путь «накопим новую историю».
Если нужна полная история
Для Cortex существует утилита thanosconvert, которая умеет грузить TSDB-блоки Prometheus в объектное хранилище Cortex.
Процесс требует копирования файлов и аккуратной подготовки, поэтому применяется не всегда.
Зачастую старый Prometheus просто продолжает жить до тех пор, пока его retention не перестанет быть важным.
VictoriaMetrics
Умеренная сложность, но проще Cortex/Mimir
Сценарий миграции в VM выглядит примерно так:
Разворачиваем кластер VictoriaMetrics.
Настраиваем Prometheus на отправку данных через remote_write.
По желанию — заменяем Prometheus на vmagent, который умеет скрейпить метрики и отдавать их в VM.
Историю переносить необязательно: можно подождать пока VM накопит собственный retention, а старый Prometheus оставить на время.
Как перенести старые данные
VM предоставляет удобный инструмент vmctl, который импортирует данные из снапшота Prometheus.
В качестве промежуточного варианта можно оставить Prometheus только для алертов, а VM использовать как основное хранилище.
Общее правило миграции
Не выключайте Prometheus, пока не убедитесь, что новый backend полностью синхронизирован и алерты работают корректно.
Обычно обе системы работают параллельно: Prometheus продолжает отдавать live-метрики, а новое решение — накапливать долгосрочную историю.
Перенос дашбордов и алертов
Одно из преимуществ Thanos, Cortex/Mimir и VictoriaMetrics — все они поддерживают PromQL. Это значит, что:
Grafana
Меняем datasource в Grafana на новое хранилище.
Большинство панелей продолжат работать без правок, так как имена метрик и язык запросов сохраняются.
Важно учесть:
внешние лейблы (external_labels);
tenant-ID в многопользовательских системах Cortex/Mimir.
Лучше всего временно держать два источника данных в Grafana и тестировать панели параллельно.
Алерты и recording rules
Пока Prometheus активен — он может выполнять все правила как раньше.
Большинство алертов используют короткие интервалы (до часа), поэтому переноса можно не торопиться.
Если хотите перенести правила:
Thanos предоставляет компонент Ruler.
Cortex/Mimir имеют ruler-сервисы с HA-поддержкой.
Нужно удостовериться, что PromQL-выражения полностью совместимы, особенно если использовались нестандартные функции.
Alertmanager менять не нужно — он работает поверх любого источника, который предоставляет алерты.
Перенос исторических данных
Если доступ к старой истории критичен — заранее планируйте:
vmctl (VictoriaMetrics)
thanosconvert (Cortex)
выгрузку TSDB-блоков в Thanos
Но чаще выбирается простая стратегия:
“Начиная с этой даты храним данные надолго, прошлое можно оставить Prometheus’у".
Как избежать потерь данных при миграции
1. Запуск в параллели
Новый backend работает вместе с Prometheus от нескольких часов до полного периода retention. Это позволяет:
проверить, что поток метрик приходит корректно;
убедиться, что нет разрывов временных интервалов;
дождаться накопления одинаковой истории в новом хранилище.
2. Мониторинг remote_write
Следите за:
remote_write_pending_samples;
задержками отправки;
возможными ошибками подключения.
При высокой нагрузке корректно настройте:
размеры партий,
таймауты,
сетевую подсистему,
график миграции (лучше делать в период низкого трафика).
3. Аккуратное отключение Prometheus
Если решили полностью заменить Prometheus:
убедитесь, что все TSDB-блоки выгружены;
проверьте, что данные из WAL отправлены и нет «висящих» образцов, живущих только в оперативке.
Даже 1–2 минуты необработанных данных могут привести к «провалам» в графиках.
4. Резервное копирование
Перед отключением обязательно сделайте снапшот:
в случае ошибки можно поднять Prometheus заново,
либо импортировать данные в новое хранилище.
Thanos, например, позволяет подключать снапшоты как дополнительный источник Store.
5. Тестирование на стенде
Перед продом:
развёрните тестовый стенд,
проверьте scrape, отправку метрик, дашборды и алерты,
убедитесь, что работает аутентификация, TLS, multitenancy (если есть).
Это помогает заранее выявить любые несовместимости.