SlideShare a Scribd company logo
1 of 40
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Building Modern Applications Using
Amazon DynamoDB Transactions
Raj Chilakapati
Sr. Solution Architect, AWS
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Agenda
1. Introduction to atomicity, consistency, isolation, and durability
(ACID) in DynamoDB, and the new transactional API
2. Modern application use cases for the transactional API
3. Important things to know when integrating the transactional API
into your application: metering, concurrency control, and
interaction with other features
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
What you will learn
• How the new transactional API works
• How you can use the new API in your application through
case studies demonstrating transactional design patterns
• How the new API interacts with DynamoDB features
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Why is this important?
The transactional API can be used to
implement real-world transactional
scenarios
The transactional API can be used to
simplify the implementation of cloud
application flows
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Prerequisites
You should be familiar with DynamoDB concepts such as
tables, items, partition keys and sort keys, indexes, Time
To Live, and streams. We will only briefly introduce these
concepts in this session before using them in the use
cases.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Transactional API at a glance
TransactWriteItems
Transact up to 10 items
Evaluate conditions
If all conditions are simultaneously true, perform write
operations
TransactGetItems
Transact up to 10 items
Return a consistent, isolated snapshot of all items
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Atomicity, consistency, isolation, and durability (ACID)
in DynamoDB
• Before: ACID support for single-item operations
• NEW: ACID support for multi-item operations
Nontransactional Transactional
New
TransactGetItems
TransactWriteItems
Existing
BatchGetItem, BatchWriteItem
Query, Scan
GetItem, PutItem, UpdateItem,
DeleteItem
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Transactions at DynamoDB scale
• Apply transactions to items in:
• Same partition key, or across partition keys
• Same table, or across tables
• Same Region only
• Same account only
• DynamoDB tables only
• Transactions scale like the rest of DynamoDB
• Limitless concurrent transactions
• Low latency, high availability
• Scales horizontally
• Your responsibility: Design to avoid hot key
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Path of success with NoSQL transactions
Design choices
• Transact any items in your account
• Service APIs vs. client-side library
• Request/response-based
• Limit of 10 items
How they help you
• Scale your data and relations within it
• Reduces complexity, and improves cost
and performance
• Keeps business logic in your application
and not in the database layer
• Consistent low latency, never deadlock
• Consistent low latency, high availability
• Addresses vast majority of use cases
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
User profile management (use case #1)
• Problem statement
• Users identified by user name and optionally email
• No two users can share the same identifier (user name or email)
• Users can change their email
• What is demonstrated
• Enforcing unique constraints
• Strongly consistent global indexing
• Heterogeneous tables
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
User profile management
• Solution
• Users table contains two kinds of records
• Profile record, keyed by opaque user name and containing user details
• Alias records, keyed by user email and referencing the profile record
Id UserNameRef Email Phone #
“John123” “john@example.com” “444-555-0110”
“john@example.com” “Joe123”
“jane456” “444-555-0199”
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Insert new profile
data = await dynamoDb.transactWriteItems({ TransactItems: [
{ Put: {
TableName: 'Users',
Item: { Id: { S: 'John123' }, Email: {S: 'john123@example.com'}, ...},
ConditionExpression: 'attribute_not_exists(Id)‘ }},
{ Put: {
TableName: 'Users',
Item: { Id: { S: 'john123@example.com' }, UserNameRef: {S: 'John123'}},
ConditionExpression: 'attribute_not_exists(Id)',}}
] }).promise();
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Update email address
data = await dynamoDb.transactWriteItems({ TransactItems: [
{ Put: { TableName: 'Users',
Item: { Id: { S: 'John123' }, Email: {S: 'john123@example.org'}, ...},
ConditionExpression: 'attribute_exists(Id) and Email = :old_email',
ExpressionAttributeValues: {':old_email' :{'S': 'john123@example.com'}}}},
{ Put: { TableName: 'Users',
Item: { Id: { S: 'john123@example.org' }, UserNameRef: {S: 'John123'}},
ConditionExpression: 'attribute_not_exists(Id)', }},
{ Delete: { TableName: 'Users',
Item: { Id: { S: 'john123@example.com' }}}).promise();
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management (use case #2)
• Problem statement
• Guests create room reservations
• Guests check in to rooms, fulfilling a reservation
• Guests check out of rooms, closing a reservation
• What is demonstrated
• Ensuring idempotency – operations with side effects happen at
most once
• Ensuring multi-item changes are only triggered when valid
(consistency)
• Ensuring multi-item changes happen all together (atomicity)
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management data model
Guests
Id (primary key)
Name, Email, etc.
Reservations (set)
OccupiesRooms (set)
Reservations
Id (primary key)
GuestId
FulfilledByRoom
State
Rooms
Id (primary key)
RentedToReservation
State
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management data model
Record Type Id (PK) Attributes
Guest “John”
Reservations : { “500”, “501” }
OccupiesRooms : { “20014” }
Reservation “500”
GuestId: “John”
State: “PENDING”
Reservation “501”
GuestId: “John”
State: “FULFILLED”
FulfilledByRoom: “20014”
Room “20014”
State: “OCCUPIED”
RentedToReservation : “501”
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management: Create a reservation
• Idempotency – how to ensure only a single reservation is
created upon retries?
• Solution
• Client generates a unique reservation ID
• Client generates TransactWriteItems request with the following operations
• Conditional Put for the new reservation
• Update the customer reservations set: Add the new reservation
• Client transaction is now idempotent and can be retried
without double booking
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management: Check-in
Record Type Id (PK) Attributes
Customer “John123”
Reservations : { “567” }
OccupiesRooms : {}
Reservation “567”
CustomerId: “John123”
State: “PENDING”
FulfilledByRoom: null
Room “20014”
State: “FREE”
RentedToReservation : null
Before
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management: Check-in
Record Type Id (PK) Attributes
Customer “John123”
Reservations : { “567” }
OccupiesRooms : { “20014” }
Reservation “567”
CustomerId: “John123”
State: “FULFILLED”
FulfilledByRoom: “20014”
Room “20014”
State: “OCCUPIED”
RentedToReservation : “567”
After
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management: Checkout
Record Type Id (PK) Attributes
Customer “John123”
Reservations : { “567” }
OccupiesRooms : { “20014” }
Reservation “567”
CustomerId: “John123”
State: “FULFILLED”
FulfilledByRoom: “20014”
Room “20014”
State: “OCCUPIED”
RentedToReservation : “567”
Before
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Hotel reservation management: Checkout
Record Type Id (PK) Attributes
Customer “John123”
Reservations : { “567” }
OccupiesRooms : { “20014” }
Reservation “567”
CustomerId: “John123”
State: “CLOSED”
FulfilledByRoom: “20014”
Room “20014”
State: “FREE”
RentedToReservation : “567”
After
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Concurrency control
• Optimistic
• No deadlocks possible
• Low latency
• Optimized for scale-out
• Your responsibility
• Design for scale-out
• Avoid unnecessary conflicts
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Metering transactions
Transactions perform 2x the work of nontransactional
counterparts
Transactions are metered 2x their constituent
operations
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Why didn’t my transaction succeed?
• Per-item failure reasons
• Precondition failure
• Insufficient capacity
• Transactional conflicts
• Other reasons
• Transaction is still in progress
• Service error
• Malformed request
• Permissions
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Retrying transactions: ClientRequestToken
• Ensures SDK can retry without “replaying” the same intent
multiple times
• ClientRequestToken – idempotency token at the SDK or API
level
• Autogenerated, you can override
• Applies for 10 minutes
• Provides information about transaction state and outcome
• Sometimes doesn’t remove the need for application-level
idempotency or intent design
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Application-level retries
• When the SDK gives up
• Build a new view of the world
• Retry with new preconditions and desirable end state
• How to build a snapshot of the world? Three options:
• Set ReturnValuesOnConditionCheckFailure = ALL_OLD
• Perform TransactGetItems
• Work from an eventually consistent view (results of queries, etc.)
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Integrating with other DynamoDB features
• General rule about DynamoDB data
• Committed state only
• But might not be isolated
• Examples
• Streams – Committed writes, sharded
• Backups and point-in-time recovery (PITR) – Subset of a committed
transaction is possible
• Global secondary index (GSI) – Committed writes are indexed
individually
• Global tables – Transactional API disabled by default; writes are
replicated individually
• Amazon DynamoDB Accelerator (DAX) support is on the roadmap
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Access control
• Individual operations are authorized separately
• (NEW) dynamodb:ConditionCheck
• dynamodb:UpdateItem
• dynamodb:PutItem
• dynamodb:DeleteItem
• No separate permissions for top-level new APIs
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management (use case #3)
• Problem statement
• A social media site allows attaching media to posts
• Posts need to share media efficiently
• Posts can have multiple attachments
• Unreferenced media needs to be deleted
• What is demonstrated
• External resource metadata and lifetime management
• Using Time To Live (TTL) and streams
• Reference counting using transactions
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management data model
Attachment item
S3Ref (PK) – Reference to an object in Amazon S3
RefCount – Number of posts referencing this attachment
TTL – Time when this attachment is eligible to be deleted
Post item
Id (PK) – Post ID
Attachments (set) – Set of attachment IDs
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management invariants
1. RefCount = number of posts referencing the attachment
2. If RefCount > 0, then S3Ref refers to a valid Amazon S3 object
3. TTL is set if, and only if, RefCount = 0
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management: Create attachment and
link it to a post
• Generate unique Amazon S3 object name
• Create attachment record in DynamoDB
• Set RefCount = 0,
• Set TTL = 24 hours from now
• Upload object to Amazon S3
• In a TransactWriteItems Request
• Check that the attachment is not already referenced by the post
• Increase RefCount by 1, remove TTL
• Add attachment reference to post
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management: Clone attachment
reference
• Copy the reference of an attachment from one post to
another
• In a TransactWriteItems Request:
• Check that the attachment is not already referenced by the new
post
• Increase RefCount by 1, remove TTL
• Add attachment reference to new post
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Attachment management: Delete unused external
resources
• Attachment records will be deleted a day after their
reference count drops to zero
• In AWS Lambda, process stream records representing items
deleted by TTL
• Delete the corresponding objects from Amazon S3
Thank you!
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Raj Chilakapati
chilakap@amazon.com

More Related Content

What's hot

What's hot (20)

한국투자증권의 디지털 플랫폼 구현 사례.pdf
한국투자증권의 디지털 플랫폼 구현 사례.pdf한국투자증권의 디지털 플랫폼 구현 사례.pdf
한국투자증권의 디지털 플랫폼 구현 사례.pdf
 
AWS Summit Seoul 2023 | 가격은 저렴, 성능은 최대로! 확 달라진 Amazon EC2 알아보기
AWS Summit Seoul 2023 | 가격은 저렴, 성능은 최대로! 확 달라진 Amazon EC2 알아보기AWS Summit Seoul 2023 | 가격은 저렴, 성능은 최대로! 확 달라진 Amazon EC2 알아보기
AWS Summit Seoul 2023 | 가격은 저렴, 성능은 최대로! 확 달라진 Amazon EC2 알아보기
 
Serverless Application Development with SAM
Serverless Application Development with SAMServerless Application Development with SAM
Serverless Application Development with SAM
 
AWS Backup을 이용한 데이터베이스의 백업 자동화와 편리한 복구방법
AWS Backup을 이용한 데이터베이스의 백업 자동화와 편리한 복구방법AWS Backup을 이용한 데이터베이스의 백업 자동화와 편리한 복구방법
AWS Backup을 이용한 데이터베이스의 백업 자동화와 편리한 복구방법
 
AWS Summit Seoul 2023 | SKT가 당신의 AI, Data 사업을 “T”나게 도와주는 사례와 미래
AWS Summit Seoul 2023 | SKT가 당신의 AI, Data 사업을 “T”나게 도와주는 사례와 미래AWS Summit Seoul 2023 | SKT가 당신의 AI, Data 사업을 “T”나게 도와주는 사례와 미래
AWS Summit Seoul 2023 | SKT가 당신의 AI, Data 사업을 “T”나게 도와주는 사례와 미래
 
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
 
Deep Dive on Amazon S3 Security and Management (E2471STG303-R1) - AWS re:Inve...
Deep Dive on Amazon S3 Security and Management (E2471STG303-R1) - AWS re:Inve...Deep Dive on Amazon S3 Security and Management (E2471STG303-R1) - AWS re:Inve...
Deep Dive on Amazon S3 Security and Management (E2471STG303-R1) - AWS re:Inve...
 
천만 사용자를 위한 AWS 클라우드 아키텍처 진화하기 - 김준형 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
천만 사용자를 위한 AWS 클라우드 아키텍처 진화하기 - 김준형 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019천만 사용자를 위한 AWS 클라우드 아키텍처 진화하기 - 김준형 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
천만 사용자를 위한 AWS 클라우드 아키텍처 진화하기 - 김준형 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
 
AWS System Manager: Parameter Store를 사용한 AWS 구성 데이터 관리 기법 - 정창훈, 당근마켓 / 김대권, ...
AWS System Manager: Parameter Store를 사용한 AWS 구성 데이터 관리 기법 - 정창훈, 당근마켓 / 김대권, ...AWS System Manager: Parameter Store를 사용한 AWS 구성 데이터 관리 기법 - 정창훈, 당근마켓 / 김대권, ...
AWS System Manager: Parameter Store를 사용한 AWS 구성 데이터 관리 기법 - 정창훈, 당근마켓 / 김대권, ...
 
AWS Fault Injection Simulator를 통한 실전 카오스 엔지니어링 - 윤석찬 AWS 수석 테크에반젤리스트 / 김신 SW엔...
AWS Fault Injection Simulator를 통한 실전 카오스 엔지니어링 - 윤석찬 AWS 수석 테크에반젤리스트 / 김신 SW엔...AWS Fault Injection Simulator를 통한 실전 카오스 엔지니어링 - 윤석찬 AWS 수석 테크에반젤리스트 / 김신 SW엔...
AWS Fault Injection Simulator를 통한 실전 카오스 엔지니어링 - 윤석찬 AWS 수석 테크에반젤리스트 / 김신 SW엔...
 
데이터 분석가를 위한 신규 분석 서비스 - 김기영, AWS 분석 솔루션즈 아키텍트 / 변규현, 당근마켓 소프트웨어 엔지니어 :: AWS r...
데이터 분석가를 위한 신규 분석 서비스 - 김기영, AWS 분석 솔루션즈 아키텍트 / 변규현, 당근마켓 소프트웨어 엔지니어 :: AWS r...데이터 분석가를 위한 신규 분석 서비스 - 김기영, AWS 분석 솔루션즈 아키텍트 / 변규현, 당근마켓 소프트웨어 엔지니어 :: AWS r...
데이터 분석가를 위한 신규 분석 서비스 - 김기영, AWS 분석 솔루션즈 아키텍트 / 변규현, 당근마켓 소프트웨어 엔지니어 :: AWS r...
 
[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue
 
[보험사를 위한 AWS Data Analytics Day] 6_Data Analytics의 현재와 미래-토ᄉ...
[보험사를 위한 AWS Data Analytics Day] 6_Data Analytics의 현재와 미래-토ᄉ...[보험사를 위한 AWS Data Analytics Day] 6_Data Analytics의 현재와 미래-토ᄉ...
[보험사를 위한 AWS Data Analytics Day] 6_Data Analytics의 현재와 미래-토ᄉ...
 
A deep dive into Amazon MSK - ADB206 - Chicago AWS Summit
A deep dive into Amazon MSK - ADB206 - Chicago AWS SummitA deep dive into Amazon MSK - ADB206 - Chicago AWS Summit
A deep dive into Amazon MSK - ADB206 - Chicago AWS Summit
 
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
 
Azure Cloud Governance
Azure Cloud GovernanceAzure Cloud Governance
Azure Cloud Governance
 
AWS Summit Seoul 2023 | 12가지 디자인 패턴으로 알아보는 클라우드 네이티브 마이크로서비스 아키텍처
AWS Summit Seoul 2023 | 12가지 디자인 패턴으로 알아보는 클라우드 네이티브 마이크로서비스 아키텍처AWS Summit Seoul 2023 | 12가지 디자인 패턴으로 알아보는 클라우드 네이티브 마이크로서비스 아키텍처
AWS Summit Seoul 2023 | 12가지 디자인 패턴으로 알아보는 클라우드 네이티브 마이크로서비스 아키텍처
 
민첩하고 비용효율적인 Data Lake 구축 - 문종민 솔루션즈 아키텍트, AWS
민첩하고 비용효율적인 Data Lake 구축 - 문종민 솔루션즈 아키텍트, AWS민첩하고 비용효율적인 Data Lake 구축 - 문종민 솔루션즈 아키텍트, AWS
민첩하고 비용효율적인 Data Lake 구축 - 문종민 솔루션즈 아키텍트, AWS
 
농심 그룹 메가마트 : 온프레미스 Exadata의 AWS 클라우드 환경 전환 사례 공유-김동현, NDS Cloud Innovation Ce...
농심 그룹 메가마트 : 온프레미스 Exadata의 AWS 클라우드 환경 전환 사례 공유-김동현, NDS Cloud Innovation Ce...농심 그룹 메가마트 : 온프레미스 Exadata의 AWS 클라우드 환경 전환 사례 공유-김동현, NDS Cloud Innovation Ce...
농심 그룹 메가마트 : 온프레미스 Exadata의 AWS 클라우드 환경 전환 사례 공유-김동현, NDS Cloud Innovation Ce...
 
Deep Dive on AWS Lambda
Deep Dive on AWS LambdaDeep Dive on AWS Lambda
Deep Dive on AWS Lambda
 

Similar to Building Modern Apps Using Amazon DynamoDB Transactions

Similar to Building Modern Apps Using Amazon DynamoDB Transactions (20)

[NEW LAUNCH!] Building modern applications using Amazon DynamoDB transactions...
[NEW LAUNCH!] Building modern applications using Amazon DynamoDB transactions...[NEW LAUNCH!] Building modern applications using Amazon DynamoDB transactions...
[NEW LAUNCH!] Building modern applications using Amazon DynamoDB transactions...
 
Non-Relational Revolution: Database Week SF
Non-Relational Revolution: Database Week SFNon-Relational Revolution: Database Week SF
Non-Relational Revolution: Database Week SF
 
Optimize Your SaaS Offering with Serverless Microservices (GPSTEC405) - AWS r...
Optimize Your SaaS Offering with Serverless Microservices (GPSTEC405) - AWS r...Optimize Your SaaS Offering with Serverless Microservices (GPSTEC405) - AWS r...
Optimize Your SaaS Offering with Serverless Microservices (GPSTEC405) - AWS r...
 
Non-Relational Revolution
Non-Relational RevolutionNon-Relational Revolution
Non-Relational Revolution
 
Deconstructing SaaS: Deep Dive into Building Multi-Tenant Solutions on AWS (A...
Deconstructing SaaS: Deep Dive into Building Multi-Tenant Solutions on AWS (A...Deconstructing SaaS: Deep Dive into Building Multi-Tenant Solutions on AWS (A...
Deconstructing SaaS: Deep Dive into Building Multi-Tenant Solutions on AWS (A...
 
AWS Floor28 - WildRydes Serverless Data Processsing workshop (Ver2)
AWS Floor28 - WildRydes Serverless Data Processsing workshop (Ver2)AWS Floor28 - WildRydes Serverless Data Processsing workshop (Ver2)
AWS Floor28 - WildRydes Serverless Data Processsing workshop (Ver2)
 
You Dont Need a Server for That
You Dont Need a Server for ThatYou Dont Need a Server for That
You Dont Need a Server for That
 
WildRydes Serverless Data Processing Workshop
WildRydes Serverless Data Processing WorkshopWildRydes Serverless Data Processing Workshop
WildRydes Serverless Data Processing Workshop
 
AppSync in real world - pitfalls, unexpected benefits & lessons learnt
AppSync in real world - pitfalls, unexpected benefits & lessons learntAppSync in real world - pitfalls, unexpected benefits & lessons learnt
AppSync in real world - pitfalls, unexpected benefits & lessons learnt
 
Building Real-time Serverless Backends with GraphQL
Building Real-time Serverless Backends with GraphQLBuilding Real-time Serverless Backends with GraphQL
Building Real-time Serverless Backends with GraphQL
 
Workshop: Architecting a Serverless Data Lake
Workshop: Architecting a Serverless Data LakeWorkshop: Architecting a Serverless Data Lake
Workshop: Architecting a Serverless Data Lake
 
How Amazon Migrated Items & Offers for Retail, Marketplace, & Digital to Dyna...
How Amazon Migrated Items & Offers for Retail, Marketplace, & Digital to Dyna...How Amazon Migrated Items & Offers for Retail, Marketplace, & Digital to Dyna...
How Amazon Migrated Items & Offers for Retail, Marketplace, & Digital to Dyna...
 
Microservices & Data Design: Database Week SF
Microservices & Data Design: Database Week SFMicroservices & Data Design: Database Week SF
Microservices & Data Design: Database Week SF
 
Microservices and Data Design
Microservices and Data DesignMicroservices and Data Design
Microservices and Data Design
 
Microservices & Data Design: Database Week San Francisco
Microservices & Data Design: Database Week San FranciscoMicroservices & Data Design: Database Week San Francisco
Microservices & Data Design: Database Week San Francisco
 
AWS Security Week: Cloud-Scale Authentication & Advanced Authorization with A...
AWS Security Week: Cloud-Scale Authentication & Advanced Authorization with A...AWS Security Week: Cloud-Scale Authentication & Advanced Authorization with A...
AWS Security Week: Cloud-Scale Authentication & Advanced Authorization with A...
 
An Active Case Study on Insider Threat Detection in your Applications
An Active Case Study on Insider Threat Detection in your ApplicationsAn Active Case Study on Insider Threat Detection in your Applications
An Active Case Study on Insider Threat Detection in your Applications
 
はじめよう DynamoDB ハンズオン
はじめよう DynamoDB ハンズオンはじめよう DynamoDB ハンズオン
はじめよう DynamoDB ハンズオン
 
Deconstructing SaaS: A Deep Dive into Building Multi-tenant Solutions on AWS ...
Deconstructing SaaS: A Deep Dive into Building Multi-tenant Solutions on AWS ...Deconstructing SaaS: A Deep Dive into Building Multi-tenant Solutions on AWS ...
Deconstructing SaaS: A Deep Dive into Building Multi-tenant Solutions on AWS ...
 
Microservices & Data Design
Microservices & Data DesignMicroservices & Data Design
Microservices & Data Design
 

More from Amazon Web Services

Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
Amazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
Amazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
Amazon Web Services
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
Amazon Web Services
 

More from Amazon Web Services (20)

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
 
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
 
Esegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS Fargate
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWS
 
Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot
 
Open banking as a service
Open banking as a serviceOpen banking as a service
Open banking as a service
 
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 

Building Modern Apps Using Amazon DynamoDB Transactions

  • 1.
  • 2. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Building Modern Applications Using Amazon DynamoDB Transactions Raj Chilakapati Sr. Solution Architect, AWS
  • 3. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Agenda 1. Introduction to atomicity, consistency, isolation, and durability (ACID) in DynamoDB, and the new transactional API 2. Modern application use cases for the transactional API 3. Important things to know when integrating the transactional API into your application: metering, concurrency control, and interaction with other features
  • 4. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. What you will learn • How the new transactional API works • How you can use the new API in your application through case studies demonstrating transactional design patterns • How the new API interacts with DynamoDB features
  • 5. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Why is this important? The transactional API can be used to implement real-world transactional scenarios The transactional API can be used to simplify the implementation of cloud application flows
  • 6. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Prerequisites You should be familiar with DynamoDB concepts such as tables, items, partition keys and sort keys, indexes, Time To Live, and streams. We will only briefly introduce these concepts in this session before using them in the use cases.
  • 7. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 8. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Transactional API at a glance TransactWriteItems Transact up to 10 items Evaluate conditions If all conditions are simultaneously true, perform write operations TransactGetItems Transact up to 10 items Return a consistent, isolated snapshot of all items
  • 9. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Atomicity, consistency, isolation, and durability (ACID) in DynamoDB • Before: ACID support for single-item operations • NEW: ACID support for multi-item operations Nontransactional Transactional New TransactGetItems TransactWriteItems Existing BatchGetItem, BatchWriteItem Query, Scan GetItem, PutItem, UpdateItem, DeleteItem
  • 10. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Transactions at DynamoDB scale • Apply transactions to items in: • Same partition key, or across partition keys • Same table, or across tables • Same Region only • Same account only • DynamoDB tables only • Transactions scale like the rest of DynamoDB • Limitless concurrent transactions • Low latency, high availability • Scales horizontally • Your responsibility: Design to avoid hot key
  • 11. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Path of success with NoSQL transactions Design choices • Transact any items in your account • Service APIs vs. client-side library • Request/response-based • Limit of 10 items How they help you • Scale your data and relations within it • Reduces complexity, and improves cost and performance • Keeps business logic in your application and not in the database layer • Consistent low latency, never deadlock • Consistent low latency, high availability • Addresses vast majority of use cases
  • 12. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 13. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. User profile management (use case #1) • Problem statement • Users identified by user name and optionally email • No two users can share the same identifier (user name or email) • Users can change their email • What is demonstrated • Enforcing unique constraints • Strongly consistent global indexing • Heterogeneous tables
  • 14. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. User profile management • Solution • Users table contains two kinds of records • Profile record, keyed by opaque user name and containing user details • Alias records, keyed by user email and referencing the profile record Id UserNameRef Email Phone # “John123” “john@example.com” “444-555-0110” “john@example.com” “Joe123” “jane456” “444-555-0199”
  • 15. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Insert new profile data = await dynamoDb.transactWriteItems({ TransactItems: [ { Put: { TableName: 'Users', Item: { Id: { S: 'John123' }, Email: {S: 'john123@example.com'}, ...}, ConditionExpression: 'attribute_not_exists(Id)‘ }}, { Put: { TableName: 'Users', Item: { Id: { S: 'john123@example.com' }, UserNameRef: {S: 'John123'}}, ConditionExpression: 'attribute_not_exists(Id)',}} ] }).promise();
  • 16. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Update email address data = await dynamoDb.transactWriteItems({ TransactItems: [ { Put: { TableName: 'Users', Item: { Id: { S: 'John123' }, Email: {S: 'john123@example.org'}, ...}, ConditionExpression: 'attribute_exists(Id) and Email = :old_email', ExpressionAttributeValues: {':old_email' :{'S': 'john123@example.com'}}}}, { Put: { TableName: 'Users', Item: { Id: { S: 'john123@example.org' }, UserNameRef: {S: 'John123'}}, ConditionExpression: 'attribute_not_exists(Id)', }}, { Delete: { TableName: 'Users', Item: { Id: { S: 'john123@example.com' }}}).promise();
  • 17. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management (use case #2) • Problem statement • Guests create room reservations • Guests check in to rooms, fulfilling a reservation • Guests check out of rooms, closing a reservation • What is demonstrated • Ensuring idempotency – operations with side effects happen at most once • Ensuring multi-item changes are only triggered when valid (consistency) • Ensuring multi-item changes happen all together (atomicity)
  • 18. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management data model Guests Id (primary key) Name, Email, etc. Reservations (set) OccupiesRooms (set) Reservations Id (primary key) GuestId FulfilledByRoom State Rooms Id (primary key) RentedToReservation State
  • 19. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management data model Record Type Id (PK) Attributes Guest “John” Reservations : { “500”, “501” } OccupiesRooms : { “20014” } Reservation “500” GuestId: “John” State: “PENDING” Reservation “501” GuestId: “John” State: “FULFILLED” FulfilledByRoom: “20014” Room “20014” State: “OCCUPIED” RentedToReservation : “501”
  • 20. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management: Create a reservation • Idempotency – how to ensure only a single reservation is created upon retries? • Solution • Client generates a unique reservation ID • Client generates TransactWriteItems request with the following operations • Conditional Put for the new reservation • Update the customer reservations set: Add the new reservation • Client transaction is now idempotent and can be retried without double booking
  • 21. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management: Check-in Record Type Id (PK) Attributes Customer “John123” Reservations : { “567” } OccupiesRooms : {} Reservation “567” CustomerId: “John123” State: “PENDING” FulfilledByRoom: null Room “20014” State: “FREE” RentedToReservation : null Before
  • 22. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management: Check-in Record Type Id (PK) Attributes Customer “John123” Reservations : { “567” } OccupiesRooms : { “20014” } Reservation “567” CustomerId: “John123” State: “FULFILLED” FulfilledByRoom: “20014” Room “20014” State: “OCCUPIED” RentedToReservation : “567” After
  • 23. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management: Checkout Record Type Id (PK) Attributes Customer “John123” Reservations : { “567” } OccupiesRooms : { “20014” } Reservation “567” CustomerId: “John123” State: “FULFILLED” FulfilledByRoom: “20014” Room “20014” State: “OCCUPIED” RentedToReservation : “567” Before
  • 24. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Hotel reservation management: Checkout Record Type Id (PK) Attributes Customer “John123” Reservations : { “567” } OccupiesRooms : { “20014” } Reservation “567” CustomerId: “John123” State: “CLOSED” FulfilledByRoom: “20014” Room “20014” State: “FREE” RentedToReservation : “567” After
  • 25. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 26. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Concurrency control • Optimistic • No deadlocks possible • Low latency • Optimized for scale-out • Your responsibility • Design for scale-out • Avoid unnecessary conflicts
  • 27. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Metering transactions Transactions perform 2x the work of nontransactional counterparts Transactions are metered 2x their constituent operations
  • 28. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Why didn’t my transaction succeed? • Per-item failure reasons • Precondition failure • Insufficient capacity • Transactional conflicts • Other reasons • Transaction is still in progress • Service error • Malformed request • Permissions
  • 29. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Retrying transactions: ClientRequestToken • Ensures SDK can retry without “replaying” the same intent multiple times • ClientRequestToken – idempotency token at the SDK or API level • Autogenerated, you can override • Applies for 10 minutes • Provides information about transaction state and outcome • Sometimes doesn’t remove the need for application-level idempotency or intent design
  • 30. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Application-level retries • When the SDK gives up • Build a new view of the world • Retry with new preconditions and desirable end state • How to build a snapshot of the world? Three options: • Set ReturnValuesOnConditionCheckFailure = ALL_OLD • Perform TransactGetItems • Work from an eventually consistent view (results of queries, etc.)
  • 31. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Integrating with other DynamoDB features • General rule about DynamoDB data • Committed state only • But might not be isolated • Examples • Streams – Committed writes, sharded • Backups and point-in-time recovery (PITR) – Subset of a committed transaction is possible • Global secondary index (GSI) – Committed writes are indexed individually • Global tables – Transactional API disabled by default; writes are replicated individually • Amazon DynamoDB Accelerator (DAX) support is on the roadmap
  • 32. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Access control • Individual operations are authorized separately • (NEW) dynamodb:ConditionCheck • dynamodb:UpdateItem • dynamodb:PutItem • dynamodb:DeleteItem • No separate permissions for top-level new APIs
  • 33. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 34. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management (use case #3) • Problem statement • A social media site allows attaching media to posts • Posts need to share media efficiently • Posts can have multiple attachments • Unreferenced media needs to be deleted • What is demonstrated • External resource metadata and lifetime management • Using Time To Live (TTL) and streams • Reference counting using transactions
  • 35. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management data model Attachment item S3Ref (PK) – Reference to an object in Amazon S3 RefCount – Number of posts referencing this attachment TTL – Time when this attachment is eligible to be deleted Post item Id (PK) – Post ID Attachments (set) – Set of attachment IDs
  • 36. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management invariants 1. RefCount = number of posts referencing the attachment 2. If RefCount > 0, then S3Ref refers to a valid Amazon S3 object 3. TTL is set if, and only if, RefCount = 0
  • 37. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management: Create attachment and link it to a post • Generate unique Amazon S3 object name • Create attachment record in DynamoDB • Set RefCount = 0, • Set TTL = 24 hours from now • Upload object to Amazon S3 • In a TransactWriteItems Request • Check that the attachment is not already referenced by the post • Increase RefCount by 1, remove TTL • Add attachment reference to post
  • 38. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management: Clone attachment reference • Copy the reference of an attachment from one post to another • In a TransactWriteItems Request: • Check that the attachment is not already referenced by the new post • Increase RefCount by 1, remove TTL • Add attachment reference to new post
  • 39. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Attachment management: Delete unused external resources • Attachment records will be deleted a day after their reference count drops to zero • In AWS Lambda, process stream records representing items deleted by TTL • Delete the corresponding objects from Amazon S3
  • 40. Thank you! © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Raj Chilakapati chilakap@amazon.com