Cloud Serverless Databases — DynamoDB, Cosmos DB & Firestore Guide
In this tutorial, you'll learn about Cloud Serverless Databases. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Cloud Serverless databases provide fully managed NoSQL storage that scales automatically, charges per operation, and eliminates capacity planning — ideal for applications with unpredictable traffic patterns.
What You'll Learn
You'll learn how to design schemas for DynamoDB, Cosmos DB, and Firestore, choose partition keys, implement access patterns, and handle Consistency Models for global applications.
Why It Matters
Traditional databases require provisioning for peak load — expensive and wasteful. Serverless databases scale from zero to millions of requests seamlessly. DodaZIP uses DynamoDB for user preferences and subscription data, paying only for actual reads and writes.
Real-World Use
A mobile game stores player profiles in Firestore. During a viral campaign, users jump from 1K to 500K overnight. Firestore scales automatically with zero downtime and zero configuration changes.
Serverless Database Architecture
flowchart LR A[Mobile App] --> B[API Gateway] B --> C[Serverless DB] C --> D["DynamoDB / Cosmos DB / Firestore"] D --> E[Global Replication] D --> F[Auto Scaling] D --> G[Pay Per Request] E --> H[Multi-Region Reads] style C fill:#48f,color:#fff style D fill:#f90,color:#fff
AWS DynamoDB
DynamoDB is a key-value and document database with single-digit millisecond performance.
# Create a DynamoDB table with on-demand capacity
aws dynamodb create-table \
--table-name UserProfiles \
--attribute-definitions \
AttributeName=userId,AttributeType=S \
AttributeName=email,AttributeType=S \
--key-schema \
AttributeName=userId,KeyType=HASH \
--global-secondary-indexes \
"[{\"IndexName\":\"EmailIndex\",\"KeySchema\":[{\"AttributeName\":\"email\",\"KeyType\":\"HASH\"}],\"Projection\":{\"ProjectionType\":\"ALL\"}}]" \
--billing-mode PAY_PER_REQUEST
import boto3
dynamodb = boto3.client("dynamodb")
def save_user_profile(user_id, email, name):
dynamodb.put_item(
TableName="UserProfiles",
Item={
"userId": {"S": user_id},
"email": {"S": email},
"name": {"S": name},
"premium": {"BOOL": False}
}
)
def get_user_by_email(email):
response = dynamodb.query(
TableName="UserProfiles",
IndexName="EmailIndex",
KeyConditionExpression="email = :email",
ExpressionAttributeValues={":email": {"S": email}}
)
return response["Items"]
save_user_profile("u123", "user@example.com", "Alice")
profile = get_user_by_email("user@example.com")
print(f"Found user: {profile}")
Azure Cosmos DB
Cosmos DB offers multi-model support (SQL, MongoDB, Cassandra, Gremlin, Table) with turnkey global distribution.
# Create a Cosmos DB account and database
az cosmosdb create \
--name dodatech-cosmos \
--resource-group my-rg \
--locations regionName=eastus failoverPriority=0 \
--default-consistency-level Session
az cosmosdb sql database create \
--account-name dodatech-cosmos \
--resource-group my-rg \
--name UserProfiles
az cosmosdb sql container create \
--account-name dodatech-cosmos \
--resource-group my-rg \
--database-name UserProfiles \
--name Users \
--partition-key-path "/userId"
GCP Firestore
Firestore is a flexible, scalable NoSQL database with real-time listeners and offline support.
# Create a Firestore database
gcloud firestore databases create \
--region us-central1 \
--type firestore-native
# Add data via CLI
gcloud firestore documents create \
--collection=users \
--document-id=u123 \
--data='{"email":"user@example.com","name":"Alice","premium":false}'
Data Access Patterns
# DynamoDB single-table design
import boto3
from decimal import Decimal
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("GameScores")
# Write a score
table.put_item(
Item={
"PK": "USER#u123",
"SK": "SCORE#2026-06-24",
"game": "SpaceInvaders",
"score": Decimal("15000")
}
)
# Query all scores for a user
response = table.query(
KeyConditionExpression="PK = :pk AND begins_with(SK, :sk)",
ExpressionAttributeValues={
":pk": "USER#u123",
":sk": "SCORE#"
}
)
for item in response["Items"]:
print(f"Score: {item['score']} on {item['game']}")
Common Errors
- Hot partitions from bad key design — A partition key with low cardinality (like
status) creates hotspots. Use high-cardinality keys like userId or a Composite key. - Ignoring DynamoDB 1MB query limit — Queries return at most 1MB. Use pagination with
LastEvaluatedKeyto fetch all results. - Overusing strong consistency — Strongly consistent reads cost more and have higher latency. Use eventual consistency for most workloads.
- Not configuring TTL for expired data — Session data and logs accumulate without TTL. Set Time-to-Live to delete old records automatically.
- Cross-region Replication costs — Global tables replicate all writes to every region. Only use multi-region writes when necessary. For read-only replicas, use read replicas instead.
Practice Questions
- What is the difference between DynamoDB on-demand and provisioned capacity? On-demand charges per request and handles any scale. Provisioned gives a fixed capacity with auto-scaling for predictable workloads.
- How does Cosmos DB achieve multi-region writes? Cosmos DB uses a multi-master Replication protocol where any region can accept writes, which are asynchronously replicated to others.
- What is the Firestore real-time listener? A snapshot listener that pushes document changes to subscribed clients in real time, ideal for chat and live dashboards.
- How do you model one-to-many relationships in Serverless databases? Use a single-table design with Composite sort keys. For DynamoDB: PK=userId, SK=orderId. For Firestore: subcollections.
- Challenge: Design a data model for a social media app with users, posts, comments, and likes. Support queries: user timeline, post with comments, trending posts. Stay within DynamoDB single-table design or Firestore collection group queries.
Mini Project
Build a Serverless API for a note-taking app:
- DynamoDB table with userId (PK) and noteId (SK)
- CRUD operations via Lambda + API Gateway
- Global secondary index for fetching notes by tag
- TTL set to 30 days for archived notes
- Query all notes for a user sorted by last modified
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro