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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
