Database / Azure Cosmos DB interview questions
What is a stored procedure in Cosmos DB and what are its limitations?
Stored procedures in Cosmos DB are JavaScript functions registered on a container and executed server-side on the Cosmos DB engine itself. They run atomically within a single partition — meaning all operations inside the stored procedure either all commit or all roll back, giving you ACID transaction semantics without distributed coordination overhead.
A stored procedure is registered and then called via the SDK or REST API:
// Register a stored procedure const sprocBody = function createDocIfAbsent(id, body) { var context = getContext(); var collection = context.getCollection(); var response = context.getResponse(); var query = { query: "SELECT * FROM c WHERE c.id = @id", parameters: [{ name: "@id", value: id }] }; var isAccepted = collection.queryDocuments(collection.getSelfLink(), query, {}, function(err, docs) { if (err) throw err; if (docs.length > 0) { response.setBody(docs[0]); } else { var accepted = collection.createDocument(collection.getSelfLink(), body, function(err, doc) { if (err) throw err; response.setBody(doc); }); if (!accepted) throw new Error("createDocument not accepted"); } }); if (!isAccepted) throw new Error("queryDocuments not accepted"); }; await container.scripts.storedProcedures.create({ id: "createIfAbsent", body: sprocBody }); // Execute it const result = await container.scripts.storedProcedure("createIfAbsent").execute(partitionKey, [id, body]);
Key limitations to know for interviews:
- Single partition scope only — A stored procedure cannot touch items across multiple partition key values. All reads and writes must target the same logical partition passed at invocation time.
- Continuation token required for large result sets — Stored procedures have a time and response size budget. If a bulk operation does not complete in one execution, you must implement pagination using continuation tokens and re-invoke the procedure.
- No external HTTP calls — Server-side scripts cannot call external APIs or Azure services. Logic must be pure JS within the Cosmos DB context API.
- JavaScript only — No other language is supported for stored procedures, triggers, or user-defined functions.
More Related questions...