KKeySync
← Back to quests

Quest · quest 7

Boost Mew's Stats

Battle statistics change fast! If two players battle at the same time, you could have a race condition. If both read "Wins: 10", add 1, and write "Wins: 11", one win is lost forever. DynamoDB solves this with Atomic Counters using the ADD action.

Atomic countersNumeric updatesConsistency

Key takeaways

  • Race conditions occur when parallel updates overwrite each other.
  • The ADD action atomically increments numeric values in DynamoDB.
  • Atomic counters are perfect for likes, views, and game stats.

The Race Condition Problem

Imagine thousands of players battling at once. A traditional read-modify-write pattern is dangerous:

If two requests happen simultaneously, both see "10", and both write "11". The total should be "12", but one update is lost!

Atomic Counters to the Rescue

DynamoDB supports atomic updates. You tell it "Add 1 to this attribute" rather than "Set this attribute to 11". DynamoDB handles the locking internally to ensure no updates are lost.

Atomic Increment Examplejavascript

Interactive Challenge

Mew has won another battle! Use the UpdateCommand with the ADD action to increment its BattlesWon stat by 1. This is better than reading the current value and adding 1, because it's atomic!

Goal: Use ADD in UpdateExpression to increment BattlesWon by 1.

Quick Quiz

Why should you use atomic counters instead of read-modify-write for game stats?