Implementing Cosmos DB Change Feed using Azure Functions in C#
Tags: cosmosdb, microsoft, azure, azurefunctions
Published: 2019-08-23 23:41:24

---
title: Implementing Cosmos DB Change Feed using Azure Functions in C#
published: true
tags: cosmosdb,microsoft,azure,azure-functions
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/933/0*CdBH8y_734rbVjL6.png)

Azure Cosmos DB has a cool feature called the [Change Feed](https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed) which allows us to perform real-time analytics on our container by listening to any changes that occur within the container.

These changes are then produced as a sorted list of documents that were change in the order that they were modified. These are persisted and can be processed incrementally. The output can then be consumed by multiple consumers for parallel processing.

This feature is pretty useful in situations where a change in an item can trigger another event or an additional action. One example could be an item is inserted within our container, and we use this to trigger an alert to a website saying that there’s a new item in our container.

**Change Feed functionality is enabled by default on all Cosmos DB accounts**. You don’t have to do anything special to set it up and you can use the throughput that you provision on your Cosmos account to read from the Change Feed like any regular Cosmos DB operation.

Currently, the Change Feed includes inserts and update operations made to items within a container (which is what we’ll focus on in this tutorial). If you want to capture deletes on items in your container, you can use a flag that captures soft deletes or set a [**Time to Live (TTL)**](https://docs.microsoft.com/en-us/azure/cosmos-db/time-to-live) period on your items and use that property for the Change Feed to capture. Bear in mind that the Change Feed will need to be processed in a shorter time than the TTL interval.

Changes appear exactly once in the change feed. Managing any check-pointing logic that you may require needs to be done by your application. The [Change Feed Processor library](https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed-processor) is good for this as it provides automatic check-pointing. Don’t worry about this now for this simple example.

Changes can be synchronized from any point in time and within each logical partition key value, it’s sorted by order of modification. If you have a large container, the Change Feed can be processed by multiple consumers and we can have multiple Change Feeds on the same container running at the same time.

[**At the time of this blog post, only the SQL API and the Gremlin API support the Change Feed across .NET, Java, Python and Node.js applications**](https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed#supported-apis-and-client-sdks).

There are three ways in which we can work with the Change Feed:

1. [Use the Azure Cosmos DB SQL API SDK](https://docs.microsoft.com/en-us/azure/cosmos-db/read-change-feed#using-the-azure-cosmos-db-sql-api-sdk)
2. [Use the Change Feed processor library](https://docs.microsoft.com/en-us/azure/cosmos-db/read-change-feed#using-the-change-feed-processor-library)
3. [Use Azure Functions](https://docs.microsoft.com/en-us/azure/cosmos-db/read-change-feed#using-azure-functions)

Using Azure Functions is **BY FAR** the easiest way to get started with Cosmos DB change feed. We essentially create Functions that are triggered on each new event in our container’s change feed. The [CosmosDB Trigger](https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-function#prerequisites) allows us to use to Change Feed functionality without worrying about any infrastructure.

For our purposes, I’m going to create two Functions:

1. An [HTTP trigger](https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook) function that allows us to Insert and Update new items.
2. A [CosmosDB Trigger](https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2) Function that uses the Change Feed to track changes and inserts on our container, and then persists these to a lease container.

I’m using the 2.x run-time for our Functions.

Now even though the Change Feed supports both Gremlin API and SQL API Cosmos DB accounts, [The CosmosDB Trigger for Azure Functions only supports the SQL API](https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2#supported-apis), so that’s what we’ll use in this demo.

You can view the [entire code repository here](https://github.com/willvelida/ChangeFeedDemo/). This includes the relevant models and helper classes that I use in this project. I’m just using the [Azure Cosmos DB local emulator](https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator) as my Cosmos account. The local emulator is pretty cool for doing local development without spending money on an actual database in Azure.

Let’s start by creating our HTTP trigger functions to create and update our items:

{% gist https://gist.github.com/willvelida/e70fa859f974e51217dcfa9a43bceabb %}

Here we have two Functions, **CreateTaskItem** and **UpdateTaskItem.** In our create function, we’re using the HTTP Trigger input to make a POST request to our Cosmos DB database. We’re just creating a simple TaskItem and persisting it to our TaskCollection Collection. I’ve used the CosmosDB binding here just for this example, but if you’re using Azure Functions and Cosmos DB for production use cases, you should consider using a Singleton instance of Cosmos DB. For our Update function, we’re just making a PUT request to a route of task/{id} where id is our id of the Task.

Now let’s create another function that listens to our HTTP Functions and records these changes to the Change Feed:

{% gist https://gist.github.com/willvelida/8f3b6fa6d27082da8b970e314e57d63a %}

Here I’ve created a function called **ChangeFeedListener** that connects to our _TaskItemCollection_ and listens to any changes on that container. It then persists these changes to a _LeaseCollection_ container. Within our Function, every time we create or update a _TaskItem_ in our _TaskItemCollection_, it prints how many documents were changed (only 1 in our simple use case) and what the id of the document that was changed was.

**In production scenarios** , we could send this as a message to event hubs, send it via a text using the [Twilio binding](https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-twilio) or even send it as a notification to a web site. But for now, this simple function will do.

We’ve finished both our Functions, so let’s do something with them!

Since I’m running things locally, I’m just going to Trigger my HTTP function using [Postman](https://www.getpostman.com/). Let’s start with our Create function and create a task. For that, we’ll make a **POST** request to our Function app and pass in a **JSON** body that includes _TaskName_, _TaskDescription_ and _IsCompleted_ properties.

![](https://cdn-images-1.medium.com/max/1024/1*gzWLuXgswI5eKzOQbpiJXQ.png)

Hit the send button to send our **POST** request and provided our Function works, we should see the following **JSON** response:

![](https://cdn-images-1.medium.com/max/611/1*gc_O5udwxqhlAYIJWrW9EQ.png)

Now that our HTTP Function has been triggered, it shouldn’t be too long until our **ChangeFeedListener** function gets triggered to tell us that there has been a modification. Take a note of the document ID below.

![](https://cdn-images-1.medium.com/max/732/1*kFgGrUcNScJnyGies9ddRw.png)

It’s the same as our Id for the _TaskItem_ document we just created! Copy that id in postman and pass it as a parameter for our **UpdateTaskItem** Function. Let’s change the _TaskDescription_ and _IsCompleted_ value and update our item:

![](https://cdn-images-1.medium.com/max/1024/1*F4QTd0bEKLlTomALOSblJw.png)

Take a look at the response body that our Function returns. We can see that our item has now been changed with the updated values.

![](https://cdn-images-1.medium.com/max/631/1*NhqObuyhI134T05MujmiVg.png)

And when we look in the logs for our Function app, we see that the Change Feed has tracked our update on our _TaskItem_.

![](https://cdn-images-1.medium.com/proxy/1*ABe2v0qmU2lX6xLm2m2BSQ.png)

So there you have it! A pretty basic example of Azure Cosmos DB Change Feed in action!

Take the time to have a [look at the code](https://github.com/willvelida/ChangeFeedDemo/) and feel free to clone it and have a play around with it! As you can see, implementing Change Feed functionality is pretty simple and straightforward using Azure Functions.

We can also use the Change Feed processor in the [new Azure Cosmos SDK v3 library](https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed-processor) to leverage Change Feed features, so in the future I’ll have a go with that and write something up.

If you have any questions, feel free to comment here or reach out to me.