title
stringlengths
3
46
content
stringlengths
0
1.6k
12:2
Azure, like other clouds, offers a wide range of storage services. The first approach that we may consider is defining a scalable set of virtual machines hosted in the cloud where we can implement our custom solutions. For instance, we can create a SQL Server cluster on our cloud-hosted virtual machines to increase reliability and computational power. However, usually, custom architectures are not the optimal solution and do not take full advantage of the opportunities offered by cloud infrastructure. Scalability, fast setup, focus on the business, and security are some of the criteria that you might consider while deciding on your data storage on Azure. To help you with this, many of the platform-as-a-service (PaaS) options for storing data can be a great solution.
12:3
Therefore, this chapter will not discuss such custom architectures but will focus mainly on the various PaaS storage offerings that are available in the cloud and on Azure. These offerings include scalable solutions based on plain disk space, relational databases, NoSQL databases, and in-memory data stores such as Redis.
12:4
Choosing a more adequate storage type is based not only on the application’s functional requirements but also on performance and scaling-out requirements. In fact, while scaling out when processing resources causes a linear increase in performance, scaling out storage resources does not necessarily imply an acceptable increase in performance. In short, no matter how much you duplicate your data storage devices, if several requests affect the same chunk of data, they will always queue for the same amount of time to access it!
12:5
Scaling out data causes linear increases in read operation throughput since each copy can serve a different request, but it doesn’t imply the same increase in throughput for write operations since all copies of the same chunk of data must be updated! Accordingly, more sophisticated techniques are required to scale out storage devices, and not all storage engines scale equally well.
12:6
Relational databases do not scale well in all scenarios. Therefore, scaling needs and the need to distribute data geographically play a fundamental role in the choice of a storage engine, as well as in the choice of SaaS offering.
12:7
In this chapter, we will cover the following topics:
12:8
12:9
Understanding the different repositories for different purposes
12:10
Choosing between SQL and NoSQL document-oriented databases
12:11
Azure Cosmos DB – an opportunity to manage a multi-continental database
12:12
12:13
Let us get started!
12:14
Technical requirements
12:15
This chapter requires that you have the following:
12:16
12:17
Visual Studio 2022 free Community edition or better, with all the database tool components installed.
12:18
A free Azure account. The Creating an Azure account subsection in Chapter 1, Understanding the Importance of Software Architecture, explains how to create one.
12:19
For a better development experience, we advise that you also install the local emulator of Cosmos DB, which can be found at https://aka.ms/cosmosdb-emulator.
12:20
You can find the sample code for the chapter at https://github.com/PacktPublishing/Software-Architecture-with-C-Sharp-12-and-.NET-8-4E.
12:21
12:22
Understanding the different repositories for different purposes
12:23
This section describes the functionalities that are offered by the most popular data storage techniques. We will mainly focus on the functional requirements they are able to satisfy. Performance and scaling-out features will be analyzed in the next section, which is dedicated to comparing relational and NoSQL databases.
12:24
In Azure, the various offerings can be found by typing product names into the search bar at the top of all Azure portal pages.
12:25
The following subsections describe the various kinds of databases that we can use in our C# projects.
12:26
Relational databases
12:27
These databases are the most common and studied type of storage. They guarantee a high level of service and store an immeasurable amount of data. Dozens of applications have been designed to store data in this kind of database, and we can find them in banks, stores, industries, and so on. When you store data in a relational database, the basic principle is to define the entities and properties you will save in each of them, defining the correct relationship between these entities.
12:28
For decades, relational databases were the only option imagined for designing great projects. Many big companies around the world have built their own database management system. Oracle, MySQL, and MS SQL Server would be listed by many as the ones you can trust to store your data.
12:29
Usually, clouds offer several database engines. Azure offers a variety of popular database engines, such as Oracle, MySQL, PostgreSQL, and SQL Server (Azure SQL).
12:30
Regarding the Oracle database engine, Azure offers configurable virtual machines with various Oracle editions installed on them, which you can easily verify by the suggestions you get after typing Oracle into the Azure portal search bar. Azure fees do not include Oracle licenses; they just include computation time, so you must bring your own license to Azure.
12:31
With MySQL on Azure, you pay to use a private server instance. The fees you incur depend on the number of cores you have, how much memory must be allocated, and backup retention time.
12:32
MySQL instances are redundant, and you can choose between local or geographically distributed redundancy:
12:33
12:34
Figure 12.1: Creating a MySQL server on Azure
12:35
Azure SQL Database was one of the first PaaS options available on Azure, and for this reason, it has evolved a lot in recent years, which has made it one of the most flexible offers. Today, it also includes a serverless pricing model, where you are billed for the compute used per second. Here, you can configure resources that are used by every single database. When you create a database, you have the option to place it on an existing server instance or create a new instance.
12:36
There are several pricing options that you may choose while defining your solution, and Azure keeps incrementing them to make sure you will be able to handle your data in the cloud. Basically, they vary due to the computing capacity you need.
12:37
For instance, in the Database Transaction Units (DTUs) model, fees are based on the database storage capacity that has been reserved and a linear combination of I/O operations, CPU usage, and memory usage that is determined by a reference workload. Considering the difficulty of understanding exactly how DTUs are calculated, Azure also offers vCore-based models, where you have flexibility, control, and transparency of individual resource consumption.
12:38
Roughly, maximal database performance increases linearly when you increase the DTUs.
12:39
12:40
You can find detailed information about the options you have for purchasing Azure SQL Database at https://learn.microsoft.com/en-us/azure/azure-sql/database/purchasing-models?view=azuresql.
12:41
12:42
12:43
Figure 12.2: Creating an Azure SQL Database
12:44
You can also configure data replication by enabling read scale-out. This way, you can improve the performance of read operations. Backup retention is fixed for each offering level (basic, standard, and premium).
12:45
If you select Yes for Want to use SQL elastic pool?, the database will be added to an elastic pool. Databases that are added to the same elastic pool will share their resources, so resources that are not used by a database can be used during the usage CPU peaks of other databases. It is worth mentioning that elastic pools can only contain databases hosted on the same server instance. Elastic pools are an efficient way to optimize resource usage to reduce costs.
12:46
NoSQL databases
12:47
One of the biggest challenges that relational databases have caused software architects is related to how we deal with database structural schema changes. The agility of changes needed at the beginning of this century brought the opportunity to use a new database style called NoSQL. The next subtopics will present several types of NoSQL databases.
12:48
Document-oriented database
12:49
The most common type of database, where you have the key and complex data, is called a document.
12:50
For instance, in NoSQL document-oriented databases, relational tables are replaced with more general collections that can contain heterogeneous JSON objects. That is, collections have no predefined structure and no predefined fields with length constraints (in the case of strings) but can contain any type of object. The only structural constraint associated with each collection is the name of the property that acts as a primary key.
12:51
More specifically, each collection entry can contain nested objects and object collections nested in object properties, that is, related entities that, in relational databases, are contained in different tables and connected through external keys. In NoSQL, databases can be nested in their parent entities. Since collection entries contain complex nested objects instead of simple property/value pairs, as is the case with relational databases, entries are not called tuples or rows but documents.
12:52
No relations and/or external key constraints can be defined between documents that belong to the same collection or to different collections. If a document contains the primary key of another document in one of its properties, it does so at its own risk. The developer is responsible for maintaining and keeping these coherent references. This is a tradeoff that you, as a software architect, must analyze. If you design a system that is generally dependent on relational databases, the gain of NoSQL will not be achieved, and you are at the same time sacrificing data integrity and redundancy. However, if you have a scenario where flexibility is needed, you must consider NoSQL as an option.
12:53
Finally, NoSQL storage is quite cheap. You can store a great amount of data as Base64 string properties. The developer can define rules to decide what properties to index in a collection. Since documents are nested objects, properties are tree paths. It is worth saying that you can specify which collection of paths and subpaths are indexed.
12:54
Almost all NoSQL databases are queried either with a subset of SQL or with a JSON-based language where queries are JSON objects whose paths represent the properties to query and whose values represent the query constraints that have been applied to them.
12:55
The possibility of nesting children objects inside documents can be simulated in relational databases with the help of one-to-many relationships. However, with relational databases, we are forced to redefine the exact structure of all the related tables, while NoSQL collections do not impose any predefined structure on the objects they contain. The only constraint is that each document must provide a unique value for the primary key property.
12:56
It is true that today, we have the possibility to define JSON columns in relational databases such as Azure SQL, so we can take a hybrid approach when defining our data model, having a schema for part of it but being flexible on other parts of it. However, NoSQL databases continue to be the best option when the structure of our objects is extremely variable, like social media and Internet of Things (IoT) solutions.
12:57
However, often, they are chosen for the way they scale out read and write operations and, more generally, for their performance advantages in distributed environments. Their performance features, which compare them to relational databases, will be discussed in the next section.
12:58
Graph database
12:59
Social media sites tend to use this kind of database since the data is stored as graphs.
12:60
The graph data model is an extreme case of a completely unstructured document. The whole database is a graph where queries can add, change, and delete graph documents.
12:61
In this case, we have two kinds of documents: nodes and relationships. While relationships have a well-defined structure (the primary key of the nodes connected by the relationship, plus the relationship’s name), nodes have no structure at all since properties and their values are added together during node update operations.
12:62
12:63
It is important to you, as a software architect, to decide if this kind of structure presented in graph databases is the best one for the use case for which you are designing the system, always remembering that such a decision can make the system more complicated than needed.
12:64
12:65
Graph data models were conceived to represent the features of people and the objects they manipulate (media, posts, and so on), along with their relationships in social applications. The Gremlin language was conceived specifically to query graph data models. We will not discuss this in this chapter, but references are available in the Further reading section.
12:66
Key-value database
12:67
This is a useful database for implementing caches since you can store key-value pairs. Redis is a great example of it and it will be detailed soon in this chapter.
12:68
Wide-column store database
12:69
This is a type of database where the same column in each row can store different data.
12:70
NoSQL databases will be analyzed in detail in the remaining sections of this chapter, which are dedicated to describing Azure Cosmos DB and comparing it with relational databases.
12:71
Redis
12:72
Redis is a distributed in-memory storage based on key-value pairs and supports distributed queuing. It can be used as permanent in-memory storage and as a web application cache for database data. Alternatively, it can be used as a cache for pre-rendered content.
12:73
Redis can also be used to store a web application’s user session data. This was done originally with Microsoft SQL Server, but due to the performance provided by memory databases, Redis is the best alternative today.
12:74
In fact, ASP.NET Core supports session data to overcome the fact that the HTTP protocol is stateless. More specifically, user data that is kept between page changes is maintained in server-side stores such as Redis and indexed by a session key stored in cookies.
12:75
12:76
Interaction with the Redis server in the cloud is typically based on a client implementation that offers an easy-to-use interface. The client for .NET is available through the StackExchange.Redis NuGet package. The basic operations of the StackExchange.Redis clients have been documented in https://stackexchange.github.io/StackExchange.Redis/Basics, while the full documentation can be found at https://stackexchange.github.io/StackExchange.Redis.
12:77
12:78
The user interface for defining a Redis server on Azure is quite simple:
12:79
12:80
Figure 12.3: Creating a Redis cache
12:81
The Pricing tier dropdown allows us to select one of the available memory/replication options. A quick-start guide that explains how to use Azure Redis credentials and the URI with the StackExchange.Redis .NET client can be found at https://docs.microsoft.com/en-us/azure/azure-cache-for-redis/cache-dotnet-core-quickstart.
12:82
Azure storage accounts
12:83
All clouds offer scalable and redundant general-purpose disk memory that you can use as virtual disks in virtual machines and/or as external file storage. Azure storage account disk space can also be structured in tables and queues. Consider using this option if you need cheap blob storage. However, there are more sophisticated options, as we have mentioned before. Depending on the scenario you have, Azure NoSQL databases are a better option than tables, and Azure Redis is a better option than Azure storage queues.
12:84
12:85
Figure 12.4: Creating a storage account
12:86
In the rest of this chapter, we will focus on NoSQL databases and how they differ from relational databases. Next, we will look at how to choose one over the other.
12:87
Choosing between SQL and NoSQL document-oriented databases
12:88
As a software architect, you may consider some aspects of SQL and NoSQL databases to decide the best storage option for you. In many cases, both will be needed. The key point here will surely be how organized your data is and how big the database will become.
12:89
In the previous section, we stated that NoSQL document-oriented databases should be preferred by you, as a software architect, when data has almost no predefined structure. They not only keep variable attributes close to their owners, but they also keep some related objects close since they allow related objects to be nested inside properties and collections.
12:90
Unstructured data can be represented in relational databases if variable properties of a tuple (t) can be placed in a connected table containing the property name, property value, and the external key of t. However, the problem in this scenario is performance. In fact, property values that belong to a single object would be spread all over the available memory space. In a small database, all over the available memory space means far away but on the same disk; in a bigger database, it means far away but in different disk units; in a distributed cloud environment, it means far away but in different – and possibly geographically distributed – servers.
12:91
On the other hand, in the NoSQL document-oriented database design, we always try to put all related objects that are likely to be processed together into a single entry. Related objects that are accessed less frequently are placed in different entries. Since external key constraints are not enforced automatically, and NoSQL transactions are very flexible, the developer can choose the best compromise between performance and coherence.
12:92
It is important to mention that today, we can store unstructured data as columns with JSON (or XML) types in relational databases. This approach allows the use of patterns typically implemented in document databases to also be achievable in relational databases, such as avoiding joins by inserting complete objects in a JSON column. However, the adoption of the NoSQL document-oriented database can be considered the best option since it was designed for this purpose.
12:93
Therefore, we can conclude that relational databases perform well when tables that are usually accessed together can be stored close together. NoSQL document-oriented databases, on the other hand, automatically ensure that related data is kept close together since each entry keeps most of the data it is related to inside it as nested objects. Therefore, NoSQL document-oriented databases perform better when they are distributed to a different memory and to different geographically distributed servers.
12:94
Unfortunately, the only way to scale out storage write operations is to split collection entries across several servers according to the values of shard keys. For instance, we can place all the records containing usernames that start with A on a server, the records containing usernames that start with B on another server, and so on. This way, write operations for usernames with different start letters may be executed in parallel, ensuring that the write throughput increases linearly with the number of servers.
12:95
However, if a shard collection is related to several other collections, there is no guarantee that related records will be placed on the same server. Also, putting different collections on different servers without using collection sharding increases write throughput linearly until we reach the limit of a single collection per server, but it doesn’t solve the issue of being forced to perform several operations on different servers to retrieve or update data that are usually processed together.
12:96
This issue becomes catastrophic for performance in relational databases if access to related distributed objects must be transactional and/or must ensure structural constraints (such as external key constraints) are not violated. In this case, all related objects must be blocked during the transaction, preventing other requests from accessing them during the whole lifetime of a time-consuming distributed operation.
12:97
NoSQL document-oriented databases do not suffer from this problem and perform better with sharding and, consequently, with write-scaled output. This is because they do not distribute related data to different storage units and instead store them as nested objects of the same database entry. On the other hand, they suffer from different problems, like not supporting transactions by default.
12:98
It is worth mentioning that there are situations where relational databases perform well with sharding. A typical instance is a multi-tenant application. In a multi-tenant application, all entry collections can be partitioned into non-overlapping sets called tenants. Only entries belonging to the same tenant can refer to each other, so if all the collections are sharded in the same way according to their object tenants, all related records end up in the same shard, that is, in the same server, and can be navigated efficiently.
12:99
12:100
In this chapter, we did not talk about how to define sharding with Azure SQL. Here is the link to the official documentation if you want to find out more: https://docs.microsoft.com/en-us/azure/sql-database/sql-database-elastic-scale-introduction.
12:101