Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

AWS databases from Python: RDS, DynamoDB, DocumentDB and ElastiCache

How to use AWS managed databases (RDS, DynamoDB, DocumentDB, ElastiCache) from Python: concepts, exact definitions, boto3 and client-driver syntax, worked examples and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

AWS provides managed database services so engineers can store, query and cache application data without managing underlying servers. Knowing how to use RDS, DynamoDB, DocumentDB and ElastiCache from Python (using boto3 and standard Python DB drivers) is essential for building cloud applications, designing low-latency systems and preparing answers in cloud engineering exams.

Key ideas

  • Managed service — AWS manages the infrastructure tasks (provisioning, patching, backups) for you; you operate at the level of instances, clusters or tables.
  • ACID — properties required by relational transactions: Atomicity, Consistency, Isolation, Durability. Exact statement: a transaction either commits all its writes (atomic), moves the database between valid states (consistency), executes as if isolated from other transactions (isolation), and once committed its effects persist (durability). These properties assume the DB engine implements transactions.
  • BASE — a common model for many NoSQL systems: Basically Available, Soft state, Eventual consistency. Exact statement: services prioritising availability and partition tolerance accept that reads may not immediately reflect the latest writes.
  • DynamoDB read/write capacity units (RCU/WCU) — capacity units measure provisioned throughput. Formal definitions used in exam answers: 1 Write Capacity Unit (WCU) = one write per second for an item up to 1 KB. 1 Read Capacity Unit (RCU) = one strongly consistent read per second for an item up to 4 KB; an eventually consistent read of same size costs 0.5 RCU. Also note: item size includes attribute names and values and is rounded up to the next KB; the maximum item size is 400 KB. Transactional reads/writes consume 2× capacity. Writes and updates also consume capacity on any global secondary indexes for the projected attributes. You can alternatively use on-demand capacity mode (no provisioning; billed per request).
  • RDS instance endpoint — network address (DNS) you use to connect to the database engine. RDS provides automatic backups, Multi-AZ failover and read replicas depending on engine.
  • DocumentDB — AWS managed database compatible with the MongoDB API for document-style storage. You use MongoDB drivers (pymongo) to connect.
  • ElastiCache — AWS managed in-memory cache; supports Redis (single-threaded, data structures, persistence) and Memcached (multi-threaded, simple key-value). Caching patterns: cache-aside, write-through, write-back. In cache-aside the application checks cache and on miss reads the DB and populates cache.
  • boto3 — the AWS SDK for Python. Two common interfaces: client (low-level service calls) and resource (higher-level Python objects, e.g., DynamoDB Table). Use boto3 to create/manage services; use database drivers to read/write data at runtime. Do not confuse creating instances (boto3) with connecting to instances (DB drivers).

Diagrams to draw for an exam answer (label exactly):

  • For RDS connection: draw a box for VPC -> subnet group boxes (private/public subnets) -> RDS instance inside private subnet, show Security Group (SG) with inbound rule from App Server SG port 3306 (or engine's port) -> App Server outside or in same VPC. Label endpoint and port.
  • For DynamoDB with API Gateway + Lambda: draw client -> API Gateway -> Lambda -> DynamoDB Table. Indicate IAM role attached to Lambda with PutItem/GetItem permissions.

Formulas

(List of syntax to remember and capacity definitions.) boto3.client('rds') — low-level RDS client (create, modify, describe instances) boto3.client('rds-data') — use for Aurora Serverless Data API SQL execution boto3.resource('dynamodb') and table = dynamodb.Table('MyTable') — high-level DynamoDB resource and Table object table.get_item(Key={'PK': 'value'}) — read item table.put_item(Item={'PK': 'value', 'attr': 'v'}) — write item boto3.client('elasticache') — manage clusters, replication groups redis.Redis(host='endpoint', port=6379, password=None) — connect to ElastiCache Redis using redis-py; if in-transit encryption/auth are enabled, pass ssl=True and set password to the AUTH token pymysql.connect(host=ENDPOINT, user=USER, password=PASS, db=DB, port=3306) — connect to MySQL RDS from Python psycopg2.connect(host=ENDPOINT, dbname=DB, user=USER, password=PASS, port=5432) — connect to PostgreSQL RDS pymongo.MongoClient('mongodb://USER:PASSWORD@HOST:27017/?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false', tlsCAFile='rds-combined-ca-bundle.pem') — connect to DocumentDB/MongoDB (DocumentDB requires TLS; supply AWS CA bundle) 1 WCU = 1 write/s for item ≤ 1 KB — Write Capacity Unit definition 1 RCU = 1 strongly-consistent read/s for item ≤ 4 KB (or 0.5 RCU for eventually-consistent) — Read Capacity Unit definition

Worked examples

Example 1 — DynamoDB PutItem/GetItem (step-by-step trace)

  1. Table definition: Hash key UserId (string), Provisioned mode for simplicity.
  2. Python code (high-level):
    • dynamodb = boto3.resource('dynamodb')
    • table = dynamodb.Table('Users')
    • table.put_item(Item={'UserId': 'u123', 'Name': 'Ravi', 'Age': 21})
    • resp = table.get_item(Key={'UserId': 'u123'})
    • print(resp['Item'])
  3. Trace on put_item: boto3 sends PutItem to DynamoDB API -> DynamoDB stores item in partition based on hash of 'u123' -> returns 200 OK. On get_item: API locates partition -> returns item as JSON.
  4. Expected printed output: {'UserId': 'u123', 'Name': 'Ravi', 'Age': Decimal('21')} (numbers are Decimal by default in boto3; convert if needed).

Example 2 — RDS MySQL connect and simple query using pymysql Given: endpoint mydb.xxxxx.region.rds.amazonaws.com, database college, user ceuser, password Pass123, port 3306. Steps:

  1. Ensure RDS is in same VPC or accessible (SG allows inbound from app SG).
  2. Python code:
    • import pymysql
    • conn = pymysql.connect(host='mydb.xxxxx.region.rds.amazonaws.com', user='ceuser', password='Pass123', db='college', port=3306)
    • cur = conn.cursor()
    • cur.execute("SELECT count(*) FROM students")
    • print(cur.fetchone())
  3. Output example: (120,) meaning 120 rows. Always close connection in finally block. Notes: For Aurora Serverless use boto3.client('rds-data').execute_statement(...) when Data API is enabled.

Example 3 — ElastiCache Redis cache-aside pattern with redis-py Given: Redis endpoint myredis.xxxxx.region.cache.amazonaws.com, TTL 300s. Steps:

  1. App wants student profile for id s12.
  2. Code:
    • r = redis.Redis(host='myredis...', port=6379)
    • val = r.get('student:s12')
    • if val is None: read DB (RDS) -> r.setex('student:s12', 300, json.dumps(profile)) -> return profile
    • else: parse json.loads(val) and return cached profile
  3. Trace: first request misses cache -> DB read -> cache set -> subsequent requests hit Redis and avoid DB.

Common mistakes

  • Using wrong default port for an engine or forgetting the port in connection string.
  • Misunderstanding DynamoDB capacity: expecting 1 WCU to allow larger items; writes >1 KB consume multiple WCUs.
  • Forgetting to set encryption/SSL flags when connecting to DocumentDB (TLS required by managed clusters by default).
  • Using resource vs client incorrectly: boto3.resource('dynamodb') returns higher-level Table objects; client methods use low-level JSON parameters.
  • Not handling pagination or provisioned throughput errors (ProvisionedThroughputExceededException) in DynamoDB.

For your exam

Question types you will see:

  • Definitions: e.g., define RDS, DynamoDB, DocumentDB, ElastiCache; define ACID and BASE.
  • Short notes: compare RDS vs DynamoDB, or explain cache-aside vs write-through.
  • Programming questions: small Python programs using boto3 to create a table or to put/get an item, or pseudo-code for cache-aside.
  • Diagrams: network design showing RDS inside private subnet and security group rules. What a full-marks answer includes:
  • Clear definitions with bold terms, engine examples and when to choose each service.
  • Correct syntax or pseudo-code for boto3 and the DB driver used (pymysql/psycopg2/pymongo/redis-py).
  • For diagrams: label VPC, subnets, security groups, endpoints and ports.
  • For capacity/throughput questions: give exact RCU/WCU definitions and explain effect of item size.

Quick check

  1. What Python library do you use to manage AWS services programmatically?
  2. In DynamoDB, how many WCUs does writing an item of size 2.4 KB consume?
  3. Name two caching patterns for ElastiCache and briefly state which one populates cache only on a miss. Answers: 1. boto3. 2. 3 WCUs (each WCU = 1 KB so 2.4 KB → ceil(2.4/1)=3). 3. Cache-aside and write-through; cache-aside populates on a miss.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?