Bird
Raised Fist0
Azurecloud~10 mins

Functions with Cosmos DB integration in Azure - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Process Flow - Functions with Cosmos DB integration
Trigger: HTTP Request or Timer
Azure Function Starts
Read/Write to Cosmos DB
Process Data
Return Response or Complete
Function Ends
The function starts on a trigger, interacts with Cosmos DB to read or write data, processes it, then returns a response or completes.
Execution Sample
Azure
module.exports = async function (context, req) {
  const item = req.body;
  context.bindings.outputDocument = item;
  context.res = { status: 201, body: 'Item saved' };
};
This Azure Function receives data from an HTTP request and saves it to Cosmos DB using output binding.
Process Table
StepActionInput/StateCosmos DB InteractionOutput/Result
1Function triggered by HTTP requestRequest body with item dataNo interaction yetFunction starts
2Read request body{ id: '123', name: 'Test' }No interactionItem extracted from request
3Assign item to Cosmos DB output bindingItem data assignedPrepare to write item to Cosmos DBBinding set for write
4Await Cosmos DB write operationWaiting for DB confirmationWrite item to Cosmos DB collectionItem saved in DB
5Set HTTP responseStatus 201, message 'Item saved'No interactionResponse ready to send
6Function completesResponse sentNo interactionFunction ends
💡 Function ends after sending HTTP response confirming Cosmos DB write
Status Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
contextInitializedRequest body readOutput binding setAwaiting DB writeResponse set
itemUndefined{ id: '123', name: 'Test' }{ id: '123', name: 'Test' }{ id: '123', name: 'Test' }{ id: '123', name: 'Test' }
context.resUndefinedUndefinedUndefinedUndefined{ status: 201, body: 'Item saved' }
Key Moments - 3 Insights
Why do we assign the item to context.bindings.outputDocument instead of calling Cosmos DB directly?
Azure Functions use bindings to simplify integration. Assigning to outputDocument tells the platform to write to Cosmos DB automatically, as shown in step 3 and 4 of the execution_table.
What happens if the Cosmos DB write fails during the await operation?
The function will throw an error during step 4, stopping execution before setting the response. Proper error handling is needed to manage this, which is not shown here.
Why is the HTTP response set after awaiting the Cosmos DB write?
We wait for confirmation that the data is saved before responding, ensuring the client knows the operation succeeded, as seen in step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of 'item' after step 2?
AEmpty object {}
B{ id: '123', name: 'Test' }
CUndefined
DNull
💡 Hint
Check the 'Input/State' column at step 2 in execution_table
At which step does the function write data to Cosmos DB?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Cosmos DB Interaction' column to find when the write happens
If the HTTP response was set before awaiting Cosmos DB write, what would change in the execution_table?
AStep 6 would be earlier
BStep 4 would be removed
CStep 5 would occur before step 4
DNo change
💡 Hint
Consider the order of 'Set HTTP response' and 'Await Cosmos DB write operation' steps
Concept Snapshot
Azure Functions with Cosmos DB integration use bindings to connect easily.
Trigger starts function, input data is read.
Assign data to output binding to save in Cosmos DB.
Await completion before sending response.
This ensures data is saved before client is notified.
Full Transcript
This visual execution shows how an Azure Function integrates with Cosmos DB using output bindings. The function triggers on an HTTP request, reads the request body, assigns the data to the Cosmos DB output binding, waits for the database write to complete, then sends an HTTP response confirming the save. Variables like 'item' and 'context.res' change state step-by-step. Key moments clarify why bindings are used and why awaiting the database write is important. The quiz tests understanding of the execution order and variable states.

Practice

(1/5)
1. What is the main benefit of using Azure Functions with Cosmos DB integration?
easy
A. Automatically run code when data changes in Cosmos DB
B. Manually trigger code only through HTTP requests
C. Store large files directly in Cosmos DB
D. Replace Cosmos DB with Azure Blob Storage

Solution

  1. Step 1: Understand Azure Functions with Cosmos DB

    Azure Functions can be triggered automatically by changes in Cosmos DB data.
  2. Step 2: Identify the main benefit

    This automatic trigger saves resources by running code only when needed, without manual calls.
  3. Final Answer:

    Automatically run code when data changes in Cosmos DB -> Option A
  4. Quick Check:

    Functions trigger on data changes = A [OK]
Hint: Functions run on data change events automatically [OK]
Common Mistakes:
  • Thinking functions run only on HTTP triggers
  • Confusing Cosmos DB with file storage
  • Assuming manual triggers are required
2. Which of the following is the correct binding direction for a Cosmos DB input binding in an Azure Function?
easy
A. direction: "out"
B. direction: "both"
C. direction: "trigger"
D. direction: "in"

Solution

  1. Step 1: Recall binding directions

    Input bindings receive data into the function, so their direction is "in".
  2. Step 2: Match binding direction for Cosmos DB input

    Cosmos DB input binding must have direction set to "in" to read data.
  3. Final Answer:

    direction: "in" -> Option D
  4. Quick Check:

    Input binding direction = in [OK]
Hint: Input bindings always use direction "in" [OK]
Common Mistakes:
  • Using "out" for input bindings
  • Confusing trigger with input binding
  • Using invalid directions like "both"
3. Given this Azure Function code snippet triggered by Cosmos DB changes, what will be logged if a new document with id "123" is added?
module.exports = async function (context, documents) {
  if (!!documents && documents.length > 0) {
    context.log(`Document id: ${documents[0].id}`);
  }
};
medium
A. No output logged
B. Document id: undefined
C. Document id: 123
D. Error: documents is not defined

Solution

  1. Step 1: Understand the trigger input

    The function receives an array 'documents' with changed documents; the first document has id "123".
  2. Step 2: Analyze the logging statement

    The code logs the id of the first document, which is "123".
  3. Final Answer:

    Document id: 123 -> Option C
  4. Quick Check:

    documents[0].id = 123 logged [OK]
Hint: documents array holds changed items; access first with documents[0] [OK]
Common Mistakes:
  • Assuming documents is undefined
  • Logging without checking documents length
  • Confusing document id property
4. You wrote an Azure Function triggered by Cosmos DB changes, but it never runs when documents change. Which is the most likely cause?
medium
A. The function code has a syntax error
B. The function.json binding has incorrect connection string name
C. The Cosmos DB container is empty
D. The function app is stopped

Solution

  1. Step 1: Check trigger configuration

    If the connection string name in function.json is wrong, the function won't connect to Cosmos DB changes.
  2. Step 2: Consider other causes

    Syntax errors cause failures but usually show errors; empty container still triggers on inserts; stopped app won't run but question implies function exists.
  3. Final Answer:

    The function.json binding has incorrect connection string name -> Option B
  4. Quick Check:

    Wrong connection string stops trigger [OK]
Hint: Check connection string name in function.json first [OK]
Common Mistakes:
  • Ignoring binding configuration errors
  • Assuming empty container prevents triggers
  • Not verifying function app status
5. You want to create an Azure Function that writes a summary document to Cosmos DB whenever multiple documents are added. Which binding setup should you use?
hard
A. Use Cosmos DB trigger for input and Cosmos DB output binding for summary document
B. Use HTTP trigger and Cosmos DB input binding only
C. Use Cosmos DB input binding only, no trigger
D. Use Timer trigger and Cosmos DB output binding only

Solution

  1. Step 1: Identify trigger for reacting to data changes

    Cosmos DB trigger runs the function automatically when documents change.
  2. Step 2: Use output binding to write summary

    Output binding lets the function write a new summary document back to Cosmos DB.
  3. Final Answer:

    Use Cosmos DB trigger for input and Cosmos DB output binding for summary document -> Option A
  4. Quick Check:

    Trigger input + output binding for writing = C [OK]
Hint: Trigger on changes, output binding to write summary [OK]
Common Mistakes:
  • Using HTTP trigger instead of Cosmos DB trigger
  • Missing output binding for writing data
  • Using timer trigger without data event