The post has been translated automatically. Original language: Russian
Technical debt is discussed either as a disaster or as something that will be thought about later. Both are incorrect. Debt is a normal tool: you take speed now in exchange for additional work later. The problem starts where no one counts the percentages. Debt can be different, and decisions are also different. A conscious duty. We know that the solution is temporary, we know why, and we know when we will return. This is the healthiest option.An unconscious duty. We did our best, and then we found out what was better. He learns by experience, but is not treated by discipline.Debt from changed requirements. The code was correct for the previous task. It's not anyone's fault, but you'll have to rewrite it anyway.Debt from negligence. They knew how to do it, they did it differently, they didn't write it down. The only type who is not justified by anything.It is useless to mix them in one conversation: the first type is planned, the second trains the team, the third is inevitable, and the fourth needs to be stopped by the process. How to understand that debt has become expensive The evaluation of simple tasks began to grow. A change in one place requires edits in the other three. There are sections of the code that no one but one person wants to touch. Bugfixes regularly lead to new bugs.Onboarding a new developer takes weeks instead of days. The team increasingly responds, "it's easier to rewrite than to fix." The third and fifth signs are the most significant. They mean that no one has the whole system in their head anymore. What really worksWrite down the debt in the same place where the tasks live, and not in a separate forgotten document. An unfixed debt becomes folklore after six months. Link refactoring to tasks that are already included in this code. A separate "sprint for technical debt" almost always loses the fight against priorities. Formulate the cost in the language of business. Not "bad architecture", but "each new integration takes three weeks instead of three days". Distinguish between debt in hot and dead areas. The perfect code in a module that no one has touched for two years is not needed by anyone. To agree that part of the debt remains forever. Giving it all back is also a form of perfectionism. The main idea It is not the duty itself that is dangerous, but its invisibility. A team that knows where its corners are cut and how much it costs manages the situation. The team that finds out about this at the moment of production failure only reacts. And how do you record the technical debt: in the backlog, in the comments to the code, or is it based on the memory of the team?
Когда сервис падает, первый вопрос звучит просто: что происходит. Ответить на него быстро получается только у тех, кто заранее решил, где искать. Три инструмента отвечают на три разных вопроса, и путать их дорого.
Кто за что отвечает
Метрики отвечают на вопрос «что-то не так и насколько». Это числа во времени: количество запросов, время ответа, доля ошибок, загрузка ресурсов. Дешёвые в хранении, удобны для графиков и алертов, но не объясняют причину. Логи отвечают на вопрос «что именно произошло с этим запросом». Подробные записи о событиях. Незаменимы при разборе конкретного случая, но дороги в хранении и плохо подходят для поиска закономерностей. Трейсы отвечают на вопрос «где потерялось время». Путь одного запроса через все сервисы с длительностью каждого шага. Без них в распределённой системе поиск узкого места превращается в перебор. Типичная ошибка это попытка закрыть все три задачи логами. Работает, пока сервисов два, и перестаёт работать, когда их десять.
Что делает логи полезными
Структурированный формат вместо свободного текста. JSON с полями ищется и фильтруется, строка «ошибка при обработке» не ищется никак. Идентификатор запроса, который проходит через все сервисы. Без него связать записи из разных мест почти невозможно. Уровни, используемые по назначению. Если весь код пишет в INFO, уровни бесполезны. Если всё в ERROR, алерты перестают читать. Отсутствие персональных данных и токенов. Логи попадают в поиск, бэкапы и на экраны, и это отдельный риск. Разумный объём. Лог на каждую итерацию цикла это не наблюдаемость, а способ не найти ничего.
Про метрики и перцентили
Среднее время ответа скрывает почти всё интересное. При среднем в 200 мс девяносто девятый перцентиль может быть шесть секунд, и именно эти пользователи пишут в поддержку. Смотреть стоит на p50, p95 и p99 вместе: разрыв между ними показывает, стабилен сервис или работает рывками.
Простое правило порядка действий
Метрика показала проблему, трейс показал, в каком сервисе она, лог показал, что конкретно пошло не так. Начинать с логов это самый долгий путь. Отдельно стоит сказать про алерты. Алерт должен означать, что нужно что-то сделать. Уведомления, на которые никто не реагирует, обучают команду игнорировать и те, что действительно важны. А с чего вы обычно начинаете разбор инцидента: с графиков или сразу идёте в логи?