DynamoDB can return a single item from a table with 10 billion records in under 2ms — not because it is faster than MongoDB per se, but because a DynamoDB GetItem operation is a direct hash lookup into a single partition. The partition key is hashed, the hash selects exactly one of the table’s internal shards, and the item is read from that shard’s B-Tree with no routing fanout, no query planner evaluation, and no index traversal across multiple storage nodes. MongoDB can match that latency for equivalent key lookups — but only if the query uses the shard key directly. If the application needs to query by a field that is not the partition key (DynamoDB) or not the shard key (MongoDB), the two systems diverge dramatically in what they require from the engineer to maintain production performance.

The root decision — DynamoDB or MongoDB — is a decision about where you want to pay the access pattern tax. DynamoDB charges it at table design time: every access pattern must be modeled as a primary key, sort key, or GSI before the table is created. MongoDB charges it at index design time, which can happen iteratively as access patterns evolve. Neither approach is free — DynamoDB’s upfront cost is schema rigidity; MongoDB’s deferred cost is operational index management, cache sizing, and query planner tuning at scale.

Situation

DynamoDB and MongoDB are both document-oriented databases that store JSON-compatible data. The similarity ends at the query layer. Their internal storage architectures make fundamentally different tradeoffs between write scalability, query flexibility, and access pattern determinism.

DimensionDynamoDBMongoDB
Storage engineProprietary — multi-tenant log-structured storage on SSD across partition fleetWiredTiger B-Tree — single-tenant per instance, O_DIRECT I/O, internal cache pool
Primary key modelPartition key (required) + sort key (optional) — determines physical placement_id — required; shard key (optional, for sharded collections) — determines chunk placement
Secondary query modelGSI (Global Secondary Index) — replicated copy of data with alternate key; LSI (Local Secondary Index) — same partition, alternate sortCompound B-Tree index — covers multiple fields with prefix-ordered traversal; no data copy
Access pattern rigidityHigh — GSI must be pre-declared; backfill is not retroactive; table scan is O(N)Moderate — indexes can be added to any field at any time; background build on live data
Throughput modelProvisioned (RCU/WCU) or on-demand (per-request pricing) — capacity auto-scaled per partitionInstance-based — IOPS/throughput bounded by instance type, WiredTiger cache, and storage
Transaction modelSingle-table transactions (TransactWriteItems, up to 25 items) or cross-table (limited)Multi-document ACID transactions (replica set or sharded, with cross-shard support in 4.2+)
Pricing modelPay for RCU/WCU + storage + GSI RCU; scan costs full table RCUPay for instance + storage; query cost is operational, not billing

The Problem

The failure mode that drives teams to regret a DynamoDB or MongoDB choice at scale is almost always the same: an access pattern that was not anticipated at design time.

For DynamoDB, the failure is a query requirement that cannot be expressed as a primary key lookup or a declared GSI. If the product team needs to query IoT device records by firmware_version — a field that was not in the original table design — there are only two options: add a GSI on firmware_version (if DynamoDB’s GSI limit of 20 per table allows it and the query pattern justifies the 2× storage cost and eventual consistency lag) or perform a full table scan with a filter expression, which consumes full read capacity units for every item in the table regardless of how selective firmware_version is.

For MongoDB, the equivalent failure is adding indexes reactively without understanding the WiredTiger cache implications: each additional index adds write amplification (every insert, update, delete must maintain all indexes) and consumes WiredTiger cache (index pages are loaded for writes even when never used for reads). A collection with 15 indexes where 8 have zero $indexStats accesses is paying 15× write amplification while only benefiting from 7 indexes’ read performance.

How do you determine — before writing a line of schema code — which access patterns are primary-key-expressible (DynamoDB wins), which are query-predicate-based (MongoDB’s index flexibility helps), and which are analytically open-ended (neither model serves without a separate OLAP layer)?

DynamoDB Storage Internals: Partition Hashing, GSI Fan-Out, and Read Consistency

Partition key hashing and hot partitions. DynamoDB’s storage layer distributes items across internal partitions using a consistent hash of the partition key. A table with 1 million provisioned WCUs may have thousands of internal partitions; each partition handles a share of the total capacity. A table where 80% of writes target items with customerId = "megacorp" will route 80% of write traffic to a single partition — consuming that partition’s WCU allocation and throttling writes that exceed it, while the other partitions are idle.

The DescribeTableReplicaAutoScaling and CloudWatch metric ConsumedWriteCapacityUnits broken down by TableName and GlobalSecondaryIndexName reveal aggregate throttling — but DynamoDB does not expose per-partition metrics directly. Detecting hot partitions requires inferring from error patterns: ProvisionedThroughputExceededException on a subset of partition key values while the table aggregate WCU appears under capacity.

import boto3
import time
from collections import Counter

dynamodb = boto3.client('dynamodb', region_name='us-east-1')
cloudwatch = boto3.client('cloudwatch', region_name='us-east-1')

def detect_hot_partition_via_throttle_sampling(table_name: str, sample_duration_seconds: int = 60):
    """
    Sample throttled requests to infer hot partition keys.
    DynamoDB does not expose per-partition metrics — throttle patterns approximate it.
    """
    waiter_client = boto3.client('dynamodb', region_name='us-east-1',
        config=boto3.session.Config(retries={'max_attempts': 1}))
    
    throttled_keys = Counter()
    end_time = time.time() + sample_duration_seconds
    
    # This requires a sample query set representative of production traffic
    sample_partition_keys = load_production_traffic_sample()
    
    for pk in sample_partition_keys:
        if time.time() > end_time:
            break
        try:
            waiter_client.get_item(
                TableName=table_name,
                Key={'customerId': {'S': pk}},
                ConsistentRead=True
            )
        except waiter_client.exceptions.ProvisionedThroughputExceededException:
            throttled_keys[pk] += 1
    
    return throttled_keys.most_common(10)  # Top 10 hot partition keys

def get_table_throttle_rate(table_name: str, minutes: int = 15) -> float:
    """Get table-level throttle rate from CloudWatch."""
    response = cloudwatch.get_metric_statistics(
        Namespace='AWS/DynamoDB',
        MetricName='WriteThrottleEvents',
        Dimensions=[{'Name': 'TableName', 'Value': table_name}],
        StartTime=time.time() - (minutes * 60),
        EndTime=time.time(),
        Period=60,
        Statistics=['Sum']
    )
    total_throttles = sum(d['Sum'] for d in response['Datapoints'])
    return total_throttles / minutes  # throttles per minute

GSI fan-out and eventual consistency lag. A Global Secondary Index is a separate, replicated copy of the table data with a different partition key and optional sort key. DynamoDB replicates writes to GSIs asynchronously — the documented behavior is eventual consistency. After a write to the base table, the corresponding GSI entry may lag by up to several seconds before reflecting the new value. For queries that require reading the GSI version of an item immediately after writing to the base table, this lag creates a window where the query returns stale data.

The GSI also consumes WCU independently of the base table: each write to the base table that affects the GSI projected attributes triggers a write to the GSI at its separately provisioned WCU. A table with 3 GSIs and 10,000 WCU may need 40,000 WCU total (10K for base + 10K × 3 for GSI writes) for write-heavy workloads where all three GSI keys are updated on each base table write.

DynamoDB Streams and analytics fan-out. DynamoDB Streams captures changes to items in near-real-time and makes them available to Lambda triggers or Kinesis Data Streams consumers. For analytics that would otherwise require full table scans, the pattern is to fan out writes from the primary table via Streams to an OpenSearch/S3/Redshift sink — maintaining a secondary analytical representation that supports arbitrary query patterns without consuming DynamoDB read capacity.

MongoDB Storage Internals: WiredTiger IXSCAN, Shard Key Routing, and Cache Implications

WiredTiger IXSCAN vs DynamoDB GetItem — the physical difference. A MongoDB IXSCAN on a compound index {customerId: 1, timestamp: -1} traverses a WiredTiger B-Tree stored in a private data file on the mongod host, using O_DIRECT reads that bypass the OS page cache and load directly into WiredTiger’s internal cache. If the index pages are cache-resident, the IXSCAN reads entirely from memory. If the index pages are cache-evicted (working set exceeds cacheSizeGB), each IXSCAN page requires a physical disk read — increasing latency from sub-millisecond (cache hit) to 0.2–5ms per page (SSD read) or 5–20ms per page (HDD).

DynamoDB’s GetItem operation, by contrast, routes to a specific partition’s B-Tree node via the hash routing layer — a network round-trip to the DynamoDB storage service (typically 1–5ms from EC2 in the same region), regardless of data size. DynamoDB’s SSD fleet is shared infrastructure, so there is no cache sizing concern — but also no opportunity for sub-millisecond memory-only access as MongoDB provides for cache-resident data.

Shard key selection and scatter-gather prevention. In a sharded MongoDB deployment, a query that includes the shard key as an equality predicate routes to exactly one shard (targeted query). A query that omits the shard key or uses a range that spans multiple chunks routes to all shards simultaneously (scatter-gather). Scatter-gather multiplies latency: the mongos router sends the query to all shards, waits for all responses, merges them, and returns the result — latency is the max of all shard latencies, not the average.

// Verify query routing behavior
db.devices.find({customerId: "abc123", firmwareVersion: "2.4.1"})
          .explain("executionStats")

// In the explain output, look for:
// "queryPlanner.winningPlan.stage": "SHARD_MERGE"  → scatter-gather (bad)
// "queryPlanner.winningPlan.stage": "SINGLE_SHARD" → targeted query (good)

// For the sharding plan specifically:
db.devices.explain("executionStats")
          .find({customerId: "abc123"})
// If customerId is the shard key: SINGLE_SHARD
// If customerId is NOT the shard key: SHARD_MERGE to all shards

Index maintenance cost at scale. Each MongoDB index on a collection imposes write amplification: every insert, update, and delete must update the corresponding B-Tree structure in WiredTiger. For a collection with 12 indexes (not uncommon in evolving applications), each insert requires 12 separate B-Tree write operations — plus the collection B-Tree itself. Under write-heavy workloads, index maintenance becomes the dominant WiredTiger I/O operation, visible in db.serverStatus().wiredTiger.cache["pages written from cache"] climbing disproportionately relative to document count.

// Identify write amplification from indexes
const status = db.serverStatus();
const pagesWritten = status.wiredTiger.cache["pages written from cache"];
const docsInserted = status.opcounters.insert;
const ratio = pagesWritten / docsInserted;
print(`Write amplification ratio: ${ratio.toFixed(1)}x per insert`);
// A ratio above 10x suggests too many indexes relative to write throughput

// Find indexes with zero reads — pure write amplification overhead
db.devices.aggregate([{$indexStats: {}}, 
  {$project: {name: 1, ops: "$accesses.ops"}},
  {$match: {ops: 0, name: {$ne: "_id_"}}}])

In Practice

The access pattern inventory — the prerequisite decision. Before choosing DynamoDB or MongoDB, the documented engineering practice (from AWS’s DynamoDB design documentation and MongoDB’s data modeling documentation) is to enumerate every access pattern as: entity, query type (lookup/range/filter), fields used, required consistency, and write frequency. Each pattern maps to either a DynamoDB primary key/GSI or a MongoDB index:

Access PatternDynamoDB SolutionMongoDB Solution
”Get device by ID”GetItem on deviceId (PK)find({_id: deviceId}) — _id always indexed
”Get all devices for customer”Query on customerId (PK) or GSI if customerId is not PKCompound index {customerId: 1} + IXSCAN
”Get devices by firmware version”GSI on firmwareVersion (add at design time)createIndex({firmwareVersion: 1}) — can add post-launch
”Get devices last seen in past 24h”Requires lastSeen as sort key or GSI sort keyIndex {lastSeen: -1} + range query
”Full-text search on device notes”Not supported natively — requires OpenSearch integrationAtlas Search or $text index (on Atlas or self-managed)
“Devices matching complex filter (3+ conditions)“Cannot — GSI max 2 key fields; complex filter = scanCompound index matching the filter fields (ESR rule)

The critical column is the last one: patterns that require 3+ field predicates in an arbitrary filter are incompatible with DynamoDB’s 2-field key model without a scan or application-layer filtering. For these patterns, MongoDB’s compound index model is the better fit — as long as the index is correctly designed and the WiredTiger cache is sized for the index working set.

Where It Breaks

Failure ModeRoot CauseProduction Blast RadiusMitigation
DynamoDB hot partition — throughput throttlingWrite traffic concentrated on a small number of partition key values (low cardinality PK or skewed distribution); DynamoDB throttles at the partition level before the table-level capacity is exhaustedProvisionedThroughputExceededException on writes to specific items while aggregate WCU appears underutilized; item-level retries exhaust application thread poolAudit partition key cardinality before table creation; for write-skewed workloads, use a write-sharding suffix (append a random 1–10 suffix to the partition key, scatter writes, aggregate reads)
DynamoDB GSI eventual consistency — stale read immediately after writeApplication writes to base table, immediately queries GSI for the same item; GSI replication lag (milliseconds to seconds) returns pre-write valueApplication reads stale data; for financial or inventory applications, this creates double-spend or oversell conditionsFor read-after-write consistency, read from the base table (consistent read) rather than the GSI; design application flows to not require immediate GSI consistency
MongoDB scatter-gather on missing shard key — query fanoutApplication query omits the shard key predicate; mongos routes to all shards; latency is max(all shard latencies) not averageQuery latency multiplies with shard count; a 10-shard cluster produces 10× the latency of a single-shard query for scatter-gather patternsRun explain("executionStats") on all production query shapes and verify SINGLE_SHARD plan; any SHARD_MERGE plan requires shard key inclusion or explicit scatter budget
MongoDB index proliferation — write amplificationTeam adds indexes reactively for each new query; collection accumulates 15+ indexes; each insert/update touches all 15 WiredTiger B-TreesWrite throughput degrades; insert latency climbs from 1ms to 10–50ms per document; bulk import operations stallAudit indexes monthly via $indexStats; drop any index with ops: 0 since last restart; consolidate overlapping compound indexes
DynamoDB table scan for unindexed filter — RCU exhaustionAn access pattern requires filtering on a non-PK, non-GSI field; application falls back to Scan with FilterExpression; DynamoDB charges RCU for every item scanned before the filter is appliedA scan of a 10M item table at 4KB average item size consumes 10M RCU — potentially thousands of dollars for a single query; with provisioned capacity, the scan exhausts all table WCU, throttling concurrent operationsNever rely on DynamoDB Scan for production read paths; any access pattern requiring a non-key filter must be modeled as a GSI at table design time or handled by a separate search system (OpenSearch, Atlas Search)
MongoDB WiredTiger cache miss — index pages evictedApplication adds new indexes that collectively exceed the WiredTiger cacheSizeGB; index pages for recently added indexes are not cache-resident; IXSCAN operations require disk readsIXSCAN latency increases from sub-millisecond (cache hit) to 2–10ms (SSD disk read); affects all queries that use the new or competing indexesSum all index sizes via db.collection.stats().indexSizes and compare to WiredTiger cache capacity; new indexes should fit within the cache headroom before deployment
DynamoDB GSI limit reached — access pattern blockedTable accumulates 20 GSIs (DynamoDB’s hard limit); a new access pattern requires a 21st GSINew access pattern cannot be served without a full table redesign or migration to a different data modelModel all anticipated access patterns before table creation; use sparse GSIs (only project items meeting a filter condition) to reduce GSI count; consider DynamoDB Streams + a secondary index in OpenSearch for open-ended query patterns
MongoDB resharding latency — shard key change impacts availabilityApplication discovers the original shard key causes hot shards; MongoDB resharding is initiated; during resharding (which can take hours for large collections), write operations experience additional latency while chunks are migratedWrite latency increases 2–5× during active resharding; for collections with billions of documents, resharding can run for 6–24 hoursChoose shard keys with long-term write distribution in mind; test shard key cardinality and write distribution under production-representative traffic before launch; use analyzeShardKey (MongoDB 7.0+) to evaluate distribution before committing

2026 Access Pattern Architecture Update

DynamoDB introduced zero-ETL integration with Amazon OpenSearch Service (GA 2024), allowing real-time replication from DynamoDB tables to OpenSearch indexes without a Lambda or Kinesis intermediary. This eliminates the most common workaround for DynamoDB’s access pattern rigidity — supporting complex queries through a separate search tier — with lower operational overhead. For deployments requiring both DynamoDB’s partition-key throughput and MongoDB-equivalent predicate flexibility, the DynamoDB + OpenSearch zero-ETL integration is the documented architecture pattern as of 2025.

MongoDB 8.0 (GA October 2024) introduced analyzeShardKey improvements that provide cardinality and frequency distribution analysis for any candidate shard key before collection sharding is committed — allowing engineers to detect hot-partition risk in DynamoDB terms (low-cardinality key values) before deployment rather than discovering it under production load.

What to Do Next

  • Problem: DynamoDB and MongoDB handle unplanned access patterns oppositely — DynamoDB requires a GSI declared at design time (with 20 GSI max, eventual consistency, and 2× storage cost) while MongoDB requires an index declared any time (with no hard count limit but write amplification and cache cost); choosing the wrong model for the dominant access pattern forces expensive migrations at scale.
  • Solution: Enumerate every access pattern as a 5-column table (entity, query type, fields, consistency requirement, write frequency) before choosing a storage model; map each pattern to DynamoDB key/GSI or MongoDB compound index to identify which model covers 100% of patterns within its constraints.
  • Proof: DynamoDB’s GetItem documentation explicitly states that partition key hash routing routes to exactly one partition, providing O(1) lookup; MongoDB’s explain("executionStats") output shows IXSCAN vs COLLSCAN and totalDocsExamined vs nReturned, providing quantifiable evidence of index effectiveness per query shape.
  • Action: For the most complex query pattern in your current or planned application — the one that filters on the most fields simultaneously — verify whether it can be expressed as a DynamoDB primary key lookup or GSI query; if it requires a filter scan in DynamoDB or a COLLSCAN in MongoDB, that pattern is your architecture constraint and must drive the model decision.

Sources to Verify

  1. AWS DynamoDB Developer Guide — Partitions and Data Distribution: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.Partitions.html
  2. AWS DynamoDB Developer Guide — Global Secondary Indexes (eventual consistency, WCU, and projection): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
  3. MongoDB Manual — Sharding — Shard Key Selection and analyzeShardKey: https://www.mongodb.com/docs/manual/core/sharding-shard-key/
  4. MongoDB Manual — $indexStats — Measuring Index Usage: https://www.mongodb.com/docs/manual/reference/operator/aggregation/indexStats/
  5. WiredTiger Architecture — B-Tree and Cache Internals: https://source.wiredtiger.com/develop/arch-btree.html
  6. AWS DynamoDB — Best Practices for Designing and Using Partition Keys Effectively: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html
  7. MongoDB Manual — Data Modeling — Document Model vs. Relational: https://www.mongodb.com/docs/manual/core/data-modeling-introduction/