Quick revision
The short answer
We map an Order bean with @DynamoDbPartitionKey on getCustomerId and @DynamoDbSortKey on getCreatedAt, then run a Query with QueryConditional.sortGreaterThanOrEqualTo for 'now minus 30 days', scanIndexForward(false) for newest first and limit(20). Each page DynamoDB returns carries a lastEvaluatedKey; we hand it to the client as an opaque cursor and pass it back as exclusiveStartKey to fetch the next page.
What to remember
In this answer, we mapped an Order bean with partition key customerId and sort key createdAt, queried it with sortGreaterThanOrEqualTo, scanIndexForward(false) and limit(20), and took a single page per API call. We saw that DynamoDB pages with LastEvaluatedKey and ExclusiveStartKey rather than offsets, that the key should reach clients as an opaque, checked cursor, that filters apply after the limit so pages can shrink, and that projections keep responses small.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We map an Order bean with @DynamoDbPartitionKey on getCustomerId and @DynamoDbSortKey on getCreatedAt, then run a Query with QueryConditional.sortGreaterThanOrEqualTo for 'now minus 30 days', scanIndexForward(false) for newest first and limit(20). Each page DynamoDB returns carries a lastEvaluatedKey; we hand it to the client as an opaque cursor and pass it back as exclusiveStartKey to fetch the next page.
Why this question is asked
Paging through a customer's recent orders is one of the most common DynamoDB reads, and it is where many teams first meet the details that differ from SQL: there is no OFFSET, the order comes from the sort key, and a page can be smaller than the limit even when more data exists. Interviewers ask for the code because it shows whether we understand how Query really works rather than only the annotations. In this answer, we will map the bean, build the query, look at how pages and cursors work, see why filters can shrink pages, and use projections to read less.
1Mapping the Order Bean
The enhanced client is the higher-level part of the AWS SDK for Java v2. It maps Java objects to DynamoDB items, much like JPA maps entities to rows. A class annotated with @DynamoDbBean needs a public no-argument constructor and getters and setters; the key annotations go on the getters.
The sort key must compare in time order. DynamoDB compares strings byte by byte, so an ISO-8601 string works as long as every value has the same shape. Instant.toString() drops the fractional part when it is zero, so '09:30:00Z' and '09:30:00.250Z' would not compare correctly; truncating to seconds on every write and query avoids that. An epoch number in milliseconds is the other safe choice. Note also that two orders in the same second would collide on the key, so in real code we often make the sort key createdAt plus '#' plus orderId.
2Building the 30-Day Query
A Query names one partition key value and a condition on the sort key. 'The last 30 days' means 'createdAt greater than or equal to now minus 30 days', and newest first means reading the sort key backwards.
Notice the iterator().next(). table.query(request) returns a PageIterable, and iterating it fully would keep calling DynamoDB until all 30 days are read. For an API that serves one page per HTTP request we take exactly one page. The attributesToProject call is a projection expression: DynamoDB still charges read capacity by the size of the items it reads, but the response is smaller and, on an index, the projection avoids needing attributes the index does not hold.
3How Pagination Works
DynamoDB never uses offsets. A Query reads items in sort key order and stops when it has evaluated the limit, or when it has read 1 MB of data, whichever comes first. If it stopped before the end of the range, the response includes LastEvaluatedKey, the primary key of the last item it read. To continue, we send the same request with ExclusiveStartKey set to that key, and DynamoDB resumes right after it.
8 messages in order. Play them, or step through them one at a time.
The client receives something like {"items": [...], "next": "Qy00Mnwy..."} and sends next back unchanged. We keep it opaque so clients cannot build their own keys, and we check that the cursor belongs to the customer making the request, so one customer cannot page through another's data. Many teams also sign or encrypt the cursor.
4Why a Page Can Have Fewer Than 20 Items
A filter expression, such as status = 'SHIPPED', is applied after DynamoDB reads the items and after the limit is counted. So with limit(20) DynamoDB reads 20 orders, drops the ones that are not shipped, and might return 3, with a LastEvaluatedKey that says more exist. The same thing happens when the 1 MB cap is hit. And because filtered items were still read, we pay read capacity for all 20.
So the client must never treat 'fewer than 20' as 'last page'; only a missing cursor means the end. If the filter removes most items, the better fix is a key or index that holds only the wanted items, such as a GSI keyed by customerId with a sort key of status plus createdAt.
5Follow-up questions
Can we jump to page 5 directly?
Not with DynamoDB keys alone. Paging is cursor based, so to reach page 5 we must read pages 1 to 4. If users really need page numbers, we cap them, cache cursors, or serve that view from a search index. For most APIs, 'next' and 'previous' with cursors are enough.
How do we count the orders in the last 30 days?
Query with select COUNT returns a count per page but still reads every item, so a count over a large range is as expensive as reading it. If the count is shown often, we keep a counter item updated on each write, or accept an approximate number.
What changes if the table uses on-demand capacity?
The code is the same. On-demand only changes billing and scaling; the 1 MB page cap, limit before filter and cursor rules all still apply.
6Conclusion
In this answer, we mapped an Order bean with partition key customerId and sort key createdAt, queried it with sortGreaterThanOrEqualTo, scanIndexForward(false) and limit(20), and took a single page per API call. We saw that DynamoDB pages with LastEvaluatedKey and ExclusiveStartKey rather than offsets, that the key should reach clients as an opaque, checked cursor, that filters apply after the limit so pages can shrink, and that projections keep responses small.
Open with
I would map Order as a DynamoDbBean with DynamoDbPartitionKey on getCustomerId and DynamoDbSortKey on getCreatedAt, storing createdAt as an ISO-8601 UTC string with a fixed format, or as epoch millis, so it sorts by time.
Then, if they want more
For the query I compute now minus 30 days and build a QueryConditional with sortGreaterThanOrEqualTo, using a Key with the customer id as partition value and that timestamp as sort value. The QueryEnhancedRequest sets the conditional, scanIndexForward false so it reads newest first, limit 20, and attributesToProject for just the fields the screen needs.
Then table.query returns a PageIterable; for an API I take only the first page, because iterating would keep calling DynamoDB. Pagination is key based, not offset based. Each page includes lastEvaluatedKey when there may be more data, and I return it to the client as an opaque cursor, usually base64 encoded and checked against the caller's customer id.
On the next request I decode it and pass it as exclusiveStartKey. One thing to watch: the limit counts items evaluated before any filter expression, and a page also stops at 1 MB, so a page can return fewer than 20 items while more exist. The client should stop only when there is no cursor.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Apache Cassandra documentation, Amazon DynamoDB developer guide
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Using the AWS SDK for Java v2 enhanced client, write the code to query a table Orders...": https://scrivio-interview-library.netlify.app/databases/cassandra-and-dynamodb/1ba4db395f/