DynamoDB
User Login
Database Design
AWS
Authentication

DynamoDB and User Login table

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

DynamoDB is a fully managed NoSQL database service provided by Amazon Web Services (AWS). It is designed to deliver high performance and availability, making it a popular choice for applications that require fast, predictable, and scalable data storage. DynamoDB is particularly well-suited for web, mobile, gaming, Internet of Things (IoT), and other applications requiring low-latency data access.

In this article, we will delve into DynamoDB's features, and focus on designing a user login table using DynamoDB, including technical explanations and examples.

Key Features of DynamoDB

DynamoDB boasts several features that make it versatile for various use cases:

  • Scalability: DynamoDB automatically scales tables to adjust for capacity and maintain performance.
  • Durability and Availability: It replicates data across multiple availability zones within a region to ensure high availability and data durability.
  • Managed: DynamoDB is a fully managed service, relieving users of the operational complexities associated with database management.
  • Fast Performance: Provides single-digit millisecond latency, ideal for high-throughput applications.
  • Security: Offers built-in security measures, such as encryption at rest and in transit, IAM policies, and VPC endpoints.

Creating a User Login Table

To manage user authentication efficiently, we can leverage DynamoDB to create a user login table. This table can store users' credentials and other relevant information in a secure and scalable manner.

Table Design

A typical user login table in DynamoDB would include the following attributes:

  • Partition Key: userID (String) - A unique identifier for the user.
  • Sort Key: loginTime (String) - The timestamp when the login event occurred, this can be useful to track login history.
  • Attributes:
    • hashedPassword (String) - The hashed version of the user's password.
    • salt (String) - A random string used in conjunction with the password hashing process.
    • lastLogin (String) - The timestamp of the last successful login.
    • failedAttempts (Number) - Count of consecutive failed login attempts.

Example Table Schema

The following table presents an example schema for the User Login table:

Attribute NameData TypeDescription
userIDStringUnique identifier for the user (Primary Key - Partition Key)
loginTimeStringTimestamp of login attempts (Primary Key - Sort Key)
hashedPasswordStringHashed password for secure storage
saltStringSalt value used during password hashing
lastLoginStringTimestamp of the user’s last successful login
failedAttemptsNumberNumber of consecutive unsuccessful login attempts

Writing Data to the Table

Here is a Python example using the AWS SDK (boto3) to insert a new user login record into this DynamoDB table:

python
1import boto3
2from datetime import datetime
3
4# Initialize a session using Amazon DynamoDB
5dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
6
7# Select your table
8table = dynamodb.Table('UserLogin')
9
10# Insert a new item
11response = table.put_item(
12    Item={
13        'userID': 'user123',
14        'loginTime': datetime.now().strftime("%Y%m%d%H%M%S"),
15        'hashedPassword': 'hashed_password_example',
16        'salt': 'random_salt',
17        'lastLogin': '20231001T123456',
18        'failedAttempts': 0
19    }
20)
21
22print("PutItem succeeded:")
23print(response)

Querying the User Login Table

DynamoDB allows you to query based on the partition key and optionally sort key to fetch one or more records. Below is an example of how to get the login history for a particular user:

python
1from boto3.dynamodb.conditions import Key
2
3def get_login_history(user_id):
4    response = table.query(
5        KeyConditionExpression=Key('userID').eq(user_id)
6    )
7    
8    return response['Items']
9
10login_history = get_login_history('user123')
11for record in login_history:
12    print(record)

Enhancing User Login Security

To enhance security in the user login system, consider the following:

  1. Password Hashing: Always store hashed passwords combined with a salt to protect against rainbow table attacks.
  2. Multi-Factor Authentication (MFA): Implement MFA for an additional security layer during login.
  3. Rate Limiting: Restrict the number of login attempts to prevent brute-force attacks.
  4. Data Encryption: Use Amazon KMS to encrypt sensitive data both at rest and in transit.

Summary of Key Points

Feature/ConceptDescription
ScalabilityAutomatically adjusts table's capacity and maintains performance
DurabilityData replicated across Availability Zones, ensuring high availability
SecurityProvides encryption, IAM roles, and VPC endpoints for enhanced security
User Login TableContains userID, loginTime, hashedPassword, salt, lastLogin, failedAttempts
Python Integrationboto3 library is used for interacting with DynamoDB
Best PracticesInclude password hashing, MFA, rate limiting, and encryption

Conclusion

DynamoDB provides a robust infrastructure for building a scalable user login system. Its advanced features such as automatic scaling, low-latency access, and comprehensive security measures make it ideal for handling user authentication tasks efficiently. By applying best practices in security and operational management, developers can harness DynamoDB's potential to create secure and reliable systems.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.