Why DynamoDB Pagination Isn't Returning the Records You Expect — And How to Fix It
While implementing pagination in the front end, understand how Dynamo DB filters and returns data
The Bug That Wasn't Really a Bug
It started as a routine frontend development task: implement paginated results for a filtered product listing page. The requirement was straightforward — fetch 10 records of active products per page, show a "Load More" button, repeat. The backend was powered by AWS DynamoDB, and everything looked clean on paper.
Then came testing.
Page one returned 10 records. Good. But on filtering — show only items with status = "ACTIVE" — the page returned 6 records. Sometimes 7. Occasionally 4. The table had well over 50 matching records. Something was clearly wrong, but the code looked correct. No off-by-one errors. No misconfigured limits. The filter expression was accurate.
So what was happening?
Understanding How DynamoDB Actually Reads Data
To understand the problem, you first need to understand a fundamental difference between how DynamoDB reads data versus how most developers expect it to read data.
The Intuitive Mental Model (Which Is Wrong for DynamoDB)
When most developers think about fetching filtered, paginated data, they picture something like this:
- Scan the entire dataset
- Apply the filter (e.g., status = "ACTIVE")
- From the filtered results, return the first N records
This is how SQL databases work. It's how Excel's filter-then-slice behavior works. It feels natural because the result set is logically "clean" before pagination is applied.
How DynamoDB Actually Works
DynamoDB does the opposite. Its read flow is:
- Read up to N items from the table (where N is your Limit value)
- Then apply the FilterExpression to that already-limited batch
- Return whatever survives the filter
This means DynamoDB's Limit parameter controls how many items are read from storage, not how many items are returned to you. The filter happens after the read cap is applied, not before.
Here's a concrete example. Suppose your table has 20 records, and 12 of them have status = "ACTIVE":
Record 1 → status: ACTIVE ✓
Record 2 → status: INACTIVE ✗
Record 3 → status: INACTIVE ✗
Record 4 → status: ACTIVE ✓
Record 5 → status: ACTIVE ✓
Record 6 → status: INACTIVE ✗
Record 7 → status: ACTIVE ✓
Record 8 → status: INACTIVE ✗
Record 9 → status: ACTIVE ✓
Record 10 → status: ACTIVE ✓
If you set Limit: 10 and FilterExpression: status = "ACTIVE", DynamoDB reads the first 10 records, applies the filter, and returns only 6 — even though there are 12 matching records in the table and you explicitly asked for 10.
This is not a bug. It is documented behavior. But it's a subtle behavior that catches many developers off guard.
Why DynamoDB Works This Way
DynamoDB is designed for massive scale and consistent, predictable performance. It achieves this partly by limiting how much data it reads per operation at the storage layer. The Limit parameter is a hard cap on RCU (Read Capacity Unit) consumption per request, not a guarantee of N filtered results.
If DynamoDB applied filters before the limit, it would have to scan an unknown number of records to satisfy every query, which could cause wildly unpredictable latency and capacity consumption — the exact opposite of what makes DynamoDB valuable at scale.
Understanding this trade-off is key to using DynamoDB correctly.
The Fix:
- Option 1 - Application side - Loop Until You Have Enough Records
The correct approach is to implement a pagination loop on the application side. Instead of making a single DynamoDB call with Limit: 10, you make repeated calls, accumulating results, until you have enough filtered records to fill your page — or until DynamoDB tells you there are no more records left (i.e., LastEvaluatedKey is absent).
The Key Mechanism: LastEvaluatedKey
DynamoDB uses LastEvaluatedKey as its pagination cursor. When a response includes this key, it means there are more records in the table beyond what was just returned. You pass this key back as ExclusiveStartKey in the next request to continue from where you left off.
If LastEvaluatedKey is absent in the response, you've reached the end of the table.
- Option 2 - The DynamoDB-Side Fix: Global Secondary Indexes
The application-side loop works, but it is a workaround — you are compensating for a mismatch between how DynamoDB reads data and what your query logically needs. The cleaner, more scalable fix is to eliminate FilterExpression entirely by redesigning the access pattern using a Global Secondary Index (GSI).
Why a GSI Solves This Properly
When you use Query on a GSI (instead of Scan with a filter), DynamoDB reads only the items that match your key condition. There are no non-matching records being read and discarded. This means Limit on a Query behaves exactly as you originally expected — it directly controls how many matching records are returned. No application-side loop required.
Step 1: Create a GSI on the Filter Attribute
Step 2: Query the GSI Instead of Scanning the Table - With the GSI in place, replace the Scan + FilterExpression approach with a Query against the index.
Taking It Further: The Sparse GSI Pattern
A regular GSI indexes every item in the table — including INACTIVE, ARCHIVED, and DELETED records (in our example). If only a small fraction of your records are ever queried (e.g., you almost always want ACTIVE items), you can go one step further with a sparse GSI.
The idea is simple: only write the status attribute on items you want indexed. DynamoDB GSIs only include an item if that item has the GSI's partition key attribute. If the attribute is absent, the item is silently excluded from the index.
So instead of writing status = "INACTIVE" on inactive items, you simply omit status entirely. The GSI then becomes a pre-filtered index containing only ACTIVE items — and querying it is both faster and cheaper because the index itself is smaller.
Choosing the Right Approach
Approach | How it works | When to use |
|---|---|---|
Application-side loop (Scan + FilterExpression) | Loop until N filtered results are collected | Quick fix; low-traffic tables; filter attribute not known at table design time |
GSI Query | Query an index keyed on the filter attribute | Filter value is known and bounded (e.g. status, category, region) |
Sparse GSI | Only index "interesting" items by omitting the attribute on others | High read volume; majority of items are not queried; want smallest possible index |
For most production workloads with a bounded filter like status, the GSI Query approach is the recommended solution. The sparse GSI is the optimisation to reach for once scale demands it.
Important Caveats and Best Practices
1. Prefer Query Over Scan Where Possible
The code above uses Scan, which reads every item in the table. For large tables, this is expensive. If your filter aligns with a partition key or a Global Secondary Index (GSI), always use Query instead — it's significantly cheaper and faster.
For example, if you're filtering by userId, create a GSI on userId and use a Query with a KeyConditionExpression. Reserve FilterExpression for secondary refinements on top of a key-based query.
2. Set a Sensible Multiplier for Limit
If your filter is highly selective (e.g., only 10% of records match), you may need a larger multiplier — or accept that more loop iterations will occur. Tune this based on your data's selectivity.
3. Watch Out for RCU Costs
Each loop iteration consumes Read Capacity Units. A very selective filter on a large table could trigger dozens of internal reads to fill a single page. Monitor your CloudWatch metrics for ConsumedReadCapacityUnits and consider whether a different data model (e.g., pre-filtering at write time using a sparse GSI) is more appropriate.
4. Sparse GSI Pattern for Efficient Filtering
A common DynamoDB pattern to avoid this problem entirely is the sparse index. Instead of storing status = "ACTIVE" or status = "INACTIVE" on every item, only write the attribute on items that match the "interesting" state. A GSI on that attribute will only index those items, giving you a pre-filtered index to query directly — no FilterExpression needed, no wasted reads.
Summary
Concept | SQL / Intuitive Behavior | DynamoDB Actual Behavior |
|---|---|---|
Filter timing | Filter first, then paginate | Paginate first (by read limit), then filter |
Limit meaning | Max records returned | Max records read from storage |
Quick fix (app-side) | N/A | Loop with LastEvaluatedKey until page is full |
Proper fix (DB-side) | N/A | GSI + Query — Limit returns exactly N matching records |
Optimal fix (DB-side) | N/A | Sparse GSI — only index the records you ever query |
The DynamoDB pagination quirk is one of those things that doesn't bite you in development (small datasets, high match rates) but surfaces immediately in production or during proper testing. There are two valid ways to address it: fix it in the application layer with a loop, or fix it at the data model layer with a GSI. The former is quick; the latter is correct. In an ideal world, you do both — add the loop as a safety net, and redesign around a GSI for performance and cost efficiency at scale.
Key Takeaways
- DynamoDB applies FilterExpression after reading up to Limit items — not before.
- The quick application-side fix: loop using LastEvaluatedKey / ExclusiveStartKey until you've collected enough filtered results.
- The proper DynamoDB-side fix: create a GSI on your filter attribute and use Query instead of Scan — Limit then returns exactly N matching records with no overreading.
- For maximum efficiency, use the sparse GSI pattern: omit the attribute on items you don't want indexed, keeping the index small and queries fast.
- Prefer Query over Scan wherever possible — Scan reads the entire table regardless of how many results you need.
- Test pagination with realistic data distributions — a small, high-match-rate dev table will never expose this issue.
Understanding DynamoDB's read mechanics isn't just about fixing this one bug — it shapes how you model data, design access patterns, and control costs at scale. Once it clicks, it changes how you think about every table you build on DynamoDB.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article