Skip to main content

Scenario: Amazon DynamoDB Consistency

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"A user updates their profile and immediately refreshes the page but sees stale data. You're using DynamoDB with global tables. Diagnose and fix without killing availability."

2. Real-World Context​

DimensionDetail
Company / systemAmazon DynamoDB — AWS managed key-value/document store; evolved from the Dynamo paper (2007)
ScaleSingle-digit ms latency; multi-region Global Tables; tunable read consistency per request
Why architects careDefault reads are eventually consistent; GSI has a separate replication timeline; Global Tables add cross-region lag
Public referencesDynamoDB developer guide on read consistency; session guarantees

AWS deployment context​

Typical profile/cart service on AWS: API Gateway + Lambda or ECS Fargate behind ALB; Amazon DynamoDB base table + GSI for email lookup; DynamoDB Global Tables for multi-region; optional DAX (microsecond cache); CloudFront for API responses (separate stale-read risk); CloudWatch for SuccessfulRequestLatency and replication lag; Route 53 geo-routing for read-your-writes via same region.

Step-by-step flow:

StepActionExplanation
1PUT profileUser saves profile change via PUT /profile.
2RouteCloudFront may cache GET responses — second stale-read source.
3WriteAPI writes to DynamoDB leader partition in us-east-1.
4PutItem leaderStrongly consistent write commits on partition leader.
5Async replicateGSI update is asynchronous — email lookup may lag.
6Global Table syncCross-region replication typically < 1s but not zero.
7GET stale readUser refreshes immediately — hits eventually consistent read path.
8Eventually consistent GetItemRead may hit replica before write propagates — stale data.

3. Step-by-Step Interview Answer​

Minutes 0–5: Diagnose​

  1. Symptom: Stale read after write — classic read-your-writes violation.
  2. Questions: Same region? Read from GSI or base table? Eventually vs strongly consistent read? CloudFront cache?
  3. Likely causes (ranked):
    • Eventually consistent GetItem on base table (default)
    • Read from GSI after write to base table (async GSI replication)
    • Global Tables cross-region read after write in different region
    • DAX cache not invalidated after write
    • CloudFront / API cache serving old response

Step-by-step flow (diagnosis):

StepActionExplanation
1Check read APIIs ConsistentRead=true set? Default is false.
2Check tableBase table vs GSI — GSI always eventually consistent.
3Check regionWrite us-east-1, read us-west-2 → Global Table lag.
4Check DAXDAX hit may return pre-write value until TTL/invalidation.
5Check CDNCloudFront may cache GET /profile independently of DynamoDB.

Minutes 5–15: DynamoDB consistency model​

Step-by-step flow:

StepActionExplanation
1Strong writePutItem always writes to partition leader — durable on ack.
2–3Async replicateLeader replicates to AZ replicas asynchronously (typically <1s).
4Eventually consistent readDefault GetItem may read from any replica — stale possible.
5Strongly consistent readConsistentRead=true reads from leader — latest write guaranteed.
Read typeGuaranteeRCU costUse when
Eventually consistentMay return stale data0.5× (half RCU)Lists, analytics, non-critical reads
Strongly consistentLatest write on leader partition1× (full RCU)Read-after-write, profile, cart
TransactionalACID across ≤100 items same region2×Multi-item atomic updates

GSI caveat — separate replication timeline:

Step-by-step flow:

StepActionExplanation
1PutItem baseWrite commits on base table leader.
2200 OKAPI returns success — user expects data visible.
3Query GSILookup by email on GSI immediately after write.
4Empty/staleGSI has not received update yet — classic bug.
5Async backfillDynamoDB propagates change to GSI asynchronously.
6–7RetryGSI query succeeds after replication lag.

Minutes 15–30: Fixes (pick by requirement)​

OptionMechanismTradeoff
A — Strong read after writeConsistentRead=true on GetItem2× RCU cost; leader latency
B — Return in write responseReturn updated item from PutItem responseNo second read needed
C — Session tokenSticky routing until replica catches upPlatform complexity
D — Geo-routingRoute read+write to same regionCross-region stale reads remain
E — DAX invalidationWrite-through or TTL=0 on profile keysCache layer management
F — Avoid GSI for read-after-writeQuery base table by PK after writeGSI only for search, not critical path

Step-by-step flow:

StepActionExplanation
A1–A2Strong readAfter write, explicitly request consistent read on base table.
B1–B2Write responseReturnValues=ALL_NEW — client gets fresh data without GetItem.
C1–C3Session tokenApp-level sequence in item + routing logic for session guarantees.

Minutes 30–45: CAP framing and Global Tables​

During partition, DynamoDB chooses availability with eventual consistency for default reads. Strong reads route to leader — may fail if leader unreachable.

Step-by-step flow:

StepActionExplanation
1PutItem EastUser updates profile in us-east-1.
2Async replicateGlobal Table streams change to us-west-2 (typically <1s).
3GetItem WestUser in California reads us-west-2 — may see old profile.

Global Tables fixes:

StrategyImplementation
Geo-DNS stickyRoute 53 latency routing — user always hits home region
UX "syncing"Show spinner for 1–2s after save; poll with strong read
Conflict resolutionLast-writer-wins with version attribute + conditional writes
Critical readsConsistentRead=true in same region as write

Measure: SuccessfulRequestLatency, UserErrors, ReplicationLatency (Global Tables), GSI backfill lag, DAX CacheHitRate.


4. Whiteboard Guide​

  1. Client → API → DynamoDB leader partition (label write path)
  2. Show replicas with lag arrow labeled "eventual (default read)"
  3. Branch: GSI with async replication (dashed line, longer lag)
  4. Branch: Global Table cross-region arrow
  5. Annotate fixes: ConsistentRead=true, ReturnValues=ALL_NEW, geo-DNS

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1PutItemWrite always hits leader — strongly consistent on ack.
2Replica lagDefault read may hit replica before replication.
3GSI lagGSI always eventual — separate timeline.
4Global TableCross-region replication adds lag.
5ConsistentReadFix for same-region read-after-write.
6ReturnValuesFix without second round-trip.

5. Principal-Level Signals​

  • Distinguishes DynamoDB strong read (base table) vs GSI eventual (always)
  • Does not claim "DynamoDB is strongly consistent" globally — only per-request opt-in
  • Proposes session guarantees when strong read on every request is too expensive
  • Checks CloudFront / DAX before blaming DynamoDB
  • Measures Global Table replication lag before tuning UX
  • Knows GSI cannot use ConsistentRead — design around it

6. Red Flags​

  • "DynamoDB is strongly consistent" — only with ConsistentRead=true on base table
  • Query GSI immediately after PutItem to base table for read-your-writes
  • Strong read on every list/browse request — 2× RCU cost at scale
  • Ignore CloudFront cache when diagnosing stale profile
  • Global Tables without conflict resolution strategy for concurrent writes

7. Follow-Up Questions​

QuestionStrong answer
Can GSI use strongly consistent reads?No — GSI reads are always eventually consistent
Strong read cost?2× RCU vs eventual; reads from leader — slightly higher latency
Shopping cart offline sync?Version vectors + conditional writes + last-writer-wins merge
DAX vs strong read?DAX is cache — write-through or invalidate; not a consistency fix alone
When Global Tables?Multi-region active-active; accept eventual cross-region or geo-route

9. Practice Drill​

Answer in 15 minutes: "Design a shopping cart that works offline on mobile and syncs when online." Tie to version vectors, conditional writes, and conflict resolution. Then whiteboard the GSI stale-read sequence from memory.


10. Production High-Level Design​

Build guide for profile/cart services with correct DynamoDB consistency guarantees on AWS.

10.1 Architecture diagram index​

SectionTopic
§2End-to-end AWS deployment
§3Leader/replica + GSI lag
§10.2C4 logical context
§10.3Full stack with Global Tables
§10.4When to use each read type
§11.4Profile update sequence
§11.5Version vectors + conflict resolution
§12Global Tables HA/DR
§13Metrics and alerts
§146-week rollout
§15Consistency integration tests
§16Production readiness

10.2 System context (C4 Level 1)​

Step-by-step flow:

StepActionExplanation
1Client requestProfile update or cart sync.
2BFF routingAPI applies consistency policy per operation type.
3Base tableCritical reads/writes on Users by user_id PK.
4GSIEmail lookup only — never for read-after-write path.
5CartPer-user partition — version attribute for offline merge.

10.3 AWS production architecture​

Step-by-step flow:

StepActionExplanation
1Geo routeRoute 53 sends user to nearest region for latency.
2WriteProfile update writes to local region DynamoDB leader.
3Global replicateChange streams replicate to other regions (<1s typical).
4Read eventualCross-region read may be stale — use geo-sticky or strong read in write region.
AWS componentConsistency responsibility
DynamoDB base tableConsistentRead=true for read-your-writes
GSIAlways eventual — not for critical read-after-write
Global TablesCross-region eventual; conflict handler required
DAXWrite-through or explicit invalidation on PutItem
CloudFrontCache-Control: no-store on profile GET or purge on PUT
Route 53Latency routing for same-region read-after-write

10.4 Consistency decision matrix​

OperationRead typeTableRationale
Profile update → show profileStrong or ReturnValuesBase tableRead-your-writes
Search user by emailEventually consistentGSIStale OK for search
Cart after add itemStrong on base tableCart tableUser expects immediate cart
Browse product catalogEventually consistentCatalog tableStale OK
Admin audit logStrongBase tableCompliance
Cross-region profile viewEventually consistent + UX delayGlobal Table replicaAccept lag or geo-route

11. Production Low-Level Design​

11.1 Table schema — Users​

{
"TableName": "Users",
"KeySchema": [{"AttributeName": "user_id", "KeyType": "HASH"}],
"GlobalSecondaryIndexes": [{
"IndexName": "email-index",
"KeySchema": [{"AttributeName": "email", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"}
}],
"BillingMode": "PAY_PER_REQUEST"
}

Item shape:

{
"user_id": "U123",
"email": "user@example.com",
"display_name": "Alice",
"version": 42,
"updated_at": "2026-07-28T21:00:00Z",
"region_written": "us-east-1"
}

11.2 API contract​

Endpoint: PUT /v1/profile — return updated item from PutItem (ReturnValues=ALL_NEW).

Endpoint: GET /v1/profile — default ConsistentRead=true on DynamoDB.

11.3 SDK calls — correct patterns​

Anti-pattern:

dynamodb.put_item(TableName="Users", Item={...})
response = dynamodb.get_item(TableName="Users", Key={"user_id": {"S": "U123"}})
# WRONG — eventually consistent; may return stale data

Pattern A — Strong read:

dynamodb.put_item(TableName="Users", Item={...})
response = dynamodb.get_item(
TableName="Users",
Key={"user_id": {"S": "U123"}},
ConsistentRead=True,
)

Pattern B — Return from write (preferred):

response = dynamodb.put_item(
TableName="Users",
Item={...},
ReturnValues="ALL_NEW",
)
return deserialize(response["Attributes"])

Pattern C — Conditional write with version:

dynamodb.put_item(
TableName="Users",
Item={**item, "version": current_version + 1},
ConditionExpression="version = :v OR attribute_not_exists(version)",
ExpressionAttributeValues={":v": current_version},
)

11.4 Profile update handler — step-by-step​

Step-by-step flow:

StepActionExplanation
1PUT profileClient submits profile update.
2ForwardCloudFront passes PUT to origin.
3PutItemWrite to base table leader with ReturnValues=ALL_NEW.
4200 + attributesDynamoDB returns committed item.
5Cache-Controlno-store — prevent CloudFront stale GET.
6200 freshClient receives updated profile immediately.
7–11GET refreshStrong read on base table — read-your-writes guaranteed.

11.5 Shopping cart — offline sync​

Step-by-step flow:

StepActionExplanation
1POST syncMobile reconnects with local cart version.
2Strong readFetch server state with ConsistentRead=true.
3ConflictServer version 4 < client version 5 — diverged offline.
4MergeUnion items, max qty — Dynamo AP semantics.
5Conditional writeOptimistic lock with version attribute.
6–7Merged cartClient receives merged state at version 6.

11.6 DAX integration​

PatternConsistencyWhen
Write-through DAXDAX updates cache on PutItemProfile writes
TTL=60sStale reads possibleNon-critical reads only
Bypass DAXDirect DDB with ConsistentReadRead-after-write critical path

11.7 GSI design rules​

RuleRationale
Never query GSI for read-after-writeGSI is always eventually consistent
Use GSI for login lookup by emailStale by 100ms OK
Base table PK lookup after writeuser_id known — use base table

12. HA/DR — Global Tables and Failover​

Conflict mitigation:

dynamodb.put_item(
Item={**item, "version": new_version, "updated_at": now()},
ConditionExpression="updated_at < :client_time OR attribute_not_exists(updated_at)",
ExpressionAttributeValues={":client_time": client_updated_at},
)
Failover stepActionRTO
1Route 53 fails over to us-west-2~60s TTL
2Global Table already has dataRPO <1s
3Brief cross-region stale readsUX "syncing" banner

13. Observability and Operations​

MetricAlert threshold
SuccessfulRequestLatency GetItem p99> 50ms
Strong read ratio> 30% — cost review
ReplicationLatency Global Tables> 1000ms
ConditionalCheckFailed spikeConflict storm

Runbook — stale profile reports:

StepAction
1Confirm user_id, timestamp, region
2Check if read used GSI
3Check CloudFront cache on GET
4Verify ConsistentRead=true or ReturnValues
5Check Global Table replication lag

14. Implementation Roadmap (6-Week Rollout)​

WeekDeliverable
1Audit all read paths + GSI usage
2ConsistentRead + ReturnValues on profile/cart
3CloudFront no-store on profile GET
4DAX write-through evaluation
5Global Tables conflict handling
6Read-your-writes integration tests in CI

15. Testing Strategy​

TestPass criteria
PutItem → GetItem eventualMay fail — documents bug
PutItem → GetItem ConsistentRead=trueAlways matches
PutItem → immediate GSI QueryMay be empty — expected
Write East → read WestDocument acceptable lag
Offline cart mergeNo data loss

16. Architecture Review Checklist​

#GateStatus
1Read-after-write uses base table + ConsistentRead or ReturnValues☐
2GSI never on critical read-after-write path☐
3CloudFront no-store on profile GET☐
4Global Tables conflict resolution with version☐
5Cart offline sync uses version vectors☐
6DAX write-through or bypass on critical reads☐
7ReplicationLatency dashboard☐
8Read-your-writes integration test in CI☐