title: App Engine, transactions, and idempotency
body: <p>Please help me find my misunderstanding.</p>
  
  <p>I am writing an RPG on App Engine. Certain actions the player takes consume a certain stat. If the stat reaches zero the player can take no more actions. I started worrying about cheating players, though -- what if a player sent two actions very quickly, right next to each other? If the code that decrements the stat is not in a transaction, then the player has a chance of performing the action twice. So, I should wrap the code that decrements the stat in a transaction, right? So far, so good.</p>
  
  <p>In GAE Python, though, we have this in the <a href="https://developers.google.com/appengine/docs/python/datastore/transactions#Using_Transactions" rel="noreferrer">documentation</a>:</p>
  
  <blockquote>
    <p><strong>Note</strong>: If your app receives an exception when submitting a transaction, it does not
    always mean that the transaction failed. You can receive Timeout, TransactionFailedError, or
    InternalError exceptions in cases where transactions have been committed and eventually will 
    be applied successfully. Whenever possible, make your Datastore transactions idempotent so
    that if you repeat a transaction, the end result will be the same.</p>
  </blockquote>
  
  <p>Whoops. That means that the function I was running that looks like this:</p>
  
  <pre><code>
  def decrement(player_key, value=5):
    player = Player.get(player_key)
    player.stat -= value
    player.put()
  </code></pre>
  
  <p>Well, that's not gonna work because the thing isn't idempotent, right? If I put a retry loop around it (do I need to in Python? I've read that I don't need to on SO... but I can't find it in the docs) it might increment the value twice, right? Since my code can catch an exception but the datastore still committed the data... huh? How do I fix this? Is this a case where I need <a href="http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine" rel="noreferrer">distributed transactions</a>? Do I really?</p>