SkillSprout
Chapter 6 · Lesson 4
Intermediate
5 min read

OpenSearch, Athena and Data Lifecycle Choices

Overview

DynamoDB and RDS are not the best tool for every query. Amazon OpenSearch Service provides full-text search, relevance ranking, log analytics and vector search. Amazon Athena runs SQL directly on files in S3 with no servers. Choosing a specialised store, and knowing how data is serialised, expires and stays consistent, is part of DVA-C02 task 1.3.

Think of a library. The catalogue database finds a book by its ID instantly (DynamoDB). A search engine finds books that talk about "volcano safety" ranked by relevance (OpenSearch). A researcher with boxes of old records asks questions across all boxes without moving them (Athena over S3).

Combine these with lifecycle features (TTL, S3 lifecycle) and consistency options to design data layers that are cheap, fast and correct.

Key Concepts

  • OpenSearch Service stores JSON documents in indexes split into shards and replicas, queried with a query DSL for search, aggregations and k-NN vectors.
  • It runs in managed domains (or Serverless collections) and is accessed with SigV4 or fine-grained access control with master users, roles and index permissions.
  • A common pattern is DynamoDB Streams or zero-ETL to OpenSearch, keeping the primary store authoritative and the search index derived.
  • Athena is serverless SQL over S3 using the Glue Data Catalog; you pay per data scanned.
  • Reduce Athena cost with columnar formats (Parquet/ORC), compression, partitioning and LIMIT-aware queries.
  • Consistency models: DynamoDB eventually vs strongly consistent reads; S3 is strongly consistent for reads after writes; replicas and caches are eventually consistent.
  • Data lifecycle: DynamoDB TTL, S3 lifecycle rules, log retention and ElastiCache TTLs remove or move data automatically.
  • Serialisation converts objects to JSON, Avro, Protobuf or Parquet; choose compact, schema-aware formats for streaming and analytics.

Detailed Notes

Which store for which question

NeedBest fitWhy
Key lookup at any scaleDynamoDBSingle-digit millisecond, serverless
Relational joins and transactionsRDS or AuroraSQL and ACID
Full-text search, relevance, autocompleteOpenSearchInverted index, analyzers
Ad hoc SQL on S3 filesAthenaNo cluster, pay per scan
Sub-millisecond cachingElastiCache or DAXIn-memory
Time-limited dataDynamoDB TTL or S3 lifecycleNo code needed

Indexing and searching with OpenSearch

python
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth

creds = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(creds, "eu-west-1", "es")
client = OpenSearch(hosts=[{"host": "search-products-abc.eu-west-1.es.amazonaws.com", "port": 443}],
                    http_auth=auth, use_ssl=True, connection_class=RequestsHttpConnection)

client.index(index="products", id="p1", body={"name": "Trail running shoe", "price": 89})
hits = client.search(index="products", body={
    "query": {"multi_match": {"query": "running shoes", "fields": ["name^2", "description"]}}
})["hits"]["hits"]

Size shards sensibly (tens of GB each), use index templates and Index State Management to roll old indexes to cheaper tiers or delete them. Use bulk APIs for ingestion.

Keeping DynamoDB and OpenSearch in sync

A Lambda on DynamoDB Streams indexes each change. Make updates idempotent by using the item key as the document ID, and send failures to a DLQ.

python
def handler(event, context):
    actions = []
    for r in event["Records"]:
        key = r["dynamodb"]["Keys"]["pk"]["S"]
        if r["eventName"] == "REMOVE":
            actions.append({"delete": {"_index": "products", "_id": key}})
        else:
            doc = deserialize(r["dynamodb"]["NewImage"])
            actions += [{"index": {"_index": "products", "_id": key}}, doc]
    bulk(actions)

Athena over S3

sql
CREATE EXTERNAL TABLE logs (
  ts timestamp, status int, path string
)
PARTITIONED BY (dt string)
STORED AS PARQUET
LOCATION 's3://my-logs/parquet/';

SELECT status, count(*) FROM logs
WHERE dt = '2025-03-01' GROUP BY status;

Partition by date so queries read only the days required, store data as Parquet, and use a Glue crawler or partition projection to register partitions. Query results are written to an S3 output location.

Consistency in practice

DynamoDB reads are eventually consistent by default (half the cost); pass ConsistentRead=True on base tables when you must read your own writes. GSIs and global-table replicas are always eventually consistent. S3 gives strong read-after-write consistency for objects and listings. Caches and read replicas add staleness, so choose TTLs deliberately.

Data lifecycle

bash
aws dynamodb update-time-to-live --table-name sessions \
  --time-to-live-specification "Enabled=true,AttributeName=expiresAt"
aws s3api put-bucket-lifecycle-configuration --bucket my-logs --lifecycle-configuration file://lc.json
json
{"Rules":[{"ID":"archive","Status":"Enabled","Filter":{"Prefix":"logs/"},
 "Transitions":[{"Days":30,"StorageClass":"STANDARD_IA"},{"Days":90,"StorageClass":"GLACIER"}],
 "Expiration":{"Days":365}}]}

DynamoDB TTL deletes expired items within roughly 48 hours and the deletes are free; filter expired items out of reads in the meantime. Lifecycle also cleans incomplete multipart uploads and old object versions.

Serialisation

JSON is human-friendly but verbose. Use Avro or Protobuf with a schema registry for streams, Parquet for analytics, and the SDK's marshalling helpers (TypeSerializer/TypeDeserializer in boto3) to convert DynamoDB JSON to native types. Always handle character encoding and base64 for binary data.

Real World Example

A retailer searched products with DynamoDB scans and contains filters, which was slow and expensive. They kept DynamoDB as the source of truth, streamed changes to OpenSearch for search and autocomplete, and moved yearly clickstream files to Parquet in S3 queried by Athena at a fraction of the earlier cost. Session items now expire through TTL and old logs transition to Glacier through lifecycle rules.

Architecture Diagram

Source of truth with a search index
Architecture
Data layer
DynamoDBsource of truth
Indexer
OpenSearchsearch index
S3 ParquetAthena queries

Changes flow from DynamoDB to OpenSearch; archived data is queried in place.

  1. 1Writes go to DynamoDB, the authoritative store.
  2. 2Streams trigger a Lambda that indexes changes into OpenSearch.
  3. 3Applications query OpenSearch for search and ranking.
  4. 4Cold data lands in S3 as Parquet and is queried with Athena.

Best Practices

  • ✓Keep one system of record and treat search indexes as rebuildable copies.
  • ✓Use Parquet, compression and partitions to cut Athena scan costs.
  • ✓Automate expiry with TTL and lifecycle rules instead of cron cleanup.
  • ✓Use strongly consistent reads only where needed; they cost more.
  • ✓Use document IDs from natural keys so index updates are idempotent.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • 'Full-text search' or 'autocomplete' means OpenSearch.
  • 'SQL on S3 without servers' means Athena (pay per data scanned).
  • Expiring items automatically with no cost is DynamoDB TTL; S3 uses lifecycle rules.
  • Strongly consistent reads are not available on GSIs.

Chapter quiz

Advanced Compute, API Design and Specialised Data Stores · 10 questions

  1. 1.A Lambda function in private subnets can reach RDS but times out calling the Secrets Manager API. What is the most cost-effective fix?

  2. 2.Thousands of concurrent Lambda executions are exhausting an Aurora MySQL instance's connections. What should you add?

  3. 3.A function needs to cache secrets locally with low latency and fewer API calls. Which option is built for this?

  4. 4.A REST API must return 404 when the backend reports 'NotFound', without changing Lambda code, and must reject invalid bodies before invoking it. What do you use?

  5. 5.You want API Gateway to put a record on an SQS queue without a Lambda function. How?

  6. 6.An edge-optimised API custom domain is being created. In which Region must the ACM certificate exist?

  7. 7.Four EC2 web servers must serve the same uploaded files across AZs, with automatic capacity growth. Which storage fits?

  8. 8.Pods in an EKS cluster need to read one DynamoDB table and nothing else. What is the best practice?

  9. 9.Product search needs fuzzy matching and ranked results over millions of records already stored in DynamoDB. What do you add?

  10. 10.Analysts query terabytes of JSON logs in S3 with Athena and costs are high. Which change helps most?

0 of 10 answered

Finished this lesson?

0 of 46 lessons done · 0% of the course