Introduction
Moving a live NoSQL workload between clouds is rarely about copying data once. The real challenge is keeping the target in sync while the source keeps taking writes, so that the cutover needs no downtime and loses no records.
In this article, I walk through how we migrated an Amazon DynamoDB table to Google Cloud Firestore with zero downtime. The pattern splits the job into two tracks that run together:
- Streaming track (CDC): DynamoDB Streams trigger an AWS Lambda function that writes every insert, update and delete to Firestore in near real time. Lambda authenticates to Google Cloud through Workload Identity Federation, so no service account keys leave Google Cloud.
- Backfill track (historical data): a point-in-time export of the table lands in Amazon S3, Storage Transfer Service copies it into Cloud Storage, and a Dataflow pipeline loads it into Firestore.
The walkthrough uses a single CustomerProfiles table with about 30,000 items. The same steps scale to larger tables; the code needs adapting only where your schema differs.
What you will build:
- A Firestore database and a Workload Identity Federation pool and provider trusted by your AWS account
- A Python 3.12 Lambda function that turns DynamoDB Stream events into Firestore writes
- A DynamoDB export to S3 and a Storage Transfer Service job that copies it to Cloud Storage
- An Apache Beam pipeline on Dataflow that loads the export into Firestore
Prerequisites and sample dataset
You need admin-level access on both sides and a few local tools:
- A Google Cloud project with billing enabled, and the Firestore, IAM Credentials, Security Token Service, Storage Transfer Service and Dataflow APIs enabled
- An AWS account with permissions for DynamoDB, Lambda, IAM and S3
gcloud, the AWS CLI, Docker and Python 3.12 on your workstation
Data model
The source table, CustomerProfiles, uses on-demand capacity and a single partition key, customer_id (String). DynamoDB only declares key attributes; every other attribute is schemaless. The table below shows how each DynamoDB type lands in Firestore.
Attribute
DynamoDB type
Firestore type
customer_id, name, email, device_type
String (S)
string
age
Number (N)
integer
account_balance
Number (N)
double
is_active
Boolean (BOOL)
boolean
address
Map (M)
map
signup_date
String (S), ISO-8601
string (convert to timestamp if you query by date)
A sample item looks like this:
{
"customer_id": "f5e4d3c2-b1a0-9f8e-7d6c-5b4a39281701",
"name": "Carlos Gomez",
"email": "cgomez@example.com",
"age": 45,
"account_balance": 5600.75,
"is_active": true,
"device_type": "Web",
"address": {
"street": "789 Pine Road",
"city": "Miami",
"zipcode": "33101",
"country": "USA"
},
"signup_date": "2020-11-03T09:45:10"
}
The relevant part of the table description (aws dynamodb describe-table --table-name CustomerProfiles):
{
"Table": {
"TableName": "CustomerProfiles",
"BillingModeSummary": { "BillingMode": "PAY_PER_REQUEST" },
"AttributeDefinitions": [
{ "AttributeName": "customer_id", "AttributeType": "S" }
],
"KeySchema": [
{ "AttributeName": "customer_id", "KeyType": "HASH" }
]
}
}
Generate test data (optional)
To try this as a proof of concept, seed the table with fake records. batch_writer groups writes into batches of 25, the DynamoDB limit.
import boto3
from faker import Faker
import uuid
import random
import time
from decimal import Decimal
fake = Faker()
dynamodb = boto3.resource('dynamodb', region_name='ap-south-1') # set your region
table = dynamodb.Table('CustomerProfiles')
def generate_and_insert_data(num_records):
print(f"Generating and inserting {num_records} records into DynamoDB...")
start_time = time.time()
with table.batch_writer() as batch:
for i in range(1, num_records + 1):
# DynamoDB needs Decimal, not float, for numbers
random_balance = str(round(random.uniform(10.0, 5000.0), 2))
item = {
'customer_id': str(uuid.uuid4()), # partition key
'name': fake.name(),
'email': fake.email(),
'age': random.randint(18, 90),
'account_balance': Decimal(random_balance),
'is_active': random.choice([True, False]),
'device_type': random.choice(['iOS', 'Android', 'Web']),
'address': {
'street': fake.street_address(),
'city': fake.city(),
'zipcode': fake.zipcode(),
'country': fake.country()
},
'signup_date': fake.date_time_this_decade().isoformat()
}
batch.put_item(Item=item)
if i % 5000 == 0:
print(f"Inserted {i} records...")
print(f"Done: {num_records} records in {round(time.time() - start_time, 2)} s.")
if __name__ == '__main__':
generate_and_insert_data(30000)
The Lambda and Dataflow code below is written for this schema. If your attributes differ, adjust the type handling and the key field.
Part 1: Google Cloud setup for streaming
The streaming track needs a Firestore database to write to, and a way for AWS Lambda to authenticate without a service account key. Workload Identity Federation (WIF) provides that: Lambda presents its AWS role credentials, and Google Cloud exchanges them for a short-lived token.
Step 1: Create the Firestore database
In the console, go to Firestore and click Create database. Choose Native mode, pick a location close to your users, and keep the database ID as (default). The code in this article writes to the (default) database.
[Screenshot: Firestore Create database page]
The CLI equivalent:
gcloud firestore databases create \
--database="(default)" \
--location=asia-south1 \
--type=firestore-native
Step 2: Create a Workload Identity Pool
Go to IAM & Admin > Workload Identity Federation and click Create pool. Give it a name and ID, for example aws-lambda-pool.
[Screenshot: Create identity pool]
gcloud iam workload-identity-pools create aws-lambda-pool \
--location=global \
--display-name="AWS Lambda pool"
Step 3: Add an AWS provider to the pool
Add a provider of type AWS, give it a name and ID, and enter your 12-digit AWS account ID. Under Configure provider attributes, click Edit mapping and keep only the mappings below. attribute.aws_role lets you grant access to one specific IAM role rather than the whole AWS account.
[Screenshot: Add AWS provider and attribute mapping]
gcloud iam workload-identity-pools providers create-aws aws-provider \
--location=global \
--workload-identity-pool=aws-lambda-pool \
--account-id=123456789012 \
--attribute-mapping="google.subject=assertion.arn,attribute.aws_role=assertion.arn.contains('assumed-role') ? assertion.arn.extract('{account_arn}assumed-role/') + 'assumed-role/' + assertion.arn.extract('assumed-role/{role_name}/') : assertion.arn"
Step 4: Grant the Lambda role access to Firestore
Federated identities have no permissions until you grant them. Give the Lambda execution role (created in Part 2) the Cloud Datastore User role on the project:
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--role=roles/datastore.user \
--member="principalSet://iam.googleapis.com/projects/<PROJECT_NUMBER>/locations/global/workloadIdentityPools/aws-lambda-pool/attribute.aws_role/arn:aws:sts::123456789012:assumed-role/LambdaDynamoToFirestoreRole"
If you prefer service account impersonation, grant the same principal roles/iam.workloadIdentityUser on a service account that holds roles/datastore.user, and select that service account when you download the config in the next step.
Step 5: Download the credential configuration file
On the pool page, click Connect service, choose Download config, select the AWS provider, and click Save. Then download the file from the dialog.
[Screenshot: Download credential configuration]
gcloud iam workload-identity-pools create-cred-config \
projects/<PROJECT_NUMBER>/locations/global/workloadIdentityPools/aws-lambda-pool/providers/aws-provider \
--aws \
--output-file=credentials.json
This file holds no secrets. It only tells the Google auth library where to exchange the AWS credentials, so it is safe to package with the function. Save it as credentials.json.
Part 2: AWS setup for streaming (CDC)
On the AWS side, a Lambda function consumes DynamoDB Stream records and applies each insert, update or delete to the matching Firestore document. The document ID is the DynamoDB partition key, so a record always maps to the same document.
Step 1: Write the Lambda function
Save this as lambda_function.py. It unmarshals the DynamoDB JSON, converts Decimal values (which Firestore rejects) to int or float, and commits in batches below the Firestore limit of 500 writes per batch.
# Python 3.12
import os
import decimal
from boto3.dynamodb.types import TypeDeserializer
from google.cloud import firestore
# Created once per container and reused across invocations
deserializer = TypeDeserializer()
firestore_client = firestore.Client(project=os.environ.get('GCP_PROJECT_ID', '<PROJECT_ID>'))
COLLECTION = 'CustomerProfiles'
PARTITION_KEY = 'customer_id'
def clean_decimals(obj):
"""DynamoDB numbers arrive as Decimal; Firestore needs int or float."""
if isinstance(obj, decimal.Decimal):
return int(obj) if obj % 1 == 0 else float(obj)
if isinstance(obj, dict):
return {k: clean_decimals(v) for k, v in obj.items()}
if isinstance(obj, list):
return [clean_decimals(i) for i in obj]
return obj
def unmarshal_dynamodb_json(low_level_data):
return {k: deserializer.deserialize(v) for k, v in low_level_data.items()}
def lambda_handler(event, context):
batch = firestore_client.batch()
mutation_count = 0
failed_sequence_numbers = []
for record in event.get('Records', []):
try:
event_name = record['eventName']
keys = unmarshal_dynamodb_json(record['dynamodb']['Keys'])
doc_id = str(keys.get(PARTITION_KEY, ''))
if not doc_id:
continue
doc_ref = firestore_client.collection(COLLECTION).document(doc_id)
if event_name == 'REMOVE':
batch.delete(doc_ref)
elif event_name in ['INSERT', 'MODIFY']:
new_image = clean_decimals(
unmarshal_dynamodb_json(record['dynamodb']['NewImage'])
)
new_image['_migration_source'] = 'dynamodb_cdc_stream'
# NewImage is the full item, so overwrite the document.
# This also drops attributes that were removed in DynamoDB.
batch.set(doc_ref, new_image)
mutation_count += 1
# Commit early to stay under Firestore's 500-write batch limit
if mutation_count >= 400:
batch.commit()
batch = firestore_client.batch()
mutation_count = 0
except Exception as e:
print(f"Failed to process record {record.get('eventID')}: {e}")
failed_sequence_numbers.append(
{'itemIdentifier': record['dynamodb']['SequenceNumber']}
)
if mutation_count > 0:
try:
batch.commit()
except Exception as e:
print(f"Final batch commit failed: {e}")
# Retry the whole batch from the first record
if event.get('Records'):
return {'batchItemFailures': [
{'itemIdentifier': event['Records'][0]['dynamodb']['SequenceNumber']}
]}
return {'batchItemFailures': failed_sequence_numbers}
Step 2: Create the Lambda execution role
Create a trust policy that lets Lambda assume the role:
cat <<EOF > trust-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
EOF
Create the role and attach the managed policy that lets Lambda read DynamoDB Streams and write logs:
aws iam create-role \
--role-name LambdaDynamoToFirestoreRole \
--assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy \
--role-name LambdaDynamoToFirestoreRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole
The role name must match the one in the Workload Identity Federation binding from Part 1, Step 4.
Step 3: Package the function
Build the dependencies inside the Lambda base image, so compiled packages such as grpcio match the Lambda runtime. Then add the code and credentials.json to the bundle.
# 1. Dependencies
cat <<EOF > requirements.txt
google-cloud-firestore
grpcio
EOF
# 2. Install them with the Lambda Python 3.12 image
mkdir -p package
docker run --rm -v "$PWD":/var/task --entrypoint /bin/bash \
public.ecr.aws/lambda/python:3.12 \
-c "pip install -r requirements.txt -t /var/task/package/"
# 3. Add the code and the WIF credential config
cp lambda_function.py package/
cp credentials.json package/
# 4. Zip it
cd package && zip -r ../function.zip . && cd ..
Step 4: Deploy the function
GOOGLE_APPLICATION_CREDENTIALS points the Google auth library at the WIF config. At runtime the library reads the role credentials Lambda already provides and exchanges them for a Google Cloud token.
aws lambda create-function \
--function-name DynamoToFirestoreCDC \
--zip-file fileb://function.zip \
--handler lambda_function.lambda_handler \
--runtime python3.12 \
--role arn:aws:iam::123456789012:role/LambdaDynamoToFirestoreRole \
--timeout 60 \
--environment "Variables={GOOGLE_APPLICATION_CREDENTIALS=/var/task/credentials.json,GCP_PROJECT_ID=<PROJECT_ID>}"
Step 5: Enable DynamoDB Streams
In the AWS console, open DynamoDB > Tables > CustomerProfiles > Exports and streams. Under DynamoDB stream details, click Turn on and choose New and old images.
[Screenshot: Turn on DynamoDB stream with New and old images]
aws dynamodb update-table \
--table-name CustomerProfiles \
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
Step 6: Connect the stream to Lambda
In the same section, click Create trigger, select DynamoToFirestoreCDC, and set the batch size. Edit the trigger and tick Report batch item failures. Without it, Lambda ignores the batchItemFailures the function returns, and failed records are not retried individually.
[Screenshot: DynamoDB trigger configuration]
aws lambda create-event-source-mapping \
--function-name DynamoToFirestoreCDC \
--event-source-arn <STREAM_ARN> \
--starting-position LATEST \
--batch-size 100 \
--function-response-types ReportBatchItemFailures
From this point, every change in DynamoDB is mirrored to Firestore. Write a test item and confirm the document appears in the Firestore console before you start the backfill.
Part 3: Export historical data and move it to Cloud Storage
With CDC running, take a snapshot of the existing data. DynamoDB’s native export to S3 reads from point-in-time backups, so it consumes no table read capacity and does not affect live traffic.
Step 1: Enable point-in-time recovery
Export to S3 requires point-in-time recovery (PITR). Open the table, go to Backups, and under Point-in-time recovery click Edit and enable it.
[Screenshot: Enable PITR]
aws dynamodb update-continuous-backups \
--table-name CustomerProfiles \
--point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
Step 2: Export the table to S3
Create an S3 bucket for the export. Then, on the table’s Exports and streams tab, click Export to S3:
- Choose the bucket and set the prefix to
exports/CustomerProfiles. The Dataflow pipeline relies on this layout later. - Under Additional settings, set the export file format to DynamoDB JSON.
[Screenshot: Export to S3 settings]
aws dynamodb export-table-to-point-in-time \
--table-arn arn:aws:dynamodb:ap-south-1:123456789012:table/CustomerProfiles \
--s3-bucket <EXPORT_BUCKET> \
--s3-prefix exports/CustomerProfiles \
--export-format DYNAMODB_JSON
A table of this size exports in a few minutes. Note the export’s export time; you will use it to reason about overlap with CDC. The data files land as gzipped JSON under exports/CustomerProfiles/AWSDynamoDB/<export-id>/data/.
[Screenshot: Completed export in S3]
Step 3: Let Storage Transfer Service read the bucket
Storage Transfer Service (STS) reads S3 by assuming an AWS IAM role through federation, so no AWS access keys are stored in Google Cloud. First, enable the Storage Transfer API and wait a few minutes. Then fetch the Google-managed service account’s subject ID for your project:
curl --location --request GET \
"https://storagetransfer.googleapis.com/v1/googleServiceAccounts/<PROJECT_NUMBER>" \
--header "X-Goog-User-Project: <PROJECT_ID>" \
--header "Authorization: Bearer $(gcloud auth print-access-token)"
Copy the subjectId from the response. In the AWS IAM console, create a role, choose Custom trust policy as the trusted entity, and paste the policy below with your subject ID:
[Screenshot: IAM role with custom trust policy]
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Federated": "accounts.google.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": { "accounts.google.com:sub": "<SUBJECT_ID>" }
}
}
]
}
On the next page, attach AmazonS3ReadOnlyAccess. Read-only access is enough for the transfer, but STS cannot delete source objects after copying them. For production, scope the policy to the export bucket only. Name the role, create it, and note its ARN.
[Screenshot: Role created, ARN visible]
Step 4: Create the transfer job
In the Google Cloud console, go to Storage Transfer > Create transfer job:
- Source: Amazon S3. Destination: Google Cloud Storage.
- Enter the bucket name and the prefix
exports/CustomerProfiles/. Choose AWS IAM role for identity federation and paste the role ARN. - Choose the destination bucket, with the folder
CustomerProfiles/, and click Create.
[Screenshot: Transfer source settings]
[Screenshot: Transfer destination settings]
The CLI equivalent, with the role ARN in a small credentials file:
echo '{"roleArn": "arn:aws:iam::123456789012:role/<STS_ROLE_NAME>"}' > s3-role.json
gcloud transfer jobs create \
s3://<EXPORT_BUCKET>/exports/CustomerProfiles/ \
gs://migration-datastore-bucket/CustomerProfiles/ \
--source-creds-file=s3-role.json
The copy runs over the public internet. For sensitive or very large datasets, you can route it through a VPN or Interconnect instead. When the job finishes, the console shows it as succeeded with the object count and bytes transferred.
[Screenshot: Completed transfer job]
Part 4: Load the export into Firestore with Dataflow
With the export in Cloud Storage, an Apache Beam pipeline on Dataflow reads the gzipped DynamoDB JSON, converts each item to a plain dictionary, and writes it to Firestore.
One detail matters for correctness. By the time the backfill runs, CDC may already have written a newer version of some items. The pipeline therefore uses create(), which only writes a document if it does not exist yet. Documents already written by the stream are skipped, so the snapshot never overwrites a fresher change.
Step 1: Install the libraries
pip install 'apache-beam[gcp]' boto3 google-cloud-firestore
Step 2: Write the pipeline
Save this as migration_pipeline.py:
import json
import decimal
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions
from boto3.dynamodb.types import TypeDeserializer
from google.api_core.exceptions import AlreadyExists
from google.cloud import firestore
SOURCE_GLOB = 'gs://migration-datastore-bucket/CustomerProfiles/**/*.json.gz'
COLLECTION = 'CustomerProfiles'
PARTITION_KEY = 'customer_id'
def clean_decimals(obj):
"""DynamoDB numbers arrive as Decimal; Firestore needs int or float."""
if isinstance(obj, decimal.Decimal):
return int(obj) if obj % 1 == 0 else float(obj)
if isinstance(obj, dict):
return {k: clean_decimals(v) for k, v in obj.items()}
if isinstance(obj, list):
return [clean_decimals(i) for i in obj]
return obj
class ParseDynamoDBExport(beam.DoFn):
"""Each export line is {"Item": {...DynamoDB JSON...}}."""
def setup(self):
self.deserializer = TypeDeserializer()
def process(self, element):
try:
item = json.loads(element).get('Item', {})
record = {k: self.deserializer.deserialize(v) for k, v in item.items()}
yield clean_decimals(record)
except Exception as e:
print(f"Failed to parse element: {e}")
class WriteToFirestoreIfAbsent(beam.DoFn):
def __init__(self, project_id, collection_name, partition_key):
self.project_id = project_id
self.collection_name = collection_name
self.partition_key = partition_key
def setup(self):
self.db = firestore.Client(project=self.project_id)
def process(self, element):
doc_id = str(element.get(self.partition_key, ''))
if not doc_id:
return
element['_migration_source'] = 'dynamodb_export'
doc_ref = self.db.collection(self.collection_name).document(doc_id)
try:
# create() fails if the document exists, so a newer
# version written by the CDC stream is never overwritten
doc_ref.create(element)
except AlreadyExists:
pass
def run_migration_pipeline(argv=None):
pipeline_options = PipelineOptions(argv)
pipeline_options.view_as(SetupOptions).save_main_session = True
gcp_project = pipeline_options.get_all_options().get('project')
with beam.Pipeline(options=pipeline_options) as pipeline:
(
pipeline
| 'ReadFromGCS' >> beam.io.ReadFromText(SOURCE_GLOB)
| 'ParseDynamoDBJSON' >> beam.ParDo(ParseDynamoDBExport())
| 'WriteToFirestore' >> beam.ParDo(
WriteToFirestoreIfAbsent(
project_id=gcp_project,
collection_name=COLLECTION,
partition_key=PARTITION_KEY,
)
)
)
if __name__ == '__main__':
run_migration_pipeline()
The **/*.json.gz glob picks up only the data files and skips the export’s manifest files. ReadFromText decompresses gzip automatically based on the file extension.
Step 3: Add the worker dependencies
Create a requirements.txt for the Dataflow workers:
boto3
google-cloud-firestore
Step 4: Run the job on Dataflow
The worker service account needs Dataflow Worker, Cloud Datastore User, and read access to the export bucket plus write access to the temp bucket. We used Storage Admin in the POC; scope this down for production.
python migration_pipeline.py \
--runner=DataflowRunner \
--project=<PROJECT_ID> \
--region=us-central1 \
--temp_location=gs://<TEMP_BUCKET>/temp \
--job_name=dynamodb-to-firestore-migration \
--service_account_email=<WORKER_SA>@<PROJECT_ID>.iam.gserviceaccount.com \
--max_num_workers=100 \
--requirements_file=requirements.txt
--max_num_workers=100 is a ceiling, not a target; Dataflow autoscaling uses far fewer workers for a table of 30,000 items. Open the job in the Dataflow console to watch it run.
[Screenshot: Dataflow job graph while running]
When the job succeeds, every stage shows as complete.
[Screenshot: Dataflow job succeeded]
The CustomerProfiles collection in Firestore now holds the migrated documents, each keyed by customer_id.
[Screenshot: Firestore data viewer with migrated documents]