This guide provides detailed steps and best practices for migrating from Amazon DynamoDB to the PolarDB DynamoDB-compatible edition. PolarDB provides a purpose-built suite of migration tools that combines full synchronization with incremental synchronization to help you achieve a smooth data migration with minimal downtime.
Migration process overview
The migration process consists of five stages and is completed by three core tools working together: nimo-shake (data synchronization, including full synchronization and incremental synchronization), nimo-full-check (data check), and PolarDBBackSync (reverse data synchronization).
Full synchronization
Tool:
nimo-shakeProcess: The tool first automatically creates, in the target PolarDB cluster, a table schema that is consistent with the source. It then efficiently reads the full data from the source database by using concurrent
Scanoperations and writes the data to the target cluster in batches by usingBatchWriteItem. By default, data is written directly through the PostgreSQL protocol. For details, see Full synchronization in PostgreSQL direct-write mode in Step 1.
Incremental synchronization
Tool:
nimo-shakeProcess: After the full synchronization is complete, the tool automatically uses the AWS DynamoDB Streams mechanism to capture, in real time, all data changes (inserts, deletes, and updates) on the source since the migration started, and synchronizes the changes to the target cluster to ensure eventual data consistency. This process supports resumable transfer.
Consistency check
Tool:
nimo-full-checkProcess: You can run this tool at any time during or after data synchronization. The tool concurrently reads data from the source and the target, compares the data by primary key, and generates a detailed difference report to verify data integrity.
(Optional) Reverse synchronization
Tool:
PolarDBBackSync.jar(based on Realtime Compute for Apache Flink)Process: After you verify data consistency, you can create a reverse synchronization link from PolarDB for PostgreSQL to the source DynamoDB to ensure data integrity if you need to roll back your business. Based on Flink, the tool captures the changed data of the source PolarDB in real time, and calls the PutItem or DeleteItem operation of DynamoDB based on the change type to update the data in DynamoDB.
Business cutover
Process: When the incremental data latency is minimal and the consistency check reports no differences, briefly stop business writes. After all data is synchronized, switch the application connections to the PolarDB cluster to complete the migration.
Usage notes
Performance impact: The data migration process, especially the full synchronization stage, places a certain read and write load on the source database and the target database. Perform the migration during off-peak hours and evaluate the capacity of your databases in advance.
Security configuration: Before the business cutover, control the write permissions of the target PolarDB cluster and allow only the account of the data synchronization tool to write data, so as to prevent unexpected data pollution.
Preparations
Before you start the migration, make sure that you have completed the following preparations:
Obtain the toolkits:
Migration toolkit: NimoShake-20260807.zip. The package contains three migration tools:
nimo-shake,nimo-full-check, andnimo-repair.(Optional) Reverse migration toolkit: PolarDBBackSync.jar.
PolarDB cluster:
For an existing cluster or a new cluster, Enable the DynamoDB-compatible feature, Obtain the DynamoDB endpoint, and Create a dedicated DynamoDB account to obtain the credential (AccessKey) used for API access.
(Optional) Parameter settings: If you need to configure reverse synchronization, you must change the PolarDB cluster parameter
wal_leveltological. Changing this parameter requires a cluster restart, so complete this setting before you start the overall migration process.
AWS DynamoDB:
Obtain the access credential (AccessKey ID and Secret Access Key) of AWS DynamoDB.
Runtime environment: Prepare an ECS instance or another server that can connect to both the PolarDB cluster and AWS DynamoDB, so that you can run the migration toolkits.
Migration procedure
Step 1: Configure and start data synchronization
Unzip
NimoShake.zip, go to theNimoShakedirectory, and edit the shared configuration fileconf/nimo.conf. Thenimo-shake,nimo-full-check, andnimo-repairtools share this file, and each tool reads only the parameters that it can recognize. The following are the core configuration items required to start synchronization:Parameter
Description
Example value
sync_modeThe synchronization mode.
allindicates full synchronization plus incremental synchronization, andfullindicates full synchronization only.allsource.access_key_idThe AccessKey ID of the source AWS DynamoDB.
AKIAIOSFODNN7...source.secret_access_keyThe Secret Access Key of the source AWS DynamoDB.
wJalrXUtnFEMI...source.regionThe region in which the source AWS DynamoDB resides.
cn-north-1target.endpoint_urlThe DynamoDB endpoint of the target PolarDB (including the port number).
http://pe-xxx.rwlb.rds...target.access_key_idThe AccessKey of the DynamoDB account for the target PolarDB.
your-polardb-access-keytarget.secret_access_keyThe SecretKey of the DynamoDB account for the target PolarDB.
your-polardb-secret-keyfilter.collection.whiteThe allowlist used for table filtering. Separate multiple tables with
;. This parameter cannot be used together with the denylist.c1;c2filter.collection.blackThe denylist used for table filtering. Separate multiple tables with
;. This parameter cannot be used together with the allowlist.c1;c2To use the S3 snapshot-based check mode (recommended; see Step 2), you must also configure the following native PostgreSQL connection parameters:
Parameter
Description
Example value
s3.export_state_fileThe path to the export state file. This file is written by
nimo-shakeand read bynimo-full-check.../nimo-shake-s3-exports.jsons3.export_bucketThe name of the destination S3 bucket for the DynamoDB data export.
my-export-buckets3.export_prefixThe S3 path prefix used to organize the exported files.
exports/my-project/target.pg.endpoint_urlPolarDB for PostgreSQL native port address (in the
host:portformat).pc-xxx.pg.polardb.rds...:5432target.pg.userPolarDB for PostgreSQL username (which is also used as the schema name).
NoteA DynamoDB account is essentially a standard database account. Its access key (SK) is generated by encrypting the password that you set with a compatible algorithm. Therefore,
target.pg.userandtarget.access_key_idcorrespond to the same account, whereastarget.pg.passwordis your custom password and the SK is a key derived from that password.your-usernametarget.pg.passwordPolarDB for PostgreSQL password.
your-passwordtarget.pg.check_databaseThe name of the separate database that stores the incremental check tables.
During the incremental synchronization stage,
nimo-shakewrites the primary keys of changed records to the incremental check tables in this database for thes3/incrcheck modes to read. You must manually create this database before startup, andnimo-shakeandnimo-full-checkmust be configured with the same value.Notetarget.pg.check_databasepoints to a separate database that stores only the incremental check tables. Before you start synchronization, use a Privileged Account to manually create the database and set its owner to**target.pg.user**(the DynamoDB account described above). This way, the account has the permissions to create schemas and incremental check tables in the database.nimoshake_check(Optional) Full synchronization in PostgreSQL direct-write mode
By default, full synchronization uses the native PostgreSQL direct-write mode to write data directly to PolarDB through the standard PostgreSQL protocol, bypassing the DynamoDB compatibility layer API for higher performance. To fall back to the DynamoDB layer API (
BatchWriteItem, which writes a maximum of 25 items at a time), you can manually change this parameter todynamodb. Configure the following parameters in theconf/nimo.conffile, in the[SHAKE]section:Parameter
Description
Default value
full.write_protocolThe protocol used for full writes.
postgresql(default): the PostgreSQL direct-write high-performance mode.dynamodb: the DynamoDB layer API (BatchWriteItem, with a maximum of 25 items per batch).
postgresqlfull.document.write.batchThe number of documents to write in each batch. In PostgreSQL direct-write mode, the batch size is not limited to 25 documents, so you can increase this value to further improve write throughput. If you switch back to the
dynamodbprotocol, change this value back to 25.1000full.document.concurrencyThe number of concurrent write threads per table. In PostgreSQL direct-write mode, the tool automatically sets the connection pool size based on this value to ensure a one-to-one correspondence between threads and connections.
4NotePostgreSQL direct-write mode also requires you to configure the four
target.pg.*parameters. They share the same set of configurations with thes3/incrcheck modes, so you do not need to enter them again.This mode affects only the write path during the full synchronization stage. Incremental synchronization always writes data through the DynamoDB compatibility layer API.
(Optional) Stream Buffer protection for long-running full synchronization
AWS DynamoDB Streams retains change records for only 24 hours. If the source table has a large data volume and the full synchronization is estimated to take longer than 24 hours, AWS automatically discards incremental changes that remain in Streams for more than 24 hours, which causes data loss in incremental synchronization. To address this, you can enable Stream Buffer. From the start of full synchronization, the incremental listener writes Streams change records to a local buffer on disk in real time, bypassing the 24-hour retention limit. After the full synchronization is complete, the changes are consumed and replayed from the local buffer to ensure that no change is lost. This feature is disabled by default. Enable it only when the estimated full synchronization duration approaches or exceeds 24 hours. Configure the following parameters in
conf/nimo.conf:Parameter
Description
Default value
incr.stream_buffer.enableThe master switch of Stream Buffer.
falseincr.stream_buffer.dirThe buffer file directory. If you leave this parameter empty, the directory defaults to the same level as the checkpoint (
<workdir>/<id>-buffer).Empty
incr.stream_buffer.max_seg_size_mbThe maximum size of a single buffer segment file, in MB. The segment is rotated when this value is exceeded.
64incr.stream_buffer.max_seg_countThe maximum number of records in a single buffer segment. The segment is rotated when this value is exceeded.
10000incr.stream_buffer.max_seg_duration_secThe time interval at which a buffer segment is forcibly rotated, in seconds.
300incr.stream_buffer.max_size_mbThe global disk quota, in MB, shared by all shards and tables (not per shard). Plan this value based on the disk space available on the machine.
51200(50 GB)incr.stream_buffer.quota_backoff_secAfter the buffer exceeds the global quota, the write end logs an ERROR record every 30 seconds to prompt O&M personnel to expand the disk or accelerate the full synchronization. After
quota_backoff_secseconds elapse, the synchronization program automatically terminates.1800You can roughly estimate the disk capacity by using the following empirical formula:
Required disk (MB) ≈ Full synchronization duration (seconds) × Peak writes (records/second) × (Average bytes per record / 3) / 1MB × 1.5. Always reserve more disk space than you need rather than less.During full synchronization, the read end does not consume the buffer. Therefore, once the buffer exceeds
max_size_mb, it cannot drain itself. In this case, the process crashes after the backoff. You must expand the disk or improve the full synchronization speed before you restart the process.
Select the binary file that corresponds to your operating system architecture to start the synchronization task.
Note(Recommended) Run the task in the background with
nohupto prevent the synchronization task from being interrupted when the terminal service is disconnected.# Run this command in the NimoShake directory nohup ./bin/nimo-shake.linux.amd64 -conf=./conf/nimo.conf > /dev/null 2>&1 &The program first performs the full synchronization. After the full synchronization is complete, the program automatically switches to the incremental synchronization stage and continues to run.
Step 2: Perform data consistency checks
nimo-full-checkandnimo-shakeshare the sameconf/nimo.conffile, so you do not need to switch directories or edit additional configuration files. Use themodeparameter to select a check mode:scan: scans and compares the source and target data in real time. This mode is the simplest to configure and requires no additional infrastructure, but it continuously consumes DynamoDB read quota during the check.s3(recommended): When the full synchronization is complete,nimo-shakeautomatically exports the source data to S3 and generates a point-in-time snapshot.nimo-full-checkuses this snapshot as the baseline for the check, so the source DynamoDB does not need to be scanned again. You must configure the S3-related parameters in Step 1.incr(used together with the s3 mode): During the incremental synchronization stage,nimo-shakewrites the primary key of each changed record to the incremental check table in PolarDB (ct_{user}_{table}).nimo-full-checkreads the incremental check table and performs a targeted check only on the records that have changed.Comparison of the two check methods
scan mode
s3 / incr mode
Required downtime
Longer. Business writes must be stopped during the check to prevent the source data from changing while the scan is in progress.
Shorter. The check is based on a snapshot. After writes are stopped, you only need to confirm that the incremental data has caught up before the cutover.
Impact on the source
Continuously consumes DynamoDB read quota.
The full check is based on an S3 snapshot and does not consume DynamoDB quota. The incremental check (incr mode) queries only the records that have changed, which consumes less quota.
Configuration complexity
Low.
Higher. It requires additional configuration for S3 and PolarDB for PostgreSQL connections.
(Optional) Continuous incremental check (drain mode, disabled by default): By default, the
incrmode checks, in one pass, all change records accumulated in the incremental check table within the cutover downtime window. When incremental synchronization runs for a long period (hours to days), the incremental check table accumulates many primary keys to be checked, which makes the final check at cutover time-consuming. After you enable continuous incremental check (drain),nimo-full-check mode=incrruns as a resident process: during incremental synchronization, it continuously checks and consumes the records that have been confirmed as consistent in the incremental check table, so that the incremental check table remains small before the cutover. At cutover time, only a very small number of remaining records need one final check, which significantly reduces the check time within the downtime window. This feature is disabled by default and does not affect any existing behavior. Enable it only when the incremental period is long and the cutover downtime is critical.ImportantThis switch
check_drain.enableapplies to bothnimo-shakeandnimo-full-check. The two tools share the sameconf/nimo.conffile, so a single configuration takes effect for both tools.As a best practice, before you enable this feature in the production environment, complete a full service traffic verification on a test instance.
You can configure the following parameters in
conf/nimo.conf(no modification is required by default):Parameter
Description
Default value
check_drain.enableThe master switch of continuous incremental check (drain). It applies to both
nimo-shakeandnimo-full-check.false(default) means the behavior is exactly the same as the current behavior (theincrmode runs to completion in one pass and then exits).falsecheck_drain.finalize_flag_fileThe path to the finalize sentinel file. At cutover time, O&M personnel run
touchon this file, and the resident check process then enters the final check phase in the next round, produces the authoritative difference report, and exits. This parameter is required whenenable=true.Empty
check_drain.check_qpsThe maximum number of
BatchGetItemrequests per second for the drain check (independent limits for the source and the target). This parameter limits the pressure that drain places on the source and the target, so that drain does not compete for incremental synchronization resources. You can increase this value if the check is too slow.20NoteIn addition to the parameters in the preceding table,
conf/nimo.confalso contains advanced tuning parameters such ascheck_drain.cycle_interval_sec,check_drain.settle_sleep_ms, andcheck_drain.consistent_read. In most cases, you can keep the default values. See the comments in the configuration file for their meanings.After you enable drain, the cutover stage no longer requires you to run
nimo-full-checkagain. Instead, you runtouchon the finalize sentinel file described above to trigger the resident process to finish and produce the final difference report. For details, see Perform a business cutover - Last check.incrmode: the resident process must start after thes3baseline check is complete. The rest of the check process is the same as in the default case.
Start the check task.
nohup ./bin/nimo-full-check.linux.amd64 -conf=./conf/nimo.conf > /dev/null 2>&1 &The check tool stores the detailed logs and the data difference reports in the default directories
logs/andnimo-full-check-diff/, respectively.[INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 91, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] [success: 96, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 92, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] [success: 97, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 93, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 94, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] [success: 98, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 95, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] [success: 99, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 96, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] [success: 100, fail: 0] item matches! [INFO] documentChecker[2] with table[{nimo-shake src1}] check completed. real total count: 100 [INFO] documentChecker[2] with table[{nimo-shake src1}] close executor [INFO] documentChecker[2] finishes checking table[src1] [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 97, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 98, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 99, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] [success: 100, fail: 0] item matches! [INFO] documentChecker[0] with table[{nimo-shake src2}] check completed. real total count: 100 [INFO] documentChecker[0] with table[{nimo-shake src2}] close executor [INFO] documentChecker[0] finishes checking table[src2] [INFO] all documentCheckers finish [INFO] checker finishes! [INFO] full-check completes!(Optional) Repair inconsistent data:
When data inconsistency exists between the source DynamoDB and the current PolarDB for PostgreSQL cluster, the inconsistent tables are displayed in the specified diff directory. Example:
NoteThe default diff directory is
nimo-full-check-diff. You can configure it inconf/nimo.confby using thediff_output_fileparameter.nimo-full-check-diff/ └── testtable-0 └── testtable-1Run the repair task:
nohup ./bin/nimo-repair.linux.amd64 -conf=./conf/nimo-repair.conf > /dev/null 2>&1 &
Step 3: (Optional) Configure reverse synchronization
Before the business cutover, you can configure in advance a reverse synchronization link from PolarDB for PostgreSQL to the source DynamoDB. This link is started while the business is officially switched to PolarDB, and is used to enable reverse data backflow and provide a safeguard for business rollbacks. To configure the link, follow these steps:
Environment preparation
Make sure that the PolarDB parameter
wal_levelis set tological.Create a privileged database account and grant permissions:
(Optional) If you have not created a privileged account, go to PolarDB console, and on the page of the cluster, create a privileged account.
Create a logical replication slot and a publication: Use a privileged account to connect to the
polardb_internal_dynamodbdatabase, and run the following SQL commands to create a logical replication slot, grant the replication permission to the DynamoDB Account, and finally publish a subscription that contains all tables in the database. You can then view the active status of the logical replication slot that you created.-- Create a logical replication slot. The name 'flink_slot' must be the same as the slot name specified in the subsequent Flink configuration SELECT * FROM pg_create_logical_replication_slot('flink_slot', 'pgoutput'); -- Grant the REPLICATION permission to the dedicated DynamoDB account that you created earlier -- Replace <your_dynamodb_user> with the name of your dedicated DynamoDB account ALTER ROLE <your_dynamodb_user> REPLICATION; -- Check the replication slot status. At this point, the active value of flink_slot should be f (false) SELECT * FROM pg_replication_slots;Activate and configure Flink:
Activate Realtime Compute for Apache Flink, and create a Flink workspace.
ImportantThe Flink workspace must reside in the same VPC as the PolarDB cluster.
For the Flink workspace, Public internet access so that the workspace can connect to AWS DynamoDB.
Configure the PolarDB cluster IP address allowlist:
In the Flink console, click the View Details button of the workspace, and on the Workspace Details page, obtain the CIDR Block information of the workspace.
Go to PolarDB console, and on the page of the cluster, click Add Whitelist and add the CIDR block of Flink.
Verify connectivity between the PolarDB cluster and the Flink workspace:
In the Flink console, go to the workspace and click the Network Probe icon in the upper-right corner.
Enter the PolarDB private endpoint and port of the primary node of the cluster, and then click Probe.
If a pop-up message displays Network Probe Connection Successful, the cluster allowlist is configured correctly.
Deploy a Flink job
Download the reverse synchronization tool: PolarDBBackSync.jar.
Prepare the configuration file: Create a configuration file named
application.yamlwith the following content:snapshot: mode: never source: # PolarDB primary node private endpoint hostname: pc-xxx.pg.polardb.rds.aliyuncs.com # PolarDB primary node private port port: 5432 # Name of the logical replication slot created earlier slotName: flink_slot target: # Destination AWS DynamoDB region region: cn-north-1 # (Optional) Table filtering configuration. You can declare only one of whiteTableSet and blackTableSet filter: # whiteTableSet: tables to be reverse-synchronized # blackTableSet: tables not to be reverse-synchronized whiteTableSet: blackTableSet: # Flink job checkpoint interval, in milliseconds checkpoint: interval: 3000Upload files: Go to the Flink console, find and go to the target workspace, and on the File Management page, upload
PolarDBBackSync.jarandapplication.yaml.Store credentials securely: To avoid exposing keys in plaintext, use the Variable Management feature of Flink to store sensitive information. On the Variable Management page, add the following four variables:
Variable name
Variable value
polardbusernamePolarDB DynamoDB account.
polardbpasswordPolarDB DynamoDB account original password, not the DynamoDB account secret key.
dynamodbakThe AccessKey of AWS DynamoDB.
dynamodbskThe SecretKey of AWS DynamoDB.
configfilename(Optional) The name of the additional dependency file. Default value:
application.yaml.Deploy and start the job:
Go to the Job O&M page and choose Deploy Job > JAR Job.
Enter the following main parameters and configure the other parameters based on your business environment. Then, click Deploy.
Parameter name
Value reference
Deployment Mode
Set this parameter to Stream Mode.
Deployment Name
Enter a name for the job deployment. PolarDBBackSync is used in this example.
Engine Version
Set this parameter to vvr-11.3-jdk11-flink-1.20.
JAR URI
Select the uploaded
PolarDBBackSync.jar.Entry Point Class
Set this parameter to
org.example.PolarDBCdcJob.Entry Point Main Arguments
Set this parameter to:
--polardbusername ${secret_values.polardbusername}--polardbpassword ${secret_values.polardbpassword}--dynamodbak ${secret_values.dynamodbak}--dynamodbsk ${secret_values.dynamodbsk}(Optional)
--configfilename ${secret_values.configfilename}Additional Dependency Files
Select the uploaded
application.yaml.ImportantIf your password or other parameter values contain special characters, the Flink job may fail to parse the parameters. To prevent this issue, after the job is created, go to Deployment Details > Run Parameter Configuration , click Edit, and add the following configuration to Other Configurations to prevent this type of issue:
env.java.opts: -Dconfig.disable-inline-comment=true.After the deployment succeeds, click Start > Stateless.
Verification and cleanup
Verification: After the job starts, use a privileged account to connect to the PolarDB cluster's
polardb_internal_dynamodbdatabase and runSELECT * FROM pg_replication_slots;. If theactivefield of the flink_slot replication slot changes tot(true), the Flink job is connected. You can then start importing service traffic into the PolarDB cluster.Cleanup: When reverse synchronization is no longer required, you can perform the following steps to release the related resources and reduce costs.
Realtime Compute for Apache Flink:
Stop the job: Go to the Flink console. In the target workspace, go to the Job O&M page, find the target job, and click Stop
Release the instance: Return to the Flink console, find the target workspace, and click Release Resources.
PolarDB cluster: Use a privileged account to connect to the
polardb_internal_dynamodbdatabase and run the following command to delete the logical replication slot.SELECT pg_drop_replication_slot('flink_slot');
Step 4: Perform a business cutover
After the incremental synchronization latency is low and the data consistency check reports no differences, you can plan the business cutover. When you are ready to perform the final business switch, follow these rigorous steps:
Final check: Before the planned downtime window, run the consistency check tool repeatedly until you confirm that the incremental synchronization latency is minimal and that the number of data differences has dropped to 0 or to an acceptable range.
Stop source writes: At the start of the downtime window, suspend all business applications that write data to the source AWS DynamoDB.
Wait for synchronization to complete: Observe the logs of
nimo-shaketo confirm that no new incremental data needs to be synchronized.Last check: Run the
nimo-full-checktool again to ensure that the data on the source and the target is completely consistent.NoteIf you have enabled continuous incremental check (drain mode), you do not need to start
nimo-full-checkagain in this step: the resident check process has continuously checked and consumed the incremental check table during the incremental period. After you confirm that thenimo-shakeincremental write rate has dropped to zero (the queue is drained), create the finalize sentinel file (the file specified bycheck_drain.finalize_flag_file, for example,touch /tmp/nimo-finalize). The resident process then automatically enters the final check phase, produces the authoritative difference report, and exits.Stop the synchronization tool: After you confirm that the data is fully synchronized, stop the
nimo-shakeprocess.Switch application connections: Stop the business applications and change their database connection configurations from the AWS DynamoDB endpoint to the DynamoDB endpoint of PolarDB.
(Optional) Start the reverse synchronization task: While the business is officially switched to PolarDB, start the reverse synchronization task. Based on Realtime Compute for Apache Flink, the task enables reverse data backflow and provides a safeguard for business rollbacks.
Start the business: Restart the business applications. The cutover is now complete.
(Optional) Stop the reverse synchronization task: After the cutover is complete, your business has run stably for a period of time, and you have confirmed that data consistency meets your business requirements, you can safely stop the reverse synchronization task (stop the Flink job and release the related resources).
Appendix: Simulate real-time service traffic for a test environment
To simulate a real migration scenario with continuous data writes in a test environment, you can use the following Go sample code. The code periodically writes and updates data in the source DynamoDB table.
This step is only for testing and verifying the migration process. You do not need to perform it in an actual production migration.
package main
import (
"context"
"fmt"
"log"
"math/rand"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
// --- Configuration for your source AWS DynamoDB ---
var (
region = "cn-north-1" // AWS DynamoDB region
accessKey = "your-aws-access-key" // AWS DynamoDB access key
secretKey = "your-aws-secret-key" // AWS DynamoDB secret key
)
// --- Helper function to create a DynamoDB client ---
func createClient() (*dynamodb.Client, context.Context) {
ctx := context.Background()
sdkConfig, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
if err != nil {
log.Fatalf("Failed to load AWS config: %v", err)
}
client := dynamodb.NewFromConfig(sdkConfig, func(o *dynamodb.Options) {
o.Credentials = credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")
})
return client, ctx
}
// --- Function to create a table and populate it with initial data ---
func initializeData(client *dynamodb.Client, ctx context.Context) {
tableName := "src1" // Example table name
// Create table if not exists
_, err := client.CreateTable(ctx, &dynamodb.CreateTableInput{
TableName: &tableName,
AttributeDefinitions: [ ]types.AttributeDefinition{
{AttributeName: aws.String("pk"), AttributeType: types.ScalarAttributeTypeS},
},
KeySchema: [ ]types.KeySchemaElement{
{AttributeName: aws.String("pk"), KeyType: types.KeyTypeHash},
},
ProvisionedThroughput: &types.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(100),
WriteCapacityUnits: aws.Int64(100),
},
})
if err != nil {
// Ignore if table already exists, fail on other errors
if _, ok := err.(*types.ResourceInUseException); !ok {
log.Fatalf("CreateTable failed for %s: %v", tableName, err)
}
}
fmt.Printf("Waiting for table '%s' to become active...\n", tableName)
waiter := dynamodb.NewTableExistsWaiter(client)
err = waiter.Wait(ctx, &dynamodb.DescribeTableInput{TableName: &tableName}, 5*time.Minute)
if err != nil {
log.Fatalf("Waiter failed for table %s: %v", tableName, err)
}
// Insert 100 sample items
for i := 0; i < 100; i++ {
pk := fmt.Sprintf("%s_user_%03d", tableName, i)
item := map[string]types.AttributeValue{
"pk": &types.AttributeValueMemberS{Value: pk},
"val": &types.AttributeValueMemberN{Value: fmt.Sprintf("%d", i)},
}
client.PutItem(ctx, &dynamodb.PutItemInput{TableName: &tableName, Item: item})
}
fmt.Printf("Inserted 100 initial items into '%s'.\n", tableName)
}
// --- Function to simulate continuous business traffic ---
func simulateTraffic(client *dynamodb.Client, ctx context.Context) {
tableName := "src1"
fmt.Println("Starting periodic updates to simulate traffic. Press Ctrl+C to stop.")
i := 0
for {
pk := fmt.Sprintf("%s_user_%03d", tableName, i%100)
newValue := fmt.Sprintf("%d", rand.Intn(1000))
_, err := client.UpdateItem(ctx, &dynamodb.UpdateItemInput{
TableName: &tableName,
Key: map[string]types.AttributeValue{
"pk": &types.AttributeValueMemberS{Value: pk},
},
ExpressionAttributeValues: map[string]types.AttributeValue{
":newval": &types.AttributeValueMemberN{Value: newValue},
},
UpdateExpression: aws.String("SET val = :newval"),
})
if err != nil {
fmt.Printf("Update error: %v\n", err)
} else {
fmt.Printf("Updated pk=%s with new val=%s\n", pk, newValue)
}
i++
time.Sleep(1 * time.Second) // Update one record per second
}
}
func main() {
client, ctx := createClient()
initializeData(client, ctx)
simulateTraffic(client, ctx)
}