Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Advanced Serverless Architectures with Microsoft Azure
Advanced Serverless Architectures with Microsoft Azure

Advanced Serverless Architectures with Microsoft Azure: Design complex serverless systems quickly with the scalability and benefits of Azure

Arrow left icon
Profile Icon Daniel Bass
Arrow right icon
R$217.99
Book Feb 2019 278 pages 1st Edition
eBook
R$80.00 R$173.99
Print
R$217.99
Subscription
Free Trial
Renews at R$50p/m
Arrow left icon
Profile Icon Daniel Bass
Arrow right icon
R$217.99
Book Feb 2019 278 pages 1st Edition
eBook
R$80.00 R$173.99
Print
R$217.99
Subscription
Free Trial
Renews at R$50p/m
eBook
R$80.00 R$173.99
Print
R$217.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Advanced Serverless Architectures with Microsoft Azure

Chapter 1. Complete Serverless Architectures

Note

Learning Objectives

By the end of this chapter, you will be able to:

  • Create a Function-as-a-Service

  • Use a Database-as-a-Service

  • Create a serverless web application

Note

This chapter will cover the main components that are required to make a complete serverless architecture, beyond the FaaS components (Azure Functions).

Introduction


Serverless architecture, while still a small field, has continued to grow as a topic of interest in software development. Some serverless architectures are now becoming highly complex, powering massively scalable applications that deliver business value across domains. As serverless architecture advances in complexity, it presents unique challenges that aren't really present in other approaches, or if they are present, they are hidden by the other, more major issues that plague those approaches. This book will give you a pragmatic, rational, and experience-based approach to architecting your serverless solution to minimize issues and maximize scalability.

Let's first define Serverless. The current working definition of serverless that's defined in this book is as follows: "A service that abstracts away all server details, provides reactive scaling to demand, and is charged on a resource-usage-based payment model". This encompasses serverless databases and takes into account reactive scaling. Serverless fits use cases from simple web applications to massively scaled and complex applications with millions of users. This book will help you build from a simple web application (with the capability to scale to millions of users with no extra effort from the developers) to a complex application, thus utilizing security, observability, queuing, and caching.

Incorporating serverless components in other styles of architecture is relatively straightforward—for instance, it is easy to use a Function-as-a-Service as a simple replacement for a RESTful API. This approach generally works well, and you can gain large advantages by doing this. To fully realize the benefits of serverless, however, a complete serverless architecture is needed. Building one of these once will also change the way you think about application architecture, meaning that even if you have requirements that demand a non-serverless component, you can still keep the rest of the architecture serverless-first. The components that are covered in this chapter are Function-as-a-Service (FaaS), the Serverless Database, and the Serverless Website. Other components that will be covered later are queues, event hubs, authentication services, and monitoring and logging services.

Function-as-a-Service with a Simple HTTP Trigger


The core component of any serverless architecture is the Function-as-a-Service. The idea of any Function-as-a-Service is basically this: you write your code, send it to your cloud provider, and they handle every aspect of making that available to yourself and your customers. This means developers focus purely on the business logic, and not on unrelated technical things. This also means developers can deliver value much faster, and in a modern business, this is the single-most important advantage you can have.

If you've completed the previous book, Beginning Serverless Architectures with Microsoft Azure, you will know about Azure's product in this area very well: Azure Functions. Azure Functions can be written in C# (.NET Core 2), F# (.NET Core 2) or Javascript (Node 8 and 10). There's a plethora of other languages with varying levels of support, such as Python, Java, and PowerShell, but as they are in preview or marked as experimental, they won't be covered here, and they aren't advised for production use. The experimental languages, and Python and Java in their preview states, have very poor performance as well. Azure Functions also comes in two versions, 1.x and 2.x. We will solely be using version 2.x in this book.

Note

1.x's underlying infrastructure is written in .NET and 2.x's is written in the newer, faster, and cross-platform .NET Core. Version 2 is now in General Availability, and therefore it is advised to only use it for new projects (unless you have some strong dependency on a .NET-only library). It would also be advisable to convert any existing functions to version 2 for the performance benefits alone, but it's also likely that version 1 will eventually be deprecated. If you are looking for support for other languages, Java is the most likely next language to be fully supported by Azure Functions and there are a large number of unsupported yet reasonably functional languages. Alternatively, AWS Lambda supports Java, Go, and Python, in addition to C# and Node.js.

Exercise 1: Creating an Azure Function

In this exercise, you will be learning how to create a function, which is the most important component of any serverless architecture, in C#. We will be using Azure Functions to do this. We will also see how to run this function locally and in the cloud:

Note

If you are getting asked what environment to attach to when you click the play button, you are likely to be in a folder too high. Make sure you have opened Visual Studio Code inside the ProductsApi folder.

  1. Let's begin by first creating our Azure function. Create a new folder in your development area called ProductsApi. Open a command-line tool inside the folder and open Visual Studio Code by typing code . or clicking on the Visual Studio Code icon:

    Figure 1.1: Empty Visual Studio Code screen

  2. Click on the Azure logo, which will appear on the pane on the left if you've downloaded the Azure Functions extension. Then, click on the Sign in to Azure… button and authorize Visual Studio Code with your Azure subscription. Select your free subscription if asked:

    Figure 1.2: Azure Functions Extension screen before signing in to Azure

  3. Now that your environment is ready, click the folder icon with a small lightning bolt icon (see the previous screenshot) in the Azure Functions pane on the left to create a new Azure Functions project. A message will appear in the command palette at the top of the screen. Select your current folder:

    Figure 1.3: Creating a new Azure Functions project

  4. After this, you will be prompted to select a language for your project. Select C# :

    Figure 1.4: Selecting C#

  5. The Azure Functions extension will have scaffolded you a project with no real code—just a .csproj file to define the build process and host.json and local.settings.json files, as shown in the following screenshot:

    Figure 1.5: Scaffolded Azure Function project

    Note

    The host.json file defines the characteristics of the underlying container/runtime, such as how long the function can live for, the version of the runtime (1 or 2), or whether you want sampling in your logging. The local.settings.json file stores application settings, similar to IIS Application Settings, for when you are running the function locally. This is for release variables, passwords, and so on.

  6. Open the Azure Functions extension again and click the lightning bolt with the small plus sign on it to add a function (see Figure 1.2). Select HttpTrigger when prompted for a function template:

    Figure 1.6 Choosing the HttpTrigger template

  7. Name the function GetProducts, as follows:

    Figure 1.7 Naming the function

  8. When prompted to set the namespace, set it to ProductsApi, as follows:

    Figure 1.8 Setting the namespace

  9. You will then be prompted to set AccessRights. Set it to Function:

    Figure 1.9 Setting Access Rights

  10. Once this is done, a function will be templated for you, as follows:

    Figure 1.10 Templated function

  11. When prompted, click Restore on the popup in the bottom right that states that some packages are missing. If you're not prompted, open a terminal window by clicking on the Terminal −> new Terminal button at the top of Visual Studio Code and typing dotnet restore in the ProductsApi folder:

    Figure 1.11: Restoring packages in the inbuilt terminal

  12. Click on the debug button (the bug with the cross through it, which is visible on the left pane of the window) and click on the green play button to start the debug session:

    Figure 1.12: Running the local function

  13. We have now started our Azure Function on our local machine, so let's test it. Visit the address shown in the terminal (by azure-functions-core-tools) in your browser, and try adding a query parameter for the name, like this: http://localhost:7071/api/GetUserData?name=Bob. The following screenshot shows the output obtained for this query:

    Figure 1.13: Browser showing the output of the local Azure function

  14. Let's get our function onto the cloud, where it belongs. Open the Azure Functions tab again and click the up arrow to upload this function to Azure (see Figure 1.2). Create a new Function App with a globally unique name (hence it cannot be specified here):

    Figure 1.14: Choosing a Function App

    The name that's used in this exercise is AdvancedServerlessProductsApi:

    Figure 1.15 Creating a Function App

    Figure 1.16: Choosing a resource group

  15. When prompted to select a resource group, click on Create new resource group, as shown in the following screenshot:

    The resource group that was created in this exercise is named productapi-rg:

    Figure 1.17: Creating a new resource group

  1. Next, click on Create new storage account when prompted:

    Figure 1.18: Choosing a storage account

    Enter the name of your storage account (the one used in this exercise is productapi):

    Figure 1.19: Creating a new storage account

  2. Next, choose your local Azure Region when prompted, as shown in the following screenshot:

    Figure 1.20: Choosing an Azure Region

    This may take a little while. You will see progress windows in the bottom right corner:

    Figure 1.21: Successfully deployed Function App

  3. Your Function App should now have appeared on the left, as shown in the following screenshot. If you expand the functions dropdown, you can find the function you have just deployed and right-click it to get the URL:

    Figure 1.22: Deployed function viewed through Visual Studio Code extension

  4. Try out your function by copying the URL into your browser:

    Figure 1.23: Function running in the cloud

Congratulations, you've created and run an Azure function locally and in the cloud. You should be able to see from this just how quick and easy it is to develop and deploy Azure functions. The function listens for a simple HTTP trigger event and returns a simple message. Anything that you can do in C# can be done using this function.

Serverless Database with Cosmos DB


Most applications need a data persistence layer. The most performant and scalable database with no management on Azure is Cosmos DB. It's the best database available for a serverless architecture, especially as serverless functions can quickly expose scaling issues in conventional databases with their instant and infinite scaling. The following are some of its features:

It's the best database available for a serverless architecture, especially as serverless functions can quickly expose scaling issues in conventional databases with their instant and infinite scaling.

Cosmos DB is considered serverless because it is entirely managed, with no server-level specifics, and is charged per resource used rather than upfront. There can be a blurred line with managed services—if they are managed enough, they can be considered serverless. However, Cosmos DB is definitely serverless because of its resources-used payment model. To expand on this point further, other managed services such as a piece of SaaS software would only count toward a true serverless architecture if they were charged per-resource-usage. This is still fairly uncommon, with software such as Apigee, Sitecore, or Salesforce generally demanding large licenses, irrespective of usage.

  • It is a NoSQL database with customizable levels of consistency (with a tradeoff against performance) and multiple supported data models.

  • It is charged per request (and the complexity of that request) and the data stored.

  • It is generally fairly expensive but will scale infinitely across the globe.

Exercise 2: Creating a Cosmos DB Instance

This exercise will walk you through creating a Cosmos DB instance in the Azure portal. Follow these steps:

  1. Open the Azure Portal and search for "cosmos." Click on the result that says Azure Cosmos DB:

    Figure 1.24: Searching for Cosmos DB

  2. You should see a screen like the following one, which has an Add button in the top left. Click Add:

    Figure 1.25: Screen before creating an Azure Cosmos DB instance

  3. On clicking Add, you will see a window like the one shown in the following screenshot. Fill in the Resource Group, the name you want your Cosmos DB instance to have (advancedserverlessproductdb is used as the Account Name in this exercise), and the region you want it to be in (Location). Select the SQL API. Given that this is a development book for learning, switch off Georedundancy:

    Note

    In a real deployment, you would certainly want to enable Georedundancy. Under the hood, it deploys Cosmos DB to each of the "paired" Azure datacenters, such as North Europe and West Europe, for example. Multi-region Writes are certainly something you should consider if you are running a truly global application, with users wanting to edit data across the world. One thing to bear in mind with this is that if you have a consistency model that forces cross-regional locks on writing, this setting could contribute to a deterioration in performance.

    Figure 1.26: Azure Cosmos DB setup – Basics

  4. Click Review + create on the bottom of the screen and then click on the Create button. This will kick off the deployment of your Cosmos DB:

    Figure 1.27: Summary of Azure Cosmos DB account

    It's likely to take a little while. If you click on the notifications button (the bell icon) in the portal, you can check on how it is progressing:

    Figure 1.28: Notification of progress when creating a Cosmos DB

    Note

    If you click the Download a template for automation link in the bottom right (see Figure 1.27), you will get the ARM template and scripts in Bash, PowerShell, and Ruby for deploying that template. Behind the scenes, the portal simply submits the same template, and this template and code is very useful for your CI/CD pipelines.

You now have an Azure Cosmos DB running, ready to be your serverless persistence layer. This database will happily handle any plausible scale that can be thrown at it, without you having to lift a finger. It also has the ability to trigger Azure Functions on data that are being entered or modified in it, which is a core capability that we will be building on. If you need a RDBMS, and a NoSQL database is simply unacceptable, then other contenders to Cosmos DB would be the SQL Azure, Azure for PostgresSQL, and Azure for MySQL. However, these have the disadvantage of lack of true elastic scaling from a serverless point of view, and all the usual tradeoffs of SQL versus NoSQL apply. Generally, though, they will fit most requirements; they just need more management than a true serverless solution such as Cosmos DB. As always for any application architecture, pragmatism applies.

Serverless Websites with Azure Storage


The final component of the basic serverless architecture is a client frontend. The most common one is web-based, but obviously mobile apps or chatbots are also used. We will be using a web-based frontend in this book.

This is the area that serverless is least developed in. The core idea, however, is to have some way of serving the raw HTML, CSS, and JS files to the client, and having JavaScript call the serverless backend from the client side. The only issue is where and how to host those HTML files.

There are multiple approaches to this. Many applications will be expanding on a current platform, perhaps a CMS such as Adobe Experience Manager, Wordpress, or Sitecore CMS. In that case, the best approach is likely to be embedding your frontend application as a JavaScript Single Page Application in a framework such as Angular, React, or Vue.

If working with a completely greenfield application where you can build a truly serverless application architecture, however, there are a greater range of options, which are listed in order of "serverless-ness" in the following list. One thing to be clear about, however, is that this isn't a fully solved problem yet, so each option will have some disadvantages that will hopefully be fixed over time:

  • Use Azure Storage Static Website Hosting: This has very recently come out of preview, and is now in General Availability. It may be a little unstable given how new the feature is. This feature allows you to use Azure Storage as the repository for your HTML, CSS, and JS files, and set a default home page and a default error page. This is the most serverless option as there are no implementation details or management requirements whatsoever—you can literally put your frontend code there and it will work. This will be the option we will follow in this book.

  • Serve files using an Azure Function: The second option is to use an Azure function as a way of hosting your HTML, CSS, or JS files. If you put your HTML code files into the C# project, you can reply to any HTTP Trigger with them. Azure Functions have standard IIS routing too, which can be used to route to the different pages. This has a few disadvantages though: Azure Functions are charged per gigabyte of RAM per second, so using them to simply transfer potentially large files isn't ideal (as that file will be loaded into the RAM and will need to be encoded and decoded, resulting in needless expense). Also, it isn't very serverless—this solution requires custom, non-business-value-oriented code just to serve up web pages. It will, however, scale along with your serverless backend, and Azure Functions are more mature than Azure Storage Static Website Hosting.

  • Deploy Files to an Azure App Service: The third option is to deploy the files to an Azure App Service. This Platform-as-a-Service technology is well-suited to this task and can host more complex MVC applications as well. They can also scale horizontally without management, which is advantageous. However, the number is limited depending on how "big" a resource you demand. The major issue is the level of management and implementation detail. All we want as serverless developers is a bucket to put files in, and Azure's App Services have all sorts of details we aren't interested in, for example, the number of virtual cores on each instance or the RAM currently being used. One point in their favor for small projects though is the "free" category of hosting, which allows you to deploy a custom web app to the internet for free. This is really useful for prototypes, too.

As you can see, the options progress in management level, adding more and more effort expended into non-business value activities. This is without going down to the level of maintaining a virtual machine or a Kubernetes cluster or, even worse, a physical machine in a rack.

Note

There is in fact a fourth option for utilizing AWS. The storage service in AWS is called S3 and has a fully supported static website hosting feature, which you can read about here: https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html. There aren't any compatibility issues in doing this—latency isn't even an issue as users will be calling the Azure Functions' endpoints from their browsers. Lambda (AWS's FaaS service) can also serve files like Azure Functions.

Exercise 3: Hosting a Serverless Website on Azure Storage

The aim of this exercise is to host a simple Hello World! page on Azure Storage, thus creating a serverless website:

  1. First, you need files to host. Create a new folder called ServerlessWebsite in your development area and create new index.html and error.html files in there:

    Figure 1.29: Empty website files

  2. Create a simple page for both the index and error. The following code can be used to display Hello World!:

    <html>
    <body>
        <h1>Hello World!</h1>
    </body>
    </html>

    The following example can be used to display Error:

    Figure 1.30: Error page

  3. Now that you've created the files to host, let's create an account on Azure Storage where you can host these files. Open the Azure Portal and search for "storage":

    Figure 1.31: Searching for storage

  4. Select Storage accounts. You should see a screen like the one shown in the following screenshot, with at least one storage account already existing from when you created it. You may see more if you have already been using Azure and have already made some storage accounts:

    Note

    It's possible that you will see other categories of storage account in the search, such as classic. This depends on your Azure Account, so you won't necessarily see any others. Just always select the one that precisely says Storage accounts.

    Figure 1.32: Azure Storage Accounts page

  5. Click Add. You should be taken to a screen like the one shown in the following screenshot. Enter the same resource group that you did for Cosmos DB and the Azure Function App. Give your storage account an appropriate name for hosting a website (the one in this exercise is named webfrontendadvanceds). Choose a location near to you. Choose Standard performance, StorageV2, and simple Locally Redundant Storage or RA-GRS. In production, you will probably want a greater level of georedundancy, but for development purposes, locally redundant storage is fine. Premium performance is actually designed for virtual machine disks, not for web hosting, and is not currently supported with static site hosting. Finally, choose the Hot access tier; Cold is for archiving data:

    Note

    Note that storage account names have to be globally unique. Hence, do not try and create a storage account with the exact same name as the one that's used in this exercise.

    Figure 1.33: Creating a storage account

  6. Click the Review + create button and then create the storage account. This may take a little while to provision. You will receive a notification in the top right of the page when it has been created:

    Figure 1.34: Creating a storage account

  7. Now, you can host the files you created on your Azure Storage account. Go to the storage account you just created (it will appear on the pane on the left) and click on it:

    Figure 1.35: Storage Account Home

  8. Scroll down the left column and look for Static website (preview) under Settings. Enable it and set your Index document name to index.html and your Error document path to error.html, as shown in the following screenshot:

    Figure 1.36: Setting up static website hosting

  9. Click on the Azure tab. We are going to use the Azure Storage extension of Visual Studio Code to deploy the site. Click the Azure Storage account and open the Blob Containers sub-item until you get to the $web item. Right-click it and select Deploy to Static Website:

    Figure 1.37: Deploy to Static Website

    Note

    Using the Azure Storage extension of Visual Studio Code is the easiest manual way to upload files to Azure Storage. If you are doing an automated deployment, you should use a PowerShell script to connect.

  10. You will now be prompted to select a folder to deploy. Select the ServerlessWebsite folder:

    Figure 1.38: Selecting a folder to deploy

  11. Click Delete and Deploy if the following message comes up. It won't if you have never deployed anything to this Azure Storage account before:

     

    Figure 1.39: Confirming deployment

    As before, updates on the deployment will appear in the bottom right:

    Figure 1.40: Deployment updates

  12. You can finally test your website by visiting the address of your Azure Blob Storage account in your browser. This can be found by clicking on the browse site button in the successful deployment update, going back to the static website part of the portal, or by using the pattern they all follow: https://{StorageAccountName}.z6.web.core.windows.net:

    Figure 1.41: Serverless website hosted on Azure Storage

You now have the fundamental building blocks of a complete serverless architecture. With Azure Storage hosting your website, you can build any web application. Of course, other client-side delivery methods such as mobile apps and chatbots are possible. Mobile apps are a perfect fit, simply calling the serverless backend directly. Chatbots would use Alexa or Google Assistant as their frontend and call in to the serverless backend.

Exercise 4: Displaying Product Data on Your Serverless Website

In this exercise, you will be displaying product data from the serverless database (Cosmos DB) on the serverless website hosted in the Azure Storage, using the Azure Function you created in the first exercise. It will serve as the basis for the rest of your work on this book, and an inspiration for how easy and quick this development process is:

  1. First of all, you need some product data to display. Go to the Cosmos DB instance in the Azure Portal and select Data Explorer:

    Figure 1.42: Cosmos DB Data Explorer

  2. Click on the New Database option to create a database. Call it serverless and click on OK:

    Figure 1.43: Creating a database

  3. Next, click on the New Collection option and create a collection called products in the serverless database that we created in the preceding step. Set its throughput to 400 Resource Units (this is how Cosmos DB charges for compute usage on queries) and set the Partition key to /colour. Again, click on OK:

    Figure 1.44: Creating a collection

  4. Click on Documents inside the Collection, as shown in the following screenshot:

    Figure 1.45: Selecting Documents inside the collection

  5. Click on the New Document option. Insert some records into the Cosmos DB, which will represent products. An example is shown in the following code. Make sure that you do not remove or misspell any of the property names as it will cause problems later. The ID follows the pattern {typeId}_{name}_{colour}_{size}. Cosmos DB will add some fields, including a very useful Etag, which will be used later. In general, you don't need to worry about the automatically added fields; Cosmos DB will handle them:

    {
        "id":"tshirt_metallica_black_xl",
        "typeId": "tshirt",
        "name": "Metallica",
        "colour": "black",
        "size": "xl",
        "quantityInStock": 100
    }

    Figure 1.46: Creating a Cosmos DB record

    You have now added your product data to Cosmos DB. Now, you need to display this data on your website using the Azure function we created previously.

  6. Open the GetProducts Azure Function from Exercise 1, Creating an Azure Function. Install the DocumentDB package by opening the terminal in the ProductsApi folder and entering the following command:

    dotnet add package Microsoft.Azure.WebJobs.Extensions.CosmosDB --version 3.0.1

    Note

    Due to version upgrades, the latest version may not exactly match the one given here. We recommend that you use the latest version for this and the subsequent exercises and activities, in order to ensure that the command functions.

    Next, we need to ensure that all the NuGet packages are installed, which we do by "restoring". Use the following command:

    dotnet restore

    Your file will look as follows:

    Figure 1.47: Installing the DocumentDB extension

  7. We need to give our function the ability to read from the Cosmos DB. This is done using a DocumentClient object from the SDK. Add a using statement for Microsoft.Azure.Documents.Client and create a private static DocumentClient property called client:

    private static DocumentClient client = new DocumentClient(new Uri("cosmos endpoint"),"key");

    Figure 1.48: Added DocumentClient

  8. Next, we need the Unique Resource Identifier (URI) for the Collection inside the Cosmos DB instance. This will allow us to create queries against that collection. Create a private static Uri property that uses the UriFactory to create a URI for the DocumentCollection:

    private static Uri productCollectionUri = UriFactory.CreateDocumentCollectionUri("serverless","products");

    Your file will look as follows:

    Figure 1.49: Adding productCollectionUri

  9. Add a private static QueryOptions property with the MaxItemCount set to –1. This sets the number of docs returned in a query to infinite, which is something to be cautious of as your database scales:

    private static readonly FeedOptions productQueryOptions = new FeedOptions { MaxItemCount = -1 };

    Figure 1.50: Adding productQueryOptions

  10. Now, we need to return the products from Cosmos DB. We don't need the post method anymore, so delete post from the function signature. Change the return type to Task<List<Product>>. The Cosmos DB SDK uses an Iqueryable syntax that lets you use LINQ expressions in C# to generate queries on the database. This is superb for simple queries, but it is advisable to double-check what database queries it is generating for complex queries as they may not be optimally efficient. We will use the syntax to simply return all. Delete the entire function body and replace it with this:

    return client.CreateDocumentQuery<Product>(productCollectionUri, productQueryOptions).ToList();

    Also, add the following using statement:

    using System.Linq;

    Figure 1.51: Adding query returning products

  11. Add a Product class in a file called Product.cs in a folder called Models with properties matching the ones in the Cosmos DB. Add a JsonProperty annotation on the ID property to force it into lower case:

    Figure 1.52: Product Model

  12. Add the following three using statements to the GetProducts function:

    using System.Collections.Generic; using ProductsApi.Models;
  13. Now, go to Cosmos DB in the Azure Portal and click on Keys. Retrieve the endpoint and the primary key and enter them into the DocumentClient. This is vital to authorize your function to connect to your Cosmos DB.

  14. Test the function by pressing the play button on the debug tab and going to the address in your browser. You should see an output similar to the following when testing:

    Figure 1.53: Testing the function

  15. Open the ServerlessWebsite folder in VS Code. Add a table to the index.html file using the following code:

    <table>
        <thead>
            <tr>
                <th>
                    Name
                </th>
                <th>
                    Size
                </th>
                <th>
                    Colour
                </th>
                <th>
                    Quantity In Stock
                </th>
            </tr>
        </thead>
        <tbody id='tableBody'>
        </tbody>
    </table>

    Figure 1.54: HTML Table

  16. Add a function that takes the object from the API and returns a table row by using the following code:

    <script>
        function rowOfDataFromObject(data){
            let row = document.createElement('tr');
    
            let nameTableElement = document.createElement('td');
            nameTableElement.appendChild(document.createTextNode(data.name));
            row.appendChild(nameTableElement);
    
            let sizeTableElement = document.createElement('td');
            sizeTableElement.appendChild(document.createTextNode(data.size));
            row.appendChild(sizeTableElement);
    
            let colourTableElement = document.createElement('td');
            colourTableElement.appendChild(document.createTextNode(data.colour));
            row.appendChild(colourTableElement);
    
            let quantityTableElement = document.createElement('td');
            quantityTableElement.appendChild(document.createTextNode(data.quantityInStock));
            row.appendChild(quantityTableElement);
    
            return row;
        }
    </script>

    Figure 1.55: Function that returns a table row from a product object

  17. Add a HTTP GET call to the Azure function either by running locally or in the cloud using the fetch method, and turn it into a table row using the JavaScript method you just created (in the following screenshot, the function being called is one that would be running locally as the address in the fetch method is a localhost address):

    Figure 1.56: Fetching product data from the Azure function

  18. Append the rows to the table using the ID set in the HTML and the table rows created by the method:

    document.getElementById("tableBody").appendChild(productRow);

    Figure 1.57: Appending rows to table

  19. Cross Origin Resource Sharing (CORS) is an important security measure that applies to Azure functions as well. It prevents scripts from unexpected websites calling your Azure Function. For the moment, though, this prevents us from testing effectively, so we are going to open it up to all. In production, you would give it only the addresses you expect, so this would be the URL of your website, for example. Open the ProductsApi folder and add a local.settings.json file if it isn't already there. Modify it to add an element called Host with a property called CORS with the value *:

    Figure 1.58: Setting CORS rules to permissive

  20. Finally, test your HTML page by opening it from your local disk or uploading it to Azure Storage and opening in your browser:

    Figure 1.59: Working web page displaying products

You've successfully created your first serverless application in only a couple of hours. This solution almost certainly scales better than anything most developers have ever made and required little extra effort from us.

Activity 1: Creating a Serverless Application for Viewing User Data

You are a developer working for Serverless Ltd. and you have been tasked with creating a serverless application for a client that lets them view basic data about the end customers of their clothing company. For this purpose, you need to create an end-to-end serverless app to view users. Follow these steps to complete this activity:

  1. Create a collection called users in the Cosmos DB database named serverless.

  2. Add some user data to it. The example object just uses name and email address:

    {
        "name": "Daniel",
        "emailAddress": "no@email.com"
    }
  3. Create an Azure function called GetUsers that reads from the users collection.

  4. Create an index.html file that displays that data on a web page by using JavaScript to call the Azure function:

    Figure 1.60: Resulting User Table

Note

The solution for this activity can be found on page 230.

Summary


This approach, with a simple website supported by serverless functions and a serverless database, will scale incredibly well and is very fast to develop. One particularly important thing to note is the total separation of frontend and backend development—this will free both disciplines of development to progress rapidly. Generally, frontend developers would use a SPA framework such as Angular, React, or Vue to produce an interactive web application, but it's equally possible to use vanilla JS or jQuery to call the serverless backend. In the next chapter, we will be covering asynchronous processing and caching as a way to increase the scalability of serverless architecture.

Left arrow icon Right arrow icon

Key benefits

  • Use serverless systems to help you fulfill complex requirements
  • Develop your knowledge of Azure Microsoft Serverless
  • Understand concepts with a hands-on approach and helpful examples

Description

Advanced Serverless Architectures with Microsoft Azure redefines your experience of designing serverless systems. It shows you how to tackle challenges of varying levels, not just the straightforward ones. You'll be learning how to deliver features quickly by building systems, which retain the scalability and benefits of serverless. You'll begin your journey by learning how to build a simple, completely serverless application. Then, you'll build a highly scalable solution using a queue, load messages onto the queue, and read them asynchronously. To boost your knowledge further, the book also features durable functions and ways to use them to solve errors in a complex system. You'll then learn about security by building a security solution from serverless components. Next, you’ll gain an understanding of observability and ways to leverage application insights to bring you performance benefits. As you approach the concluding chapters, you’ll explore chaos engineering and the benefits of resilience, by actively switching off a few of the functions within a complex system, submitting a request, and observing the resulting behavior. By the end of this book, you will have developed the skills you need to build and maintain increasingly complex systems that match evolving platform requirements.

What you will learn

  • Understand what true serverless architecture is
  • Study how to extend and scale architectures until they become ‘complex
  • Implement durable functions in your design
  • Improve the observability of your serverless architecture
  • Implement security solutions using serverless services
  • Learn how to ‘practise chaos engineering in production
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 28, 2019
Length 278 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788479127
Vendor :
Microsoft
Languages :
Concepts :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Publication date : Feb 28, 2019
Length 278 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788479127
Vendor :
Microsoft
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together

Stars icon
Total R$ 240.00 611.97 371.97 saved
Azure Serverless Computing Cookbook
R$80 R$218.99
Advanced Serverless Architectures with Microsoft Azure
R$80 R$173.99
Serverless Integration Design Patterns with Azure
R$80 R$218.99
=
Book stack Total R$ 240.00 611.97 371.97 saved Stars icon

Table of Contents

8 Chapters
Preface Chevron down icon Chevron up icon
1. Complete Serverless Architectures Chevron down icon Chevron up icon
2. Microservices and Serverless Scaling Patterns Chevron down icon Chevron up icon
3. Azure Durable Functions Chevron down icon Chevron up icon
4. Security Chevron down icon Chevron up icon
5. Observability Chevron down icon Chevron up icon
6. Chaos Engineering Chevron down icon Chevron up icon
Appendix Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela