Convenient Semaphore with DynamoDB

DynamoDB is a non-blocking asynchronous storage, and it is great. Mostly. However, sometimes you just need to ensure that only one instance of script accesses a certain share of information in your table. In my case it was operation or purgin+rebuilding records, which under race conditions would result in a massive data loss.

So, I decided to build a semaphore. I inited the following schema:

The basic framework in my case is Phalcon (you should try it, it is awesome). The Semaphore model has to be a singleton, or better a generator of singletons – I resorted to the latter:

Related parts of the  ModelBase :

I used official AWS framework’s DynamoDB client for PHP for further request processing. 

Note two points here:

  • The non-matching condition in putItem request throws a  ConditionalCheckFailedException , so you should catch and process it. And since AWS DynamoDB client does not bother issuing different classes of exceptions, defining its own codes, you should be sure to get out of the cycle if any other exception occurs. 
  • The cloud version, unlice local version of DynamoDB does not like integers. Seriously, it forces you to typecast your integers to string, in order to store them as “number”. 

So you can use this setup as follows: