Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Project: Seat Booking with DynamoDB Transactions

Projects prove transactions. Lagos events lead Chioma Adeyemi and Pune founder Vikram Patil ship SeatHold: FREE→HELD→SOLD with TransactWriteItems, ClientRequestToken, and hold TTL. Reuse transactions; link CRUD for Put syntax — do not rewrite it.

In this chapter

  • Model seat + order keys
  • Hold a seat with TransactWrite + condition
  • Use ClientRequestToken for idempotency
  • Release abandoned holds with a conditional update
  • Lab + cleanup

1. Everyday example: cinema counter slip

Counter holds a seat slip for 10 minutes while you pay. Two cashiers must not sell A12 twice. That is TransactWrite with a Status=FREE condition and a deadline on the hold. The deadline is part of the booking rules, while DynamoDB TTL is asynchronous item deletion.

2. Vertical steps

Patterns -> Keys -> Hold txn -> Pay/Release -> CleanupPatternsKeysHold txnPay/ReleaseCleanup
Cleanup

3. Purpose

Partial success (seat held, order missing) creates double-books and angry queues. Interviews and MNC tickets ask how you make multi-item booking atomic.

4. Overview

SeatHold single-table: PK=EVENT#id SK=SEAT#row-num (Status, Version, HoldUser, HoldExpires); PK=ORDER#id SK=META. TransactWrite: condition FREE→HELD + Put ORDER. Pay: condition on HELD, the expected hold owner and version, and HoldExpires still in the future, then atomically mark the seat SOLD and the matching order PAID. Abandon: a scheduled worker conditionally returns the matching expired hold to FREE and removes its hold fields. Keep DynamoDB TTL off permanent seat items. If you use TTL to clean up temporary records, store those separately.

5. Steps

  1. List 6 access patterns (list free seats, hold, pay, my orders…).
  2. Draw sample EVENT#9 SEAT#A-12 + ORDER#o1 items.
  3. Create lab-ddm-seats; Put 5 FREE seats.
  4. TransactWrite hold with Condition Status=FREE and ClientRequestToken.
  5. Second client same seat must cancel — read CancellationReasons.
  6. Set a short HoldExpires deadline. Test two clients against the same seat, then test the conditional payment and expiry paths. After the exercise, delete only the lab table you created.

6. Key sketch

EntityPKSK
SeatEVENT#9SEAT#A-12
Order metaORDER#o1META
My orders GSIUSER#u1ORDER#ts

7. Commands with output and meaning

aws dynamodb create-table --table-name lab-ddm-seats \
  --attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
  --key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST --region ap-south-1
# Hold (SDK preferred). CLI sketch. First seed the seat as FREE as above.
hold_expires=$(($(date +%s) + 600))
aws dynamodb transact-write-items --client-request-token book-o1-u1 --transact-items '[
 {"Update":{"TableName":"lab-ddm-seats","Key":{"PK":{"S":"EVENT#9"},"SK":{"S":"SEAT#A-12"}},
  "ConditionExpression":"#S = :free","UpdateExpression":"SET #S = :held, HoldUser = :u, HoldExpires = :t ADD Version :one",
  "ExpressionAttributeNames":{"#S":"Status"},
  "ExpressionAttributeValues":{":free":{"S":"FREE"},":held":{"S":"HELD"},":u":{"S":"u1"},":t":{"N":"'"$hold_expires"'"},":one":{"N":"1"}}}},
 {"Put":{"TableName":"lab-ddm-seats","ConditionExpression":"attribute_not_exists(PK)","Item":{"PK":{"S":"ORDER#o1"},"SK":{"S":"META"},"Seat":{"S":"A-12"},"Status":{"S":"PENDING"}}}}
]'
# Output: {} on success. Cancelled = read CancellationReasons. Meaning: atomic hold+order.

On-demand table; condition FREE; Reuse the same ClientRequestToken and identical parameters on a retry. The token deduplicates for 10 minutes. Persist or check the order and hold state for business-level idempotency after that window. Link transactions chapter for SDK details.

8. Industry stories

  • Entertainment (Chioma): zone-sharded EVENT#id#zone for opening night.
  • Airlines (Omar): seat + bag add-on in one txn.
  • Healthcare (Meera): clinic slot hold + patient note.
  • Education (Sofia): exam hall seats.
  • Retail (Aisha): flash SKU reservation.
  • Gov (Priya): passport appointment counters.

9. Lab

  1. Patterns + draw + create lab-ddm-seats with 5 FREE seats.
  2. Hold A-12; second hold fails; retry same ClientRequestToken safely.
  3. Enable TTL on HoldExpires; pay txn or release; delete table.

Cleanup (stop billing)

  1. Delete lab resources you created.
  2. Confirm with describe that names are gone.

10. Ops checklist before you ship

  1. Confirm TTL attribute name and units (epoch seconds).
  2. Decide soft-delete vs hard-delete vs archive-to-S3.
  3. Enable PITR on any table you cannot rebuild from source.
  4. Document RPO/RTO and who runs restore drills.
  5. If multi-region: pick write stickiness and conflict rules.
  6. If DAX: prove cache-miss path and warm-up plan.
  7. Tag Owner + Expiry on every lab resource.
  8. Budget alert in the account before load tests.

11. Copy-paste DynamoDB CLI starters (batch 2)

export AWS_DEFAULT_REGION=ap-south-1

# TTL status
aws dynamodb describe-time-to-live --table-name ShopApp

# PITR / continuous backups
aws dynamodb describe-continuous-backups --table-name ShopApp

# On-demand backup
aws dynamodb create-backup --table-name ShopApp --backup-name lab-shop-$(date +%Y%m%d)

# List backups
aws dynamodb list-backups --table-name ShopApp

# Global table description (v2)
aws dynamodb describe-table --table-name ShopApp --query 'Table.Replicas'

12. More industry stories

  • Retail (Aisha Khan, Dubai): TTL clears abandoned carts; soft-delete keeps 30-day undo.
  • Bank (Lucas Meyer, Berlin): PITR on ledger table; restore drill every quarter.
  • Travel (Omar Haddad, Amman): Global Tables for catalog reads; inventory writes sticky.
  • Gaming (Carlos Rivera, Mexico City): DAX for hot profile Gets; never cache money ledgers.
  • Social (Priya Nair, Kochi): adjacency edges for follows; sparse GSI for unread inbox.
  • IoT (Mei Lin, Shenzhen): device#day PK + TTL 14 days; rollups to S3.

13. Glossary (batch 2)

TermMeaning
TTLTime to Live — attribute with epoch seconds; DynamoDB deletes later
Soft deleteFlag deleted=true; item remains until TTL/archive
PITRPoint-in-time recovery — continuous backups window
Global TableMulti-region replicated DynamoDB table
LWWLast-writer-wins conflict resolution on replicas
DAXDynamoDB Accelerator — in-memory cache cluster
Adjacency listEdge items modeling relationships in one table
Fan-outWrite once; push copies to many feeds/inboxes

14. Practice: explain out loud

  1. 60s: TTL vs soft-delete vs S3 archive.
  2. 60s: PITR vs on-demand backup.
  3. 60s: when Global Tables help and hurt.
  4. 60s: DAX consistency trade-off.
  5. 60s: CartLite checkout keys in one breath.
  6. 60s: follow edge vs feed item.
  7. Record once; cut filler; record again.

15. Safe lab hygiene

  • Use ap-south-1 labs with a budget alert.
  • Prefix lab tables with lab- and your initials.
  • Delete replicas, DAX clusters, and backups you created for labs.
  • Never enable Global Tables on production without a write plan.
  • Tag every resource Owner + Expiry.
  • Export/import labs can create large S3 bills — delete prefixes.

17. Delete / archive decision pad

NeedPreferWhy
Undo 7-30 daysSoft-delete flagUser restore
Hard expiry, no readTTL attributeAuto delete later
Compliance keep coldExport/archive to S3Cheap long store
Mistake recoveryPITR / backupTable-level restore

18. Ten oral drill questions

  1. What units does DynamoDB TTL use?
  2. Does TTL delete instantly?
  3. PITR window typical length?
  4. Global Tables conflict default?
  5. When sticky writes matter?
  6. DAX vs API Gateway cache?
  7. Cart PK for a shopper?
  8. Order lines under which PK?
  9. Follow edge SK example?
  10. Unread inbox sparse GSI idea?

19. RPO / RTO mini workshop

  1. Write the worst data loss you can accept (RPO) in minutes.
  2. Write how long restore may take (RTO) before business pain.
  3. Map: on-demand backup vs PITR vs multi-region replica.
  4. Schedule a restore drill on a lab table this month.
  5. Name the person who runs the drill.

20. Cost watch list (batch 2)

  • PITR storage and on-demand backup storage.
  • Global Tables: replicated WCUs in every region.
  • DAX node hours even at idle.
  • Export to S3 + S3 storage + Athena later.
  • Streams + Lambda still bill during TTL deletes.

21. Project Definition of Done

  1. Access patterns written and peer-reviewed.
  2. Sample items drawn for happy path + one failure.
  3. Lab table created, exercised, deleted (or tagged Expiry).
  4. At least one conditional write or transaction exercised.
  5. Cleanup commands pasted in your notes.
  6. One interview answer recorded out loud.
  • TTL hygiene → Backup/PITR for “oops” recovery.
  • Global Tables → sticky writes from capacity/hot lessons.
  • DAX → only after Query shapes are correct.
  • P1 CartLite reuses modeling + transactions.
  • P2 Social reuses adjacency + Streams ideas.

23. Quick self-check (yes/no)

  1. I can explain TTL delay vs instant DeleteItem.
  2. I know when soft-delete beats hard delete.
  3. I can start PITR and say what restore costs in time.
  4. I can name one reason NOT to use Global Tables.
  5. I know DAX does not fix a bad partition key.
  6. I can sketch CartLite USER# and ORD# keys.
  7. I can sketch a follow edge item.
  8. I delete lab replicas/DAX/backups the same day.

24. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
TransactionCanceledExceptionRead CancellationReasons; refresh seat.
Blind hold without conditionCondition Status=FREE.
Reuse token with new payloadNew ClientRequestToken per booking.
Hot EVENT# partitionShard by zone / on-demand.
Hold foreverHoldExpires TTL or release path.
Partial Put seat then orderOne TransactWrite.
Rewrite Put chapter hereLink CRUD.
Leave lab tableDelete same day.
Ignore VersionADD Version on hold/pay.

25. Troubleshooting checklist

  1. Cancel on hold: seat already HELD/SOLD — offer neighbors.
  2. IdempotentParameterMismatch: new token.
  3. Throttle opening night: shard EVENT# + on-demand.
  4. TTL not deleting: attr must be Number epoch seconds.
  5. Need strong read before UI: TransactGetItems / consistent Get.

26. FAQ

Q. Should I always use a single table?

Often yes for related access patterns; not a religion. Separate tables are fine for unrelated domains or different capacity/security needs.

Q. Do I still need RDS?

Yes for heavy joins, multi-row SQL reports, and strong relational constraints. See the intro DynamoDB vs RDS chapter.

Q. Is Scan evil?

Scan is a tool for rare admin jobs and small tables. Design so hot paths use Query/GetItem.

Q. Where are Put/Get command details?

In the CRUD survey, CLI and SDK chapters — this deep set links them instead of copying.

Q. Optimistic locking enough?

One item yes; seat+order needs TransactWrite.

Q. TransactGetItems?

Consistent multi-item read before checkout UI.

Q. Payment fails after hold?

A scheduled release changes the seat back to FREE only if it still holds the expected buyer and version and the hold has expired. A late release must not undo a payment that already set the seat to SOLD.

Q. Max actions?

≤100 per transaction.

27. Interview Q&A

Q. (B) Stop double-book?

TransactWrite condition FREE→HELD + order.

Q. (B) Idempotency?

ClientRequestToken.

Q. (M) Payment fail?

TTL/compensate release.

Q. (M) CancellationReasons?

Per-item why txn cancelled.

Q. (S/MNC) Opening-night heat?

On-demand + zone shards + sticky UX.

Q. (MNC) Seat vs inventory service?

Same txn across tables or single-table both types.

28. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Atomic hold+order with a condition — never two lonely Puts.

Ravindra Bagale's Tip (MR)

Hold+order एका txn मध्ये; condition विसरायचं नाही.

Tip (HI)

होल्ड और ऑर्डर एक ट्रांज़ैक्शन में — अकेले Put नहीं।

Try at home

  1. Draw FREE/HELD/SOLD state machine.
  2. Lab hold + conflict.
  3. Write pay + release bullet list.

In short

  1. SeatHold = EVENT# seats + ORDER#.
  2. TransactWrite + FREE condition.
  3. Token + hold TTL.
  4. Cleanup labs.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Atomic hold. Two lonely Puts double-book seats. TransactWrite: FREE→HELD + ORDER with ClientRequestToken. Condition FREE → Put order → token → read CancellationReasons on fail. Chioma Adeyemi treats hold+order as one interview story.
Revision card: Atomic hold · Download PNG · Open card page
Revision card: Hold TTL. Abandoned HOLDs block inventory forever. HoldExpires epoch seconds + TTL or explicit release to FREE. Set HoldExpires → enable TTL → pay path clears hold → test abandon. Vikram Patil releases holds when payment Step times out.
Revision card: Hold TTL · Download PNG · Open card page
Comparison: Lonely Puts vs TransactWrite. Lonely Puts: Seat Put then order Put can partial-fail. TransactWrite: One TransactWrite holds seat and writes order.
Comparison: Lonely Puts vs TransactWrite · Download PNG · Open card page
Comparison: Forever HELD vs Hold TTL/release. Forever HELD: HELD with no expiry blocks inventory. Hold TTL/release: HoldExpires TTL or explicit release to FREE.
Comparison: Forever HELD vs Hold TTL/release · Download PNG · Open card page
Interview card: FREE condition. Blind holds overwrite sold seats. ConditionExpression Status=FREE (and Version). Lab: two clients; second must cancel — show CancellationReasons.
Interview card: FREE condition · Download PNG · Open card page
Interview card: ClientRequest token. Retry without token double-submits orders. ClientRequestToken unique per logical booking. Same token+payload safe; new payload needs new token.
Interview card: ClientRequest token · Download PNG · Open card page
Interview card: FREE HELD SOLD. Missing state machine leaves seats stuck. FREE→HELD on hold; HELD→SOLD on pay; release→FREE. Draw diagram → implement both txns → TTL abandon path.
Interview card: FREE HELD SOLD · Download PNG · Open card page
Interview card: Zone shards. Single EVENT# melts on opening night. Shard EVENT#id#zone or sell zones separately + on-demand. Load-test one PK → add suffix → retest throttle metrics.
Interview card: Zone shards · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Maple Leaf Books is a bookselling business in Toronto. Emily Tremblay looks after its IT and cloud work. They count money in CAD and run their AWS resources in the ca-central-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Make the hold and order atomic

A cinema checkout must either reserve seat A12 and create its order together, or change neither item. Name the DynamoDB write operation.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Guard the initial seat hold

The on-sale request should hold A12 only when nobody holds it yet. In the original model, what Status value should the hold condition require?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Retry an ambiguous booking request

The booking client times out and does not know whether its identical TransactWriteItems call succeeded. Which request field should it reuse within the API’s idempotency window?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Release an expired seat hold

What should return an expired hold to FREE while keeping the seat item? Enter 1 for DynamoDB TTL deletion or 2 for a conditional update that checks the current hold and deadline.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Describe seats table

CLI.

Describe table ShopApp

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Seat states YAML

Machine.

YAML: free: FREE, held: HELD, sold: SOLD.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Easy Choose the target state after conditional release

An expired A12 hold still belongs to the correct buyer and version. What Status should the guarded release write if the seat is available again?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Identify the exception when the booking condition fails

Two clients try to hold one seat. Which DynamoDB exception type does the failed TransactWriteItems call raise when its condition cannot be satisfied?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Form a key for a known seat

This lesson uses EVENT#id as partition key and SEAT#row-num as sort key. What sort key identifies seat A-12?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Apply payment to the right hold

The customer paid for a still-valid hold, and the app checks its owner and version. Which seat state should the successful transaction set?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Choose a write for two records

A Version check is enough to guard changes to one record. The seat item and order item must now update together. Name the DynamoDB operation that enforces both outcomes atomically.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Hold flow YAML

Steps.

YAML: condition: FREE, write: order.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard Reduce opening-night writes on one event key

Independent seat updates are grouped under one extremely busy event key. What key design technique adds different zone suffixes to spread the writes?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Calculate the action ceiling

How many actions can one TransactWriteItems request contain at most, assuming all items and the total payload are within their size limits? Enter the number.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Check that the test seat table is gone

Which read-only DynamoDB operation verifies whether the disposable booking table still exists after cleanup?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Avoid a second order item with the same primary key

The transaction includes a Put for order o1 and should never overwrite an existing order with that key. Which DynamoDB condition function checks the key is absent?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.