Multi-Region Active-Active Serverless Patterns with Global Tables

On this page

An active-active serverless application runs the same stack in two or more AWS Regions and takes live traffic in all of them. The compute part is easy: API Gateway and Lambda are Regional and stateless, so the same deployment can run anywhere. The hard part is the data. Every Region has to read and write the same records, and the moment two Regions accept writes, you have to decide what happens when they disagree.

Amazon DynamoDB global tables are the usual answer on AWS, and since 30 June 2025 they offer two consistency modes with very different rules: multi-Region eventual consistency (MREC), the long-standing default, and multi-Region strong consistency (MRSC). This article covers request routing, what each mode guarantees, the write patterns AWS recommends for each, a tested orders API that keeps updates conflict-free on MREC, the cost of replication, and how to take a Region out of service.

Request routing

Each Region gets its own Regional API Gateway endpoint with the same custom domain name, and Route 53 latency-based alias records point that name at each Region. With Evaluate Target Health enabled and a health check per Region, Route 53 skips a Region whose endpoint is unhealthy and answers with the next-best latency record instead. Edge-optimized endpoints route through CloudFront to a single home Region, so they are the wrong building block here; Regional endpoints behind Route 53 are the standard pattern.

Architecture diagram: Route 53 latency records with health checks route users to a Regional API Gateway in eu-west-1 or us-east-1; each Region runs the same Lambda functions against its own DynamoDB replica, and the replicas replicate asynchronously
The same stack runs in each Region. Lambda talks only to the local replica, so an impairment in one Region does not reach into the other.

Two Route 53 details matter in practice. First, the health check should test something that fails when the Region cannot serve requests, not just that Lambda answers; the sample’s /health handler reads a canary item from the local replica with a one-second timeout and one attempt. Second, if every record in a group is unhealthy, Route 53 treats them all as healthy and keeps answering. A deep health check that depends on a shared component can therefore fail open in every Region at once, which is a reason to keep it Regional.

Consistency modes

A global table has one consistency mode, chosen when it is created and fixed afterwards.

BehaviourMREC (default)MRSC (since 30 June 2025)
ReplicationAsynchronous, typically within a secondSynchronous to at least one other Region before the write returns
Recovery point objectiveEqual to the replication delay, usually a few secondsZero
Strongly consistent readsLatest version only if the item was last written in the same RegionAlways the latest version, in any Region
Condition expressionsEvaluated against the local replica’s copyEvaluated against the latest version
Concurrent writes to one itemLast writer wins, by an internal timestamp, per itemThe second write fails with ReplicatedWriteConflictException and can be retried
TransactionsAtomic only in the Region where they runNot supported
RegionsAny number, in any RegionExactly three: three replicas, or two replicas and a witness, in one Region set
Other limitsNone specificNo TTL, no LSIs; GSI reads are eventually consistent; must be created on an empty table
ℹ️
MRSC REGION SETS

In April 2026 MRSC tables must sit inside one Region set: US (N. Virginia, Ohio, Oregon), EU (Ireland, London, Paris, Frankfurt) or AP (Tokyo, Seoul, Osaka). The witness is owned by DynamoDB, does not appear in your account, and cannot be read or written. Write latency includes a round trip to another Region in the set, so measure it with your own item sizes before committing.

Global tables carry a 99.999% availability SLA, against 99.99% for a single-Region table, in either mode. The mode decides what you lose and what you have to design for when Regions disagree.

Conflicts in MREC

In MREC, each Region accepts a write, acknowledges it and replicates it later. If two Regions update the same item before replication catches up, DynamoDB keeps the write with the later internal timestamp and discards the other, per item. Nothing fails; one update simply disappears.

⚠️
COUNTERS AND CONDITIONS

Because MREC evaluates condition expressions against the local replica, a version check or attribute_not_exists guard does not protect against a concurrent write in another Region. Two Regions can both read a stock level of 10, both write 9, and both pass their conditions; the table converges to 9 instead of 8. Atomic counters have the same exposure. For values that must not lose updates, give each item a single writing Region or use an MRSC table.

AWS’s prescriptive guidance for global tables describes three write patterns that follow from this:

  • Write to any Region (no primary): suitable for MRSC tables, and for MREC when every write is idempotent, such as append-only events where a duplicate is harmless.
  • Write to one Region (single primary): all writes go to one Region at a time and reads can go anywhere. Simple, but every remote write pays the cross-Region latency.
  • Write to your Region (mixed primary): each item has a home Region and is written only there. Writes stay close to most users and never conflict, because only one Region ever writes a given item.

Orders API with home Regions

The sample implements the third pattern on an MREC table. Creates are idempotent: the client’s Idempotency-Key header is the item key, a conditional put creates the item once, and a replay with the same body returns the stored order. Each order records the Region that created it as its home_region. Updates are accepted only there, with an optimistic version check; a request in the wrong Region gets HTTP 421 with an x-home-region header, and the client retries against that Region’s endpoint.

%%{init: {'theme': 'base', 'themeVariables': {'actorBkg': '#FFF3E0', 'actorBorder': '#FF9900', 'actorTextColor': '#232F3E', 'signalColor': '#0073BB', 'signalTextColor': '#0F172A', 'noteBkgColor': '#FFF8E7', 'noteBorderColor': '#FF9900', 'noteTextColor': '#232F3E'}}}%%
sequenceDiagram
    participant C as Client
    participant EU as eu-west-1 API
    participant US as us-east-1 API
    C->>US: PATCH /orders/k-1 (expected_version 1)
    Note over US: Order k-1 has home_region eu-west-1
    US-->>C: 421, x-home-region: eu-west-1
    C->>EU: PATCH /orders/k-1 (expected_version 1)
    Note over EU: Version check on the only Region that writes k-1
    EU-->>C: 200, version 2

This is the complete order logic, as tested:

Python126 lines
"""Order writes for a DynamoDB global table in MREC mode, using the
"write to your Region" (mixed primary) pattern.

- Creates are idempotent: the client's idempotency key is the item key, and a
  conditional put means a retry, or the same request arriving in two Regions,
  creates the item once (after replication; see the article for the window).
- Every order has a home Region, set when it is created. Updates are accepted
  only in that Region, so concurrent updates to one order never race across
  Regions and last-writer-wins never has to choose between them.
- Updates use an optimistic version check. In MREC mode condition expressions
  are evaluated against the local replica, which is exactly why updates must
  stay in the home Region.
"""

from __future__ import annotations

import hashlib
import json
import time
from decimal import Decimal
from typing import Any

from botocore.exceptions import ClientError

ALLOWED_STATUS = {"PLACED", "PAID", "SHIPPED", "CANCELLED"}


class OrderError(Exception):
    status = 400


class Conflict(OrderError):
    status = 409


class NotFound(OrderError):
    status = 404


class WrongHomeRegion(OrderError):
    """The order must be updated in another Region."""

    status = 421  # Misdirected Request

    def __init__(self, home_region: str):
        super().__init__(f"order is homed in {home_region}")
        self.home_region = home_region


def _fingerprint(customer_id: str, amount: Decimal) -> str:
    raw = json.dumps({"c": customer_id, "a": str(amount)}, sort_keys=True)
    return hashlib.sha256(raw.encode()).hexdigest()


def _parse_amount(value: Any) -> Decimal:
    try:
        amount = Decimal(str(value))
    except Exception as exc:  # noqa: BLE001
        raise OrderError("amount must be a number") from exc
    if amount <= 0 or amount.as_tuple().exponent < -2:
        raise OrderError("amount must be positive with at most two decimals")
    return amount


def create_order(table, region: str, idempotency_key: str, customer_id: str,
                 amount: Any, now_ms: int | None = None) -> tuple[dict[str, Any], bool]:
    """Return (order, created). created is False for an idempotent replay."""
    if not idempotency_key or len(idempotency_key) > 64:
        raise OrderError("Idempotency-Key header is required (max 64 chars)")
    if not customer_id:
        raise OrderError("customer_id is required")
    amount = _parse_amount(amount)
    fp = _fingerprint(customer_id, amount)
    now_ms = now_ms or int(time.time() * 1000)
    item = {
        "pk": f"ORDER#{idempotency_key}",
        "customer_id": customer_id,
        "amount": amount,
        "status": "PLACED",
        "version": 1,
        "home_region": region,
        "request_fingerprint": fp,
        "created_at_ms": now_ms,
        "updated_at_ms": now_ms,
        "updated_in": region,
    }
    try:
        table.put_item(Item=item, ConditionExpression="attribute_not_exists(pk)")
        return item, True
    except ClientError as exc:
        if exc.response["Error"]["Code"] != "ConditionalCheckFailedException":
            raise
    existing = table.get_item(Key={"pk": item["pk"]}, ConsistentRead=True).get("Item")
    if existing is None:  # deleted between the put and the get
        raise Conflict("order changed concurrently; retry")
    if existing.get("request_fingerprint") != fp:
        raise Conflict("idempotency key reused with a different request")
    return existing, False


def update_status(table, region: str, order_id: str, new_status: str,
                  expected_version: int, now_ms: int | None = None) -> dict[str, Any]:
    if new_status not in ALLOWED_STATUS:
        raise OrderError(f"status must be one of {sorted(ALLOWED_STATUS)}")
    key = {"pk": f"ORDER#{order_id}"}
    current = table.get_item(Key=key, ConsistentRead=True).get("Item")
    if current is None:
        raise NotFound("order not found")
    if current["home_region"] != region:
        raise WrongHomeRegion(current["home_region"])
    now_ms = now_ms or int(time.time() * 1000)
    try:
        resp = table.update_item(
            Key=key,
            UpdateExpression="SET #s = :s, version = version + :one, updated_at_ms = :t, updated_in = :r",
            ConditionExpression="version = :v AND home_region = :r",
            ExpressionAttributeNames={"#s": "status"},
            ExpressionAttributeValues={":s": new_status, ":one": 1, ":t": now_ms,
                                       ":v": expected_version, ":r": region},
            ReturnValues="ALL_NEW",
        )
    except ClientError as exc:
        if exc.response["Error"]["Code"] == "ConditionalCheckFailedException":
            raise Conflict("version mismatch; read the order and retry") from exc
        raise
    return resp["Attributes"]

The Lambda handlers in the repository wrap these functions for an API Gateway HTTP API, return whole numbers as JSON integers and amounts as exact decimal strings, and set short timeouts with the SDK’s standard retry mode.

One window remains. If a client retries the same create in two Regions before the first write has replicated, both conditional puts succeed locally and last writer wins picks one; the bodies are identical, so only the recorded home Region can differ. Clients that pin a session to one Region, which latency routing does by default, rarely hit this, and a deterministic home Region, for example the customer’s account Region, removes it.

Items that need strong consistency

Some data cannot be partitioned by home Region: a shared stock level, a balance, a seat map. Those items belong in a separate MRSC table. CloudFormation supports MRSC through MultiRegionConsistency and GlobalTableWitnesses on AWS::DynamoDB::GlobalTable:

YAML45 lines
AWSTemplateFormatVersion: "2010-09-09"
Description: >
  DynamoDB global table in multi-Region strong consistency (MRSC) mode for
  items that must never diverge, such as stock levels or balances. Two
  replicas (us-east-1, us-east-2) and a DynamoDB-managed witness (us-west-2),
  all in the US Region set. Deploy this stack in us-east-1. The table must be
  created empty; MRSC cannot be enabled on a table that already holds items.

Parameters:
  TableName:
    Type: String
    Default: inventory

Resources:
  InventoryTable:
    Type: AWS::DynamoDB::GlobalTable
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      TableName: !Ref TableName
      BillingMode: PAY_PER_REQUEST
      MultiRegionConsistency: STRONG
      GlobalTableWitnesses:
        - Region: us-west-2
      AttributeDefinitions:
        - AttributeName: pk
          AttributeType: S
      KeySchema:
        - AttributeName: pk
          KeyType: HASH
      SSESpecification:
        SSEEnabled: true
      Replicas:
        - Region: us-east-1
          DeletionProtectionEnabled: true
          PointInTimeRecoverySpecification:
            PointInTimeRecoveryEnabled: true
        - Region: us-east-2
          DeletionProtectionEnabled: true
          PointInTimeRecoverySpecification:
            PointInTimeRecoveryEnabled: true

Outputs:
  TableArn:
    Value: !GetAtt InventoryTable.Arn

Splitting data this way is normal. Orders, profiles and history stay on the MREC table with local writes; the few items where a lost update is a business error go to the MRSC table and accept the extra write latency. If those items also need multi-item transactions, MRSC cannot hold them and they need a single writing Region on an MREC table instead.

Region evacuation

Taking a Region out of service is a routing change, not a database change, but the order of steps depends on the write pattern. With write to one Region or write to your Region, all writes in the old Region must have replicated before another Region starts writing those items, otherwise last writer wins can reorder them. With MRSC or idempotent writes, traffic can move immediately.

  • Manual drain: the sample’s health handler returns 503 when REGION_DRAINED is set, so Route 53 stops sending traffic to that Region within a few health-check intervals.
  • Orchestrated switch: Amazon Application Recovery Controller Region switch, available since 1 August 2025, runs a plan of ordered steps for failover and failback, and for removing or adding a Region in an active-active application.
  • Capacity: each Region must be able to carry the other’s traffic. On-demand tables and Lambda scale with traffic, but account concurrency quotas and downstream dependencies in the surviving Region need headroom.
⚖️
DATA RESIDENCY

A global table copies every item to every replica Region, and Route 53 failover sends users to another Region’s compute. If personal or health data must stay in a jurisdiction, keep all replicas and the witness inside it (for example the EU Region set for MRSC) and document the Regions in the processing record. A table replicated to the US is a transfer of personal data out of the EU whether or not the US Region ever serves a request.

Cost

Writes to a global table are billed as replicated write units in every Region that holds a replica, and replicated writes are priced the same as single-Region writes. DynamoDB does not charge cross-Region data transfer for replication. A witness in an MRSC table incurs no replicated write, storage or transfer charges. AWS cut replicated write prices on 1 November 2024, by 67% for on-demand and 33% for provisioned capacity.

10 million 1 KB writes a month, on-demand, US EastReplicated write unitsMonthly write cost
Single-Region table10 million WRUs$6.25
MREC, two replicas20 million rWRUs$12.50
MRSC, two replicas and a witness20 million rWRUs$12.50
MRSC, three replicas30 million rWRUs$18.75

Worked cell: two replicas × 10 million writes = 20 million rWRUs, and 20 × $0.625 = $12.50. Storage is also charged in each replica Region, and every GSI update is charged as a write in each Region, so a table with two GSIs and two replicas pays for six writes per item write.

Production considerations

  • Watch replication lag. MREC tables publish a ReplicationLatency metric per Region pair; alarm on it, because it is your effective recovery point. MRSC tables do not publish it.
  • Test failure, not just failover. Pause a Region in a test account and check that health checks fail, traffic moves and the surviving Region holds the load.
  • Keep Lambda Regional. A function that calls the other Region’s endpoint for every request turns a Regional failure into a global one.
  • Use idempotency keys everywhere. Clients will retry after a failover, sometimes into the other Region; idempotent creates make those retries safe.
  • Mind TTL on MRSC. MRSC tables have no TTL, so expiring data needs a scheduled cleanup or a separate MREC table.

Decision framework

Decision matrix comparing MREC with writes in any Region, MREC with writes in each item's home Region, and MRSC across write latency, recovery point, concurrent updates, transactions, TTL and LSIs, and Region coverage
MREC with a home Region per item keeps writes local and conflict-free for most data. MRSC is for the items that cannot lose an update, within one Region set.

Default to MREC with home Regions for most serverless active-active applications: writes stay local, any number of Regions works, TTL and LSIs are available, and no update is ever silently lost because only one Region writes each item. Use MRSC for the items that must read the latest value everywhere or cannot lose an update, and accept three Regions in one set, higher write latency and no transactions. Write anywhere on MREC only when every write is idempotent.

The choice changes if your recovery point objective is zero for the whole dataset. Then MRSC is the only option on DynamoDB, and its Region-set and feature limits shape the rest of the design.

📝
HOW THIS WAS CHECKED

The order logic and Lambda handlers were tested with Python 3.13, boto3==1.42.89 (13 April 2026) and moto 5.1.22: eight tests cover idempotent creates, rejected key reuse, validation, the version check, the home-Region redirect and the health endpoint. Both CloudFormation templates pass cfn-lint 1.48.1 (1 April 2026), which rejects a misspelled MultiRegionConsistency property. Replication between Regions was not tested, because local emulators do not replicate. DynamoDB prices were read from the AWS pricing page in November 2026.

Key takeaways

  • Route 53 latency records with health checks over Regional API Gateway endpoints are the routing layer; keep each Region’s Lambda functions talking only to the local replica.
  • MREC replicates asynchronously and resolves conflicts per item with last writer wins; condition expressions are evaluated only against the local replica.
  • MRSC, generally available since 30 June 2025, gives zero RPO and the latest read in any Region, in exactly three Regions of one Region set, without TTL, LSIs or transactions.
  • Giving each item a home Region makes MREC conflict-free; reserve MRSC for the items that cannot lose an update.
  • Replicated writes cost the same as single-Region writes in each replica Region, with no cross-Region transfer charge for replication.

How do you decide which items get a home Region and which go to a strongly consistent table? Share your approach in the comments.

Glossary

Active-active
An architecture where every Region serves live read and write traffic.
Global table
A DynamoDB table replicated to replicas in several Regions.
Replica
A full copy of a global table in one Region.
MREC
Multi-Region eventual consistency: asynchronous replication with last writer wins.
MRSC
Multi-Region strong consistency: synchronous replication to at least one other Region, zero RPO.
Witness
A DynamoDB-managed MRSC component in a third Region that stores replicated data but serves no reads or writes.
Last writer wins
Conflict resolution that keeps the write with the latest internal timestamp for each item.
Home Region
The one Region allowed to write a given item in the write-to-your-Region pattern.
Recovery point objective (RPO)
The amount of recent data a failure can lose.
Replicated write unit (rWRU)
The on-demand billing unit for a write to a global table, charged in each replica Region.
Evaluate Target Health
The Route 53 alias setting that skips a target with no healthy records.
Idempotency key
A client-supplied identifier that makes a retried request produce the same result.

References & Further Reading


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.