title: Worker synchronization in web frameworks, namely Django
body: <p>Although the scope of possible tools concerned with this kind of problem is broad, we are using Django.</p>
  
  <p>In a system of our interest, we use 2 kind of workers; <code>gunicorn</code> workers are responsible with serving django views, <code>celery</code> is responsible with some routines which should be executed asynchronously.  Both type of workers can read from/write to database, so hereinafter they will be simply referred as <code>workers</code>.</p>
  
  <p>One may perform a database operation as follows:</p>
  
  <pre><code>&gt;&gt;&gt; from someapp.models import mymodel 
  
  &gt;&gt;&gt; foo = mymodel(field1='bar', field2='baz')
  &gt;&gt;&gt; foo.save()
  &gt;&gt;&gt; foo.id
  5
  </code></pre>
  
  <p>given it exists in the DB, you may also get the same <code>foo</code> object as follows, </p>
  
  <pre><code>&gt;&gt;&gt; foo = mymodels.objects.get(id=5)
  &gt;&gt;&gt; foo.field1
  'bar'
  </code></pre>
  
  <p>Lets do a case study;</p>
  
  <p>There are 2 workers operating on the system, and in the same time they read the same row in <code>mymodel</code></p>
  
  <pre><code># Both processes
  foo = mymodel.objects.get(id=5)
  </code></pre>
  
  <p>then, worker 1 changes <code>field1</code> to <code>'bird'</code> </p>
  
  <pre><code># Worker 1
  foo.field1 = 'bird'
  </code></pre>
  
  <p>worker 2 changes <code>field2</code> to <code>'dinosaur'</code></p>
  
  <pre><code># Worker 2
  foo.field2 = 'dinosaur'
  </code></pre>
  
  <p>at this point, nothing is written to the database. If</p>
  
  <pre><code># Worker 1
  foo.save()
  </code></pre>
  
  <p>the concerned row changes as:</p>
  
  <pre><code> id  |  field1 | field2  
  -----+---------+------
   5   |  bird   | baz
  </code></pre>
  
  <p>after this operation, if</p>
  
  <pre><code># Worker 2
  foo.save()
  </code></pre>
  
  <p>this happens:</p>
  
  <pre><code> id  |  field1 | field2  
  -----+---------+------
   5   |   bar   | dinosaur
  </code></pre>
  
  <p>As you would agree, this is a serious synchronization problem. Is there elegant way of solving this? How should I proceed?</p>
  
  <p>One thing is, this problem is too obvious, yet I've never seen anywhere in the internet that mentions what I've described here, which made me cast some doubt on the validity of this problem.</p>