What is the difference between a global secondary index and a local secondary index in DynamoDB?
A GSI has its own partition and sort key and can be added any time, with its own throughput. An LSI keeps the table's partition key with a different sort key, must be created with the table, and shares its capacity.
Explain it simply
A table is a library sorted by book ID. A GSI is a completely separate catalogue sorted by author, useful for a different kind of search. An LSI is another sorting of books inside the same shelf, say by publish year, so you can only search within one shelf.
Example
Base table: Orders (PK customer_id, SK order_id)
LSI : PK customer_id, SK order_date
"orders of one customer sorted by date"
create only at table creation, max 5 per table
shares the table's throughput
allows strongly consistent reads
item collection per partition key limited to 10 GB
GSI : PK status, SK order_date
"all PENDING orders by date" (across all customers)
can be added or removed anytime, max 20 per table (default)
separate throughput
eventually consistent reads onlyGSIs are eventually consistent because data is copied to them asynchronously. Writes to the table also write to its indexes, which uses extra capacity.
When the query needs a different partition key, you need a GSI. When it only needs another sort order inside the same partition key, an LSI can do it.
What to say in the interview
"A GSI has a different partition key, can be added later and has its own capacity but only eventually consistent reads. An LSI shares the partition key with another sort key, must be defined at table creation and allows strong consistency. Most real designs use GSIs."
Common mistakes
- Planning to add an LSI after the table already exists.