NoSQL Secondary Indexes

Difficulty: Advanced

Question

What is a Global Secondary Index (GSI) in DynamoDB, and how does it differ from a Local Secondary Index (LSI)?

Answer

A Global Secondary Index is a separately maintained copy of selected attributes from a DynamoDB table, organized under a different partition key and optional sort key. It lets you run efficient Query operations on access patterns the base table's key cannot serve, such as finding orders by restaurant when the table is keyed by customer. GSIs are updated asynchronously, so reads from them are always eventually consistent.

Why DynamoDB needs secondary indexes

DynamoDB can only Query efficiently by partition key (plus an optional sort key condition). If your table is PK = customer_id, SK = order_time, you can fetch "orders for customer 42 this week" cheaply. But "all pending orders for restaurant 7" would require a full Scan, which reads every item and costs read capacity for all of it. A GSI keyed by restaurant_id and status#order_time turns that into a fast query.

How a GSI works

  • You choose a new partition key and optional sort key from any attributes.
  • DynamoDB asynchronously propagates every write on the base table to the index. Reads lag slightly and are eventually consistent only.
  • You choose a projection: KEYS_ONLY, INCLUDE (specific attributes), or ALL. Querying an attribute not projected requires a second read from the base table.
  • Index keys do not need to be unique.
  • Items missing the GSI key attribute are not written to it, which gives you sparse indexes, for example indexing only items where is_flagged exists.
  • A GSI has its own capacity (provisioned mode) and can be added or deleted at any time.
  • If a GSI cannot keep up with writes, DynamoDB throttles writes on the base table, so under-provisioning a GSI hurts the main workload.

GSI vs LSI

AspectGlobal Secondary IndexLocal Secondary Index
Partition keyAny attributeSame as base table
Sort keyAny attributeDifferent from base table
When createdAny timeOnly at table creation
Read consistencyEventually consistent onlyEventual or strongly consistent
CapacitySeparate from the tableShared with the table
Size limitsNone per partition10 GB per partition key value (item collection)
Default limit per table20 (adjustable quota)5

Design patterns and gotchas

  • Overloaded GSIs in single-table design: one GSI with generic attributes like GSI1PK and GSI1SK serves several entity types.
  • Hot partitions apply to GSIs too. A GSI keyed by status with only three values will concentrate traffic.
  • Every GSI multiplies write cost: each base write that touches indexed attributes also consumes write capacity on each affected GSI.
  • Do not use a GSI for read-after-write flows that need the latest value; query the base table with strong consistency instead.
How a write reaches a GSI. The base table write succeeds first; the index catches up asynchronously.
  1. PutItem to base table: Keyed by customer_id and order_time.
  2. Base write acknowledged: Client gets success immediately.
  3. Async propagation: DynamoDB copies projected attributes.
  4. GSI partition by restaurant_id: Item stored under the new key.
  5. Query on GSI: Eventually consistent read by restaurant.

Code examples

Create a table with a GSI (AWS CLI)

aws dynamodb create-table \
  --table-name Orders \
  --billing-mode PAY_PER_REQUEST \
  --attribute-definitions \
      AttributeName=customer_id,AttributeType=S \
      AttributeName=order_time,AttributeType=S \
      AttributeName=restaurant_id,AttributeType=S \
  --key-schema \
      AttributeName=customer_id,KeyType=HASH \
      AttributeName=order_time,KeyType=RANGE \
  --global-secondary-indexes '[{
      "IndexName": "ByRestaurant",
      "KeySchema": [
        {"AttributeName": "restaurant_id", "KeyType": "HASH"},
        {"AttributeName": "order_time",    "KeyType": "RANGE"}
      ],
      "Projection": {"ProjectionType": "INCLUDE",
                     "NonKeyAttributes": ["status", "amount_paise"]}
  }]'

The GSI re-keys the same orders by restaurant and projects only the attributes the restaurant dashboard needs.

Query the GSI with the JavaScript SDK v3

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";

const db = DynamoDBDocumentClient.from(new DynamoDBClient({}));

const res = await db.send(new QueryCommand({
  TableName: "Orders",
  IndexName: "ByRestaurant",           // query the GSI, not the table
  KeyConditionExpression: "restaurant_id = :r AND order_time >= :t",
  ExpressionAttributeValues: { ":r": "R-7", ":t": "2026-10-01" },
  // ConsistentRead: true is NOT allowed on a GSI
}));
console.log(res.Items);

Passing IndexName routes the query to the GSI; strongly consistent reads are rejected for global indexes.

Key points

  • GSI = different partition key and optional sort key, maintained asynchronously.
  • GSI reads are eventually consistent only; LSI reads can be strongly consistent.
  • GSIs can be added any time; LSIs only at table creation and share the partition key.
  • Projection (KEYS_ONLY, INCLUDE, ALL) controls what is copied and what you can read without a base lookup.
  • Under-provisioned GSIs throttle writes on the base table.

Common follow-up questions

  • What is a sparse index and when would you use one?
  • How does single-table design use overloaded GSIs?
  • What happens to base table writes if a GSI is throttled?
  • Why does an LSI impose a 10 GB limit per partition key value?

Interview tips

  • Start from the access pattern problem (Query vs Scan) before describing the index; it shows you design DynamoDB around queries.
  • Contrast GSI and LSI on consistency, creation time and partition key; those are the classic follow-ups.
  • Mention write amplification and GSI back-pressure to show production awareness.

Concepts covered

DynamoDB, Global Secondary Index, Local Secondary Index, Partition Key, Projection

More Database Design questions