Jump to content

Amazon DynamoDB

From Wikipedia, the free encyclopedia
Amazon DynamoDB
Developer(s)Amazon.com
Initial releaseJanuary 2012; 12 years ago (2012-01)[1]
Written inJava
Operating systemCross-platform
Available inEnglish
Type
LicenseProprietary
Websiteaws.amazon.com/dynamodb/

Amazon DynamoDB is a fully managed proprietary NoSQL database offered by Amazon.com as part of the Amazon Web Services portfolio.[2][3] DynamoDB offers a fast persistent key–value datastore with built-in support for replication, autoscaling, encryption at rest, and on-demand backup among other features.[4][5]

Background

[edit]

Werner Vogels, CTO at Amazon.com, provided a motivation for the project in his 2012 announcement.[6] Amazon began as a decentralized network of services. Originally, services had direct access to each other's databases. When this became a bottleneck on engineering operations, services moved away from this direct access pattern in favor of public-facing APIs. Still, third-party relational database management systems struggled to handle Amazon's client base. This culminated during the 2004[7][8] holiday season, when several technologies failed under high traffic.

Engineers were normalizing these relational systems to reduce data redundancy, a design that optimizes for storage. The sacrifice: they stored a given "item" of data (e.g., the information pertaining to a product in a product database) over several relations, and it takes time to assemble disjoint parts for a query. Many of Amazon's services demanded mostly primary-key reads on their data, and with speed a top priority, putting these pieces together was extremely taxing.[9]

Content with compromising storage efficiency, Amazon's response was Dynamo: a highly available key–value store built for internal use.[6] Dynamo, it seemed, was everything their engineers needed, but adoption lagged. Amazon's developers opted for "just works" design patterns with S3 and SimpleDB. While these systems had noticeable design flaws, they did not demand the overhead of provisioning hardware and scaling and re-partitioning data. Amazon's next iteration of NoSQL technology, DynamoDB, automated these database management operations.

Overview

[edit]
Web console
Web console

In DynamoDB, data is stored in Tables as items, and can be queried using indices. Items consist of a number of attributes which can belong to a number of data types, and are required to have a Key that is expected to be unique across the Table.

DynamoDB Tables

[edit]

A DynamoDB Table is a logical grouping of items, which represent the data stored in this Table. Given the NoSQL nature of DynamoDB, the Tables do not require that all items in a Table conform to some predefined schema.[10]

DynamoDB Items

[edit]

An Item in DynamoDB is a set of attributes that can be uniquely identified in a Table. An Attribute is an atomic data entity that in itself is a Key-Value pair. The Key is always of String type, while the value can be of one of multiple data types.

An Item is uniquely identified in a Table using a subset of its attributes called Keys.[10]

Keys In DynamoDB

[edit]

A Primary Key is a set of attributes that uniquely identifies items in a DynamoDB Table. Creation of a DynamoDB Table requires definition of a Primary Key. Each item in a DynamoDB Table is required to have all of the attributes that constitute the Primary Key, and no two items in a Table can have the same Primary Key. Primary Keys in Dynamo DB can consist of either one or two attributes.

When a Primary Key is made up of only one attribute, it is called a Partition Key. Partition Keys determine the physical location of the associated item. In this case, no two items in a table can have the same Partition Key.

When a Primary Key is made up of two attributes, the first one is called a "Partition Key" and the second is called a "Sort Key". As before, the Partition Key decides the physical Location of Data, but the Sort Key then decides the relative logical position of associated item's record inside that physical location. In this case, two items in a Table can have the same Partition Key, but no two items in a partition can have the same Sort Key. In other words, a given combination of Partition Key and Sort Key is guaranteed to have at most one item associated with it in a DynamoDB Table.[10]

DynamoDB Data Types

[edit]

DynamoDB supports numerical, String, Boolean, Document, and Set Data Types.[11]

DynamoDB Indices

[edit]

Primary Key of a Table is the Default or Primary Index of a DynamoDB Table.

In addition, a DynamoDB Table can have Secondary Indices. A Secondary Index is defined on an attribute that is different from Partition Key or Sort Key as the Primary Index.

When a Secondary Index has same Partition Key as Primary Index but a different Sort Key, it is called as the Local Secondary Index.

When Primary Index and Secondary Index have different Partition Key, the Secondary index is known as the Global Secondary Index.[10]


Development considerations

[edit]

Access Patterns

[edit]

To optimize DynamoDB performance, developers must carefully plan and analyze access patterns when designing their database schema. This involves creating tables and configuring indices accordingly. [12][13][14][15]

When querying non-indexed attributes, DynamoDB performs a full table scan, resulting in significant overhead. Even when using the "filter" operation, DynamoDB scans the entire table before applying filters. [13]

Syntax

[edit]

DynamoDB uses JSON for its syntax because of its ubiquity.[citation needed] The create table action demands just three arguments: TableName, KeySchema––a list containing a partition key and an optional sort key––and AttributeDefinitions––a list of attributes to be defined which must at least contain definitions for the attributes used as partition and sort keys. Whereas relational databases offer robust query languages, DynamoDB offers just Put, Get, Update, and Delete operations. Put requests contain the TableName attribute and an Item attribute, which consists of all the attributes and values the item has. An Update request follows the same syntax. Similarly, to get or delete an item, simply specify a TableName and Key.

System architecture

[edit]
Creation table in DynamoDB

Data structures

[edit]

DynamoDB uses hashing and B-trees to manage data. Upon entry, data is first distributed into different partitions by hashing on the partition key. Each partition can store up to 10GB of data and handle by default 1,000 write capacity units (WCU) and 3,000 read capacity units (RCU).[16] One RCU represents one strongly consistent read per second or two eventually consistent reads per second for items up to 4KB in size.[17] One WCU represents one write per second for an item up to 1KB in size.

To prevent data loss, DynamoDB features a two-tier backup system of replication and long-term storage.[18] Each partition features three nodes, each of which contains a copy of that partition's data. Each node also contains two data structures: a B tree used to locate items, and a replication log that notes all changes made to the node. DynamoDB periodically takes snapshots of these two data structures and stores them for a month in S3 so that engineers can perform point-in-time restores of their databases.

Within each partition, one of the three nodes is designated the "leader node". All write operations travel first through the leader node before propagating, which makes writes consistent in DynamoDB. To maintain its status, the leader sends a "heartbeat" to each other node every 1.5 seconds. Should another node stop receiving heartbeats, it can initiate a new leader election. DynamoDB uses the Paxos algorithm to elect leaders.

Amazon engineers originally avoided Dynamo due to engineering overheads like provisioning and managing partitions and nodes.[9] In response, the DynamoDB team built a service it calls AutoAdmin to manage a database.[18] AutoAdmin replaces a node when it stops responding by copying data from another node. When a partition exceeds any of its three thresholds (RCU, WCU, or 10GB), AutoAdmin will automatically add additional partitions to further segment the data.[16]

Just like indexing systems in the relational model, DynamoDB demands that any updates to a table be reflected in each of the table's indices. DynamoDB handles this using a service it calls the "log propagator", which subscribes to the replication logs in each node and sends additional Put, Update, and Delete requests to indices as necessary.[18] Because indices result in substantial performance hits for write requests, DynamoDB allows a user at most five of them on any given table.[19]

Query execution

[edit]

Suppose that a DynamoDB user issues a write operation (a Put, Update, or Delete). While a typical relational system would convert the SQL query to relational algebra and run optimization algorithms, DynamoDB skips both processes and gets right to work.[18] The request arrives at the DynamoDB request router, which authenticates––"Is the request coming from where/whom it claims to be?"––and checks for authorization––"Does the user submitting the request have the requisite permissions?" Assuming these checks pass, the system hashes the request's partition key to arrive in the appropriate partition. There are three nodes within, each with a copy of the partition's data. The system first writes to the leader node, then writes to a second node, then sends a "success" message, and finally continues propagating to the third node. Writes are consistent because they always travel first through the leader node.

Finally, the log propagator propagates the change to all indices. For each index, it grabs that index's primary key value from the item, then performs the same write on that index without log propagation. If the operation is an Update to a preexisting item, the updated attribute may serve as a primary key for an index, and thus the B tree for that index must update as well. B trees only handle insert, delete, and read operations, so in practice, when the log propagator receives an Update operation, it issues both a Delete operation and a Put operation to all indices.

Now suppose that a DynamoDB user issues a Get operation. The request router proceeds as before with authentication and authorization. Next, as above, we hash our partition key to arrive in the appropriate hash. Now, we encounter a problem: with three nodes in eventual consistency with one another, how can we decide which to investigate? DynamoDB offers the user two options when issuing a read: consistent and eventually consistent. A consistent read visits the leader node. But the consistency-availability trade-off rears its head again here: in read-heavy systems, always reading from the leader can overwhelm a single node and reduce availability.

The second option, an eventually consistent read, selects a random node. In practice, this is where DynamoDB trades consistency for availability. If we take this route, what are the odds of an inconsistency? We'd need a write operation to return "success" and begin propagating to the third node, but not finish. We'd also need our Get to target this third node. This means a 1-in-3 chance of inconsistency within the write operation's propagation window. How long is this window? Any number of catastrophes could cause a node to fall behind, but in the vast majority of cases, the third node is up-to-date within milliseconds of the leader.

Performance

[edit]
Capacity tab, scaling

DynamoDB exposes performance metrics that help users provision it correctly and keep applications using DynamoDB running smoothly:

  • Requests and throttling
  • Errors: ProvisionedThroughputExceededException,ConditionalCheckFailedException,Internal Server Error(HTTP 500)
  • Metrics related to Global Secondary Index creation[20]

These metrics can be tracked using the AWS Management Console, using the AWS command-line interface, or a monitoring tool integrating with Amazon CloudWatch.[21]

Best practices

[edit]

DynamoDB developers should: [22]

  • Identify data access patterns
  • Use events instead of polling

Language bindings

[edit]

Languages and frameworks with a DynamoDB binding include Java, JavaScript, Node.js, Go, C# .NET, Perl, PHP, Python, Ruby, Rust, Haskell, Erlang, Django, and Grails.[23]

Code examples

[edit]
AWS DynamoDB: item view

HTTP API

[edit]

Against HTTP API, query items:

POST / HTTP/1.1
Host: dynamodb.<region>.<domain>;
Accept-Encoding: identity
Content-Length: <PayloadSizeBytes>
User-Agent: <UserAgentString>
Content-Type: application/x-amz-json-1.0
Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<Signature>
X-Amz-Date: <Date>
X-Amz-Target: DynamoDB_20120810.Query

{
    "TableName": "Reply",
    "IndexName": "PostedBy-Index",
    "Limit": 3,
    "ConsistentRead": true,
    "ProjectionExpression": "Id, PostedBy, ReplyDateTime",
    "KeyConditionExpression": "Id = :v1 AND PostedBy BETWEEN :v2a AND :v2b",
    "ExpressionAttributeValues": {
        ":v1": {"S": "Amazon DynamoDB#DynamoDB Thread 1"},
        ":v2a": {"S": "User A"},
        ":v2b": {"S": "User C"}
    },
    "ReturnConsumedCapacity": "TOTAL"
}

Sample response:

HTTP/1.1 200 OK
x-amzn-RequestId: <RequestId>
x-amz-crc32: <Checksum>
Content-Type: application/x-amz-json-1.0
Content-Length: <PayloadSizeBytes>
Date: <Date>
 {
    "ConsumedCapacity": {
        "CapacityUnits": 1,
        "TableName": "Reply"
    },
    "Count": 2,
    "Items": [
        {
            "ReplyDateTime": {"S": "2015-02-18T20:27:36.165Z"},
            "PostedBy": {"S": "User A"},
            "Id": {"S": "Amazon DynamoDB#DynamoDB Thread 1"}
        },
        {
            "ReplyDateTime": {"S": "2015-02-25T20:27:36.165Z"},
            "PostedBy": {"S": "User B"},
            "Id": {"S": "Amazon DynamoDB#DynamoDB Thread 1"}
        }
    ],
    "ScannedCount": 2
}

Go

[edit]

GetItem in Go:

getItemInput := &dynamodb.GetItemInput{
	TableName: aws.String("happy-marketer"),
	Key: map[string]*dynamodb.AttributeValue{
		"pk": {
			S: aws.String("project"),
		},
		"sk": {
			S: aws.String(email + " " + name),
		},
	},
}
getItemOutput, err := dynamodbClient.GetItem(getItemInput)

DeleteItem in Go:

deleteItemInput := &dynamodb.DeleteItemInput{
	TableName: aws.String("happy-marketer"),
	Key: map[string]*dynamodb.AttributeValue{
		"pk": {
			S: aws.String("project"),
		},
		"sk": {
			S: aws.String(email + " " + name),
		},
	},
}

_, err := dynamodbClient.DeleteItem(deleteItemInput)
if err != nil {
	panic(err)
}

UpdateItem in Go using Expression Builder:

update := expression.Set(
	expression.Name(name),
	expression.Value(value),
)

expr, err := expression.NewBuilder().WithUpdate(update).Build()
if err != nil {
	panic(err)
}

updateItemInput := &dynamodb.UpdateItemInput{
	TableName: aws.String(tableName),
	Key: map[string]*dynamodb.AttributeValue{
		"pk": {
			S: aws.String("project"),
		},
		"sk": {
			S: aws.String("mySortKeyValue"),
		},
	},
	UpdateExpression:          expr.Update(),
	ExpressionAttributeNames:  expr.Names(),
	ExpressionAttributeValues: expr.Values(),
}
fmt.Printf("updateItemInput: %#v\n", updateItemInput)

_, err = dynamodbClient.UpdateItem(updateItemInput)
if err != nil {
	panic(err)
}

See also

[edit]

References

[edit]
  1. ^ "Amazon DynamoDB – a Fast and Scalable NoSQL Database Service Designed for Internet Scale Applications - All Things Distributed". www.allthingsdistributed.com. 18 January 2012.
  2. ^ Clark, Jack (2012-01-19). "Amazon switches on DynamoDB cloud database service". ZDNet. Retrieved 2012-01-21.
  3. ^ "Fast NoSQL Key-Value Database – Amazon DynamoDB – Amazon Web Services". Amazon Web Services, Inc. Retrieved 2023-05-28.
  4. ^ "Amazon DynamoDB Features | NoSQL Key-Value Database | Amazon Web Services". Amazon Web Services, Inc. Retrieved 2023-05-28.
  5. ^ "What is Amazon DynamoDB? - Amazon DynamoDB". docs.aws.amazon.com. Retrieved 2023-05-28.
  6. ^ a b Vogels, Werner (2012-01-18). "Amazon DynamoDB – a Fast and Scalable NoSQL Database Service Designed for Internet Scale Applications". All Things Distributed blog. Retrieved 2012-01-21.
  7. ^ "How Amazon's DynamoDB helped reinvent databases". Network World. Retrieved 2023-11-30.
  8. ^ brockmeier 1, joe (2012-01-18). "Amazon Takes Another Pass at NoSQL with DynamoDB". ReadWrite. Retrieved 2023-11-30.{{cite web}}: CS1 maint: numeric names: authors list (link)
  9. ^ a b DeCandia, Giuseppe; Hastorun, Deniz; Jampani, Madan; Kakulapati, Gunavardhan; Lakshman, Avinash; Pilchin, Alex; Sivasubramanian, Swaminathan; Vosshall, Peter; Vogels, Werner (October 2007). "Dynamo: Amazon's Highly Available Key–value Store". SIGOPS Oper. Syst. Rev. 41 (6): 205–220. doi:10.1145/1323293.1294281. ISSN 0163-5980.
  10. ^ a b c d "Core components of Amazon DynamoDB - Amazon DynamoDB". docs.aws.amazon.com. Retrieved 2023-05-28.
  11. ^ "Supported data types and naming rules in Amazon DynamoDB - Amazon DynamoDB". docs.aws.amazon.com. Retrieved 2023-05-28.
  12. ^ "Core components of Amazon DynamoDB".
  13. ^ a b "Scanning tables in DynamoDB".
  14. ^ "Improving data access with secondary indexes in DynamoDB".
  15. ^ "Querying tables in DynamoDB".
  16. ^ a b Gunasekara, Archie (2016-06-27). "A Deep Dive into DynamoDB Partitions". Shine Solutions Group. Retrieved 2019-08-03.
  17. ^ "Amazon DynamoDB Developer Guide". AWS. August 10, 2012. Retrieved July 18, 2019.
  18. ^ a b c d AWS re:Invent 2018: Amazon DynamoDB Under the Hood: How We Built a Hyper-Scale Database (DAT321), 27 November 2018, retrieved 2019-08-03
  19. ^ "Service, account, and table quotas in Amazon DynamoDB - Amazon DynamoDB". docs.aws.amazon.com. Retrieved 2024-01-09.
  20. ^ "Top DynamoDB performance metrics". 15 September 2015.
  21. ^ "How to collect DynamoDB metrics". 15 September 2015.
  22. ^ Debrie, Alex (2020). The DynamoDB Book. Independently published. ISBN 979-8365145672.
  23. ^ "Amazon DynamoDB Libraries, Mappers, and Mock Implementations Galore!". Amazon Web Services. 5 April 2012.
[edit]