NoSQL Databases
What Is a NoSQL Database?
NoSQL means “not only SQL.” It describes a family of nonrelational databases designed around data models other than normalized tables joined by foreign keys. Rather than one universal alternative to SQL, NoSQL databases optimize for different access patterns: flexible documents, simple key lookups, wide sparse rows, graph traversals, or in-memory data.
A NoSQL database usually trades some combination of rigid schema, arbitrary cross-entity joins, and broad multi-row transaction scope for horizontal scale, flexible data representation, low-latency access, or a domain-specific query model. That does not mean it has no structure, no schema, no transactions, or no query language. It means that the structure and guarantees are chosen differently.
In Azure, Azure Cosmos DB for NoSQL is the primary managed document-database example. It stores JSON documents, scales throughput and storage horizontally, supports SQL-like queries, automatic indexing, configurable consistency, global distribution, change feed, and transactional batches within a logical partition. Other Azure-adjacent NoSQL choices include Azure Managed Redis for in-memory key-value workloads, Azure Cosmos DB APIs for compatible data models, and specialized services such as Azure AI Search or Azure Data Explorer when search or telemetry is the actual workload. Azure data-model guide
How NoSQL Differs from Relational Databases
Relational databases organize data into tables with fixed columns, relationships, constraints, and a declarative SQL query language. This is excellent for business systems whose integrity depends on normalized data, joins, referential constraints, and transactions that span multiple related rows.
NoSQL databases commonly store records in shapes that resemble the application's read and write needs. A customer profile may be a single JSON document containing preferences, shipping addresses, and settings rather than several normalized tables. This can eliminate joins and support rapid schema evolution, but it shifts more responsibility to the data model and application.
| Concern | Relational database | NoSQL database |
|---|---|---|
| Primary model | Tables, rows, columns, relationships | Document, key-value, wide-column, graph, or other specialized model |
| Schema | Defined and enforced before writes | Often flexible; still requires an application-owned schema contract |
| Relationships | Foreign keys and joins are first-class | Usually embedded, denormalized, or resolved by the application |
| Transactions | Often span multiple tables and rows | Often scoped to one document, partition, or aggregate boundary |
| Scale approach | Traditionally scale up first; distributed variants exist | Frequently designed to partition and scale out from the beginning |
| Query flexibility | Broad ad hoc joins and aggregations | Strong within the chosen model; cross-partition and ad hoc queries can be costly or limited |
| Data modeling | Normalize to reduce duplication | Model around access patterns; selectively denormalize |
| Consistency | Commonly strong within the primary database | Varies by product and configuration; may offer tunable consistency |
The choice is not ideological. Many effective architectures are polyglot: Azure SQL Database for orders and payments, Cosmos DB for product catalog or session data, Blob Storage for files, Azure AI Search for search projection, and Event Hubs or Data Explorer for telemetry.
Major NoSQL Data Models
Document databases
Document stores persist semi-structured documents, usually JSON or BSON. They suit aggregates that are naturally retrieved together and evolve frequently: user profiles, product catalog items, content, configuration, shopping baskets, and device state.
{
"id": "product-482",
"tenantId": "contoso-uk",
"name": "Waterproof jacket",
"price": { "amount": 89.99, "currency": "GBP" },
"sizes": ["S", "M", "L"],
"attributes": { "material": "recycled polyester", "waterproof": true }
}
Azure example: Azure Cosmos DB for NoSQL. It uses JSON documents and a SQL-like query language, but it is not a relational SQL database. Query efficiency and transaction scope depend heavily on the chosen partition key.
Key-value stores
Key-value stores retrieve a value by a known key with very low latency. They are excellent for caching, session state, feature flags, counters, rate-limiting state, and simple lookup data. They are poor at arbitrary queries over values unless the product adds explicit indexes or secondary structures.
Azure example: Azure Managed Redis for caching and transient high-speed state; Azure Cosmos DB for Table for table/key-value-compatible scenarios.
Wide-column (column-family) stores
Wide-column databases store sparse, variable columns grouped into column families. They are optimized for large-scale writes and predictable key-based reads of wide or sparse datasets. The row key and column-family design determine what is fast; ad hoc joins and secondary-index queries are typically limited.
Azure examples: Azure Cosmos DB for Apache Cassandra and HBase on HDInsight for workloads that genuinely fit those ecosystems.
Graph databases
Graph databases model entities as vertices and relationships as edges. They make relationship traversal the central operation: “which colleagues are within three hops?”, “which products are frequently bought together?”, or “what path connects these systems?”
Azure example: Azure Cosmos DB for Apache Gremlin for graph-compatible workloads. Do not choose a graph store merely because the domain has relationships; use it when graph traversal is a primary query pattern.
Search, vector, and time-series systems
These are sometimes grouped into NoSQL discussions because they are nonrelational, but they solve more specific problems:
- Azure AI Search is for full-text, faceted, hybrid, and vector retrieval—not the authoritative transactional store.
- Azure Data Explorer is for high-ingest telemetry and time-series analytics—not a replacement for an OLTP document store.
- Azure Cosmos DB variants can support vector/search scenarios, but the data model and query needs should drive the choice.
Core Principle: Model for Access Patterns
Relational design normally starts with entities, relationships, normalization, and constraints. NoSQL design starts by listing the reads and writes the system must perform, their latency and scale targets, and their consistency needs.
For a multi-tenant catalog, these requirements might be:
- Read a single product by
tenantIdand product ID. - List products by tenant and category.
- Update a product's availability quickly.
- Fetch a customer's basket by tenant and customer ID.
- Never scan every tenant's catalog in an interactive request.
The document shape, partition key, indexes, and selective denormalization should support those operations. A NoSQL database will not “discover” an efficient model after deployment; it can execute an inefficient query at scale and charge latency and throughput for it.
flowchart LR
Requirements[Reads, writes, latency, consistency] --> Model[Document and aggregate design]
Model --> Partition[Partition-key choice]
Partition --> Indexes[Index and query design]
Indexes --> Test[Load, cost, and failure testing]
Test --> Model
Embed or reference?
Embed child data in the parent document when it is owned by the same aggregate, is usually read together, stays reasonably bounded, and should update atomically within that aggregate. Store separate documents and reference by ID when the child has independent lifecycle, unbounded growth, different access patterns, or needs to be shared.
For example, embed the current items in a small shopping basket, but do not embed years of order history into a customer profile. Keep large binary files in Azure Blob Storage and place a secure reference and metadata in the document.
Partitioning in Azure Cosmos DB
Cosmos DB for NoSQL distributes documents by a partition key. The partition key determines which logical partition stores an item and therefore controls scale, locality, query cost, and transaction boundaries.
Choose a partition key that:
- Has high enough cardinality to distribute data and throughput.
- Is present and immutable for every item.
- Matches the common point-read and query path.
- Avoids concentrating all writes on one value, such as a single “active” tenant, current date, or popular product.
- Keeps documents that must transact together in the same logical partition.
flowchart TD
Request[Read or write request] --> Key{Partition key supplied?}
Key -->|Yes| Single[Target one logical partition]
Key -->|No| FanOut[Query multiple partitions]
Single --> Efficient[Predictable latency and RU cost]
FanOut --> Costly[Higher latency and request-unit cost]
A poor partition key creates a hot partition: one logical partition receives disproportionate requests while other capacity sits idle. Increasing overall provisioned throughput may not fix the bottleneck because a single logical partition has its own throughput limits. Choose and validate the key early; changing it later typically requires data migration to a new container.
For Cosmos DB, a point read using both id and the partition key is normally the most efficient lookup. Cross-partition queries are allowed but should be an intentional, measured exception. Request-unit and partitioning guidance
Consistency and Transactions
NoSQL does not mean “eventual consistency only.” Each product defines its own consistency and transaction model.
Azure Cosmos DB provides five consistency levels, from strongest to weakest: Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual. Stronger consistency can increase latency and reduce availability in some failure scenarios; weaker consistency can improve performance and availability but lets a read return older data. Session consistency is a common application default because it lets a client read its own writes within a session. Cosmos DB consistency levels
Cosmos DB for NoSQL supports ACID transactions and transactional batches, but their scope is a single logical partition in one container. This is a feature of the model, not a missing implementation detail: choose aggregate and partition boundaries so that the invariants requiring atomicity live together.
flowchart LR
Order[Order document: partition ORD-1042] --> Batch[TransactionalBatch]
Outbox[Outbox event: partition ORD-1042] --> Batch
Batch --> Commit[Both commit or both roll back]
Customer[Customer document: partition CUST-99] -. different partition .-> NoCross[Not part of the same batch]
If a business operation must coordinate independently owned aggregates or services, use an explicit workflow, event-driven design, or compensating transaction. Do not assume a NoSQL database will provide unlimited cross-partition ACID behaviour just because a relational database could perform a multi-table transaction.
Azure Cosmos DB Throughput and Cost
Cosmos DB measures work in request units (RUs). Reads, writes, queries, indexing, and stored procedures consume RUs. Cost and latency are consequences of document size, indexing policy, query shape, partition scope, consistency, and provisioned or serverless throughput mode.
Practical implications:
- Smaller documents generally cost fewer RUs to read, write, and index.
- Automatic indexing is convenient, but indexing every path can increase write cost; tailor the indexing policy to real queries.
- A point read by
idand partition key is generally cheaper than a query. - A query that targets one partition is generally more predictable than a fan-out query.
- Store large binary payloads in Blob Storage, with a document reference in Cosmos DB.
- Respect
429 Too Many Requestsresponses and the SDK's retry-after guidance; throttling is capacity feedback, not a reason to hot-loop retries. - Use Azure Monitor and SDK diagnostics to identify high-RU operations before changing throughput blindly.
flowchart LR
Document[Document size] --> RU[Request-unit consumption]
Indexes[Indexing policy] --> RU
Query[Query and partition scope] --> RU
Consistency[Consistency level] --> RU
RU --> Cost[Cost and throughput capacity]
RU --> Latency[Latency and throttling risk]
The right capacity model depends on workload shape. Provisioned/autoscale throughput can suit predictable or continuously active workloads; serverless capacity can suit intermittent, lower-volume workloads. Benchmark with representative documents, partitions, concurrency, and queries. Cosmos DB .NET best practices
Practical .NET / C# Example
The following example reads a product by id and tenantId, then creates a product document using the Azure Cosmos DB .NET SDK. It uses a stable partition key and point reads instead of a query for the most common lookup.
using Azure.Identity;
using Microsoft.Azure.Cosmos;
public sealed class ProductRepository(Container container)
{
public async Task<Product?> GetAsync(
string tenantId,
string productId,
CancellationToken cancellationToken)
{
try
{
var response = await container.ReadItemAsync<Product>(
id: productId,
partitionKey: new PartitionKey(tenantId),
cancellationToken: cancellationToken);
return response.Resource;
}
catch (CosmosException exception) when (exception.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
public Task<ItemResponse<Product>> CreateAsync(
Product product,
CancellationToken cancellationToken) =>
container.CreateItemAsync(
item: product,
partitionKey: new PartitionKey(product.TenantId),
cancellationToken: cancellationToken);
}
public sealed record Product(
string Id,
string TenantId,
string Name,
decimal Price,
IReadOnlyList<string> Tags);
Create one long-lived CosmosClient for the process and reuse it; it manages connections and caches metadata. Use async all the way through, propagate cancellation, capture diagnostics for slow or failed requests, and retry transient faults according to the SDK guidance. Authenticate production workloads with managed identity and grant the minimum Cosmos DB data-plane role.
Parameterized, partition-scoped query
When a query is necessary, parameterize it and provide the partition key whenever the request can be constrained to one partition.
var query = new QueryDefinition(
"SELECT * FROM c WHERE c.category = @category")
.WithParameter("@category", "outerwear");
var options = new QueryRequestOptions
{
PartitionKey = new PartitionKey("contoso-uk")
};
using var iterator = container.GetItemQueryIterator<Product>(query, requestOptions: options);
var page = await iterator.ReadNextAsync(cancellationToken);
Do not infer that SQL-like syntax gives SQL Server-like query economics. In Cosmos DB, this query's cost still depends on the document shape, index, result set, and whether it stays within the specified partition.
When You Should Use NoSQL
NoSQL is a good choice when the workload aligns with the database's model, not merely because it is modern or cloud-native.
| Scenario | Why NoSQL can fit |
|---|---|
| Product catalogs and content | Attributes vary by item, nested data is natural, and documents evolve frequently. |
| User profiles, preferences, and sessions | Key-based access and aggregate reads dominate; flexible fields are common. |
| Multitenant SaaS | Tenant-centric partitioning can isolate and scale tenant access patterns. |
| Device state and IoT metadata | High-volume, semi-structured records with predictable key/query patterns are common. |
| Globally distributed applications | Low-latency regional access and configurable consistency can be more important than broad joins. |
| Event-driven projections | A denormalized read model can serve a specific query efficiently, while events update it asynchronously. |
| Graph traversal | Relationship paths are the primary business query, not an occasional reporting query. |
| Cache or ephemeral state | In-memory key-value stores provide extremely fast access and built-in expiry patterns. |
Start with a written list of operations. If most important reads can be handled by known key and partition key, and the aggregate can be read or written as a bounded document, a document store is a credible candidate.
When You Should Not Use NoSQL
NoSQL is not a default upgrade from relational databases. Avoid it, or use it only as a secondary store, when these needs dominate:
| Requirement | Why a relational or specialized service is often better |
|---|---|
| Complex joins across many changing relationships | Normalized relational models and optimizer-driven joins are clearer and safer. |
| Strong referential integrity | Foreign keys, check constraints, and declarative rules keep invariants in the database. |
| Broad, multi-entity ACID transactions | Many NoSQL products restrict transaction scope to one document or partition. |
| Ad hoc reporting and multidimensional aggregation | A warehouse, lakehouse, Fabric, or analytical database is designed for this workload. |
| Financial ledger or inventory core with strict invariants | Relational transactions and constraints often express the domain more directly. |
| Data model and access patterns are unknown | Premature denormalization creates expensive migrations; begin with discovery or a flexible relational model. |
| Team expects SQL joins and normalized reporting by default | A NoSQL model requires disciplined access-pattern design, observability, and operating practices. |
| Very low, steady, simple workload | A managed relational database may be simpler and cheaper than over-engineering partitioning and throughput. |
The worst reason to select NoSQL is “schemas are difficult.” Flexible schema moves validation and compatibility ownership to the application. Define versioned document contracts, validate inbound writes, migrate or transform older documents deliberately, and make missing or malformed fields safe to handle.
Reliability, Security, and Operations
Reliability
- Design documents around aggregate boundaries and define which invariants must be atomic.
- Use optimistic concurrency with ETags where concurrent updates must not silently overwrite each other.
- Make event-driven consumers idempotent; Cosmos DB change feed processing can be at least once.
- Back up, test restore procedures, and define regional failover behaviour before an incident.
- Monitor throttling, hot partitions, latency, availability, storage growth, and change-feed lag.
Security
- Prefer Microsoft Entra ID and managed identities over account keys for application access.
- Use Azure RBAC with distinct data-plane roles for readers, writers, and operators.
- Use private endpoints and network controls where the workload needs private data access.
- Encrypt data at rest and classify fields before replicating or exposing them in change feeds, events, logs, or search indexes.
- Keep secrets such as migration credentials in Azure Key Vault; do not place them inside documents.
Operations
- Treat the partition key and indexing policy as production architecture, not as implementation details.
- Capture request diagnostics for slow or failed operations, but avoid logging complete sensitive documents.
- Track RU consumption per operation and partition-key range, not just total account consumption.
- Plan retention and time-to-live (TTL) policies for ephemeral data such as sessions, event projections, and inbox/outbox documents.
- Test the application with realistic skew: one large tenant or viral product can expose a hot partition that evenly distributed test data misses.
Advantages and Disadvantages
Advantages
- Flexible document shapes support iterative product development and heterogeneous data.
- Horizontal partitioning can scale high-volume workloads when the key is well designed.
- Purpose-built models can offer excellent key-based latency and throughput.
- Denormalized read models avoid expensive joins for known access patterns.
- Managed Azure offerings can provide global distribution, automatic indexing, change feed, backup, and observability integration.
Disadvantages and trade-offs
- Data duplication, denormalization, and schema evolution move more consistency work into the application.
- Poor partition keys or cross-partition queries can create unpredictable latency and cost.
- Transactional scope and ordering can be narrower than a relational design requires.
- Flexible schema can hide data-quality defects until a consumer encounters an unexpected shape.
- Query and indexing constraints make ad hoc reporting less natural.
- Operational cost is driven by document size, indexing, throughput, and access pattern—not only stored gigabytes.
Practical Selection Checklist
Before selecting a NoSQL database, answer:
- What are the top reads, writes, queries, latency targets, and peak rates?
- Which data belongs to one aggregate and must change atomically?
- What is the partition key, and how will it behave for the largest tenant or hottest entity?
- Which reads are point reads, single-partition queries, or unavoidable fan-out queries?
- Which consistency level and conflict behaviour satisfy the business requirement?
- Which document fields need indexes, and which should be excluded to reduce write cost?
- What data requires strong relational constraints, reporting joins, or cross-entity transactions instead?
- How will documents evolve, validate, migrate, expire, and be recovered?
- What are the expected RU costs under representative load and failure/retry conditions?
- Does a relational, search, analytics, cache, or object store better match the primary access pattern?
Interview-Ready Summary
NoSQL is a family of nonrelational data models—document, key-value, wide-column, graph, and specialized stores—not a single technology and not a replacement for SQL in every system. Its strengths are flexible data representation, horizontal scale, low-latency access, and models tailored to known access patterns. Its trade-offs are fewer universal join/constraint facilities, narrower transaction scopes in many products, and greater responsibility for data shape, duplication, and consistency.
In Azure, Cosmos DB for NoSQL is the main document-database example. Its architecture revolves around the partition key: it determines distribution, query cost, and transactional boundaries. Use it for semi-structured, globally distributed, aggregate-oriented workloads with well-understood access patterns. Prefer a relational database for rich joins, referential integrity, broad multi-entity transactions, and ad hoc reporting. Most production systems use both where each is strongest.