A frontend colleague once pinged me with a screenshot: the rental list asked for 20 entries and showed three. The next click on "load more" returned nothing at all, yet the API still claimed there were more pages. Nothing was broken in the usual sense. The Lambda function simply passed DynamoDB's paging behavior straight through to the client, including all of its surprises.
DynamoDB pagination looks trivial in the docs, and that is exactly why it causes trouble. In my article DynamoDB pagination: build a cursor API with Lambda I build a small bike rental API that lists rentals per station, newest first, with an optional filter. Here are the ideas that matter most.
How DynamoDB hands out pages
A Query reads items of one partition in sort key order and stops after 1 MB or after Limit items. If it stopped early, the response contains a LastEvaluatedKey: the primary key of the last item it read. You send it back as ExclusiveStartKey, and DynamoDB continues right after it.
Two things follow from this. There is no offset, so you cannot jump to page 7; you can only move forward from a known key. In return, every page is fast and stable even while new items arrive. And a LastEvaluatedKey only means "I stopped at a limit", not "there is more data". The next page can be empty, and clients must handle that.
The trap: Limit counts what was read, not what matched
This is the mistake behind my colleague's screenshot. Limit caps the number of items DynamoDB evaluates. A FilterExpression runs only afterwards. Ask for ten rentals filtered to open ones, and DynamoDB reads ten, drops the returned ones, and hands you whatever survives. You also pay for everything that was read, not for what came back.
My rule of thumb: if a filter discards most items, the data model is wrong and the criterion belongs in the key or a global secondary index. If it only removes an item now and then, fill the page yourself in the handler. Keep querying until the page is full, the data ends, or a small round budget runs out. And when you trim surplus matches, do not reuse DynamoDB's key. It points past the last item read, so the trimmed items would silently vanish. Build the next key from the last item you actually returned.
Never give clients the raw key
The tempting shortcut is to Base64-encode LastEvaluatedKey and call it a cursor. That leaks your internal key format, invites clients to build logic on it, and lets anyone edit the cursor to read from a different partition if your API does not double-check it.
A safer cursor bundles the key with a fingerprint of the query and an expiry time, then signs it with HMAC. Without the secret, nobody can forge or modify it. A simplified sketch:
import { createHmac } from "node:crypto";
export function encodeCursor(key: PageKey, queryHash: string, secret: string) {
const payload = Buffer.from(
JSON.stringify({ key, q: queryHash, exp: Date.now() + 3600_000 })
).toString("base64url");
const sig = createHmac("sha256", secret).update(payload).digest("base64url");
return `${payload}.${sig}`;
}
On the way back in, verify the signature in constant time, check expiry and fingerprint, and answer anything invalid with a 400 rather than a 500. The fingerprint stops a cursor from one station being replayed against another, or an unfiltered cursor being reused for a filtered query. Signing gives you integrity, not secrecy; add encryption if the key itself is confidential.
My take
The signed cursor is a small amount of code that removes a whole class of bugs. Filling filtered pages, on the other hand, is a patch rather than a design. If the round budget kicks in regularly, I treat that as a signal for a dedicated index. Also cap the limit parameter, and ask your product team whether they really need page numbers. Most of the time "load more" is enough, and it fits DynamoDB perfectly.
What the full article covers
- The complete cursor module with signing, verification, expiry and fingerprint checks
- The page-filling logic in TypeScript, including the GSI key caveat and the round budget
- A Lambda handler with input validation, plus Serverless Framework v4 deployment with a Parameter Store secret
- Tests against a fake DynamoDB that page through 120 rentals, a table of common mistakes, costs and an FAQ
All the details and the runnable code are on my site: DynamoDB pagination: build a cursor API with Lambda
๐ This is the condensed version. The full article on sascha-ms.de goes deeper โ with all code samples, diagrams and a short knowledge check.
๐ Next step: Curious what your own Lambda functions cost? Try my Lambda cost calculator โ it runs right in your browser.
๐ฌ Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).
Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en
Top comments (0)