📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

In a system design, how do you choose the data store? Compare relational, document, key-value, search and blob storage, explain how you start from the access patterns rather than the technology, and tell me when you would use more than one.

Choosing data stores from access patterns: relational (Azure SQL), document (Cosmos DB), key-value (Redis), search (Azure AI Search) and blob storage, with consistency, query and cost trade-offs and when polyglot persistence is worth it.

Intermediate Theory Intermediate azure-sql blob-storage cosmos-db data-modelling redis system-design

🎯 Key points

  • List access patterns first: key lookups, range queries, joins, full-text, large binaries
  • Relational (Azure SQL): joins, ACID transactions, ad-hoc queries, strong constraints
  • Document (Cosmos DB): partition-key lookups at scale, flexible schema, RU-based cost
  • Key-value (Redis): sub-millisecond reads for caches, sessions, counters; not the system of record
  • Search (Azure AI Search / Elasticsearch): full-text, relevance and facets, fed from the source of truth
  • Blob Storage: files and large objects; store only the URL/metadata in the database
  • Relational is a common default, but start elsewhere when the dominant pattern demands it (global key-value at scale, event streams, CQRS read models)
  • Every extra store needs one source of truth, a sync mechanism (outbox, change feed), lag monitoring, backups and on-call knowledge

⏱ 30-second answer

I choose data stores from the access patterns, not the brand. I list how the data is written and read: key lookups, range queries, joins, full-text search, large files. Then:

  • Relational (Azure SQL) for joins, transactions and constraints — my default.
  • Document (Cosmos DB) for huge volumes accessed by a known partition key.
  • Key-value (Redis) for caches, sessions and counters.
  • Search (Azure AI Search) for full-text and facets; Blob Storage for files.

I start with one relational database and add a store only when a pattern can't be served well. The trade-off is fit versus complexity: each extra store means data sync, eventual consistency, backups and another thing to run.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by writing down the access patterns, because a data store is good or bad only relative to how you use it. For each entity: how is it written, how often, and how is it read — by id, by a range like 'orders for this customer in the last month', by joining to other data, by free text, or as a big file. I also note the consistency each pattern needs and the volume.

Then I map patterns to stores. Relational is my default: Azure SQL gives me joins, ACID transactions, foreign keys and unique constraints, and it comfortably handles most business systems up to terabytes. A document store like Cosmos DB fits when I have very high volume and every query knows the partition key — device telemetry by device id, a shopping cart by user id — and I can accept paying per request unit and designing around that key. Redis is for data I can lose or rebuild: caches, sessions, rate-limit counters. Search engines handle full-text and faceting, fed from the source of truth by events or an indexer. Large files always go to Blob Storage with only the metadata and URL in the database.

The mistake I see is picking a NoSQL database because it 'scales', and then needing joins and transactions it doesn't do well — or the opposite, storing PDFs in SQL Server. Polyglot persistence is fine, but every extra store needs a sync mechanism, a consistency story, backups and monitoring. I add one only when a real access pattern demands it."


Store by access pattern

Access pattern Best fit Azure AWS note
Joins, transactions, constraints, ad-hoc reporting Relational Azure SQL, PostgreSQL Flexible Server RDS, Aurora
Point reads/writes by key at very high scale Document / wide-column Cosmos DB DynamoDB
Sub-millisecond reads, counters, TTL data Key-value Azure Cache for Redis / Azure Managed Redis ElastiCache
Full-text, relevance, facets Search Azure AI Search OpenSearch
Files, images, backups Object storage Blob Storage S3
Append-only events, high-throughput streams Log / stream Event Hubs Kinesis, MSK

Trade-offs

Store Strength Weakness
Azure SQL Rich queries, ACID, mature tooling (EF Core, Query Store) Scale-up limits; sharding is manual
Cosmos DB Horizontal scale, global distribution, tunable consistency Partition key is hard to change; cross-partition queries are expensive
Redis Very fast Memory-bound; not durable enough for a system of record
Azure AI Search Relevance and facets Eventually consistent with the source
Blob Storage Cheap per GB, tiers No querying of content

Example: e-commerce

Orders, payments, stock  --> Azure SQL (transactions, constraints)
Product catalogue search --> Azure AI Search (indexed from SQL)
Cart and sessions        --> Redis (TTL, rebuildable)
Product images           --> Blob Storage + Front Door

Production example

A team storing 40 million audit events a month in Cosmos DB with a partition key of /eventType found most queries were 'all events for this customer', which fanned out across partitions and cost about 10× the expected RUs. Re-keying on /customerId brought typical queries to single-partition reads under 10 ms and cut the bill by around 70%.

🔍 What the interviewer is checking

Checks whether the candidate chooses data stores from access patterns and understands the cost of polyglot persistence.

Green flags

  • Lists access patterns before naming technologies
  • Defaults to relational and justifies any addition
  • Knows partition-key design and cross-partition costs
  • Names a source of truth and a sync mechanism

Red flags

  • "NoSQL because it scales" with no access pattern
  • Files stored in the database
  • Dual writes with no consistency plan

📚 Learn in depth

1. Why access patterns come first

Every store makes some operations cheap by making others expensive. B-tree indexes in SQL Server make range scans and joins cheap but writes pay for every index. Cosmos DB makes point reads within a partition cheap (around 1 RU for a 1 KB item) but cross-partition queries fan out. Redis keeps everything in memory, so reads are fast but capacity is bounded by RAM. You can only judge a store once you know which operations you need to be cheap.

2. A selection flow

Need transactions across rows/entities or joins?
   yes -> relational (Azure SQL)
   no  -> every query knows a single key?
            yes -> very high scale or global? -> Cosmos DB
                   otherwise                 -> relational is still fine
            no  -> free text / relevance? -> search index fed from source
Large binary? -> Blob Storage, metadata in DB
Rebuildable, latency-critical? -> Redis in front of the source

3. The source of truth

In a polyglot design, exactly one store owns each piece of data. Others are projections: the search index, the cache, a reporting replica. Projections are updated by change feed (Cosmos DB), Change Data Capture or the transactional outbox (SQL Server), or scheduled indexers. If a projection is lost, you rebuild it from the source.

4. Consistency between stores

Writing to two stores in one request without a distributed transaction risks one write succeeding and the other failing. The outbox pattern fixes this: write the business row and an outbox row in one SQL transaction, then a background worker publishes the change. Readers of projections must tolerate lag (usually seconds).

5. Cost models differ

Azure SQL is priced by vCores or DTUs plus storage; Cosmos DB by provisioned or serverless request units plus storage; Redis by memory tier; Blob Storage by GB and operations with hot, cool, cold and archive tiers. A store that's cheap at one access pattern can be expensive at another.

Try it yourself

  1. For a system you know, list every entity's write and read patterns in a table.
  2. Run the Cosmos DB emulator, store 100k items, and compare RU charges for a point read versus a cross-partition query.
  3. Compare WHERE Description LIKE '%term%' in SQL Server with a full-text CONTAINS query on 1M rows.
  4. Implement an outbox table with EF Core and a BackgroundService that publishes rows to a queue.
  5. Measure Redis GET latency with redis-benchmark versus a SQL point query from the same App Service.

💻 Code

Polyglot persistence done safely: the order is written to Azure SQL with an outbox row in one transaction; a worker later projects it to the search index.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;
using System.Text.Json;

public sealed record Order(Guid Id, Guid CustomerId, decimal Total, DateTimeOffset CreatedAt);
public sealed record OutboxMessage(Guid Id, string Type, string Payload, DateTimeOffset CreatedAt)
{
    public DateTimeOffset? ProcessedAt { get; set; }
}

public sealed class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<OutboxMessage> Outbox => Set<OutboxMessage>();
}

public sealed class PlaceOrder(ShopDb db, TimeProvider clock)
{
    public async Task<Guid> HandleAsync(Guid customerId, decimal total, CancellationToken ct)
    {
        var order = new Order(Guid.CreateVersion7(), customerId, total, clock.GetUtcNow());
        db.Orders.Add(order);

        // Same transaction as the order: either both are saved or neither.
        db.Outbox.Add(new OutboxMessage(Guid.CreateVersion7(), "OrderPlaced",
            JsonSerializer.Serialize(order), clock.GetUtcNow()));

        await db.SaveChangesAsync(ct);
        return order.Id;
    }
}
// A BackgroundService reads unprocessed outbox rows and updates the search index
// (Azure AI Search, Redis, etc.). If it crashes, rows are retried, so the
// projection update must be idempotent (upsert by order id).

⚠ Common mistakes

  • Mistake: Choosing NoSQL because it "scales". Why it is wrong: Most business systems fit comfortably in one relational database, and you lose joins, constraints and easy transactions. Instead: Start relational and move a specific pattern only when the numbers demand it.
  • Mistake: Picking a Cosmos DB partition key without the queries. Why it is wrong: Queries that don't include the key fan out across partitions and cost many more RUs; the key can't be changed without migrating data. Instead: Choose the key from the most frequent query and check for hot partitions.
  • Mistake: Storing files in the database. Why it is wrong: It bloats backups, log and buffer pool, and costs far more per GB. Instead: Store files in Blob Storage and keep the URL and metadata in the database.
  • Mistake: Treating Redis as the system of record. Why it is wrong: Eviction and failover can lose data. Instead: Use Redis as a cache or for rebuildable data; keep the truth in a durable store.
  • Mistake: Dual writes to two stores in one request. Why it is wrong: One write can succeed and the other fail, leaving them inconsistent forever. Instead: Use the outbox pattern or change feed to update projections, and monitor projection lag.
  • Mistake: Adding a search engine for simple equality filters. Why it is wrong: It adds sync lag and operational cost for something an index or SQL Server full-text search can do. Instead: Use a search engine where it earns its keep — relevance ranking, typo tolerance, faceted navigation, or complex free-text queries over tens of millions of documents.
  • Mistake: Forcing everything into one relational schema. Why it is wrong: High-volume telemetry, event streams or a globally distributed key-value workload can overwhelm a single relational database or make it very expensive. Instead: Let the dominant access pattern choose: Event Hubs for streams, Cosmos DB for global key-based access, a separate read model when CQRS queries differ greatly from writes.

🏛 Senior insight: trade-offs

Seniors default to boring: one relational database plus Blob Storage covers a surprising share of systems, and every additional store is a long-term operational commitment — backups, upgrades, security patching, access control, monitoring and someone on call who understands it. Before adding one, they do the analysis explicitly: which access pattern fails today (with numbers), what the new store costs per month, the sync mechanism and its lag, and how the team will operate it for years.

When they do add a store, they name the source of truth, the projection mechanism (outbox, change feed, CDC) and the acceptable lag, and they monitor that lag (for example, an Azure Monitor alert when the outbox's oldest unprocessed row is older than 60 seconds). In CQRS or event-sourced designs, separate read stores are the point of the architecture, so the same discipline applies from day one. They also know relational databases have grown: SQL Server's JSON support, full-text search and columnstore indexes cover many cases that used to justify a second store.

Option When it fits Cost When not to
Single Azure SQL Relational data, < a few TB, thousands of rps Scale-up ceiling Global multi-region writes
Azure SQL + Redis Read-heavy, latency-sensitive Cache invalidation Data must always be fresh
Cosmos DB first Key-based access at very high scale, global RU cost, partition design Many joins, ad-hoc reporting
+ Search index Relevance, facets, typo tolerance Sync lag, extra service Simple equality filters
CQRS read store Read shapes very different from writes Projection code, lag Simple CRUD

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Cosmos DB consistency levels or eventual consistency Why: Checks understanding of CAP and PACELC trade-offs in real databases
    How to answer

    CAP says that when a network partition splits a replicated data store, it must choose between consistency (every read sees the latest write, strictly linearisability) and availability (every working node still answers). Because partitions happen in any real network, "pick two of three" is misleading: the real choice is C or A during a partition. PACELC adds the part that matters every day: Else, when there's no partition, you trade latency against consistency, because keeping replicas in sync means waiting for them. Real systems sit at different points: SQL Server Always On with synchronous commit favours consistency at the cost of latency; Cosmos DB lets you choose one of five consistency levels; Redis replication is asynchronous and can lose acknowledged writes on failover. The trade-off is per use case, not per company.

  2. When: Candidate considers a document store for flexible schema Why: Checks whether they know SQL Server's JSON support as an alternative
    How to answer

    SQL Server reads JSON with OPENJSON (shred an array into typed rows using a WITH schema), JSON_VALUE (one scalar) and JSON_QUERY (an object or array), updates it with JSON_MODIFY, and produces it with FOR JSON PATH. To filter on a property quickly, add a computed column on JSON_VALUE and index it. The native json type stores a validated binary form and adds JSON_OBJECTAGG/JSON_ARRAYAGG and the JSON_CONTAINS/JSON index features; it's GA in Azure SQL and shipped with SQL Server 2025, though some features (like the JSON index) are documented as preview.

    The design rule: JSON for sparse, variable or pass-through data; real columns for anything you filter, join, constrain or report on.

  3. When: Candidate adds a search engine Why: Checks when SQL Server full-text search is enough and when it isn't
    How to answer

    LIKE '%term%' has a leading wildcard, so it can't seek and scans every row, and it matches substrings, not words ("cat" matches "education"). Full-text search builds an inverted index of word tokens using a language's word breaker and stemmer, populated asynchronously in the background. CONTAINS does precise word, phrase, prefix ("kett*"), proximity (NEAR) and inflectional searches; FREETEXT matches meaning, using stemming and the thesaurus. CONTAINSTABLE/FREETEXTTABLE add a RANK for ordering. It's available in Azure SQL Database with no extra service.

    Its limits are basic relevance, no typo tolerance, facets or vector search. When search is a product feature, I'd use Azure AI Search (or Elasticsearch), kept in sync from SQL.

🛠 Real-world problems: how you handle them

Cosmos DB partition key chosen without the queries
Situation
[Company]'s [audit / activity] service stored [N million] events a month in Cosmos DB in Australia East, partitioned by event type.
Signals
Monthly RU cost [several times] the estimate; 429 (request rate too large) responses during business hours; customer activity screens taking [x] seconds.
Investigation
Used Cosmos DB diagnostics and the query metrics in Azure Monitor to see high RU charge per query and cross-partition fan-out; the partition key metrics showed one hot partition for the busiest event type. Listed the actual queries from Application Insights dependency telemetry: [most] filtered by customer.
Resolution
Immediately raised autoscale max RU/s to stop throttling. Then created a new container partitioned by customer id and migrated data with the change feed, switching reads once caught up.
Prevention
Added an access-pattern table to the design template and a review step for any new partition key; Azure Monitor alerts on normalised RU consumption per partition and on 429 rates.

How to tell it (STAR)

**S:** At [company], our [activity] service on Cosmos DB was costing [several times] its estimate and throttling during business hours. **T:** I was asked to find out why and fix it without downtime. **A:** I pulled the real queries from Application Insights and found [most] filtered by customer, but the container was partitioned by event type, so every query fanned out. I raised autoscale to stop the 429s, then migrated to a container keyed on customer id using the change feed and switched reads over once it caught up. **R:** Typical queries dropped from [x] ms to under [y] ms, throttling stopped, and the monthly bill fell by about [percentage]%.

More in Core System Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me