Question 1 · Development with AWS Services
A developer is designing an Amazon DynamoDB table for a social media application. Users can follow other users and see a personalized feed of posts. The access patterns are: (1) get all posts by a specific author, sorted by timestamp descending; (2) get a single post by its unique post ID. Which primary key design BEST supports both access patterns efficiently?
Show answer & explanation
Correct answer: A
- A. Partition key: postId (UUID). Add a GSI with partition key: authorId and sort key: timestamp.
Option A uses a UUID postId as the partition key of the base table, enabling O(1) GetItem lookups for access pattern 2. A GSI with authorId as partition key and timestamp as sort key directly supports access pattern 1—querying by author and sorting by time descending with no extra reads. Option B makes the base table's partition key authorId with sort key timestamp, which handles access pattern 1 natively, but retrieving a single post by postId requires a GSI on postId—however, a GSI on a non-key attribute only supports Query (with an equality filter on the partition key), not a direct GetItem, adding slight inefficiency compared to option A's base table GetItem. More critically in option B the GSI would have postId as its partition key but no sort key, meaning you'd get a single item per partition which is fine, but the base table choice of authorId+timestamp makes it hard to have a truly unique single-key lookup without the GSI. Option A is still cleaner overall. Option C uses a LSI (sort key: timestamp) on a base table keyed by authorId+postId; LSIs must share the same partition key as the base table, so you can query by authorId and sort by timestamp via the LSI—but you cannot do a direct single-item lookup by postId alone without knowing the authorId, making access pattern 2 incomplete. Option D uses Scan with FilterExpression to retrieve posts by author, which is extremely inefficient and costly on large tables and is an anti-pattern.