惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
宝玉的分享
宝玉的分享
I
InfoQ
P
Privacy International News Feed
V
V2EX
IT之家
IT之家
S
SegmentFault 最新的问题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V2EX - 技术
V2EX - 技术
C
CERT Recently Published Vulnerability Notes
C
Check Point Blog
The Register - Security
The Register - Security
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
M
MIT News - Artificial intelligence
C
Cyber Attacks, Cyber Crime and Cyber Security
F
Fortinet All Blogs
B
Blog
N
Netflix TechBlog - Medium
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
T
Threatpost
Forbes - Security
Forbes - Security
U
Unit 42
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recorded Future
Recorded Future
L
Lohrmann on Cybersecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
月光博客
月光博客
Spread Privacy
Spread Privacy
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
I
Intezer
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
MyScale Blog
MyScale Blog
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
量子位

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
When DynamoDB Global Tables Go Stale: Chaos Testing Replication Lag with AWS FIS
Matia Rašeti · 2026-05-04 · via DEV Community

DynamoDB Global Tables replicate data across regions in seconds, but replication is still asynchronous.

That means a simple read from a replica region can occasionally return stale data, which is acceptable in most application as the user doesn’t require the latest available data all the time, but in some systems, stale reads can break important processes and stability of a platform.

So the question becomes:

How do you detect and react to stale replica reads automatically?

So, I set out to find the answer to this question — that’s when I found AWS Fault Injection Simulator (FIS) service, which in combination with DynamoDB Global Tables, can intentionally create failure scenarios and observe a resilient read path responds.

Instead of only testing infrastructure availability, this experiment also focuses on application-level resilience. To be more precise, I’m going to show you the code which can detect stale reads, reroute traffic and recover from the chaos scenario automatically.

Also, I’m going to show you how to experiment with your Lamdbas which are in this stack as well, we are going to take a look at how to inject delays and errors in your Lambda invocations.

The full project code is available in this GitHub repository link.

What This Project Demonstrates

The CDK-based stack deploys a multi-region architecture designed to simulate and handle real-world replication issues.

The stack consists of:

  • A primary DynamoDB region (us-east-1) that handles all writes
  • A replica region (eu-central-1) that normally serves reads
  • A reader Lambda that detects stale data and falls back to the primary when needed
  • A rerouter Lambda that automatically shifts read routing when replication becomes unhealthy
  • AWS Fault Injection Simulator experiments that intentionally introduce failure scenarios, which are:
    • DynamoDB Global Table replication failures
    • Lambda delays
    • Lambda failures

Together, these components allow us to observe how applications behave under replication lag, Lambda failures, and latency injections.

Core Design: Resilient Read Routing

The most interesting part of the architecture of this project is the reader Lambda, which is acting as the system’s resilience layer.

While under the normal conditions:

  1. the reader queries the replica region
  2. the system returns the result with low latency

However, if the data replication is falling behind, the Lambda detects the stale data by using the written_at timestamp.

When stale data is detected, the Lambda performs three actions:

  • If the replica data is older than 10 seconds, it is considered stale
  • The reader falls back to a strongly consistent read from the primary
  • The system self-escalates by updating an SSM parameter (/fis-global/read-routing)
  • Future reads temporarily bypass the replica entirely

This prevents the user from getting repeated stale reads and avoids performing per-request staleness checks during degraded conditions.

The following snippet is just a part of the reader Lambda, the full code can be seen inside the Github repository linked in the intro of this blog post:

STALENESS_THRESHOLD_MS = 10_000  # 10 seconds

def is_stale(item: dict) -> tuple[bool, int]:
    """
    Returns (is_stale, age_ms).
    written_at is stored as a Decimal by DynamoDB — convert safely.
    Only flags stale if age exceeds STALENESS_THRESHOLD_MS.
    """
    written_at = item.get("written_at")
    if not written_at:
        return False, 0
    written_at_ms = int(Decimal(str(written_at)))
    now_ms = int(time.time() * 1000)
    age_ms = now_ms - written_at_ms
    stale = age_ms > STALENESS_THRESHOLD_MS
    return stale, age_ms

def escalate_to_primary():
    """
    Write /fis-global/read-routing = 'primary' to SSM and update the
    local cache. The rerouter Lambda resets it to 'replica' when the
    CloudWatch alarm clears.
    """
    try:
        ssm.put_parameter(
            Name=READ_ROUTING_PARAM,
            Value="primary",
            Type="String",
            Overwrite=True,
        )
        _ssm_cache["value"] = "primary"
        _ssm_cache["fetched_at"] = time.time()
        logger.warning("SSM escalated to 'primary' — stale replication detected")
    except Exception as exc:
        logger.warning("SSM escalation failed (will retry next invocation): %s", exc)

# In the handler: replica read → staleness check → fallback → escalate
if routing == "primary":
    item = read_item(table_primary, pk, sk, consistent=True)
    read_from = "primary"
    routing_reason = "ssm_flag"
else:
    item = read_item(table_replica, pk, sk, consistent=False)
    read_from = "replica"
    if item:
        stale, age_ms = is_stale(item)
        if stale:
            logger.warning("STALE DATA: pk=%s age=%dms — falling back to primary", pk, age_ms)
            item = read_item(table_primary, pk, sk, consistent=True)
            read_from = "primary"
            routing_reason = "stale_data"
            stale_detected = True
            escalate_to_primary()
    # ... replica_miss_fallback when item not on replica yet ...

Enter fullscreen mode Exit fullscreen mode

Automated Read Rerouting

While the reader Lambda handles per-request resilience, the architecture also includes automated infrastructure-based routing recovery by implementing a CloudWatch alarm which monitors a specific DynamoDB metric — ReplicationLatency.

If the latency exceeds 5 seconds, the alarm triggers an SNS notification, which invokes the rerouter Lambda. Of course, the latency threshold can be customized, based on your architecture needs.

The rerouter Lambda updates the routing parameter:

  • primary during degraded replication
  • replica once replication returns to normal

Here is the router Lambda code example:

READ_ROUTING_PARAM = os.environ["READ_ROUTING_PARAM"]
ssm = boto3.client("ssm", region_name=PRIMARY_REGION)

def handler(event, context):
    for record in event.get("Records", []):
        message = json.loads(record["Sns"]["Message"])
        alarm_state = message.get("NewStateValue")
        alarm_name = message.get("AlarmName", "unknown")
        alarm_reason = message.get("NewStateReason", "")

        logger.info(
            "Alarm notification: name=%s state=%s reason=%s",
            alarm_name, alarm_state, alarm_reason,
        )

        if alarm_state == "ALARM":
            new_value = "primary"
            logger.warning(
                "Replication latency alarm FIRING — rerouting reads to primary (%s)",
                PRIMARY_REGION,
            )
        elif alarm_state == "OK":
            new_value = "replica"
            logger.info(
                "Replication latency alarm RESOLVED — restoring reads to replica"
            )
        else:
            logger.info("Ignoring alarm state '%s', no routing change", alarm_state)
            continue

        ssm.put_parameter(
            Name=READ_ROUTING_PARAM,
            Value=new_value,
            Type="String",
            Overwrite=True,
        )
        logger.info("SSM '%s' updated to '%s'", READ_ROUTING_PARAM, new_value)

    return {"statusCode": 200}

Enter fullscreen mode Exit fullscreen mode

Defining Chaos Experiments with AWS Fault Injection Simulator Templates

To validate the design, the project defines three chaos experiments using AWS FIS. Each experiment targets a different way the architecture in this stack can fail.

1. Replication Pause

The first experiment pauses replication for 3 minutes on the DynamoDB Global Table.

This creates a real-world scenario where:

  • writes continue in the primary
  • the replica falls behind
  • the reader detects stale data
  • the system falls back to the primary

This experiment validates the staleness detection and routing escalation logic.

from aws_cdk import aws_fis as fis

# ...

# FIS Experiment Template: Pause Replication + Reroute (3 minutes)
fis.CfnExperimentTemplate(
    self,
    "PauseAndRerouteExperiment",
    description=(
        "Pause replication for 3 min — reader self-escalates SSM to primary "
        "on first stale detect; CW alarm resets it on recovery"
    ),
    role_arn=fis_role.role_arn,
    stop_conditions=[
        fis.CfnExperimentTemplate.ExperimentTemplateStopConditionProperty(
            source="none"
        )
    ],
    targets={
        "globalTable": fis.CfnExperimentTemplate.ExperimentTemplateTargetProperty(
            resource_type="aws:dynamodb:global-table",
            resource_arns=[global_table.table_arn],
            selection_mode="ALL",
        )
    },
    actions={
        "pauseReplication": fis.CfnExperimentTemplate.ExperimentTemplateActionProperty(
            action_id="aws:dynamodb:global-table-pause-replication",
            description="Stop replication to replica for 3 minutes",
            parameters={"duration": "PT3M"},
            targets={"Tables": "globalTable"},
        ),
    },
    tags={"Experiment": "GlobalTable-PauseAndReroute"},
)

Enter fullscreen mode Exit fullscreen mode

2. Lambda Latency Injection

The second experiment introduces artificial startup delays in the Lambda reader.

Using the FIS Lambda extension, we inject:

  • 12-second invocation delays
  • lasting 2 minutes

Even when replication is healthy, this delay can cause the reader to observe stale data relative to new writes.

This tests whether the system can handle latency-induced inconsistencies.

from aws_cdk import aws_fis as fis

# ...

fis.CfnExperimentTemplate(
    self,
    "InvocationDelayExperiment",
    description=(
        "Inject 12 s startup delay into 100% of reader Lambda invocations for 2 min. "
        "Delay > STALENESS_THRESHOLD_MS → stale-data fallback fires even with healthy replication."
    ),
    role_arn=fis_role.role_arn,
    stop_conditions=[
        fis.CfnExperimentTemplate.ExperimentTemplateStopConditionProperty(
            source="none"
        )
    ],
    targets={
        "readerFn": fis.CfnExperimentTemplate.ExperimentTemplateTargetProperty(
            resource_type="aws:lambda:function",
            resource_arns=[reader_lambda.function_arn],
            selection_mode="ALL",
        )
    },
    actions={
        "addDelay": fis.CfnExperimentTemplate.ExperimentTemplateActionProperty(
            action_id="aws:lambda:invocation-add-delay",
            description="Add 12 s pre-handler delay to every reader invocation",
            parameters={
                "duration": "PT2M",
                "invocationPercentage": "100",
                "startupDelayMilliseconds": "12000",
            },
            targets={"Functions": "readerFn"},
        ),
    },
    tags={"Experiment": "Lambda-InvocationDelay"},
)

Enter fullscreen mode Exit fullscreen mode

3. Lambda Invocation Errors

The final experiment forces 100% invocation failures for any targeted Lambda, which in this case, is our reader Lambda, making the handler never execute, which simulates:

  • dependency outages
  • any of the runtime crashes happening during the Lambda initialization phase
  • any of the IAM permission errors

This validates the replica error fallback logic, ensuring the application gracefully handles failures instead of returning errors to clients.

from aws_cdk import aws_fis as fis

# ...

fis.CfnExperimentTemplate(
    self,
    "InvocationErrorExperiment",
    description=(
        "Force reader Lambda to return an error on 100% of invocations for 2 min. "
        "Triggers replica_error_fallback path in reader."
    ),
    role_arn=fis_role.role_arn,
    stop_conditions=[
        fis.CfnExperimentTemplate.ExperimentTemplateStopConditionProperty(
            source="none"
        )
    ],
    targets={
        "readerFn": fis.CfnExperimentTemplate.ExperimentTemplateTargetProperty(
            resource_type="aws:lambda:function",
            resource_arns=[reader_lambda.function_arn],
            selection_mode="ALL",
        )
    },
    actions={
        "injectError": fis.CfnExperimentTemplate.ExperimentTemplateActionProperty(
            action_id="aws:lambda:invocation-error",
            description="Return error response without executing reader handler",
            parameters={
                "duration": "PT2M",
                "invocationPercentage": "100",
                "preventExecution": "true",
            },
            targets={"Functions": "readerFn"},
        ),
    },
    tags={"Experiment": "Lambda-InvocationError"},
)

Enter fullscreen mode Exit fullscreen mode

How to combat possible Lambda initialization issues when starting the FIS experiment

During the development of this project, I kept getting errors inside the Reader Lambda, saying that it’s not supporting the AWS FIS experiment. However, the solution was written about in the documentation.

Every AWS Lambda which is a target inside the AWS FIS experiment template, needs to have a special Lambda layer added to it’s configuration. The ARN of the layer, in my case, was:

"arn:aws:lambda:us-east-1:211125607513:layer:aws-fis-extension-x86_64:280"

Enter fullscreen mode Exit fullscreen mode

and it can be found inside the Parameter Store service on AWS. Keep in mind that:

  • your region
  • Lambda architecture (x86 or ARM),

play a factor in determining the layer ARN.

In addition, to run the FIS experiment on a Lambda, it needs a S3 bucket to store the logs and you need to define the AWS_FIS_CONFIGURATION_LOCATION and AWS_LAMBDA_EXEC_WRAPPER environment variables.

AWS_FIS_CONFIGURATION_LOCATION needs to be set to the ARN of your S3 bucket, while AWS_LAMBDA_EXEC_WRAPPER needs to be set to /opt/aws-fis/bootstrap .

More information can be found in official AWS docs by clicking on the link here.

The final CDK code for the Lambda looks as following:

reader_lambda = lambda_.Function(
    self,
    "ReaderLambda",
    function_name="fis-global-reader",
    runtime=lambda_.Runtime.PYTHON_3_12,
    handler="reader.handler",
    code=lambda_.Code.from_asset("lambda", exclude=[".venv","venv","__pycache__","cdk.out","*.pyc","node_modules",".git"]),
    role=lambda_role,
    # Timeout must exceed max FIS startup delay (12 000 ms) + execution time.
    timeout=Duration.seconds(30),
    memory_size=256,
    architecture=lambda_.Architecture.X86_64, # Make sure that your architecture matches the required FIS layer!
    layers=[
        lambda_.LayerVersion.from_layer_version_arn(
            self,
            "FisExtensionLayer",
                        # Be sure that you have the layer below defined,
                        # the FIS experiment won't work otherwise!
            "arn:aws:lambda:us-east-1:211125607513:layer:aws-fis-extension-x86_64:280",
        )
    ],
    environment={
        # ...
        # FIS writes fault config to this S3 ARN; the extension layer
        # reads it before each invocation.
        "AWS_FIS_CONFIGURATION_LOCATION": fis_config_location_arn,
        # Required alongside the FIS extension layer to intercept invocations.
        "AWS_LAMBDA_EXEC_WRAPPER": "/opt/aws-fis/bootstrap",
    },
    log_group=reader_log_group,
)

Enter fullscreen mode Exit fullscreen mode

Also, please make sure that you give the Lambda necessary IAM permissions! The following role will do the trick

lambda_role = iam.Role(
    self,
    "LambdaRole",
    assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"),
    managed_policies=[
        iam.ManagedPolicy.from_aws_managed_policy_name(
            "service-role/AWSLambdaBasicExecutionRole"
        )
    ],
)
global_table.grant_read_write_data(lambda_role)
read_routing_param.grant_read(lambda_role)
read_routing_param.grant_write(lambda_role)
chaos_param.grant_read(lambda_role)

# grant_read_write_data only covers the primary ARN; the reader Lambda
# also talks to the eu-central-1 replica which has a distinct ARN.
lambda_role.add_to_policy(
    iam.PolicyStatement(
        actions=[
            "dynamodb:GetItem",
            "dynamodb:Query",
            "dynamodb:Scan",
            "dynamodb:BatchGetItem",
        ],
        resources=[
            f"arn:aws:dynamodb:{replica_region}:{self.account}:table/{global_table.table_name}",
            f"arn:aws:dynamodb:{replica_region}:{self.account}:table/{global_table.table_name}/index/*",
        ],
    )
)

# The FIS Lambda extension layer (attached to reader Lambda) must be
# able to ListBucket and GetObject from the FIS config S3 bucket.
# Required by: https://docs.aws.amazon.com/fis/latest/userguide/use-lambda-actions.html#lambda-prerequisites
lambda_role.add_to_policy(
    iam.PolicyStatement(
        sid="AllowListingFisConfigLocation",
        actions=["s3:ListBucket"],
        resources=[fis_config_bucket.bucket_arn],
        conditions={
            "StringLike": {
                "s3:prefix": [f"{fis_config_prefix}*"]
            }
        },
    )
)
lambda_role.add_to_policy(
    iam.PolicyStatement(
        sid="AllowReadingFisConfigObjects",
        actions=["s3:GetObject"],
        resources=[f"{fis_config_bucket.bucket_arn}/{fis_config_prefix}*"],
    )
)

# The FIS extension running inside the reader Lambda needs to call back
# to the FIS service to check active experiment parameters.
lambda_role.add_to_policy(
    iam.PolicyStatement(
        actions=["fis:GetExperiment", "fis:ListExperiments"],
        resources=["*"],
    )
)

Enter fullscreen mode Exit fullscreen mode

Testing the System

To exercise the architecture, the project includes a Python test harness.

The script test_global_chaos.py runs several scenarios:

  • Baseline testing under healthy replication
  • Immediate read-after-write conditions
  • Version drift during replication pauses
  • Latency injection experiments
  • Lambda error injection tests

These tests validate both data correctness and routing behavior under chaos conditions.

Starting the “DynamoDB Pause Replication” experiment

The test harness also includes a watch mode, doing the designed steps of fetching data:

  1. writing the data
  2. read the data from the replica database if there are no issues reported

While an FIS experiment runs, you can observe the system transitioning through multiple states:

  1. Normal replica reads
  2. Replica becomes stale
  3. Fallback to primary
  4. SSM routing escalation
  5. Replica recovery
  6. Routing reset

This creates a clear visualization of resilience behavior over time. You can run this experiment with the following commands:

# Deploy the stack first and make sure you have the region bootstrapped!
cdk bootstrap
cdk deploy

# Install the needed dependencies
python3 -m venv .venv
source .venv/bin/activate
pip3 install -r requirements.txt

# Run the Python script
python3 test_global_chaos.py --watch

Enter fullscreen mode Exit fullscreen mode

Here is the transition of when the system is working as expected without the experiment running and then I manually start the experiment inside the FIS console — you can see the data beginning to be stale and the Lambda switches to the primary database right away:

Reader Lambda moving from Replica to Primary Database

After stopping the experiment, the system goes back to normal, taking data from the replica database:

Reader Lambda moving back to Replica Database

I’ve made this script not start the experiment on purpose, so you can start and stop this experiment as you wish as other experiments are designed to be shorter in time.

Simulating the Lambda delay

Now, we are going to cause our reader Lambda to have a 12 second delay before running the handler code. You can start this experiment with:

python3 test_global_chaos.py --scenario delay

Enter fullscreen mode Exit fullscreen mode

and everything will be started for you, the output should like:

Running the AWS FIS Lambda Delay Experiment

It is clear that the experiment is working — you can see that the Lambda is reporting that the data is stale and the execution time is easily above the 12 second mark.

Simulating the Lambda errors

Finally, we are going to simulate failure of the reader Lambda by running:

python3 test_global_chaos.py --scenario error

Enter fullscreen mode Exit fullscreen mode

again, the script will run everything for you:

Running the AWS FIS Lambda Error Experiment

Pricing

Now it’s time to look at pricing.

AWS Fault Injection Simulator

Based on the AWS Pricing docs, AWS FIS service is priced at $0.10 per experiment minute.

So, for an example:

3 experiments × 3 minutes would cost you $0.9 USD.

This is definitely the largest cost of the project — it has cost me just above $2 to create this project from scratch.

DynamoDB Global Tables

The pricing components are:

  • write request units
  • storage
  • replication write units

Example assumption:

  • 10k test writes
  • 10k reads
  • small dataset (<100 MB)

Approximate cost would be:

  • Writes: 10k × $1.25 / million ≈ $0.012
  • Reads: 10k × $0.25 / million ≈ $0.0025
  • Replication: similar to write cost ≈ $0.01

Total DynamoDB cost is around $0.03 USD.

Lambda

One of the cheaper services of this project:

  • $0.0000166667 for every GB-second
  • $0.20 per 1M requests

If you are not using your AWS account often, this will most likely be covered by AWS Free Tier.

SSM Parameter Store

As we are using the standard parameters, they are free as per these docs!

Final Thoughts

Many distributed architectures assume that multi-region databases provide seamless replication with minimal design considerations.

In reality, applications must still handle:

  • replication delays
  • partial failures
  • latency anomalies
  • degraded infrastructure

By combining:

  • DynamoDB Global Tables
  • AWS Fault Injection Simulator
  • Application-level fallback logic

we can design systems that are explicitly tested against real-world failure scenarios, not just theoretical ones. With these code snippets and the whole GitHub repository as your reference, you have the tools to make your architecture even better.