Building a reactive application with Azure Cosmos DB

As the demand for modern, scalable, and responsive applications continues to rise, building reactive applications has become an increasingly popular trend in recent years. Reactive systems are designed to react to events and changes in the system in a timely, consistent, and fault-tolerant manner. These systems often use event-driven architectures, asynchronous programming models, and distributed data stores to achieve their goals.

One of the most popular distributed data stores is Azure Cosmos DB, a planet-scale NoSQL database service that provides global distribution, fast reads and writes, and guaranteed low latency. Azure Cosmos DB supports various APIs, including SQL, MongoDB, Cassandra, and Gremlin, making it an ideal choice for creating reactive applications that can scale horizontally.

In this tutorial, we will walk you through the process of building a reactive application with Azure Cosmos DB. We will use Azure Functions, a serverless compute service, to create the application logic and connect it to a Cosmos DB instance using the SQL API. We will also use Azure Event Grid, a fully managed event routing service, to handle events and trigger the reactive functions. By the end of this tutorial, you will have a fully functional reactive application that can scale with the demand.

Prerequisites

Before starting this tutorial, you should have the following:

  • An active Azure account
  • Azure CLI installed on your local machine
  • A text editor or an integrated development environment (IDE) of your choice
  • Basic knowledge of Azure functions, event-driven architectures, and NoSQL databases

Step 1: Create a Cosmos DB instance

The first step in building a reactive application with Azure Cosmos DB is to create an instance of the Cosmos DB service. Follow the steps below to create a Cosmos DB account in Azure Portal:

  1. Log in to the Azure Portal and click on the “+ Create a resource” button.
  2. Select the “Databases” category and choose “Azure Cosmos DB” from the list.
  3. In the “Basics” tab, fill in the required information, such as subscription, resource group, account name, and API. For this tutorial, we will use the SQL API.
  4. Choose the preferred geographical location and replication options for your Cosmos DB instance.
  5. In the “Networking” tab, choose whether to allow access from all networks or specific IP addresses or networks.
  6. Click on “Review + create” and then click on “Create” to create the Cosmos DB instance.

It may take a few minutes for the instance to be provisioned. Once the instance is created, you will be directed to the Cosmos DB account overview page. Take note of the account URI, primary key, and database name, as we will need them later in the tutorial.

Step 2: Create an Azure Function

Next, we will create an Azure Function that will serve as the reactive function for our application. Follow the steps below to create an Azure Function in Azure Portal:

  1. Log in to the Azure Portal and click on the “+ Create a resource” button.
  2. Select the “Compute” category and choose “Function App” from the list.
  3. In the “Basics” tab, fill in the required information, such as subscription, resource group, function app name, and runtime stack. For this tutorial, we will use the Node.js stack.
  4. Choose the preferred geographical location and operating system for your function app.
  5. Click on “Review + create” and then click on “Create” to create the function app.

Once the function app is created, you will be directed to the function app overview page. From there, you can create a new function by clicking on the “Functions” link on the left-hand side menu. Choose the “HTTP trigger” template and fill in the required information, such as function name and authorization level.

Replace the default code with the following code snippet:

module.exports = async function (context, req) {
    context.log('Creating a new document');
    if (req.body) {
        context.bindings.outputDocument = req.body;
        context.res = {
            status: 201,
            body: "Document created successfully"
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a document in the request body"
        };
    }
};

This function will receive a JSON document in the request body, store it in the Cosmos DB instance, and return a success message if the document is stored successfully. Note that we are using an output binding called “outputDocument” to communicate with the Cosmos DB instance. We will configure this binding in the next step.

Step 3: Configure the Cosmos DB output binding

To connect our reactive function to the Cosmos DB instance, we need to configure an output binding that will write the output document to the Cosmos DB instance. Follow the steps below to configure the Cosmos DB output binding:

  1. Navigate to the function app overview page in Azure Portal.
  2. Click on the “Functions” link on the left-hand side menu and select the function you created in the previous step.
  3. Click on the “Integrate” tab and scroll down to the “Output bindings” section.
  4. Click on the “+ Add” button and select the “Azure Cosmos DB” option from the list.
  5. Fill in the required information, such as the binding name, database name, and container name. Make sure to use the same database name and container name as the Cosmos DB instance you created in step 1.
  6. Click on “Save” to save the binding configuration.

Now, whenever the reactive function is triggered, it will write the output document to the configured Cosmos DB instance automatically.

Step 4: Create an Azure Event Grid subscription

We are now ready to start using Azure Event Grid to trigger the reactive function when an event occurs. Follow the steps below to create an Azure Event Grid subscription:

  1. Log in to the Azure Portal and navigate to the Cosmos DB instance overview page.
  2. Click on the “Events” link on the left-hand side menu and then click on “+ Event Subscription”.
  3. Fill in the required information, such as the subscription name, topic type, and subject filter. For this tutorial, we will use the “ItemCreated” event and the Cosmos DB container as the subject.
  4. Choose the preferred endpoint type and fill in the required information, such as the endpoint URL. For this tutorial, we will use the Azure Function endpoint we created in step 2.
  5. Click on “Create” to create the subscription.

Once the subscription is created, it will listen to the specified events and trigger the reactive function whenever a new document is created in the Cosmos DB container.

Step 5: Test the reactive application

We are now ready to test our reactive application. Follow the steps below to test the application:

  1. Use a REST client or tool of your choice to send a POST request to the Azure Function endpoint with a JSON document in the request body. Make sure the document has the same structure as the Cosmos DB container.
    POST https://<function-app-name>.azurewebsites.net/api/<function-name>
    Content-Type: application/json
    {
     "id": "1",
     "name": "John Doe",
     "email": "[email protected]",
     "phone": "+1 123-456-7890"
    }
    
  2. Verify that the reactive function is triggered and the document is stored in the Cosmos DB instance.
  3. Use the Azure Portal or an external tool of your choice to verify that the document is stored in the Cosmos DB container.

Congratulations! You have successfully created a reactive application with Azure Cosmos DB. You can now extend the application by adding more reactive functions, using different Cosmos DB APIs, or integrating with other Azure services.

Related Post