What is the difference between Global Secondary Indexes (GSI) and Local Secondary Indexes (LSI) in DynamoDB?
❓ Interview Prompt: Compare DynamoDB Global Secondary Indexes (GSI) vs Local Secondary Indexes (LSI) partition keys, creation rules, and capacity modes.
Secondary Indexes allow querying DynamoDB tables using alternate partition or sort keys:
| Feature | Local Secondary Index (LSI) | Global Secondary Index (GSI) |
|---|---|---|
| Partition Key | MUST be identical to base table Partition Key | CAN be completely different from base table Partition Key |
| Sort Key | Different Sort Key | Different Sort Key |
| Creation Time | ONLY during table creation | Created anytime (live table) |
| Capacity Provisioning | Consumes base table Read/Write Capacity Units (RCU/WCU) | Has its own dedicated RCU/WCU provisioned capacity |
| Item Size Limit | 10 GB limit per partition key value | Unlimited size across partitions |
Code Implementation Example
# DynamoDB Table with Global Secondary Index (GSI)
resource "aws_dynamodb_table" "orders" {
name = "Orders"
billing_mode = "PAY_PER_REQUEST"
hash_key = "OrderId" # Base Partition Key
attribute { name = "OrderId"; type = "S" }
attribute { name = "Email"; type = "S" }
global_secondary_index {
name = "EmailIndex"
hash_key = "Email" # Alternate Partition Key for querying by email!
projection_type = "ALL"
}
}LSIs must share the base table partition key and be created at table creation; GSIs can have new partition keys created anytime.