title: Race condition, url shortener algorithm/Rails/MongoDB/MongoMapper
body: <p>I created a url shortener algorithm with Ruby + MongoMapper</p>
  
  <p>It's a simple url shortener algorithm with max 3 digits 
  <a href="http://pablocantero.com/###" rel="nofollow">http://pablocantero.com/###</a></p>
  
  <p>Where each # can be [a-z] or [A-Z] or [0-9]</p>
  
  <p>For this algorithm, I need to persist four attributes on MongoDB (through
  MongoMapper)</p>
  
  <pre><code>class ShortenerData
    include MongoMapper::Document
    VALUES = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
    key :col_a, Integer
    key :col_b, Integer
    key :col_c, Integer
    key :index, Integer
  end
  </code></pre>
  
  <p>I created another class to manage ShortenerData and to generate the unique 
  identifier </p>
  
  <pre><code>class Shortener
    include Singleton
  
    def get_unique
      unique = nil
      @shortener_data.reload 
      # some operations that can increment the attributes col_a, col_b, col_c and index
      # ...
      @shortener_data.save
      unique
    end
  end
  </code></pre>
  
  <p>The Shortener usage </p>
  
  <pre><code>Shortener.instance.get_unique
  </code></pre>
  
  <p>My doubt is how can I make get_unique synchronized, my app will be 
  deployed on heroku, concurrent requests can call 
  Shortener.instance.get_unique</p>