🍃

NoSQL Interview Questions

MongoDB, Redis, Cassandra, Neo4j, CAP theorem, BASE, distributed systems, caching patterns & CQRS.

← Learn this topic from scratch first

NoSQL Fundamentals — CAP, BASE & Eventual Consistency

Q

What is the CAP Theorem and why does it matter for NoSQL database selection?

beginner

CAP Theorem states that a distributed system can only guarantee two of three properties: Consistency (every read gets the latest write), Availability (every request gets a response), and Partition Tolerance (system works despite network partitions). Since network partitions are unavoidable, the real choice is CP vs AP. CP (MongoDB, HBase, Zookeeper): returns error if consistency can't be guarantee

Q

What is the difference between ACID and BASE?

beginner

ACID (traditional relational): Atomicity (all-or-nothing), Consistency (valid state transitions), Isolation (concurrent transactions don't interfere), Durability (committed data survives crashes). Strong guarantees; single-node or expensive distributed coordination. BASE (NoSQL): Basically Available (system always responds), Soft State (state can change without explicit writes — replicas syncing),

Q

What is polyglot persistence and when do you apply it?

beginner

Polyglot persistence: using multiple different databases within the same application, each chosen for its specific strengths. Example: e-commerce platform: MySQL/PostgreSQL for orders and transactions (ACID required); MongoDB for product catalog (flexible schema for different product types); Redis for sessions and cart (fast key-value); Elasticsearch for product search (full-text); Cassandra for c

Q

You're designing a global e-commerce platform. The product catalog needs flexible schemas (different attributes per product type). Orders must be ACID-compliant. The recommendation engine needs to query relationships between users and products. What databases do you choose?

intermediate

Polyglot persistence solution: 1) Product Catalog → MongoDB: flexible BSON documents handle varying product attributes (laptop: {ram, cpu, storage}; shirt: {size, color, material}). Schema-less accommodates new product categories without migration. 2) Orders → PostgreSQL: ACID transactions are non-negotiable for payments. ORDER and PAYMENT must be atomic. 3) Recommendations → Neo4j: user→purchased

MongoDB — CRUD, Queries & Aggregation Framework

Q

What is the difference between embedded documents and references in MongoDB?

beginner

Embedded (denormalized): Related data nested inside the parent document. Example: user document containing an address subdocument. Pros: single query returns all data; atomic updates on the document; no JOINs. Cons: document grows unboundedly for one-to-many with many items; data duplication. References (normalized): Documents in different collections linked by a reference ID (like a foreign key).

Q

What is the MongoDB Aggregation Framework and how does it compare to SQL?

beginner

The Aggregation Framework is MongoDB's data transformation pipeline. Documents flow through sequential stages, each transforming the result. Key stages: $match (WHERE), $group (GROUP BY + aggregates like $sum, $avg), $sort (ORDER BY), $project (SELECT), $limit/$skip (LIMIT/OFFSET), $lookup ($lookup performs a LEFT JOIN to another collection), $unwind (flatten array fields), $addFields (add compute

Q

How does MongoDB handle transactions?

intermediate

MongoDB 4.0+ supports multi-document ACID transactions within a replica set. MongoDB 4.2+ added distributed transactions across shards. Usage: const session = client.startSession(); session.startTransaction(); try { orders.insertOne({...}, {session}); inventory.updateOne({...}, {session}); await session.commitTransaction(); } catch { await session.abortTransaction(); } Transactions have snapshot i

Q

A MongoDB aggregation pipeline on 50 million documents takes 30 seconds. How do you optimize it?

intermediate

Step 1: Check current execution: db.orders.aggregate([...], {explain: 'executionStats'}). Step 2: Move $match to the FIRST stage — filters data early. Step 3: Ensure an index exists for all $match fields: db.orders.createIndex({status:1, createdAt:-1}). Step 4: Add $project early to reduce document size flowing through pipeline. Step 5: For very large pipelines: allowDiskUse: true (but this signal

MongoDB — Indexing, Replica Sets & Sharding

Redis — Data Structures, Persistence & Pub/Sub

Q

What are the Redis persistence options and when do you use each?

beginnerPro

RDB (Redis Database Backup): periodic snapshots of the entire dataset to a binary file. Config: save 900 1 (save if 1 change in 900s), save 60 10000 (if 10000 changes in 60s). Pros: fast recovery from snapshots; compact file. Cons: data loss between snapshots. AOF (Append Only File): logs every write command. Config: appendonly yes; appendfsync everysec (flush to disk every second). Pros: near-zer

Q

What is a Redis Sorted Set and what are its use cases?

beginnerPro

A Sorted Set is a collection of unique elements, each associated with a floating-point score. Elements are ordered by score. Operations: ZADD (add), ZRANGE (by rank), ZRANGEBYSCORE (by score), ZREVRANGE (reverse order), ZINCRBY (increment score), ZRANK (get rank). Time complexity: O(log N) for most operations. Use cases: 1) Leaderboards: ZADD game:scores 1500 'alice'; ZREVRANGE game:scores 0 9 (to

Q

How do you implement a distributed lock in Redis?

intermediatePro

The correct way: SET lock:resource:123 unique_client_id NX EX 30. NX: set only if not exists (atomicity). EX 30: expire in 30 seconds (safety: auto-release if client dies). To release: only release if you own it (check UUID matches). Use Lua script for atomic check-and-delete: local val = redis.call('get', KEYS[1]); if val == ARGV[1] then redis.call('del', KEYS[1]); return 1 else return 0 end. Pro

Q

An API is being hammered: 10,000 requests/second are hitting the database for the same popular product page. How do you use Redis to fix this?

intermediatePro

Cache-Aside Pattern with Redis: 1) Check Redis first: String key = 'product:' + productId; String cached = redis.get(key); if (cached != null) return deserialize(cached). 2) Cache miss: query database, set in Redis with TTL: redis.set(key, serialize(product), 'EX', 300). Cache Stampede Prevention (when TTL expires, all 10,000 requests miss simultaneously): Use probabilistic early expiration: check

Cassandra — Partitioning, Replication & Consistency

Q

What is the difference between a partition key and a clustering key in Cassandra?

beginnerPro

Partition Key: determines which node(s) the row is stored on. Hashed by consistent hashing algorithm to determine a token, which maps to a node in the ring. All rows with the same partition key are stored together on the same node(s). Partition key is the ONLY field that can be in WHERE without ALLOW FILTERING. Clustering Key: determines the sort order of rows WITHIN a partition. Multiple rows wit

Q

What are Cassandra consistency levels and when do you use each?

beginnerPro

Consistency level determines how many replicas must respond for a read/write to succeed. Common levels: ONE: one replica acknowledges. Fastest; potential for stale reads. For non-critical reads. QUORUM: majority (RF/2 + 1) of replicas acknowledge. Balances consistency and availability. For most production reads/writes. ALL: all replicas acknowledge. Strongest consistency; any node failure = failur

Q

Why does Cassandra not support JOINs and how do you handle relationships?

intermediatePro

Cassandra is distributed — a JOIN would require querying across potentially different nodes for each row, which is O(n²) in the worst case for a large table. This would destroy performance. Solution: query-first schema design and denormalization. For a blog platform: Don't have posts table + authors table + JOINed query. Instead: Create posts_by_author table with all needed author fields duplicate

Q

You're building an IoT platform collecting 1 million sensor readings per second. Sensors report temperature every second. How do you design the Cassandra schema?

intermediatePro

Time-series design challenge: naive partition key = device_id creates hot partitions when one device writes 86,400 rows/day × years. Solution with time bucketing: CREATE TABLE sensor_readings (device_id TEXT, bucket DATE, reading_time TIMESTAMP, temperature DECIMAL, humidity DECIMAL, PRIMARY KEY ((device_id, bucket), reading_time)) WITH CLUSTERING ORDER BY (reading_time DESC) AND default_time_to_l

Neo4j — Graph Database & Cypher Queries

Q

When would you choose a graph database over a relational database?

intermediatePro

Choose a graph database when: 1) Relationships are the primary concern — not just data, but HOW data connects. 2) Variable depth traversals are needed — 'friends of friends of friends' at any depth. 3) Relationship properties matter — when/how the connection was made. 4) Performance degrades with JOINs — relational JOINs are O(n×m) per hop; graph traversal is O(1) per hop. Use cases: social networ

Q

What is Cypher and how does it query graphs?

beginnerPro

Cypher is Neo4j's declarative graph query language. It uses ASCII-art notation to express graph patterns. Key syntax: (node) represents a node. -[:RELATIONSHIP]-> represents a directed relationship. (a)-[:KNOWS]->(b) matches node a connected to node b via KNOWS relationship. Filtering: WHERE a.age > 25. Variable hop: -[:KNOWS*2..4]-> matches 2 to 4 hops. Pattern: MATCH (alice:Person {name:'Alice'}

Q

Your fraud detection team wants to identify accounts that are part of a ring of money transfers (circular transactions). How do you implement this in Neo4j?

intermediatePro

MATCH cycle = (account:Account)-[:TRANSFERRED_TO*3..7]->(account) WHERE all(rel IN relationships(cycle) WHERE rel.amount > 5000 AND rel.timestamp > datetime()-duration('P7D')) WITH account, length(cycle) AS cycleLength, [r IN relationships(cycle) | r.amount] AS amounts RETURN DISTINCT account.accountNumber, cycleLength, reduce(total=0, a IN amounts | total + a) AS totalMoneyInCycle ORDER BY totalM

Distributed Systems — Replication, Partitioning & Consistency

Q

What is the difference between leader-follower and leaderless replication?

beginnerPro

Leader-follower: one designated leader accepts all writes; followers replicate from leader. Cons: single bottleneck for writes; leader failure requires election; lag between leader and followers means followers may be stale. Examples: MongoDB, MySQL, Redis Sentinel. Leaderless (Dynamo-style): any replica can accept writes simultaneously. Client writes to W replicas; reads from R replicas. With W +

Q

What is consistent hashing and why is it important for distributed databases?

beginnerPro

Consistent hashing maps both keys and nodes to positions on a virtual ring (0 to 2^32). A key belongs to the first node clockwise from its hash position. Advantage over naive modulo hashing (key % numNodes): When you add/remove nodes with modulo hashing: almost all keys remapped (massive data movement). With consistent hashing: only the keys in the affected range need to move (typically 1/N of dat

Q

A write to your distributed database succeeded but the user can't see their update. What could be happening and how do you fix it?

intermediatePro

Root causes: 1) Read-after-write inconsistency: write went to primary/leader; read went to a replica that hasn't replicated yet. Solution: read-your-own-writes guarantee. In MongoDB: use causally consistent sessions. In Cassandra: use QUORUM for both reads and writes. 2) Load balancer routing: user's GET request routed to different server that has stale cache. Solution: sticky sessions for that us

System Design — Caching Patterns & CQRS

Top 30 Scenario-Based Questions

Q

Design a session management system for a web application handling 100,000 concurrent users.

advancedPro

Redis is the perfect fit: 1) Session data: HSET session:{sessionId} userId 42 role ADMIN lastActivity 1234567890. 2) TTL: EXPIRE session:{sessionId} 1800 (30 min idle timeout). 3) Reset on activity: EXPIRE session:{sessionId} 1800 on every request. 4) Lookup: HGETALL session:{sessionId} on each request. 5) Invalidation on logout: DEL session:{sessionId}. 6) Scale: Redis Cluster with 3 masters (300

Q

Your MongoDB queries are slow on a 100-million document collection. How do you diagnose and fix?

intermediatePro

1) Identify slow queries: db.setProfilingLevel(1, 100) (log queries > 100ms). 2) Check profile: db.system.profile.find().sort({millis:-1}).limit(5). 3) For each slow query: db.collection.find({...}).explain('executionStats'). 4) Look for: COLLSCAN (no index!) and totalDocsExamined >> nReturned. 5) Add missing indexes: if query is {status:'active', createdAt:{$gt:date}}: CREATE INDEX {status:1, cre

Q

Design a real-time leaderboard for a mobile game with 10 million players.

advancedPro

Redis Sorted Set is purpose-built: 1) Update score: ZADD game:global:scores {newScore} '{playerId}'. For increment: ZINCRBY game:global:scores {amount} '{playerId}'. 2) Get top 100: ZREVRANGE game:global:scores 0 99 WITHSCORES. 3) Get player rank: ZREVRANK game:global:scores '{playerId}' (0-based; add 1). 4) Get player score: ZSCORE game:global:scores '{playerId}'. 5) Weekly leaderboard: use separ

Q

An IoT platform receives 1 million sensor events per second. How do you design the storage?

intermediatePro

Cassandra is ideal for high-write time-series: 1) Table design (time bucketing): CREATE TABLE readings (device_id TEXT, bucket DATE, reading_ts TIMESTAMP, temperature DECIMAL, PRIMARY KEY ((device_id, bucket), reading_ts)) WITH CLUSTERING ORDER BY (reading_ts DESC). 2) Bucket by day/hour to control partition size. 3) TTL: default_time_to_live = 7776000 (90 days). 4) Compaction: TWCS for time-serie

Q

How would you implement a 'Recently Viewed Products' feature for e-commerce?

advancedPro

Redis List per user: 1) On product view: LPUSH views:user:{userId} {productId}. 2) Keep only last 20: LTRIM views:user:{userId} 0 19 (after every push). 3) Retrieve: LRANGE views:user:{userId} 0 19. 4) TTL: EXPIRE views:user:{userId} 604800 (7 days). 5) Display: fetch product details for each ID using pipeline: pipeline.get('product:'+id) for all IDs in one round trip. 6) Deduplication: if you wan

Q

Design a social media feed system (like Twitter) handling 100M users.

advancedPro

Fanout on Write for celebrities vs Pull for normal users: 1) Write path: user posts tweet → stored in tweets:MongoDB. 2) Fanout on Write (< 1K followers): for each follower: LPUSH timeline:{followerId} tweetId. LTRIM to last 1000 tweets. 3) Celebrities (> 1K followers): don't fanout on write (too expensive). On read: merge celebrity tweets with personal timeline. 4) Read path: LRANGE timeline:user

Q

A MongoDB collection has a compound index on {status:1, createdAt:-1} but queries with only createdAt are slow. Why?

intermediatePro

Leftmost prefix rule: a compound index on {status:1, createdAt:-1} supports: WHERE status = X (uses leftmost prefix). WHERE status = X AND createdAt = Y (uses both). But NOT: WHERE createdAt = Y (skips status — index not used). Fix: 1) Create a separate index on createdAt: db.orders.createIndex({createdAt:-1}). 2) Or if queries span both patterns, create two separate indexes. 3) Rule: equality con

Q

How do you handle cache invalidation when multiple services can update the same data?

intermediatePro

Cache invalidation is the hardest problem. Strategies: 1) Event-driven invalidation: when any service updates product, publish ProductUpdated event to message bus (Kafka). All services subscribed delete their cached product version. 2) TTL-based staleness: accept up to 5-minute stale data. Set TTL=300. Auto-expired even if event missed. 3) Cache versioning: store version with cached object. On upd

Q

Design a fraud detection system using Neo4j to identify suspicious account networks.

advancedPro

Graph traversal for fraud: 1) Data model: (:Account)-[:TRANSFERS_TO {amount, date}]->(:Account), (:Account)-[:OWNED_BY]->(:Person), (:Person)-[:SHARES_DEVICE {deviceId}]->(:Person). 2) Ring detection (circular transfers): MATCH cycle=(a:Account)-[:TRANSFERS_TO*3..7]->(a) WHERE all(r IN rels(cycle) WHERE r.amount > 1000) RETURN nodes(cycle). 3) Shared device fraud: MATCH (p1:Person)-[:SHARES_DEVICE

Q

Your Redis is running out of memory. How do you handle this without data loss?

intermediatePro

Investigation: 1) INFO memory: check used_memory, peak_memory, mem_fragmentation_ratio. 2) redis-cli --bigkeys: find largest keys consuming most memory. 3) MEMORY USAGE key: check specific key sizes. 4) Immediate actions: 5) Set maxmemory if not set: CONFIG SET maxmemory 4gb. 6) Set eviction policy: CONFIG SET maxmemory-policy allkeys-lru (for cache). 7) OBJECT ENCODING key: check if using memory-

Q

Implement a distributed rate limiter that works across multiple API servers.

intermediatePro

Redis-based token bucket: 1) Per request: INCR ratelimit:{userId}:{minuteTimestamp} result = INCR if result == 1: EXPIRE ratelimit:{userId}:{minuteTimestamp} 60. 2) Check: if result > maxRequests: return 429. 3) Lua script (atomic): local result = redis.call('INCR', KEYS[1]) if result == 1 then redis.call('EXPIRE', KEYS[1], 60) end if result > ARGV[1] then return 0 else return 1 end. 4) Spring: Re

Q

Design a MongoDB schema for a product catalog with highly variable attributes.

advancedPro

JSONB/document model shines here: 1) Single collection with embedded attributes: {_id, name, category, price, attributes:{ram:16, cpu:'i7'} for laptops; {size:'XL', color:'red'} for shirts}. 2) Indexes on common attributes: createIndex({'attributes.ram':1}) for laptop-specific queries. 3) Wildcard index: createIndex({'attributes.[* ]':1}) for flexible attribute queries (MongoDB 4.2+). 4) Schema va

Q

How would you migrate from a monolithic PostgreSQL to a microservices NoSQL architecture?

advancedPro

Strangler Fig pattern: 1) Phase 1 — Identify services: identify bounded contexts (Orders, Users, Products, Notifications). 2) Phase 2 — Add caching first: add Redis in front of PostgreSQL for hot data. Zero risk. 3) Phase 3 — Extract read models: create MongoDB read models fed by CDC (Change Data Capture) from PostgreSQL via Debezium. API serves reads from MongoDB. 4) Phase 4 — Extract write path:

Q

Design a Cassandra schema for storing user activity events with the ability to query: 1) All events for a user in the last 7 days, 2) All events of a specific type today.

advancedPro

Two tables for two query patterns: Table 1 for query 1: CREATE TABLE user_events (user_id UUID, bucket DATE, event_time TIMESTAMP, event_type TEXT, payload TEXT, PRIMARY KEY ((user_id, bucket), event_time)) WITH CLUSTERING ORDER BY (event_time DESC) AND default_time_to_live = 604800; Query: WHERE user_id=? AND bucket IN [today, yesterday, ...7days...]. Table 2 for query 2: CREATE TABLE events_by_t

Q

How do you implement optimistic concurrency control in MongoDB?

intermediatePro

Version-based optimistic concurrency: 1) Add version field to document: {_id, name, balance:1000, version:5}. 2) Read: fetch document including version. 3) Modify: calculate new balance. 4) Write with version check: result = db.accounts.updateOne({_id: id, version: 5}, {$set: {balance: 900}, $inc: {version: 1}}). 5) Check result.modifiedCount: if 0 → conflict (another process updated it) → re-read

Q

How do you implement CQRS with MongoDB as write store and Redis as read store?

intermediatePro

CQRS implementation: Write side: 1) OrderService writes to MongoDB (normalized, ACID-like). 2) After write: publish OrderCreated event via Spring ApplicationEventPublisher or Kafka. Read side: 3) EventHandler listens for OrderCreated. 4) Updates Redis structures: ZADD orders:user:{userId} {timestamp} {orderId} (sorted by time). 5) Updates MongoDB order_summaries collection (denormalized for displa

Q

A Cassandra query is returning stale data even after a successful write. What could be wrong?

intermediatePro

Consistency level mismatch: 1) Write with ONE (1 replica) but read with ONE from a different replica that hasn't synced. Fix: use LOCAL_QUORUM for both reads and writes (W+R > RF ensures overlap). 2) Replication lag: recently added node not fully synced. Fix: nodetool repair on the new node. 3) Hinted handoff not delivered: node was down during write, hint stored but not yet delivered. Fix: check

Q

How would you design a URL shortener using Redis and MongoDB?

advancedPro

System design: 1) ID generation: use Redis INCR for atomic sequential IDs: INCR url:counter → 123456 → encode to base62 = 'w7Xk'. 2) Storage: MongoDB for durability: {_id: 'w7Xk', originalUrl:'https://example.com/...', userId, clicks:0, createdAt}. 3) Redis cache: SET url:w7Xk 'https://example.com/...' EX 86400 (24h cache). 4) Redirect: GET url:{code} → hit Redis, return redirect. Miss → query Mon

Q

Design an e-commerce cart using Redis that persists across sessions.

advancedPro

Redis Hash per cart: 1) Cart structure: HSET cart:{userId} {productId} {quantity}. Example: HSET cart:42 prod:100 2 prod:200 1. 2) Add item: HINCRBY cart:{userId} {productId} 1. 3) Remove item: HDEL cart:{userId} {productId}. 4) Get cart: HGETALL cart:{userId} → {prod:100:2, prod:200:1}. 5) Total items: HLEN cart:{userId}. 6) TTL: EXPIRE cart:{userId} 604800 (7 days). 7) Persistence: AOF ensures c

Q

How would you implement pub/sub with Redis for real-time notifications?

advancedPro

Redis Pub/Sub for real-time: 1) Publisher (when order status changes): PUBLISH order-updates '{orderId:1001, status:SHIPPED, userId:42}'. 2) Subscriber (notification service): SUBSCRIBE order-updates (receives all messages on channel). 3) Pattern subscribe: PSUBSCRIBE order-* (all order channels). 4) Spring Boot: @Bean RedisMessageListenerContainer + MessageListenerAdapter. @Component with handleM

Q

How do you prevent a cache avalanche in production?

advancedPro

Cache avalanche: many keys expire simultaneously → DB flooded. Prevention: 1) Randomize TTL: don't set uniform TTL. Instead of TTL=3600, use TTL = 3000 + random(0,600). Keys expire spread over 10 minutes instead of all at once. 2) Eternal cache + async refresh: never expire critical keys. Background job proactively refreshes before data is too stale. 3) Circuit breaker on DB: if DB load spikes (av

Q

How would you design a document approval workflow using MongoDB and Redis?

advancedPro

Workflow design: 1) MongoDB schema: Document {_id, title, content, status: DRAFT|PENDING|APPROVED|REJECTED, submitterId, approverId, comments:[...], history:[{status, changedBy, changedAt}], version:1}. 2) State machine: only valid transitions allowed. MongoDB document update with state validation. 3) Redis for pending approvals: ZADD pending:approvals {timestamp} {documentId}. Approver views: ZRA

Q

How do you handle multi-document transactions in MongoDB for financial operations?

intermediatePro

MongoDB multi-document transactions: 1) Use case: debit Account A and credit Account B atomically. 2) Code: ClientSession session = client.startSession(); session.startTransaction(TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).readConcern(ReadConcern.SNAPSHOT).build()); try { accounts.updateOne(session, {_id:fromId, balance:{$gte:amount}}, {$inc:{balance:-amount}}); accounts.upda

Q

Design a recommendation system using Neo4j for an e-commerce platform.

advancedPro

Collaborative filtering with Neo4j: Data model: (:User)-[:PURCHASED {date, amount}]->(:Product), (:User)-[:VIEWED {count}]->(:Product), (:Product)-[:IN_CATEGORY]->(:Category). 1) Item-based: 'Customers who bought X also bought': MATCH (product:Product {id:'laptop123'})<-[:PURCHASED]-(user:User)-[:PURCHASED]->(other:Product) WHERE other <> product RETURN other.name, COUNT(user) AS cobuyers ORDER BY

Q

How do you monitor a MongoDB production cluster and what metrics matter?

advancedPro

Critical metrics and tooling: 1) MongoDB Atlas: built-in monitoring with alerts. 2) Self-hosted: MongoDB Exporter → Prometheus → Grafana. 3) Key metrics: Operation latency (op_counters.command, query, insert): alert if P99 > 100ms. Replication lag: alert if > 10s. Connection count: alert if > 80% of maxIncomingConnections. Oplog window: must be large enough for maintenance. Cache hit ratio: wiredT

Q

How do you implement geo-spatial queries in MongoDB for a location-based service?

intermediatePro

MongoDB 2dsphere index for geo-queries: 1) Schema: {_id, name, location: {type:'Point', coordinates:[longitude, latitude]}}. 2) Index: db.stores.createIndex({location:'2dsphere'}). 3) Near query (sorted by distance): db.stores.find({location: {$near: {$geometry:{type:'Point', coordinates:[-73.9857,40.7484]}, $maxDistance:5000}}}). 4) Within polygon: db.areas.find({location:{$geoWithin:{$geometry:{

Q

How do you handle a hot partition problem in Cassandra?

intermediatePro

Hot partition = one partition gets disproportionate traffic: 1) Detection: nodetool tpstats shows one node overwhelmed; cfhistograms for latency distribution by partition. 2) Causes: bad partition key (low cardinality like status:ACTIVE), or one entity has massive data (one celebrity's posts). 3) Solutions: a) Add bucket to partition key: {(user_id, bucket_date), event_time} instead of just {user_

Q

Design a messaging system using MongoDB and Redis (similar to Slack).

advancedPro

Architecture: 1) MongoDB: channels: {_id, name, members:[userId...], type}. messages: {_id, channelId, userId, text, attachments, reactions, createdAt}. 2) Index: messages.createIndex({channelId:1, createdAt:-1}). 3) Redis for real-time: SUBSCRIBE channel:{channelId} — WebSocket subscribers listen. On new message: PUBLISH channel:{channelId} {messageId, userId, text, ts}. 4) Recent messages cache:

Q

Explain how you would handle eventual consistency issues in a multi-region deployment.

intermediatePro

Multi-region eventual consistency strategies: 1) MongoDB Multi-region Atlas: use write concern majority on primary region. Cross-region replication is asynchronous. Accept that secondary region may be slightly stale. Set maxStalenessSeconds on replica read preference. 2) Cassandra multi-DC: EACH_QUORUM for operations requiring global consistency (expensive). LOCAL_QUORUM for operations fine with D

Q

How would you implement auto-complete search using Redis?

advancedPro

Redis Sorted Set for prefix search: 1) Indexing: for each product 'MacBook Pro', add all prefixes: ZADD autocomplete 0 'mac', 0 'macb', 0 'macbo', ... 0 'macbook pro', 0 'macbook pro#100' (terminator + productId). 2) Search: find prefix range: ZRANGEBYLEX autocomplete '[macb' '[macb\xff' LIMIT 0 5. 3) Returns: 'macbook', 'macbook pro#100' — extract full terms. 4) Better approach: Store prefix → li

Top 15 System Design Questions

Q

Design a URL shortener (bit.ly) that handles 100K redirects/second.

advancedPro

ID generation: Redis INCR + base62 encoding (or distributed ID like Snowflake) Write path: store {shortCode → longUrl} in MongoDB + Redis cache Read path: GET url:{code} from Redis (< 1ms); miss → MongoDB → cache Redis cluster: 3 masters × 100K ops/s each = 300K ops/s capacity MongoDB: partitioned by shortCode for durability Analytics: INCR clicks:{code} in Redis; batch flush to MongoDB hourly Cus

Q

Design Twitter/X timeline system for 200M daily active users.

intermediatePro

Write path: tweet stored in MongoDB; publish TweetCreated event to Kafka Fanout: for users with < 1K followers: push tweetId to each follower's Redis List Celebrities (> 1K followers): no fanout; pull on read and merge with personal timeline Timeline storage: Redis List per user (LPUSH tweetId; LTRIM 0 999 — keep 1000) Read path: LRANGE timeline:userId 0 49 → fetch tweet details from Redis/MongoDB

Q

Design a ride-sharing platform (Uber) with real-time driver location tracking.

advancedPro

Driver location: Redis Geospatial GEOADD drivers:{city} lon lat driverId every 4s Nearby drivers: GEORADIUS drivers:{city} lon lat 5 km with driver status Trip data: MongoDB for trip documents (flexible schema for different trip types) Real-time matching: Redis Pub/Sub for driver offer notifications Surge pricing: Redis Sorted Set tracking requests per geohash cell Driver availability: Redis Hash

Q

Design Netflix's content recommendation system.

intermediatePro

Viewing history: Cassandra — high-write time-series; partition by userId User-item matrix: stored as sparse vectors in Redis or Cassandra Collaborative filtering: offline job (Spark) computes similarity; results in Redis Cache recommendations: SETEX user:{id}:recs 3600 [videoIds] in Redis A/B testing: different recommendation algorithms; Redis for variant assignment Graph-based: Neo4j for person-g

Q

Design an e-commerce platform (Amazon) order management system.

advancedPro

Product catalog: MongoDB (variable attributes per product type) Inventory: Redis for real-time count + PostgreSQL for ACID stock management Orders: PostgreSQL for ACID transactions (payment + order + inventory must be atomic) Order history: MongoDB or Cassandra for fast retrieval by userId Cart: Redis Hash per user with TTL; persist to DB on checkout Sessions: Redis with HttpSession (Spring Sessio

Q

Design a real-time chat application (WhatsApp/Slack).

advancedPro

Messages: Cassandra partitioned by (channelId, bucket); clustered by timestamp Online presence: Redis SETEX presence:{userId} 30; client refreshes every 20s Message delivery: Redis Pub/Sub for real-time; WebSocket connection per user Unread count: Redis HINCRBY unread:{userId} {channelId} 1 Recent messages cache: Redis List (LPUSH; LTRIM 0 49) for fast initial load Search: Elasticsearch on message

Q

Design a distributed cache system (like Memcached/Redis Cluster).

advancedPro

Consistent hashing: distribute keys across cache nodes; minimize reshuffling on node change Virtual nodes: 150 vnodes per physical node for even distribution Replication: each key replicated to N nodes for fault tolerance Eviction: LRU per shard; configurable maxmemory policy Failure handling: if node fails, client routes to next node on ring (degraded mode) Connection pooling: each client maintai

Q

Design a fraud detection system for a payment platform.

advancedPro

Real-time checks: Redis for recent transaction count per card (sliding window with ZSet) Graph analysis: Neo4j for account relationship networks and ring detection ML scoring: pre-computed risk scores in Redis; updated by ML pipeline Rules engine: Redis for fast rule lookup (configurable thresholds per merchant) Event streaming: Kafka for all transactions → fraud detection consumers Historical pat

Q

Design a logging and analytics system for 1TB of logs per day.

advancedPro

Ingestion: Kafka as durable buffer; handles burst traffic Storage: Cassandra for time-series raw logs (high write, TTL for retention) Aggregation: Spark Streaming on Kafka → pre-aggregate to Cassandra summary tables Search: Elasticsearch for full-text log search (last 7 days) Redis: real-time counters (errors per minute), alerting thresholds MongoDB: stored queries, dashboard configs, alert rules

Q

Design a notification system for a large-scale application (100M users).

advancedPro

Notification storage: Cassandra partition by (userId, type); most recent first Unread count: Redis HINCRBY notifications:{userId} total 1 Push notifications: SNS/FCM for mobile push; separate queues per channel type Real-time delivery: Redis Pub/Sub or WebSocket for in-app notifications Preference management: MongoDB for user notification preferences (complex nested) Rate limiting: Redis per-user

Q

Design a food delivery platform (DoorDash/Uber Eats).

advancedPro

Restaurant catalog: MongoDB for flexible menu structure (different item types) Real-time location: Redis Geospatial for restaurant and driver locations Orders: PostgreSQL for ACID payment and order state machine Order status: Redis Pub/Sub for real-time status updates to customer Cart: Redis Hash with TTL (30 min) Delivery assignment: Redis sorted set of available drivers by distance ETAs: Redis f

Q

Design a ticket booking system (Ticketmaster) that prevents double booking.

advancedPro

Seat inventory: Redis for real-time seat availability (SET seatId if NX = reserve) Seat lock: SET seat:{eventId}:{seatId} {userId} NX EX 300 (5-min hold) Seat visualization: Redis Bitmap for large venue (1 bit per seat) Booking: PostgreSQL for final ACID booking transaction Queue: Redis ZADD waitlist:{eventId} timestamp userId for sold-out events Event catalog: MongoDB for event details (venue, ar

Q

Design a social media analytics dashboard showing real-time metrics.

advancedPro

Event ingestion: Kafka for all social events (likes, shares, comments, views) Real-time counters: Redis INCR/INCRBY for live counts per post Time-series: Redis Sorted Set for events per minute; ZRANGEBYSCORE for window Aggregations: Kafka Streams or Flink for real-time aggregate computation Dashboard storage: Redis for current metrics; Cassandra for historical time-series Trending: sliding window

Q

Design a healthcare patient records system with HIPAA compliance.

advancedPro

Patient records: MongoDB with encrypted fields (AES-256); field-level encryption Access control: Redis for session tokens; MongoDB RBAC (role-based field access) Audit trail: Cassandra for immutable audit log (who accessed what when) Search: Elasticsearch on anonymized/tokenized fields only; no PHI in index Backup: encrypted MongoDB dumps to S3; key management via AWS KMS HIPAA: data at rest encry

Q

Design a gaming platform backend (leaderboard, matchmaking, inventory).

advancedPro

Leaderboard: Redis Sorted Set; ZADD game:season:1 score playerId; real-time top N Session: Redis Hash per session; game state for active matches Inventory: MongoDB for player item collections (flexible schema per item type) Matchmaking: Redis Sorted Set by skill rating; match nearby skill players Match history: Cassandra for immutable match records (high write, time-series) Player profile: MongoDB