2

I have a Cosmos DB stored procedure that creates a new document if it doesn't already exist and returns the existing or the new document. The procedure may be called from different processes. Can I be sure that the document is only created once even if several clients are trying to create it at the same time?

function createIfNotExists(param1, param2) {
    var collection = getContext().getCollection();

    // Query documents and take 1st item.
    var query = 'SELECT * FROM c WHERE c.Param1="' + param1 + '" AND c.Param2="' + param2 + '"';
    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        query,
        function (err, items, options) {
            if (err) throw err;

            var response = getContext().getResponse();
            if (!items || !items.length) {
                var accepted = collection.createDocument(collection.getSelfLink(),
                {
                    Param1: param1,
                    Param2: param2
                },
                function (err, itemCreated) {
                    if (err) throw err;
                    response.setBody(itemCreated);
                });

                if (!accepted) throw new Error('Could not create document');
            }
            else {
                response.setBody(items[0]);
            }
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Hein Gustavsen
  • 395
  • 3
  • 15

1 Answers1

2

Can I be sure that the document is only created once even if several clients are trying to create it at the same time?

Hein, about your concern,you could dig into this document which expounds ACID in Cosmos DB.

In Azure Cosmos DB, JavaScript runtime is hosted inside the database engine. Hence, requests made within the stored procedures and the triggers execute in the same scope as the database session. This feature enables Azure Cosmos DB to guarantee ACID properties for all operations that are part of a stored procedure or a trigger. For examples.

So, i think the answer is yes for your question because the atomicity guarantees that all the operations done inside a transaction are treated as a single unit, and either all of them are committed or none of them are.

BTW,you also could set one or more unique keys before the creation of collection,please refer to this blog.

Jay Gong
  • 23,163
  • 2
  • 27
  • 32