Database / Azure Cosmos DB interview questions
What are Cosmos DB triggers and user-defined functions (UDFs)?
Cosmos DB supports two additional server-side JavaScript constructs beyond stored procedures: triggers and user-defined functions (UDFs). Both run on the Cosmos DB compute engine but serve different purposes.
Triggers are JavaScript functions attached to a container that fire automatically before or after a write operation (create, replace, delete). There are two kinds:
- Pre-triggers — Execute before the write is committed. Can modify the request (e.g., auto-populate a
createdAttimestamp, validate field formats, generate a composite field). If the pre-trigger throws, the write is rejected. - Post-triggers — Execute after the write succeeds. Useful for updating aggregate documents, sending notifications, or maintaining denormalized data. Post-triggers run within the same transaction scope as the write.
Triggers must be explicitly listed in the SDK request options — they do not fire automatically unless you opt in per request. This is a common gotcha: unlike SQL database triggers, Cosmos DB triggers require the client to declare PreTriggerInclude or PostTriggerInclude on each write request:
await container.CreateItemAsync(item, partitionKey, new ItemRequestOptions { PreTriggers = new List<string> { "validateTimestamp" }, PostTriggers = new List<string> { "updateUserAggregate" } });
User-Defined Functions (UDFs) are JavaScript helper functions callable from within a Cosmos DB query using the udf. prefix. They let you extend the query language with custom computation:
-- Query using a UDF to categorize price ranges SELECT c.id, udf.getPriceCategory(c.price) AS category FROM c
UDFs cannot modify data — they are read-only transformations used in SELECT and WHERE clauses. They also have no access to external systems or the Cosmos DB context object (unlike stored procedures).
More Related questions...