A fully managed NoSQL database service, Amazon DynamoDB offers smooth scaling along with quick and reliable performance. It is perfect for many use cases because of its ability to manage enormous volumes of data across distributed systems. In this post, we'll examine various scenarios in which DynamoDB excels and offer useful TypeScript examples in Node.js.
1. Storing User Session Data
DynamoDB is an excellent choice for storing session data due to its low latency and ability to handle high request rates. User sessions, which are typically short-lived and frequently accessed, require fast read and write operations, and DynamoDB's provisioned throughput makes it ideal for this scenario.
Example: Storing Session Data
In this example, we'll create a DynamoDB table for user sessions and perform basic CRUD (Create, Read, Update, Delete) operations using the AWS SDK in a Node.js application with TypeScript.
import AWS from 'aws-sdk';
import { v4 as uuidv4 } from 'uuid';
AWS.config.update({ region: 'us-west-2' });
const dynamoDB = new AWS.DynamoDB.DocumentClient();
const tableName = 'UserSessions';
// Create a session
const createSession = async (userId: string) => {
const sessionId = uuidv4();
const params = {
TableName: tableName,
Item: {
sessionId,
userId,
createdAt: new Date().toISOString(),
},
};
await dynamoDB.put(params).promise();
return sessionId;
};
// Get a session by ID
const getSession = async (sessionId: string) => {
const params = {
TableName: tableName,
Key: { sessionId },
};
const result = await dynamoDB.get(params).promise();
return result.Item;
};
// Update a session
const updateSession = async (sessionId: string, data: object) => {
const params = {
TableName: tableName,
Key: { sessionId },
UpdateExpression: 'set #data = :data',
ExpressionAttributeNames: {
'#data': 'data',
},
ExpressionAttributeValues: {
':data': data,
},
ReturnValues: 'UPDATED_NEW',
};
const result = await dynamoDB.update(params).promise();
return result.Attributes;
};
// Delete a session
const deleteSession = async (sessionId: string) => {
const params = {
TableName: tableName,
Key: { sessionId },
};
await dynamoDB.delete(params).promise();
};
2. Managing E-Commerce Inventory
DynamoDB's ability to scale and handle high-throughput workloads makes it ideal for managing inventory in an e-commerce application. You can store product details, track inventory levels, and handle real-time updates as customers make purchases.
Example: Inventory Management
Here's an example of managing product inventory using DynamoDB:
interface Product {
productId: string;
name: string;
quantity: number;
price: number;
}
const createProduct = async (product: Product) => {
const params = {
TableName: 'Products',
Item: product,
};
await dynamoDB.put(params).promise();
};
const updateInventory = async (productId: string, quantity: number) => {
const params = {
TableName: 'Products',
Key: { productId },
UpdateExpression: 'set quantity = quantity - :q',
ExpressionAttributeValues: {
':q': quantity,
},
ConditionExpression: 'quantity >= :q',
ReturnValues: 'UPDATED_NEW',
};
const result = await dynamoDB.update(params).promise();
return result.Attributes;
};
const getProduct = async (productId: string) => {
const params = {
TableName: 'Products',
Key: { productId },
};
const result = await dynamoDB.get(params).promise();
return result.Item;
};
In this example, we create a product, update the inventory when an item is purchased, and retrieve product details from the DynamoDB table.
3. Real-Time Leaderboards
DynamoDB’s fast read and write capabilities make it perfect for applications requiring real-time updates, such as leaderboards in gaming or sports apps. You can quickly update scores and retrieve the top players efficiently.
Example: Building a Leaderboard
Here's how to build a real-time leaderboard using DynamoDB:
interface Player {
playerId: string;
score: number;
updatedAt: string;
}
const updateScore = async (playerId: string, score: number) => {
const params = {
TableName: 'Leaderboard',
Key: { playerId },
UpdateExpression: 'set score = :s, updatedAt = :u',
ExpressionAttributeValues: {
':s': score,
':u': new Date().toISOString(),
},
ReturnValues: 'UPDATED_NEW',
};
const result = await dynamoDB.update(params).promise();
return result.Attributes;
};
const getTopPlayers = async (limit: number) => {
const params = {
TableName: 'Leaderboard',
IndexName: 'score-index',
Limit: limit,
ScanIndexForward: false, // Descending order
};
const result = await dynamoDB.scan(params).promise();
return result.Items;
};
In this scenario, we update a player’s score and retrieve the top players from the leaderboard.
4. Logging and Monitoring
DynamoDB is well-suited for logging and monitoring applications due to its ability to ingest large amounts of data rapidly. You can use DynamoDB to store logs, track events, and monitor system health.
Example: Storing Log Data
Here's how to log application events using DynamoDB:
interface LogEntry {
logId: string;
message: string;
timestamp: string;
level: 'INFO' | 'WARN' | 'ERROR';
}
const logEvent = async (logEntry: LogEntry) => {
const params = {
TableName: 'AppLogs',
Item: logEntry,
};
await dynamoDB.put(params).promise();
};
// Example usage
await logEvent({
logId: uuidv4(),
message: 'User login successful',
timestamp: new Date().toISOString(),
level: 'INFO',
});
In this example, we log an event by writing a new entry to a DynamoDB table.
5. Storing and Querying Metadata
DynamoDB is also effective for storing metadata, such as user preferences, configuration settings, or file metadata. Its flexible schema allows you to store different types of metadata without the constraints of a fixed schema.
Example: Storing File Metadata
interface FileMetadata {
fileId: string;
fileName: string;
size: number;
uploadedAt: string;
}
const storeMetadata = async (metadata: FileMetadata) => {
const params = {
TableName: 'FileMetadata',
Item: metadata,
};
await dynamoDB.put(params).promise();
};
const getFileMetadata = async (fileId: string) => {
const params = {
TableName: 'FileMetadata',
Key: { fileId },
};
const result = await dynamoDB.get(params).promise();
return result.Item;
};
In this use case, we store file metadata and retrieve it when needed.
DynamoDB is a strong, adaptable NoSQL database that works well for many applications, such as creating real-time leaderboards and maintaining user sessions. Its smooth scalability and capacity to manage workloads at high throughput make it a great option for contemporary applications. You may create extremely responsive and scalable applications that satisfy the expectations of the modern digital world by utilizing DynamoDB with Node.js and TypeScript.
That's all folks 👋🏻
Top comments (1)
Hi Wallace Freitas,
Top, very nice and helpful !
Thanks for sharing.