Is it possible that two requests at the same time double this code? (prevent double database entry)

Posted by loostro on Stack Overflow See other posts from Stack Overflow or by loostro
Published on 2012-07-01T09:10:54Z Indexed on 2012/07/01 9:15 UTC
Read the original article Hit count: 172

1) The controller code (Symfony2 framework):

    $em = $this->getDoctrine()->getEntityManager();

    // get latest toplist
    $last = $em->getRepository('RadioToplistBundle:Toplist')->findOneBy(
      array('number' => 'DESC')
    );

    // get current year and week of the year
    $week = date('W');
    $year = date('Y');

    // if:
    //   [case 1]: $last is null, meaning there are no toplists in the database
    //   [case 2]: $last->getYear() or $last->getWeek() do not match current
    //             year and week number, meaning that there are toplists in the
    //             database, but not for current week
    // then:
    //   create new toplist entity (for current week of current year)
    // else:
    //   do nothing (return)

    if($last && $last->getYear() == $year && $last->getWeek() == $week)
      return;
    else {
      $new = new Toplist();
      $new->setYear($year);
      $new->setWeek($week);
      $em->persist($new);
      $em->flush();
    }

This code is executed with each request to view toplist results (frontend) or list of toplists (backend). Anytime someone wants to access the toplist we first check if we should create a new toplist entity (for new week).

2) The question is:

Is it possible that:

  • User A goes to mydomain.com/toplist at 00:00:01 on Monday -> the code should generate new entity
  • the server slows down and it takes him 3 seconds to execute the code
  • so new toplist entity is saved to database at 00:00:04 on Monday
  • User B goes to mydomain.com/toplist at 00:00:02 on Monday
  • at 00:00:02 there the toplist is not yet saved in database, thus UserB's request triggers the code to create another toplist entity

And so.. after a few seconds we have 2 toplist entities for current week.

Is this possible?

How should I prevent this?

© Stack Overflow or respective owner

Related posts about database

Related posts about symfony-2.0