DynamoDB
medium 36 minAmazon DynamoDB is a managed key-value and document database.
See it run
Find an item by key, make a write safe, pay for a scan, cool a hot key, wait for an index, and write correctly without a lock.
Operations
Find by key
The partition key picks one row, the sort key one place in it.
Step 1 of 4
Items in rows
| first | second | third | |
|---|---|---|---|
| USER#1 | ORDER#01 | ORDER#04 | ORDER#07 |
| USER#2 | ORDER#02 | ORDER#05 | PROFILE |
| USER#3 | ORDER#03 | PROFILE | SETTINGS |
Each row is one partition key. Inside it items are sorted by the sort key.
Step 1: Items in rows
def get(pk, sk): part = partitions[hash(pk) % len(partitions)] rows = part[pk] # sorted by sk return rows[bisect(rows, sk)]def newest(pk): return partition_of(pk)[pk][-1]- Units
- 1 item
- Watch out for
- Only known questions
- Table size
- does not matter
Say the partition key and the sort key before you say any query.
In the real world
The same dynamodb doing real jobs. Pick one and step through it.
A shop removes carts seven days after the last change.
Step 1 of 4
Written
| item | returned by a read | |
|---|---|---|
| day 0 | CART#42 | yes |
The item has expiresAt = now + 604,800 seconds.
Step 1: Written
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Scan with a filter in a request
criticalIt reads and charges the whole table each time, and gets slower as it grows.
Wrongtable.scan(FilterExpression=Attr("status").eq("OPEN"))Righttable.query(IndexName="OpenTickets", KeyConditionExpression=Key("openPart").eq(0))Choosing the part by the item
criticalThe hash of one item is always the same number, so all writes still go to one key.
Wrongn = stable_hash(item_id) % 10Rightn = stable_hash(user_id) % 10 # or a random numberRead, check, write
majorTwo callers read the same old state and both write.
Wrongif not table.get_item(Key=k).get("Item"): table.put_item(Item=item)Righttable.put_item(Item=item, ConditionExpression="attribute_not_exists(PK)")Ignoring LastEvaluatedKey
majorA query returns at most 1 MB. The rest is silently missing.
Wrongitems = table.query(**args)["Items"]Rightwhile True: page = table.query(**args) items += page["Items"] if "LastEvaluatedKey" not in page: break args["ExclusiveStartKey"] = page["LastEvaluatedKey"]
Interview tips
How to explain it
- Questions first, then keys.
- A partition key spreads, a sort key orders.
- A log on two of three machines makes a write safe.
Memory trick
- 4 to read, 1 to write.
- 3,000 and 1,000 for a partition.
- Filter after, pay before.
Reach for it when
- Lookups by key at a high rate.
- The newest items of one owner.
- A team without database operators, on AWS.
Look elsewhere when
- New questions come every week.
- Reports and joins are the main work.
- You must run outside AWS.