title: How to isolate read followed by insert in CosmosDb transaction?
body: <p>I'm trying to implement locking in CosmosDb.</p>
  <p>I have a stored procedure which tries to read a record, if record does not exist - it tries to create the record.</p>
  <p>The problem is I get Conflict on insert (409) once in a while.</p>
  <p>Here is my problematic stored procedure:</p>
  <pre><code>function tryLock(lockId, createdDate, ttl) {
      var collection = getContext().getCollection();
      var collectionLink = collection.getSelfLink();
      var response = getContext().getResponse();
  
      var query = 'select * from root r where r.id = &quot;' + lockId + '&quot;';
      collection.queryDocuments(collectionLink, query, {}, function(err, documents) {
          if (err)
          {
              throw err;
          }
          if (documents.length &gt; 0)
          {
              var existingDocument = documents[0];
              var responseDoc = {locked: false, etag: existingDocument._etag, createdDate: existingDocument.createdDate };
              response.setBody(responseDoc);
          }
          else
          {
              createNewLockRecord();
          }
      });
  
      function createNewLockRecord() {
          let lockItem = {id: lockId, createdDate: createdDate, ttl: ttl};
          collection.createDocument(collectionLink, lockItem,
              function (err, createdDocument) {
                  if (err) {
                      throw err;
                  }
                  response.setBody({locked: true, etag: createdDocument._etag, createdDate: createdDocument.createdDate});
              });
      }
  }
  </code></pre>
  <p>My question is, is at possible at all what I'm trying to achieve?</p>
  <p>If I change the order of operations, for example - try inserting first, if it does not succeed - read existing record, will it improve the situation?</p>