When you write to a DynamoDB base table, the Global Secondary Index (GSI) is updated to reflect those changes. However, whether reading from the GSI always reflects the latest write depends on the consistency model you use for your read operations. DynamoDB offers two read consistency models: eventually consistent and strongly consistent.
Eventually Consistent Reads
By default, reads from DynamoDB, including reads from GSIs, use eventually consistent reads. Here’s how it works:
- Eventual Consistency: When you perform an eventually consistent read, the data returned might not reflect the most recent writes. This is because eventually consistent reads might not immediately include the results of all recent write operations. Instead they provide a "best effort" to return the latest data.
- Latency: Eventually consistent reads typically have lower latency and higher throughput because they do not need to wait for all replicas to synchronise.
- GSI Synchronization: Even though GSIs are automatically synchronised with the base table eventually consistent reads from a GSI may not immediately reflect the latest writes to the base table. There can be a short delay (usually milliseconds to a few seconds) before the GSI is updated.
Strongly Consistent Reads
If you need to ensure that a read operation returns the most recent data, you should use strongly consistent reads. Here’s how it works:
- Strong Consistency: When you perform a strongly consistent read, DynamoDB returns a response with the most up-to-date data, reflecting the updates from all prior write operations that were successful.
- GSI Reads: Strongly consistent reads can be performed on GSIs just as they can on the base table. When you perform a strongly consistent read on a GSI DynamoDB ensures that the read operation waits until the GSI has been updated to reflect the latest writes to the base table.
- How to Specify: To perform a strongly consistent read on a GSI you need to explicitly request it in your query or scan operation. For example, in the AWS SDKs you would set the
ConsistentRead parameter to true.
Example Using AWS SDK
Here is an example using the AWS SDK for Python (Boto3) to perform a strongly consistent read on a GSI:
import boto3
# Initialize a DynamoDB client
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('YourTableName')
# Perform a strongly consistent query on the GSI
response = table.query(
IndexName='YourGSIName',
KeyConditionExpression=boto3.dynamodb.conditions.Key('GSIPartitionKey').eq('some_value'),
ConsistentRead=True # This ensures a strongly consistent read
)
items = response['Items']
print(items)