The post has been translated automatically. Original language: Russian
Topic
To change the database schema on an empty project is one line. Changing it on a running service with live users is a separate task, where an error costs several minutes of unavailability or lost data.
What is dangerous on large tables
Adding a column with a default value. In older versions of the DBMS, this is a rewrite of the entire table under lock. New ones are often safe, but you need to check your version.
Creating an index in the usual way. The table is locked for writing until the end of the operation. Almost everywhere there is an option with parallel construction, and it is needed.
Changing the column type. As a rule, it means a complete rewrite of the data.
Deleting or renaming a column at the same time as the code is being deployed. At the time of the rollout, some instances are running on the old version and accessing what is no longer there.
The fourth point is the most underestimated. The problem is not the migration itself, but the fact that the code and schema are not changing at the same time.
A multi-step deployment scheme
To rename a column, the sequence looks like this.
Add a new column without deleting anything.
Embed code that writes to both places and reads from the old one.
Fill in a new column for existing rows in batches rather than a single query.
Switch the reading to a new column and make sure everything is working.
Stop writing to the old one and only then delete it, in a separate release.
Five steps instead of one, but at each stage you can roll back and at no point is there an incompatibility between the code and the schema.
Rules that save nerves
Fill in data with batch files with pauses. One UPDATE of ten million rows creates a long transaction, bloats the log and interferes with the rest of the requests.
Set the timeout to lock. Migrations that couldn't take the lock quickly should drop instead of queuing up and stopping all traffic.
Check migration against copies of real data. On a test database of thousands of lines, everything is always fast.
Keep migrations reversible where possible, and know the rollback plan in advance if not.
Do not combine schema changes and logic changes in one release. If there is a problem, it will be unclear what to roll back.
The main thing
Secure migration is not about tricky SQL, but about the fact that the schema and code are always compatible in both directions. Once this condition is met, the deployment ceases to be an event that the team prepares for in the evening after the traffic.
Do you do migrations during business hours or still at night?
Два человека выгружают один и тот же показатель за один и тот же день, и числа не совпадают. Расхождение небольшое, но объяснить его никто не может. Такая история случается почти в каждой команде.
Причина редко бывает в ошибке расчёта. Обычно расходятся определения.
Первое место, где они расходятся, это состав. Один считает все заказы, другой только оплаченные. Оба правы, но говорят о разном.
Второе это момент учёта. Заказ создан вчера, а завершён сегодня. В какой день он попадает, зависит от того, какое время взяли за основу.
Третье это источник. Одна выгрузка идёт из рабочей базы, другая из хранилища для отчётов, где данные обновляются раз в час.
Четвёртое это обработка после выгрузки. Кто-то удалил тестовые записи, кто-то оставил. Кто-то округлил на промежуточном шаге.
Помогает одна простая вещь: определение показателя, записанное словами. Что считаем, за какой период, по какому времени, что исключаем. Полстраницы текста снимают большинство вопросов.
Второе, что помогает, это единый источник для отчётности. Пока каждый строит свою выгрузку самостоятельно, расхождения будут появляться снова.
И третье. Указывайте в отчёте, когда данные обновлялись. Это сразу объясняет часть различий.
А у вас определения показателей записаны в одном месте или живут в разных выгрузках?