Previously, the order table used strings to store the amount, but now it needs to be changed to the smallest integer currency unit. This involves directly deleting the old field and adding a new field, followed by deploying the application. During rolling releases, both the old and new processes will run simultaneously: the old process will read the non-existent field, while the new process will read the data that has not yet been filled in.
Data migration security does not equal successful SQL execution. What is truly important is that, at each release stage, the running code and the database state have a valid intersection. This article assumes that applications can be rolled out incrementally, while the database retains long-term order information, and that currency information must be included.
Phase 1: Expansion Only, No Destruction
First, add the new, nullable field, such as amount_minor, while retaining the existing fields. The application continues to use the existing fields for reading, but the new version begins to write data in two formats. At this point, the data written by the old process does not include the new field, so the new read path cannot immediately require the new field to be mandatory.
ALTER TABLE orders ADD COLUMN amount_minor bigint;
The field types and conversion rules must be defined first. The minimum units for different currencies are not all the same, so it’s not appropriate to simply multiply all amounts by 100. When parsing decimals, it’s important to avoid binary floating-point errors, to clearly define the rounding strategy, and to reject any historical strings that cannot be interpreted.
Do not automatically convert historical amounts with errors into zero. Zero is a valid business value, and erroneous data should be isolated, requiring manual verification or correction. The migration log should clearly indicate which orders failed to convert and the reasons, without exposing unnecessary user data.
The amount string may contain thousands separators, currency symbols, whitespace, or historical errors. First, list the valid formats and error categories. Use a decimal point tool to convert to the appropriate currency, rejecting values that cannot be explained. Do not introduce temporary guesses into the SQL for backfilling. Different currencies require reliable rules for the minimum unit. Whether rounding is allowed should be defined by the business. When reconciling amounts, silent rounding can change the financial facts. It is important to confirm rather than pursue a full green migration.
The version of the transformation function is recorded along with the version of the backfill task, making it easier to understand how a specific order is processed according to which rule. Legitimate zero values and invalid empty strings are separated, and the default zero masking error is not used. Exception records include internal identifiers and categories, and private details are controlled for viewing on demand. The completion standards for the task include that exceptions have been resolved or explicitly isolated, not just reaching the last row of the scan pointer.
Test positive numbers, negative refund values, different currencies, the maximum value, and boundary rounding to confirm that the bigint range is sufficient. The new field has a unit semantic, and having the same type does not mean that the amounts can be directly added. The absence of a currency should also prevent conversion or enter a clear fix, and not infer the currency from the user interface language. First, maintain the business meaning, and then adjust the database storage.
Double writing is a temporary agreement
The new application maintains two fields within the same transaction, preventing one from succeeding while the other fails. If there are many sources to write to, such as the admin interface, batch processing, and third-party synchronization, they must be listed individually. Modifying only the main interface will leave behind a situation where seemingly complete data migration continues to produce old-format data.
Using database triggers to override the old write source is possible, but this introduces hidden logic and increases testing costs. Using dual writes is easier to express business transformations, while triggers are closer to a unified entry point. The choice depends on the level of control over the write path, and cannot be solely determined by the number of code lines.
The double write process requires a specified end date. Maintaining two copies of the truth values for an extended period can lead to inconsistencies, making it impossible to determine which one is correct. The migration plan should clearly outline the observation period, the conditions for switching, and the criteria for deleting old fields, rather than simply adding fields and permanently disabling them.
Cannot Chase Concurrent Writes After Backfilling
Historical data is divided into batches based on stability indicators and then backfilled. Each batch is processed within a limited set of transactions. Updating several million rows at once could hold long locks, generate a large amount of log data, and affect replication latency. Implement checkpointing to allow tasks to resume from the last completed range after a restart.
The update statements should only handle new fields that have not yet been filled, or use version conditions to avoid overwriting the values newly written by the new application. If the old application can still modify old fields, there may still be differences after the update, so it is necessary to first handle the old write source and then announce that the update is complete.
Progress on the task is not just about identifying which identifiers have been scanned; it also depends on the number of remaining empty values, the number of conversion failures, and the differences between the two fields. Even if all rows have been scanned, the presence of continuously generated new empty values cannot be considered a successful migration.
When old writes continue to exist, the rollback process only handles potential stale new values left behind by empty values. It is necessary to first establish a synchronization mechanism for old writes, or to bind the source field version during the rollback update, to avoid overwriting new application updates after reading the old amount. Database triggers can standardize boundaries, but it is necessary to test whether they duplicate or conflict with the application’s double writes. All source lists include background, import, scheduled jobs, and manual SQL, not just APIs.
Identify and record the checkpoint and affected rows for each batch, with short transactions that can be restarted. Failed batches do not advance the checkpoint; completed batches repeat execution with the same values. Monitor the rate of execution to observe lock waiting, transaction log, and replication delays. Avoid blindly opening dozens of threads. After a task is cancelled, the current transaction must have a clear result. When restoring, use the persistent state instead of the last line of the log to determine the state.
The shadow read comparison operates on business values rather than string appearances. For example, “one hundred dollars” and “one ten-thousandth” can be equivalent, but the comparison first converts them according to a defined rule. The difference statistics retain the denominator, category, and version, and the sampling logs do not output complete orders. A low overall difference rate may mask all errors in a particular currency, and it can only be detected by grouping by limited business categories.
First, observe the new reader, then switch.
The new application can perform shadow reads: the old value is still used for normal responses, while the new value is calculated and the difference is tracked. The difference records should include the order identifier and the error type, without writing the complete business payload to the logs.
Before switching, you can use controlled shadow comparison: the user still receives results from the old path, while the background reads the new values and records non-sensitive differences. Shadow reads increase the load, and setting sampling and stop conditions prevents the validation from overwhelming the main query. A zero difference only proves that the sampled data is consistent, and key types still need to be checked separately.
This is also why removing old fields cannot be done in the same release as the initial new read deployment. The compatibility window provides a window of time to identify and recover from errors, not a reason to delay the cleanup process.
When adding fields and performing continuous dual writes, the old binary often retains the old values; after stopping the writing of the old field, the old program may start normally but read outdated amounts; after deleting the old field, the old program may fail directly. The migration log clearly specifies which application version can be rolled back at each stage, and does not treat “Git can be rolled back” as a database compatibility. Rolling back the read path and rolling back the entire binary are different operations.
Before deleting a field, ensure there is sufficient observation time to confirm that old processes, offline tasks, and reports have terminated their dependencies. The feature switch can control new reads, but it cannot indefinitely maintain two separate sets of truth values. Set contract conditions with the responsible person, and simplify the code after completion. Restoring old backups also requires the corresponding application and migration path; it is not sufficient to simply test whether the backup files can be unzipped.
Before tightening constraints, verify the actual null values and anomalies. Then, validate according to the database’s supported methods. DDL locks, long transactions, and application concurrency can impact deployment. Use controlled windows and monitoring. Successful constraint validation provides data evidence, but it does not guarantee that all future write operations use the correct units. Field names with semantic meaning are helpful, but they cannot replace conversion protocols.
Requirements for a Multi-Service Compatible Window
The same field may be read by APIs, the backend, reports, exports, and external synchronization. Switching the main application process does not necessarily mean that all consumers have been updated. Create a list of consumers, recording their versions, read/write methods, and shutdown conditions. Before deleting, confirm each one individually. Auditing or observing database access can be supplemented, but lack of access does not necessarily prove that the end-of-month tasks are not dependent. Only when the execution plan is combined with actual calls can there be sufficient evidence.
After the new fields are launched, the units returned by the API must be clear. The integer “10,000” does not automatically represent “100 yuan,” and consumers need to agree on the currency and minimum unit. When the old API continues to return data in the old format, the conversion should follow the same authoritative rules to avoid rounding errors in different read paths. Versioned APIs and database migrations are related, but they are not the same release action. Independent clients may upgrade more slowly.
Fixing data migration errors also requires version control. When a batch of conversion rules is found to be incorrect, the first step is to stop the task and related new reads to identify the affected range. Then, fix it based on a reliable source. It is not possible to simply rerun all historical data and overwrite the valid new writes during the process. Record the migration task, source version, and target status to help select the precise target for fixing. Data repair requires reviewable previews and backups, and should not rely on broad updates and guesswork.
The fact that shadow reads consistently show no differences does not prove that all rare values are correct. Testing with different currencies and identifying anomalous categories remains necessary. Constraints can prevent future null values, but they cannot prove the business meaning of the values; a zero value can also legitimately come from a misconversion. Reconciliation and review of specific samples support semantic validation, while schema validation supports structural validation. Together, these two approaches determine when to enter the contract phase.
After a successful migration, remove temporary code, the “switch” and unused portions of the dual-write monitoring, while also preserving stage records. The permanent compatibility layer increases the cost of subsequent changes and makes it difficult for maintainers to determine the true values. A safe migration is not about never deleting anything, but about removing it when there is sufficient evidence, and ensuring that future users understand why the new fields can be used now.
Constraints should be tightened after data verification.
After adding non-null or other constraints to fields with null values and after clearing any existing errors, it’s important to understand the current database version’s support for phased validation and locking behavior. Do not rely on quick results from a small test environment to estimate the impact on production.
Before deleting the old field, confirm that there are no old processes, jobs, reports, or external queries that depend on it. This should be verified after observing access patterns for a period of time, followed by a clear contract phase. The backup and recovery process should also consider whether the application can read the old backup format after migration.
The operation manual records include: extending the operation, double writing, rollback, shadow reading, read switching, stopping old writes, and access conditions for deletion. It also includes check and abort conditions. If the percentage of non-empty fields reaches 100%, it is still necessary to ensure that the difference is zero and old writes are stopped to avoid only seeing a single number. In a small-scale simulation, the old and new processes are run simultaneously, along with rollback and restart, and the resources are then evaluated on representative data volumes.
The go-live report doesn’t just state that the migration was successful; it outlines the current stage, evidence, and remaining compatibility window. When an anomaly occurs, it’s important to know whether to revert to the read path or stop the rollback, to prevent administrators from accidentally deleting fields. Data migration is an ongoing process of protocol evolution, and explainable recovery is more important than the speed of a one-time script execution.
Enabling Legal Combinations of Old and New Entries in a Stage Table
Upon completion, the old process only writes the old amount, while the new process writes twice (both old and new), and the new field can still be empty. During the rollback, all old writes must be reliably synchronized or protected by versioning. After switching to the new read, the old field is maintained to allow for limited rollback. After stopping the old write, the old binary may no longer contain correct data. Finally, deleting the old read makes it completely incompatible. Listing the allowed code and data combinations for each stage in a table is more intuitive than guessing the state based on the SQL file number.
The entry conditions require concrete evidence: the number of missing fields, conversion errors, discrepancies between dual representations, and the status of old processes and jobs exiting. Successful deployment of a command at one stage does not necessarily mean that all background consumers have been updated. The recovery actions must specifically state whether to revert to read-only mode, pause the data population, or restore the compatible program. A simple git revert is not sufficient. Once the database has been reduced, old code may no longer be readable, even if it is fully present in version control.
How can concurrent updates cause incorrect re-entry?
Initially, the old value is read as ten dollars. Subsequently, the business updates the order to twelve dollars and updates the new field. Then, writing one thousand units covers the correct new value. It’s important to check the new field for emptiness only during reading, not necessarily to protect the subsequent writing. This requires atomic update conditions or reliable locking and version verification. If the source field changes, the re-calculation or skipping to the next round should be performed, and the outdated calculation should not be unconditionally written back.
After the old process is updated, it only updates the old fields, which will permanently invalidate the new values. Therefore, it is necessary to first identify all write sources. Triggers can override old writes, but when used in conjunction with application double writes, it is necessary to clearly define the authoritative direction to avoid loops or mutual overwriting. There is only one trusted definition for the transformation rule. Shadow comparison is based on business amounts, not direct equality between the old string and the new integer. When the old string format is rich, legitimate transformations and exception handling are handled separately.
The testing setup establishes synchronization points, allowing the old write, new write, and rollback operations to execute in different orders, reading the final two versions. After interrupting a batch, the checkpoint only advances to the committed range, and recovery does not skip failed records. The last line of the log is not persistent progress; transaction timeouts may also result in unknown outcomes, requiring queries to task and row status. The small-scale experiment verifies concurrency, and representative scales are used to measure the cost of logs and locks separately, without conflating the results.
Conversion rules must maintain the meaning of the amount
The currency determines the smallest unit, and precision and rounding are specified by business rules, not inferred from the user interface language. When strings contain currency symbols, thousands separators, and negative values, the allowed formats must be explicitly defined. Negative refunds may be valid, and the balance limit may differ from standard orders; absolute values or multiplication by 100 cannot be applied uniformly. bigint can store integers, but it does not automatically indicate the unit or range, which is correct from a business perspective.
Non-zero null values are not converted to zero. Values exceeding the range or an unknown currency are not filled with a default currency. Records are isolated and retain internal IDs, error categories, and rule versions, allowing for controlled manual review of necessary information. When fixing a batch of errors, the source version and task scope are used to locate the relevant data. It is not possible to re-run all old data during the update period. The reconciliation process confirms the amount and currency. The schema can only provide type and structure guarantees.
Acceptance of Shadow Reads: Coverage and Load
This section details the acceptance criteria for verifying the correct implementation of shadow reads, specifically focusing on both coverage and load.
Shadow Read adds additional database and computation work, enabling sampling and setting stop conditions. “Zero difference” only indicates that the sample coverage is consistent, and rare currencies, extreme values, and historical anomalies still require independent testing. The denominator is recorded with limited categories to avoid masking all errors of a particular currency due to a global low difference rate. The main text of private orders does not enter the log, and sufficient IDs and error categories are provided to support investigation.
When starting a new read, use a controlled range and observe the business results and recovery switch. If a new value is missing, revert according to the defined stages, and do not silently revert to zero, as this could mislead users about the actual amount. Reverting to the old field does not guarantee full compatibility with the old binary format, and other schemas and interfaces may also change. The stage table indicates the actual versions that can be rolled back, preventing a single feature switch from being misinterpreted as a complete, reversible release.
Stricter Constraints Depend on Future Protocol Writing
After historical NULL values have been cleared, if the old job can still write NULL values, the new constraints will continue to fail or the data will degrade. First, ensure that all sources use the new fields, and use the constraints as a safeguard to prevent them from masking the application’s semantic meaning. The locking and validation methods for large table DDL should be chosen based on the current PostgreSQL capabilities. Set resource limits and waiting budgets, and test small tables to ensure they complete instantly, without predicting production time.
Deleting old fields also affects reports, exports, audit scripts, and external synchronization. The short-term access logs are insufficient to prove that the end-of-month task does not exist. The consumer list is checked against the running plan. Data backup and recovery also require corresponding procedures and migration instructions. The fact that backup files can be read does not mean that the recovery site can interpret the amounts. The exercise involves rebuilding valid combinations in an isolated environment, and does not involve deleting fields in the production environment.
Read-only and replicated instances are also consumers. The primary database being repopulated does not mean that all read nodes immediately have the same state. New read switching needs to consider allowing replication latency and routing strategies. Field structure propagation and data propagation may be visible at different stages. Instead of only querying the primary database, verify the actual read path. The migration report should record read node and observation limitations. Do not use the primary database results in the console as a substitute for all interface acceptance. If financial reads require authoritative status, choose the source according to the business requirements.
Old events in the queue also represent pending consumer agreements.
All online processes have been upgraded, but the message queue still contains a batch of old-format monetary event records. When these records are re-delivered next week, consumers may again write them in the old format, or interpret the new integer values in terms of the old cent units. The migration list not only lists the current processes but also includes the event format, backlog range, and historical replay source; once the database columns have been switched, the content of the existing messages cannot be changed.
The new events explicitly carry information about the unit, currency, and protocol version. Old events are processed using validated compatibility parsers or controlled conversion paths. The creation time cannot be used to infer the format, as delays, resends, and manual re-processing can invalidate this assumption. The converted field values are then passed to a unified business write protocol, preventing the message adapter layer from introducing another independent rounding rule.
Accept and preserve synthetic events in both old and new formats. Submit them separately after switching reads, after stopping the old double-write, and after verifying that the monetary meaning is maintained and unknown versions are explicitly rejected. Before removing compatibility code, demonstrate that the supported backlog and replay range has exited the old format, or retain a separate recovery tool. This is still a pending protocol test when a real broker is not running, and does not mean that the queue has been safely cleared.
Cleaning up temporary responsibilities when closing a compatibility window
The double write, shadow comparison, rollback switch, and temporary trigger are not permanently retained. Once the contraction condition is met, the unnecessary logic is explicitly removed, and the migration phase and rules are retained for future understanding. Maintaining two copies of the truth table increases the cost of guessing when inconsistencies occur. The goal of a safe migration is to ultimately be simple, not infinitely compatible. If a legacy error has not been resolved, it cannot be considered complete if its evidence is not removed using cleanup tools.
The final report outlines the current stage, the read/write sources covered, semantic reconciliation, and the rollback scope. When performing real database competition and DDL testing, it lists the acceptance criteria that need to be executed, and confirms that the migration was performed without downtime. Maintaining compatibility between two generations of applications is an ongoing process, and the order of steps and evidence are more important than a single script run.
Acceptance with Rollback Capability
In the test environment, both the old and new write processes are run simultaneously, with continuous backfilling and switching between read and write operations. The backfilling process is interrupted midway, the task is restarted, and the application is rolled back. The process then checks for any lost amounts or silent changes in currency units. Finally, constraint tightening and the deletion of old fields are executed.
There’s also a difference in data capability compared to legacy code: new fields might allow a precision or currency that an older format couldn’t express. Even if the old columns remain, the new functionality has created irreversible mappings, and reverting the old read paths will still be corrupted. The compatibility period should limit the new representation capabilities, or explicitly reject unsupported objects with dedicated handling paths. Acceptance not only checks if the old program can start, but also verifies if it can maintain the meaning of the amounts with this new data; retaining old fields does not automatically mean retaining business rollback capabilities.