title: Concurrent requests : what best practices?
body: <p>I have a Play! Framework 2.3 project hosted on Heroku with the Postgres Addon.
  It handles requests from mobile applications (Post a message).</p>
  
  <p>For different reasons, I have duplicate (twice) rows (messages) in database : </p>
  
  <ul>
  <li>the app might send the request twice in a short time ( less than 10ms )</li>
  <li>I have multiple dynos that handle requests in parallel</li>
  <li>Event if before writing in DB, I check the message does not exist yet. So I guess the first has still not been wrote when the second comes.</li>
  </ul>
  
  <p>I also tried to write a message footprint in the memcache before handling the request (after form validation). But I still got twice messages sometimes.</p>
  
  <p>The solutions I found are :</p>
  
  <ul>
  <li>have a unique constraint on some database field (like a message timestamp client-side generated ?)</li>
  <li>regularly check to remove duplicates</li>
  </ul>
  
  <p>As I do not have means to update mobile apps I will script a regular check of duplicates.</p>
  
  <p>Any other idea ?
  What are the best practices to handle such concurrent requests ?</p>
  
  <p>Attachement : my pseudo code</p>
  
  <pre><code>public static Result submit() {
      User user = MySecured.getCurrentUser(ctx());
  
      final Form&lt;Message&gt; filledForm = form(Message.class).bindFromRequest();
  
      .... Some database pre-verification
  
      if (filledForm.hasErrors()) {
          ObjectNode error = Json.newObject();
          error.put("error", filledForm.errorsAsJson());
          return ok(error);
      } else {
  
          if(Cache.get(KEY_LOCK_FLASH_WRITING+filledForm.data().get("mail"))!=null){
              return internalServerError();
          }
  
          //Verify this flash hasnt already been handled (requests can come twice from client)
         Message sameMessage = Message.findSame(filledForm.get().mail, filledForm.get().message);
          if(sameMessage!=null){
              Logger.info("[Submit] message already exists" + sameMessage.id);
  
              ObjectNode jsonResult = Json.newObject();
              .... Processing a result ... no matter this does not happen.
              return ok(jsonResult);
          }
  
          final Message flash = filledForm.get();
  
          Cache.set(KEY_LOCK_FLASH_WRITING+flash.mail, "");
  
          ... some fields initializations like flash.author = new Author();
  
          ... Then some promises
  
  
          return ok();
      }    
  }
  </code></pre>