
DynamoDB to SQL Server Migration Without Direct Connect: AWS–Google Cloud VPN with Terraform
A step-by-step guide to build, test, and destroy a lab that costs about US$15 for 72 hours (estimated) Hernán Villavicencio Soledispa | AWS Solutions Architect, AWS User Group Quito leader, and AWS Community Builder
Summary
When AWS DMS does not work for your data source, replicating to an on-premises SQL Server means building the pipeline yourself, and testing it against Direct Connect is expensive. In this article I use Terraform to build a lab that reproduces the complete pattern with Google Cloud playing the role of “on-premises”: a site-to-site VPN with 2 IPsec tunnels and BGP, a SQL Server 2022 running in Docker on a Compute Engine VM, and a Lambda function inside a VPC with no NAT that copies a DynamoDB table (initial load) and then follows changes with DynamoDB Streams.
- What you will build: 50 Terraform resources across AWS and Google Cloud (47 in the first apply and 50 after enabling Streams in the second one).
- What we verify: 2 tunnels UP, 2 BGP sessions Established, 150 records in DynamoDB and 150 in SQL Server, and a live change that arrives through Streams with the dead-letter queue (DLQ) empty.
- Estimated cost: about US$0.22 per hour; between US$14.57 (minimum) and US$15.70 (likely) for 72 hours, with no free tier or credits. This is an estimate based on official prices checked on November 11, 2026, not an invoice.
- What it is not: a high-availability topology. It uses 2 tunnels on a single Google interface; the 99.99% SLA requires 4 tunnels. I explain this in detail below.
- Seven gotchas that will save you hours: (1) Google HA VPN requires BGP; (2) 2 tunnels on one interface work but are not HA; (3) LATEST in Streams loses the events that happen before activation; (4) the secret stays in a recovery window (30 days by default) and blocks recreating it; (5) terraform destroy needs the Lambda package and takes about 20 minutes; (6) Lambda in a VPC without NAT needs VPC endpoints; (7) SQL Server with no Internet access to port 1433.
- Code: the snippets are trimmed from a complete Terraform project. The essential scripts and the handler are in the Appendix, so you can reproduce the lab without any other resource.
The Problem and Why It Matters
This lab comes from a real case. A team needed to query a production DynamoDB table with thousands of records, containing personal and financial data, using elaborate SQL. The destination was an on-premises SQL Server, which AWS reaches through AWS Direct Connect. The first idea was AWS DMS, but in the documentation I reviewed, DynamoDB appears as a DMS target and not among the supported sources, so we had to build the replication ourselves: a Lambda that does the initial load with a paginated Scan and then follows changes with DynamoDB Streams.
The problem showed up when testing. Direct Connect is expensive to duplicate for development and staging: a dedicated link makes no sense for an environment you want to turn on for a few hours. And the riskiest part is not the Lambda but everything around it: routes, firewalls, private DNS, secrets, and the real behavior of Streams.
My thesis is simple: you can validate a good part of that pattern with a site-to-site VPN to another cloud, for a few dollars, if you define it as code and destroy it when you finish. Google Cloud plays the data center: a VM with SQL Server in Docker, with no public IP exposed on port 1433. Direct Connect is replaced by an IPsec VPN with BGP, which from the Lambda’s point of view looks the same: a private route to a remote CIDR.
Architecture
The Lambda lives in two private subnets of a VPC with no Internet Gateway or NAT. To talk to DynamoDB it uses a Gateway-type VPC endpoint; to read the secret with the credentials it uses an Interface-type Secrets Manager endpoint. The only traffic that leaves that VPC is TCP 1433 to 10.10.1.0/24, which travels through the Virtual Private Gateway and the 2 tunnels to Google Cloud.

Figure 1. Lab architecture: DynamoDB and Streams feed a Lambda in a VPC that writes to SQL Server (on a Google Cloud VM) through a 2-tunnel VPN with BGP.
The 4 building blocks of the solution:
- Network and VPN: a VPC in AWS (10.20.0.0/16), a VPC in Google Cloud (10.10.1.0/24), and the IPsec IKEv2 VPN between them, with BGP (ASN 64512 on AWS and 65010 on the Cloud Router).
- “On-premises”: an e2-medium VM with Container-Optimized OS that runs SQL Server 2022 in Docker. The firewall only allows TCP 1433 from the AWS private subnets.
- Data in AWS: the demo-merchants-table table (with Streams in NEW_IMAGE mode), a control table demo-sync-control, and a secret demo-sqlserver-onprem with the credentials.
- Synchronization: the demo-dynamodb-sqlserver-sync Lambda (Python 3.12 and pymssql) in initial load mode or in Streams mode, with an SQS queue as DLQ.
Prerequisites
- An AWS account and a Google Cloud project with billing enabled, both your own and for testing. Use your AWS profile (<YOUR_AWS_PROFILE>) and your project (<YOUR_GCP_PROJECT>); never commit them to the repository.
- Terraform 1.5 or later, AWS CLI, gcloud, jq, Python 3, and pip, with Internet access. The providers are pinned in versions.tf: hashicorp/aws ~> 6.0, hashicorp/google ~> 8.0, random, and archive.
- Local authentication: gcloud auth application-default login for Google and your profile or environment variables for AWS. Terraform enables the compute.googleapis.com API for you (enable_apis = true).
- One AWS Region and one Google Cloud region: us-east-1 and us-east4 by default.
- Optional but recommended: aws_allowed_account_ids = ["111122223333"] in terraform.tfvars so that Terraform refuses to apply in the wrong account.
# terraform.tfvars (example values, replace the placeholders)gcp_project_id = "<YOUR_GCP_PROJECT>"aws_profile = "<YOUR_AWS_PROFILE>"aws_allowed_account_ids = ["111122223333"]aws_region = "us-east-1"gcp_region = "us-east4"enable_streams_sync = false # initial load first, then StreamsStep-by-Step Implementation
All the code is organized by file: network_aws.tf, network_gcp.tf, vpn.tf, gcp_sqlserver.tf, aws_data.tf, aws_lambda.tf, and streams.tf. I show trimmed snippets from those files; I omit tags and variables to make them easier to read. Steps 1 to 6 only declare resources: nothing exists until the terraform apply in Step 7, where everything is verified with read-only commands. From Step 6 on, the scripts and the handler are in the Appendix.
Step 1. The Private AWS VPC and the Virtual Private Gateway
The private subnets have no route to the Internet. The Virtual Private Gateway (VGW) is attached to the VPC, and route propagation makes the routes it learns through BGP show up on their own in the private route table. Without propagation, the VPN would be up but the Lambda would not know how to reach Google.
locals { use_vgw = var.aws_target_gateway == "vgw" # "vgw" by default; "tgw" uses Transit Gateway use_tgw = var.aws_target_gateway == "tgw" vpn_target = { vpn_gateway_id = local.use_vgw ? aws_vpn_gateway.this[0].id : null transit_gateway_id = local.use_tgw ? aws_ec2_transit_gateway.this[0].id : null }}resource "aws_vpn_gateway" "this" { count = local.use_vgw ? 1 : 0 amazon_side_asn = var.aws_bgp_asn # 64512}resource "aws_vpn_gateway_attachment" "this" { vpc_id = aws_vpc.main.id vpn_gateway_id = aws_vpn_gateway.this[0].id}resource "aws_vpn_gateway_route_propagation" "private" { vpn_gateway_id = aws_vpn_gateway.this[0].id route_table_id = aws_route_table.private.id depends_on = [aws_vpn_gateway_attachment.this]}The code also supports Transit Gateway with aws_target_gateway = "tgw". I used VGW by default because it is simpler and cheaper for a demo; TGW charges per attachment and per GB processed, and only TGW supports ECMP, which I did not need here.
Step 2. The Google Cloud VPC and the Port 1433 Firewall
In Google I create a custom-mode VPC, a 10.10.1.0/24 subnet, and a single ingress rule: TCP 1433 from the CIDRs of the AWS private subnets, applied only to the VM with the network tag demo-sqlserver-onprem. There is no rule from 0.0.0.0/0.
resource "google_compute_firewall" "allow_sqlserver_from_aws" { name = "allow-sqlserver-from-aws" network = google_compute_network.main.name direction = "INGRESS" allow { protocol = "tcp" ports = [tostring(var.sqlserver_port)] # 1433 } source_ranges = var.aws_private_subnet_cidrs # 10.20.1.0/24, 10.20.2.0/24 target_tags = ["demo-sqlserver-onprem"]}Step 3. The VPN: HA VPN Gateway, Cloud Router, and Customer Gateway
This is the heart of the article. In Google you create an HA VPN gateway (with two interfaces and two external IPs) and a Cloud Router with your ASN. Google HA VPN only supports dynamic routing (BGP): there are no static routes on this type of gateway, so the Cloud Router is not optional.
resource "google_compute_ha_vpn_gateway" "this" { name = "${var.name_prefix}-ha-vpn-gw" region = var.gcp_region network = google_compute_network.main.id stack_type = "IPV4_ONLY"}resource "google_compute_router" "this" { name = "${var.name_prefix}-router" region = var.gcp_region network = google_compute_network.main.id bgp { asn = var.gcp_bgp_asn # 65010 advertise_mode = "DEFAULT" }}
In AWS, the customer gateway represents the Google device: its IP is that of interface 0 of the HA VPN gateway and its ASN is that of the Cloud Router. The dynamic VPN connection (static_routes_only = false) comes with 2 tunnels by default, each with its own internal /30 range in 169.254.x.x. I pin a single set of ciphers because Google’s documentation warns that the large AWS set fragments IKE packets and the tunnel can fail when renegotiating keys (rekey).
resource "aws_customer_gateway" "gcp" { bgp_asn = var.gcp_bgp_asn ip_address = google_compute_ha_vpn_gateway.this.vpn_interfaces[0].ip_address type = "ipsec.1"}resource "aws_vpn_connection" "this" { customer_gateway_id = aws_customer_gateway.gcp.id vpn_gateway_id = local.vpn_target.vpn_gateway_id # see locals below type = "ipsec.1" static_routes_only = false tunnel1_inside_cidr = "169.254.10.0/30" tunnel2_inside_cidr = "169.254.10.4/30" tunnel1_preshared_key = local.psk["t1"] tunnel2_preshared_key = local.psk["t2"] tunnel1_ike_versions = ["ikev2"] tunnel1_phase1_encryption_algorithms = ["AES256"] tunnel1_phase1_integrity_algorithms = ["SHA2-256"] tunnel1_phase1_dh_group_numbers = [14] # ... same for phase 2 and for tunnel2_* tunnel1_startup_action = "start" tunnel2_startup_action = "start"}resource "random_password" "psk" { for_each = toset(["t1", "t2"]) # one key per tunnel length = 32 special = false}locals { psk = { for k, v in random_password.psk : k => "p${v.result}" }}Step 4. The External Peer, the Tunnels, and the BGP Sessions in Google
On the Google side, the “peer” is the two public IPs of the AWS tunnels, which Terraform reads from aws_vpn_connection. That creates the right dependency: a single terraform apply creates the AWS connection, gets its IPs, and then creates the Google tunnels. For each tunnel it also creates a Cloud Router interface (with the internal IP of the Google side) and a BGP peer (with the internal IP of the AWS side and its ASN).
resource "google_compute_external_vpn_gateway" "aws" { name = "${var.name_prefix}-aws-peer-gw" redundancy_type = "TWO_IPS_REDUNDANCY" interface { id = 0 ip_address = aws_vpn_connection.this.tunnel1_address } interface { id = 1 ip_address = aws_vpn_connection.this.tunnel2_address }}locals { tunnels = { # both tunnels leave from Google's interface 0 t1 = { gcp_if = 0 peer_if = 0 cgw_inside = aws_vpn_connection.this.tunnel1_cgw_inside_address vgw_inside = aws_vpn_connection.this.tunnel1_vgw_inside_address } t2 = { gcp_if = 0 peer_if = 1 cgw_inside = aws_vpn_connection.this.tunnel2_cgw_inside_address vgw_inside = aws_vpn_connection.this.tunnel2_vgw_inside_address } }}resource "google_compute_vpn_tunnel" "this" { for_each = local.tunnels # t1 and t2 name = "${var.name_prefix}-tunnel-${each.key}" vpn_gateway = google_compute_ha_vpn_gateway.this.id vpn_gateway_interface = each.value.gcp_if # 0 on both peer_external_gateway = google_compute_external_vpn_gateway.aws.id peer_external_gateway_interface = each.value.peer_if # t1 -> 0, t2 -> 1 shared_secret = local.psk[each.key] router = google_compute_router.this.id ike_version = 2}resource "google_compute_router_interface" "this" { for_each = local.tunnels name = "${var.name_prefix}-if-${each.key}" router = google_compute_router.this.name ip_range = "${each.value.cgw_inside}/30" vpn_tunnel = google_compute_vpn_tunnel.this[each.key].name}resource "google_compute_router_peer" "this" { for_each = local.tunnels name = "${var.name_prefix}-peer-${each.key}" router = google_compute_router.this.name interface = google_compute_router_interface.this[each.key].name peer_ip_address = each.value.vgw_inside peer_asn = var.aws_bgp_asn # 64512}Step 5. SQL Server on a Compute Engine VM
The VM uses the cos-stable image (Container-Optimized OS), with no API scopes on its service account (scopes = []). The passwords for sa and for the application user are generated by Terraform and travel as instance metadata; a startup-script starts the container and applies an idempotent init.sql that creates the database, the dbo.merchants table, and a user with only db_datareader and db_datawriter.
docker run -d --name sqlserver --restart unless-stopped \ -e ACCEPT_EULA=Y -e MSSQL_PID=Developer -e MSSQL_SA_PASSWORD="${SA_PASSWORD}" \ -p 1433:1433 -v /var/mssql:/var/opt/mssql \ -v "${INIT_SQL}:/init.sql:ro" "${IMAGE}" # mcr.microsoft.com/mssql/server:2022-latestThe VM has an ephemeral external IP only to download the container image (assign_public_ip = true). The firewall does not open any port from the Internet, and port 1433 only answers to the AWS private subnets. If you want to close even that IP, set assign_public_ip = false and provide another way to download the image.
Step 6. DynamoDB, the Secret, and the Lambda Inside the VPC
The tables are PAY_PER_REQUEST. The source table has Streams with NEW_IMAGE. The secret stores host, port, user, password, and database; the host is the VM’s internal IP. With recovery_window_in_days = 0 the secret is deleted immediately on a destroy (I explain why in the lessons learned).
resource "aws_dynamodb_table" "demo" { name = var.dynamodb_table_name # demo-merchants-table billing_mode = "PAY_PER_REQUEST" hash_key = "merchant_id" stream_enabled = true stream_view_type = "NEW_IMAGE" attribute { name = "merchant_id" type = "S" }}resource "aws_secretsmanager_secret" "sqlserver" { name = var.secret_name # demo-sqlserver-onprem recovery_window_in_days = 0}Without NAT, endpoints are not optional. The Lambda needs to reach DynamoDB and Secrets Manager without going out to the Internet. DynamoDB uses a Gateway-type endpoint (it is associated with the route table and has no charge) and Secrets Manager an Interface-type endpoint, with private DNS and a security group that only allows 443 from the Lambda. I put the Interface endpoint in a single subnet to make it cheaper.
resource "aws_vpc_endpoint" "dynamodb" { vpc_id = aws_vpc.main.id service_name = "com.amazonaws.${var.aws_region}.dynamodb" vpc_endpoint_type = "Gateway" route_table_ids = [aws_route_table.private.id]}resource "aws_vpc_endpoint" "secretsmanager" { vpc_id = aws_vpc.main.id service_name = "com.amazonaws.${var.aws_region}.secretsmanager" vpc_endpoint_type = "Interface" subnet_ids = [aws_subnet.private[0].id] security_group_ids = [aws_security_group.secretsmanager_endpoint.id] private_dns_enabled = true}The Lambda’s security group has no ingress and only three egress rules: TCP 1433 to the Google CIDR, 443 to the DynamoDB endpoint prefix list, and 443 to the Secrets Manager endpoint group. Nothing goes out to 0.0.0.0/0. The function is deployed in the two private subnets:
resource "aws_lambda_function" "sync" { function_name = var.lambda_function_name # demo-dynamodb-sqlserver-sync runtime = "python3.12" handler = "handler.handler" timeout = var.lambda_timeout # 120 memory_size = var.lambda_memory_size # 256 vpc_config { subnet_ids = aws_subnet.private[*].id security_group_ids = [aws_security_group.lambda.id] } # environment { SOURCE_TABLE_NAME, SQLSERVER_SECRET_ARN, ... } trimmed}The package is built with ./scripts/build-lambda.sh, which downloads the pymssql wheels compatible with Lambda (Python 3.12, x86_64) and copies handler.py. The function’s IAM is minimal: read access to the source table, PutItem on the control table, and GetSecretValue on that secret.
The handler has two paths. For the initial load it does a paginated Scan and returns a continuation key (last_evaluated_key); for Streams it receives Records and does a MERGE per record, so reprocessing an event does not duplicate rows. REMOVE events are deliberately ignored in this demo. These are the two cores, trimmed from lambda/handler.py:
def _read_items_by_scan(start_key, page_size): # page_size = 25 by default scan_kwargs = {"Limit": page_size} if start_key: scan_kwargs["ExclusiveStartKey"] = start_key response = _dynamodb.Table(SOURCE_TABLE_NAME).scan(**scan_kwargs) return response.get("Items", []), response.get("LastEvaluatedKey") merge_sql = f""" MERGE {SQLSERVER_TARGET_TABLE} AS target USING (SELECT {placeholders}) AS source ({insert_columns}) ON target.{PARTITION_KEY} = source.{PARTITION_KEY} WHEN MATCHED THEN UPDATE SET {set_clause} WHEN NOT MATCHED THEN INSERT ({insert_columns}) VALUES ({insert_values});"""cursor.execute(merge_sql, tuple(values)) # parameterized values, not concatenatedStep 7. Deploy and Verify the VPN
cp terraform.tfvars.example terraform.tfvars # edit your values./scripts/build-lambda.shterraform initterraform planterraform applyThe tunnels can take a few minutes to come up because AWS initiates the negotiation (startup_action = "start"). Check IPsec first and then BGP, in that order, because BGP does not establish if the tunnel is down:
# AWS: status of each tunnel and routes accepted through BGPaws ec2 describe-vpn-connections \ --filters "Name=tag:Project,Values=demo-aws-gcp-vpn" \ --query 'VpnConnections[].VgwTelemetry[].[Status,StatusMessage,AcceptedRouteCount]' \ --output table# Google: tunnels and BGP sessions of the Cloud Routergcloud compute vpn-tunnels list --regions <GCP_REGION> \ --format="table(name,status,detailedStatus)"gcloud compute routers get-status <ROUTER_NAME> --region <GCP_REGION> \ --format="table(result.bgpPeerStatus[].name,result.bgpPeerStatus[].state)"The expected result, and the one I got: 2 tunnels UP in AWS, 2 tunnels ESTABLISHED in Google, and 2 BGP sessions Established. The ./scripts/check-vpn.sh script gathers all of this into a single read-only output. To confirm the route on the AWS side, look at the private route table: 10.10.1.0/24 must appear with the VGW as the propagation source.
Step 8. Fictitious Data and Initial Load
python3 -m venv .venv && . .venv/bin/activatepip install -r scripts/requirements-scripts.txtpython scripts/seed_dynamodb.py --count 150 --region us-east-1./scripts/full-load.sh --dry-run # validates without writing to SQL Server./scripts/full-load.sh # real write./scripts/verify-sql.sh # ping and count from inside the VPCThe seed uses Faker with a fixed seed and accepts between 100 and 200 records. full-load.sh invokes the Lambda in a loop, passing the continuation key on each pass, until last_evaluated_key is null. With the default page of 25 records, 150 records are read in several invocations. The output format is this (illustrative; the number of invocations depends on your table; the messages are the script’s actual output, which is in Spanish):
Invocacion 1: migrados=25 parciales=0 errores=0Invocacion 2: migrados=25 parciales=0 errores=0(one line per invocation until the table is exhausted)Full load completo en <n> invocaciones.Totales -> migrados: 150 | parciales: 0 | errores: 0There is no SSH and no extra ports: to query SQL Server from my laptop I invoke the same Lambda with {"action":"count"}, which counts rows from inside the VPC and over the VPN. It is a cheap way to demonstrate end-to-end connectivity.
Step 9. Enable Synchronization with DynamoDB Streams
The error queue and the event source mapping are only created if you enable enable_streams_sync. The mapping uses batches of 10, a maximum of 3 retries, ReportBatchItemFailures so that one bad record does not retry the whole batch, and an SQS DLQ for whatever fails for good.
resource "aws_lambda_event_source_mapping" "streams" { event_source_arn = aws_dynamodb_table.demo.stream_arn function_name = aws_lambda_function.sync.arn starting_position = var.streams_starting_position # "LATEST" batch_size = var.streams_batch_size # 10 maximum_retry_attempts = var.streams_maximum_retry_attempts # 3 function_response_types = ["ReportBatchItemFailures"] destination_config { on_failure { destination_arn = aws_sqs_queue.streams_dlq[0].arn } }}terraform apply -var enable_streams_sync=true# Wait for the mapping to be Enabled BEFORE testing:aws lambda list-event-source-mappings \ --function-name demo-dynamodb-sqlserver-sync \ --query 'EventSourceMappings[].State'End-to-End Test
The demonstration always follows the same order and does not require opening anything else:
- Count rows in DynamoDB and in SQL Server: they must match (in my run, 150 and 150).
- Insert a new record in DynamoDB with ./scripts/demo-live.sh insert, which waits a few seconds and queries the row in SQL Server and its status in the control table.
- Optionally, modify an existing record with ./scripts/demo-live.sh update <merchant_id> SUSPENDIDO 2500 and check the change in SQL Server.
- Check that the SQS DLQ is still empty.
With Streams enabled, the new record appears in SQL Server within seconds. I do not quantify the latency because it depends on the batch, the Lambda start-up, and the VPN, and my lab has no controlled measurement. If you need a latency SLA, measure it in your environment with your volume.
demo-menu.sh groups everything into a menu: DynamoDB count, SQL Server count, compare both (OK or DIFERENCIA), create a record and look it up in SQL Server every second with a configurable maximum. The recommended order is compare, create, wait, and compare again.
Costs: What It Costs to Keep It Running for 72 Hours
I calculated the cost of keeping everything deployed for 3 days with official prices checked on November 11, 2026, in us-east-1 (AWS) and us-east4 (Google Cloud). It is an estimate, not a billed cost, and it does not subtract free tier or credits.
Component | Unit price | Hours | Minimum (US$) | Likely (US$) |
|---|---|---|---|---|
AWS Site-to-Site VPN (1 connection, 2 tunnels) | 0.05 / connection-hour | 72 | 3.60 | 3.60 |
VPC endpoint Interface (Secrets Manager, 1 AZ) | 0.01 / AZ-hour | 72 | 0.72 | 0.72 |
Secrets Manager (1 secret, prorated) | 0.40 / secret-month | 72 | 0.04 | 0.04 |
Other AWS (Lambda, DynamoDB, SQS, Logs, data) | usage-based, very low | - | 0.00 | 0.04 |
AWS subtotal | | | 4.36 | 4.40 |
Google HA VPN, 2 tunnels | 0.05 / tunnel-hour | 72 | 7.20 | 7.20 |
e2-medium VM (Linux, on-demand) | 0.0377 / hour | 72 | 2.71 | 2.71 |
30 GB pd-balanced disk | 0.000136986 / GiB-hour | 72 | 0.30 | 0.30 |
HA VPN external IP (interface 1), VM ephemeral IP, data egress | per hour and per usage | 72 | 0.00 | 1.09 |
Cloud Router (BGP) | no charge | 72 | 0.00 | 0.00 |
Google Cloud subtotal | | | 10.21 | 11.30 |
TOTAL 72 hours | | | 14.57 | 15.70 |
Table 1. Estimated cost of 72 hours running (US$, prices checked on November 11, 2026, no free tier or credits).
Assumptions. Minimum: only fixed hourly charges and storage. Likely: adds Google’s external IPs and a little traffic and usage-based services. Low traffic (100 to 200 records). Each partial hour is billed as a full hour. I took the VM price in us-east4 from a third-party source because the official page loads the table with JavaScript, and the Google VPN price is the one from the general table, so confirm both in the pricing calculator.
What weighs the most is what charges by the hour even when you are not using it: the two VPNs, the Interface endpoint, and the VM add up to about 90% of the total. With everything on, it comes to about US$0.22 per hour; forgotten for a full month it would be about US$157. That is why this lab is turned on to test and destroyed when finished.
Lessons Learned
Gotchas 1, 2, 5, and 7 are already covered in their steps (mandatory BGP, 2-tunnel topology, endpoints without NAT, port 1433 firewall). These two really cost me time.
Streams with LATEST Loses Whatever Came Before Activation (Gotcha 3)
I had done a test INSERT before the event source mapping was in the Enabled state. It never reached SQL Server, with no error and no message in the DLQ, and the counts ended up off by 1. I confirmed the root cause by comparing timestamps: the record was written before the mapping was activated, and with LATEST Lambda only reads what happens afterward. The initial seed did not trigger events either, because the mapping did not exist yet.
- Correct practice: wait for the mapping to be Enabled and only then run your tests.
- Alternative: TRIM_HORIZON starts from the oldest available record. DynamoDB Streams retains 24 hours, so you will reprocess that history. With an idempotent MERGE it is safe, but it generates extra work.
- Repair: if it already happened, run ./scripts/full-load.sh again (the MERGE is idempotent) and compare counts with verify-sql.sh.
The Secret That Will Not Let You Recreate It (Gotcha 4)
Secrets Manager does not delete a secret right away: it leaves it inaccessible during a recovery window (7 to 30 days; the default is 30), and in the meantime you cannot create another one with the same name. When you destroy and redeploy the lab, that breaks the second apply. In demos use recovery_window_in_days = 0. In production, do not: that window is a safety net.
Cleanup: Destroy and Check That Nothing Is Still Charging
terraform destroy removes the VPN, the VM, the Lambda, the tables, and the secret in both clouds, but with two conditions. The Lambda’s archive_file needs the package to exist, so build it again first. And if you applied with Streams enabled, pass the same variable. Allow about 20 minutes: the Lambda’s network interfaces (ENIs) in the VPC take a while to be released. If the destroy fails because the package is missing, the resources that charge by the hour stay on.
./scripts/build-lambda.shterraform destroy -var enable_streams_sync=true
Destroying is not the same as verifying. This checklist looks for whatever charges by the hour:
# AWSaws ec2 describe-vpn-connections \ --filters "Name=tag:Project,Values=demo-aws-gcp-vpn" \ --query 'VpnConnections[].[VpnConnectionId,State]'aws ec2 describe-vpc-endpoints --query 'VpcEndpoints[].[VpcEndpointId,State]'aws lambda list-functions --query 'Functions[].FunctionName'aws dynamodb list-tablesaws secretsmanager list-secrets --query 'SecretList[].Name'aws resourcegroupstaggingapi get-resources \ --tag-filters Key=Project,Values=demo-aws-gcp-vpn# Google Cloudgcloud compute instances listgcloud compute vpn-tunnels listgcloud compute vpn-gateways listgcloud compute routers listgcloud compute addresses list
The expected result is empty lists (a VPN in deleted state is normal for a while). Remember that the tag query only sees AWS resources that support tags; that is why I also list the Google ones directly. And as the estimate above makes clear, a forgotten resource keeps charging by the hour.
Conclusions and Next Steps
With a 2-tunnel VPN, a SQL Server container, and less than US$16 (estimated), I reproduced the complete pattern of a DynamoDB replication to a private SQL Server: network, security, initial load, and live changes. The most valuable part was not the Lambda but what I learned at the edges: mandatory BGP, LATEST that does not forgive, endpoints instead of NAT, and a secret that refuses to die.
What I would do to take it further:
- Real high availability: two AWS VPN connections (4 tunnels), a FOUR_IPS_REDUNDANCY peer, and tunnels from both Google interfaces, as the official guide describes.
- Production: use AWS Direct Connect (ideally with a backup VPN), with rotated credentials, a secret recovery window, encryption, and explicit handling of REMOVE.
- Scale: move to Transit Gateway if there are several VPCs or on-premises sites, and review the performance of the row-by-row MERGE with more volume.
- Operations: alarms on the DLQ and on the tunnel status.
If you try it, I would like to know which tunnel design you chose.
Get the code All the Terraform, the Lambda function, and the helper scripts from this walkthrough are available in this repository: https://github.com/VillaviH/demo-aws-gcp-vpn
It is MIT-licensed and uses only synthetic data. The README covers prerequisites, deployment order, how to verify the tunnels and BGP, and how to destroy everything so nothing keeps charging. Feedback and pull requests are welcome.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article