No-SQL Unit 3: Questions & Answers
Unit 3: Redis, Column-Family Stores & Cassandra -> Generated and Prepared By Thiruselvan (ThiruXD)
SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)
Key-Value Stores & Redis Basics
Q1. What is a key-value store?
- A relational database with tables
- A NoSQL database that stores data as key-value pairs
- A graph database
- A document database
Answer: B) A NoSQL database that stores data as key-value pairs -> Explanation: A key-value store stores data as simple key-value pairs. Each key is unique and is used to retrieve the associated value. It is highly scalable and fast for simple lookups.
Q2. Which of the following is a real-world example of a key-value store use case?
- Complex JOIN queries
- Shopping cart storage
- ACID transactions
- Stored procedures
Answer: B) Shopping cart storage -> Explanation: Key-value stores are often used to store shopping cart data for each user. The user ID is the key, and the cart items are the value.
Q3. What does Redis stand for?
- Relational Database Server
- Remote Dictionary Server
- Rapid Data Store
- Real-time Data System
Answer: B) Remote Dictionary Server -> Explanation: Redis stands for Remote Dictionary Server. It is an open-source, in-memory key-value store.
Q4. Redis stores data primarily in:
- Disk
- Memory (RAM)
- Tape
- Cloud
Answer: B) Memory (RAM) -> Explanation: Redis is an in-memory data store, which makes it extremely fast with microsecond latency.
Q5. Which Redis command is used to store a string value?
- GET
- SET
- PUT
- STORE
Answer: B) SET -> Explanation: SET key value stores a string value in Redis. Example: SET user:101 "Ananya".
Q6. Which Redis command retrieves a value?
- SET
- GET
- FETCH
- READ
Answer: B) GET -> Explanation: GET key retrieves the value stored at the key. Example: GET user:101 returns “Ananya”.
Q7. Which Redis command increases a number by 1?
- ADD
- INCR
- PLUS
- COUNT
Answer: B) INCR -> Explanation: INCR key increases the numeric value by 1. DECR key decreases by 1.
Redis Data Structures
Q8. Which Redis data structure is an ordered collection allowing insertion from both ends?
- Set
- List
- Hash
- Sorted Set
Answer: B) List -> Explanation: A Redis List is an ordered collection of string elements that allows insertion and removal from both ends (like a queue or stack).
Q9. Which Redis command adds an element to the left of a list?
- RPUSH
- LPUSH
- LADD
- LINSERT
Answer: B) LPUSH -> Explanation: LPUSH key value adds an element to the left of a list. RPUSH adds to the right.
Q10. Which Redis command retrieves a range of list elements?
- LGET
- LRANGE
- LLIST
- LFETCH
Answer: B) LRANGE -> Explanation: LRANGE key start stop retrieves elements in a range. Example: LRANGE notifications 0 -1 returns all elements.
Q11. Which Redis data structure stores unique elements only?
- List
- Set
- Hash
- String
Answer: B) Set -> Explanation: A Redis Set is an unordered collection of unique string elements (no duplicate values).
Q12. Which Redis command adds a member to a set?
- SADD
- SINSERT
- SPUT
- SAPPEND
Answer: A) SADD -> Explanation: SADD key member adds a member to a set. Duplicate members are not added.
Q13. Which Redis command checks if a member exists in a set?
- SEXISTS
- SISMEMBER
- SCHECK
- SCONTAINS
Answer: B) SISMEMBER -> Explanation: SISMEMBER key member checks if a member exists in a set. Returns 1 if exists, 0 otherwise.
Q14. Which Redis data structure stores field-value pairs under a single key?
- String
- List
- Hash
- Set
Answer: C) Hash -> Explanation: A Redis Hash is a collection of field-value pairs, similar to a dictionary or map. It is used to store structured objects.
Q15. Which Redis command sets a field in a hash?
- HSET
- HPUT
- HADD
- HINSERT
Answer: A) HSET -> Explanation: HSET key field value sets a field in a hash. Example: HSET user:101 name "Ananya".
Q16. Which Redis command retrieves all fields and values from a hash?
- HGET
- HGETALL
- HALL
- HFETCH
Answer: B) HGETALL -> Explanation: HGETALL key returns all fields and values from a hash.
Q17. Which Redis data structure associates a score with each unique element?
- Set
- List
- Sorted Set
- Hash
Answer: C) Sorted Set -> Explanation: A Redis Sorted Set (ZSet) is a collection of unique elements, each with an associated score. Elements are automatically ordered by their score.
Q18. Which Redis command adds a member with a score to a sorted set?
- ZADD
- SADD
- ZINSERT
- ZPUT
Answer: A) ZADD -> Explanation: ZADD key score member adds a member with a score to a sorted set. Example: ZADD leaderboard 100 "Alice".
Q19. Which Redis command retrieves sorted set elements in ascending score order?
- ZREVRANGE
- ZRANGE
- ZGET
- ZLIST
Answer: B) ZRANGE -> Explanation: ZRANGE key start stop retrieves elements in ascending score order. ZREVRANGE retrieves in descending order.
Q20. Which Redis data structure is an append-only log-like structure for events?
- List
- Stream
- Set
- Hash
Answer: B) Stream -> Explanation: A Redis Stream is an append-only log-like structure for events. It is used for event sourcing and real-time analytics.
Redis Key Management
Q21. Which Redis command sets a time-to-live for a key?
- TTL
- EXPIRE
- TIMEOUT
- DELETE
Answer: B) EXPIRE -> Explanation: EXPIRE key seconds sets a time-to-live (TTL) for a key. The key is automatically deleted after the specified time.
Q22. Which Redis command checks the remaining time for a key?
- EXPIRE
- TTL
- TIME
- REMAIN
Answer: B) TTL -> Explanation: TTL key returns the remaining time in seconds. Returns -1 if the key exists but has no expiry, -2 if the key does not exist.
Q23. What does TTL return if the key does not exist?
- 0
- 1
- 2
- NULL
Answer: C) -2 -> Explanation: TTL key returns -2 if the key does not exist. Returns -1 if the key exists but has no expiry.
Q24. Which Redis command deletes a key?
- REMOVE
- DELETE
- DEL
- DROP
Answer: C) DEL -> Explanation: DEL key deletes a key from Redis.
Redis Transactions
Q25. Which Redis command starts a transaction?
- BEGIN
- START
- MULTI
- TRANSACTION
Answer: C) MULTI -> Explanation: MULTI puts Redis into transaction mode. All subsequent commands are queued instead of being executed immediately.
Q26. Which Redis command executes all queued commands in a transaction?
- RUN
- EXEC
- COMMIT
- EXECUTE
Answer: B) EXEC -> Explanation: EXEC executes all the queued commands in the order they were added. All commands are executed as a single atomic unit.
Q27. Which Redis command monitors keys for changes in a transaction?
- WATCH
- MONITOR
- OBSERVE
- TRACK
Answer: A) WATCH -> Explanation: WATCH monitors one or more keys for changes by other clients. If any watched key is modified before EXEC, the transaction is aborted.
Q28. What does EXEC return if a watched key was modified?
- OK
- nil
- Error
- 0
Answer: B) nil -> Explanation: If any watched key is modified before EXEC, the transaction is aborted and EXEC returns nil.
Q29. Which Redis command cancels a transaction?
- CANCEL
- ABORT
- DISCARD
- ROLLBACK
Answer: C) DISCARD -> Explanation: DISCARD cancels a transaction, flushing all queued commands.
Q30. Do Redis transactions rollback on runtime errors?
- Yes, always
- No, they do not rollback
- Only on syntax errors
- Only on network errors
Answer: B) No, they do not rollback -> Explanation: Redis transactions provide atomicity but do not rollback on runtime errors. If EXEC is called, all queued commands are executed, even if one fails.
Cache-Aside Strategy
Q31. In the Cache-Aside strategy, who is responsible for loading data into the cache?
- Database
- Redis
- Application
- Operating System
Answer: C) Application -> Explanation: In Cache-Aside (Lazy Loading), the application is responsible for loading data into the cache. Data is fetched from the cache first; if not found, it is loaded from the database and then stored in the cache.
Q32. What is a “cache miss”?
- Data found in cache
- Data not found in cache
- Cache is full
- Cache is empty
Answer: B) Data not found in cache -> Explanation: A cache miss occurs when the requested data is not found in the cache. The application then fetches it from the database and stores it in the cache.
Q33. In Cache-Aside write flow, what happens after updating the database?
- Cache is updated
- Cache is invalidated/deleted
- Cache is ignored
- Cache is reloaded
Answer: B) Cache is invalidated/deleted -> Explanation: On write, the application updates the database first, then invalidates (or deletes) the cache entry so the next read will load fresh data.
Q34. Which is a benefit of the Cache-Aside strategy?
- Increases database load
- Reduces database load
- Slows application performance
- Requires no cache invalidation
Answer: B) Reduces database load -> Explanation: Cache-Aside reduces database load by serving repeated reads from the cache, improving application performance.
Q35. What is a consideration when using Cache-Aside?
- No cache invalidation needed
- Possibility of stale data
- No TTL needed
- No database needed
Answer: B) Possibility of stale data -> Explanation: Cache-Aside may result in stale data until the cache is invalidated. Choosing an appropriate TTL is important.
Column-Family Stores
Q36. What is a column-family store?
- A relational database
- A NoSQL database storing data in column families
- A graph database
- A document database
Answer: B) A NoSQL database storing data in column families -> Explanation: A column-family store (wide-column store) is a NoSQL database that stores data in column families (groups of columns) rather than fixed tables with rows and columns.
Q37. Which of the following is a column-family store?
- MySQL
- PostgreSQL
- Apache Cassandra
- Oracle
Answer: C) Apache Cassandra -> Explanation: Apache Cassandra, HBase, and Amazon DynamoDB are column-family stores. MySQL, PostgreSQL, and Oracle are relational databases.
Q38. In a column-family store, each row can have:
- The same fixed columns
- A different set of columns
- Only one column
- No columns
Answer: B) A different set of columns -> Explanation: In a column-family store, each row can have a different set of columns (sparse data). Missing values are not stored.
Q39. Which is a key difference between column-family stores and relational databases?
- Column-family stores support joins
- Column-family stores have fixed schema
- Column-family stores are horizontally scalable
- Column-family stores use SQL
Answer: C) Column-family stores are horizontally scalable -> Explanation: Column-family stores are horizontally scalable (designed for clusters), while relational databases are typically vertically scalable (scale-up).
Q40. Which query language is used with Apache Cassandra?
- SQL
- CQL
- NoSQL
- PL/SQL
Answer: B) CQL -> Explanation: CQL (Cassandra Query Language) is the query language used to interact with Apache Cassandra. It is similar to SQL but designed for distributed NoSQL storage.
Apache Cassandra
Q41. What is a node in Cassandra?
- A table
- A single instance of Cassandra running on a machine
- A database
- A query
Answer: B) A single instance of Cassandra running on a machine -> Explanation: A node is a single instance of Cassandra running on a machine (physical or virtual). Each node stores a portion of the data.
Q42. What is a cluster in Cassandra?
- A single node
- A group of nodes working together
- A table
- A keyspace
Answer: B) A group of nodes working together -> Explanation: A cluster is a group of nodes that work together to store and manage data. All nodes in a cluster are peer-to-peer (equal).
Q43. What is a keyspace in Cassandra?
- A table
- A top-level container similar to a database
- A node
- A partition
Answer: B) A top-level container similar to a database -> Explanation: A keyspace is a top-level container (similar to a database in relational systems). It defines replication settings and contains one or more tables.
Q44. What is a partition in Cassandra?
- A subset of data identified by a partition key
- A table
- A node
- A keyspace
Answer: A) A subset of data identified by a partition key -> Explanation: A partition is a subset of the total data, identified by a partition key. Rows with the same partition key are stored together.
Q45. What is the replication factor in Cassandra?
- The number of tables
- The number of copies of each partition
- The number of nodes
- The number of keyspaces
Answer: B) The number of copies of each partition -> Explanation: The replication factor defines how many copies of each partition are stored across different nodes in the cluster. Helps with fault tolerance and high availability.
Q46. If RF = 3, how many copies of each partition are stored?
- 1
- 2
- 3
- 4
Answer: C) 3 -> Explanation: If RF = 3, each partition is stored on 3 different nodes (ideally in different racks/data centers).
Q47. What is the Cassandra data model hierarchy?
- Table → Keyspace → Cluster
- Cluster → Keyspace → Table
- Keyspace → Cluster → Table
- Cluster → Table → Keyspace
Answer: B) Cluster → Keyspace → Table -> Explanation: The Cassandra data model hierarchy is: Cluster (collection of nodes) → Keyspace (like a database) → Table (stores rows of data).
Q48. Which CQL command creates a keyspace?
- CREATE DATABASE
- CREATE KEYSPACE
- CREATE TABLE
- CREATE CLUSTER
Answer: B) CREATE KEYSPACE -> Explanation: CREATE KEYSPACE university WITH replication = {...} creates a keyspace in Cassandra.
Q49. Which CQL command switches to a keyspace?
- USE
- SELECT
- SWITCH
- CONNECT
Answer: A) USE -> Explanation: USE university; switches to the specified keyspace.
Q50. Which CQL command shows the structure of a table?
- SHOW TABLE
- DESCRIBE TABLE
- DISPLAY TABLE
- VIEW TABLE
Answer: B) DESCRIBE TABLE -> Explanation: DESCRIBE TABLE students; shows the structure of the specified table.
SECTION B: THEORY QUESTIONS (20)
Q1. Explain key-value stores with real-world examples.
Answer:
Definition: A key-value store is a type of NoSQL database that stores data as simple key-value pairs. Each key is unique and is used to retrieve the associated value. It is highly scalable, fast, and works well for simple lookups.
How It Works:
| Key | Value |
|---|---|
user:101 | { "name": "Ananya", "age": 25 } |
product:200 | { "name": "Laptop", "price": 55000 } |
session:abc | "token_9382xyz" |
cart:500 | [ "item1", "item2", "item3" ] |
Real-World Examples:
1. E-commerce — Shopping Cart: Key-value stores are often used to store shopping cart data for each user. The user ID can be the key, and the cart items can be the value.
Key: cart:user123
Value: ["item1", "item2", "item3"]2. Caching — User Sessions: Key-value stores are widely used for caching user session data in web applications. The session ID is the key and the session information is the value.
Key: session:abc123
Value: { "user_id": 101, "status": "active" }Advantages:
- Simple model
- High performance
- Scalable
- Flexible
- Simple lookups
Q2. Explain Redis and its data structures.
Answer:
Redis (Remote Dictionary Server) is an open-source, in-memory key-value store. It is widely used for caching, session management, real-time analytics, and message queuing.
Redis Data Structures:
| Data Structure | Description | Use Case |
|---|---|---|
| String | Basic key-value | Caching, counters |
| List | Ordered collection | Queues, logs |
| Set | Unordered unique | Tags, followers |
| Hash | Field-value pairs | User profiles |
| Sorted Set | Unique + score | Leaderboards |
| Stream | Append-only log | Event sourcing |
1. String:
SET user:101 "Ananya"
GET user:101
INCR counter2. List:
LPUSH notifications "msg1"
RPUSH notifications "msg2"
LRANGE notifications 0 -13. Set:
SADD tags "redis"
SMEMBERS tags
SISMEMBER tags "redis"4. Hash:
HSET user:101 name "Ananya"
HGET user:101 name
HGETALL user:1015. Sorted Set:
ZADD leaderboard 100 "Alice"
ZRANGE leaderboard 0 -1 WITHSCORES
ZSCORE leaderboard "Alice"Why Redis?
- In-memory (fast)
- Multiple data structures
- Persistence
- Replication
- Pub/Sub
- Transactions
- TTL
Q3. Explain Redis String and List data structures with commands.
Answer:
1. String: A simple key-value pair where the value is a string (text, number, or binary data).
Redis Commands:
SET user:101 "Ananya"
GET user:101 # Returns "Ananya"
INCR counter # Increase by 1
DECR counter # Decrease by 1Example Use Case: Store user names, configuration settings, counters.
2. List: An ordered collection of string elements that allows insertion and removal from both ends (like a queue or stack).
Structure:
Left ← [A] [B] [C] [D] → RightRedis Commands:
LPUSH notifications "msg1" # Add to left
LPUSH notifications "msg2"
RPUSH notifications "msg3" # Add to right
LRANGE notifications 0 -1 # Get all
# Returns ["msg2", "msg1", "msg3"]
LPOP notifications # Remove from left
RPOP notifications # Remove from rightExample Use Case: Maintain recent activity logs, message queues, notification lists.
Comparison:
| Aspect | String | List |
|---|---|---|
| Type | Single value | Ordered collection |
| Order | N/A | Maintained |
| Duplicates | N/A | Allowed |
| Use Case | Caching, counters | Queues, logs |
Q4. Explain Redis Set and Sorted Set data structures with commands.
Answer:
1. Set: An unordered collection of unique string elements (no duplicate values).
Structure:
A
B CRedis Commands:
SADD tags "redis"
SADD tags "nosql"
SADD tags "database"
SMEMBERS tags # Returns all
# ["redis", "nosql", "database"]
SISMEMBER tags "redis" # Check membership
SINTER tags otherSet # IntersectionExample Use Case: Store unique items such as tags, user IDs, or followers.
2. Sorted Set (ZSet): A collection of unique elements, each with an associated score. Elements are automatically ordered by their score.
Structure:
┌─────────┬───────┐
│ Member │ Score │
├─────────┼───────┤
│ Charlie │ 60 │
│ Bob │ 80 │
│ Alice │ 100 │
└─────────┴───────┘Redis Commands:
ZADD leaderboard 100 "Alice"
ZADD leaderboard 80 "Bob"
ZADD leaderboard 60 "Charlie"
ZRANGE leaderboard 0 -1 WITHSCORES
# Returns ["Charlie", 60, "Bob", 80, "Alice", 100]
ZREVRANGE leaderboard 0 -1 # Descending order
ZSCORE leaderboard "Alice" # Get scoreExample Use Case: Leaderboards, rankings, priority queues, or scheduling.
Comparison:
| Aspect | Set | Sorted Set |
|---|---|---|
| Order | Unordered | Ordered by score |
| Score | No | Yes |
| Use Case | Tags, followers | Leaderboards |
Q5. Explain Redis Hash and Stream data structures with commands.
Answer:
1. Hash: A collection of field-value pairs (like a dictionary or map) suitable for storing objects.
Structure:
Key: user:101
┌──────────┬──────────────────┐
│ Field │ Value │
├──────────┼──────────────────┤
│ name │ Ananya │
│ age │ 25 │
│ email │ ananya@gcu.edu │
│ role │ faculty │
└──────────┴──────────────────┘Redis Commands:
HSET user:101 name "Ananya"
HSET user:101 age 25
HGET user:101 name # Returns "Ananya"
HGETALL user:101 # Get all fields
HINCRBY user:101 age 1 # Increment numeric fieldExample Use Case: Store user profiles, product details, or application settings.
2. Stream: An append-only log-like structure for events.
Redis Commands:
XADD mystream * event "login" user "Rahul"
XREAD COUNT 10 STREAMS mystream 0
XRANGE mystream - +Example Use Case: Event sourcing, activity feeds, real-time analytics.
Comparison:
| Aspect | Hash | Stream |
|---|---|---|
| Type | Field-value pairs | Append-only log |
| Order | N/A | Chronological |
| Use Case | Objects | Events |
Q6. Explain Redis key management commands.
Answer:
1. Create a Key (SET):
SET username "Ananya"
# 127.0.0.1:6379> SET username "Ananya"
# OKIf the key already exists, SET will update its value.
2. Retrieve a Value (GET):
GET username
# 127.0.0.1:6379> GET username
# "Ananya"Returns the value stored at the key. If the key does not exist, returns (nil).
3. Set Expiry (EXPIRE):
EXPIRE username 60
# 127.0.0.1:6379> EXPIRE username 60
# (integer) 1The key will be automatically deleted after the specified time (in this case, 60 seconds).
4. Check TTL (TTL):
TTL username
# 127.0.0.1:6379> TTL username
# (integer) 42Returns the remaining time in seconds.
1: key exists but has no expiry2: key does not exist
5. Common Key Commands:
| Command | Purpose |
|---|---|
SET key value | Create/update key |
GET key | Retrieve value |
DEL key | Delete key |
EXISTS key | Check existence |
EXPIRE key seconds | Set TTL |
TTL key | Check remaining TTL |
PERSIST key | Remove TTL |
KEYS pattern | Find keys by pattern |
RENAME old new | Rename key |
Use Case: Managing cache entries with automatic expiry, session data, and temporary tokens.
Q7. Explain Redis transactions with MULTI, EXEC, and WATCH.
Answer:
Redis Transaction: A Redis transaction groups multiple commands into a single atomic unit. Commands are queued and executed together.
1. MULTI — Start a Transaction:MULTI puts Redis into transaction mode. All subsequent commands are queued instead of being executed immediately.
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET user:1 "Ananya"
QUEUED
127.0.0.1:6379(TX)> INCR login_count
QUEUED
127.0.0.1:6379(TX)> EXPIRE user:1 3600
QUEUED2. EXEC — Execute All Queued Commands:EXEC executes all the queued commands in the order they were added. All commands are executed as a single atomic unit.
127.0.0.1:6379(TX)> EXEC
1) OK
2) (integer) 1
3) (integer) 1Important: If EXEC is called, all queued commands are executed, even if one of them fails (runtime errors do not rollback).
3. WATCH — Optimistic Locking:WATCH monitors one or more keys for changes by other clients. If any watched key is modified before EXEC, the transaction is aborted.
127.0.0.1:6379> WATCH balance:100
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> DECRBY balance:100 50
QUEUED
127.0.0.1:6379(TX)> EXEC
(nil) # if balance:100 was modified by another client4. DISCARD — Cancel Transaction:
127.0.0.1:6379(TX)> DISCARD
OKUse Case: Transfer money between two accounts (ensure both debit and credit happen together).
Key Takeaways:
- MULTI starts the transaction
- EXEC executes all queued commands
- WATCH helps detect changes and prevents lost updates
- Redis transactions provide atomicity, but do not rollback on runtime errors
Q8. Explain the Cache-Aside strategy with read and write flows.
Answer:
Cache-Aside Strategy (Lazy Loading): The application is responsible for loading data into the cache. Data is fetched from the cache first; if not found, it is loaded from the database and then stored in the cache for future requests.
How It Works:
- Application checks the cache for the data.
- If the data is found (cache hit), return it directly from the cache.
- If the data is not found (cache miss), fetch it from the database.
- Store the data in the cache (for a defined TTL) and return it to the client.
Read Flow (Cache Miss):
Client → Application → Redis Cache → (not found) → Database
↓
Store in cache (with TTL)
↓
Return data to clientAfter the first request, the data is cached, so subsequent requests will be faster.
Read Flow (Cache Hit):
Client → Application → Redis Cache → (found) → Return data (fast response)Write Flow (Cache-Aside):
Application → Update database → Invalidate/delete cache entryOn write, the application updates the database first, then invalidates (or deletes) the cache entry so the next read will load fresh data.
Example: E-commerce Product Details: When a user views a product (e.g., product ID 101), the application first checks Redis. If not found, it fetches the product details from the database, stores it in Redis (e.g., for 5 minutes), and returns it to the user.
Product ID: 101
Name: Running Shoes
Price: ₹2,999
Stock: 50
Cached for 5 minutesKey Benefits:
- Reduces database load
- Improves application performance
- Simple to implement
- Works well for read-heavy applications
- Gives control to the application
Things to Consider:
- First request is slower (cache miss)
- Need to handle cache invalidation on data updates
- Possibility of stale data (until invalidated)
- Choose an appropriate TTL
Q9. Explain column-family stores and compare them with relational databases.
Answer:
Column-Family Store (Wide-Column Store): A column-family store is a type of NoSQL database that stores data in column families (groups of columns) rather than fixed tables with rows and columns. It is optimized for large-scale, distributed storage and high write/read throughput.
Key Characteristics:
- Stores data in column families
- Each row can have a different set of columns (sparse data)
- Designed to handle very large datasets across multiple machines
- Optimized for fast reads and writes
- Examples: Apache Cassandra, HBase, Amazon DynamoDB
Example: Column-Family Store
| Row Key (user_id) | name | age | city | |
|---|---|---|---|---|
| u1 | Ananya | a@gcu.edu | 25 | Bangalore |
| u2 | Rahul | r@mail.com | — | Delhi |
| u3 | Meera | — | 30 | Chennai |
Each row can have a different set of columns. Missing values are not stored (sparse storage).
Comparison with Relational Database:
| Feature | Column-Family Store | Relational Database |
|---|---|---|
| Data model | Column families with flexible columns | Fixed tables with rows and columns |
| Schema | Dynamic | Fixed |
| Storage format | By column families | By rows |
| Best for | Large-scale, distributed workloads | Transactional applications |
| Scalability | Horizontally scalable | Vertically scalable |
| Query language | CQL (Cassandra) | SQL |
| Joins | Not supported | Supported |
| Use cases | Time-series, IoT, logs | Banking, ERP, inventory |
When to Use Column-Family Store:
- Very large amounts of data
- Sparse or changing attributes
- High write/read throughput
- Horizontal scalability
When to Use Relational Database:
- Complex queries and joins
- Highly structured and consistent data
- ACID transactions
Q10. Explain Apache Cassandra’s core concepts: node, cluster, keyspace, partition, and replication factor.
Answer:
1. Node: A node is a single instance of Cassandra running on a machine (physical or virtual). Each node stores a portion of the data (data partitions). Nodes are equal — there is no master or slave.
2. Cluster: A cluster is a group of nodes that work together to store and manage data. All nodes in a cluster are peer-to-peer (equal). Provides high availability, fault tolerance, and horizontal scalability.
Cassandra Cluster
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│Node 1│ │Node 2│ │Node 3│ ... │Node N│
└──────┘ └──────┘ └──────┘ └──────┘3. Keyspace: A keyspace is a top-level container (similar to a database in relational systems). It defines replication settings and contains one or more tables. You must create a keyspace before creating tables.
Keyspace: ecom
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Table │ │ Table │ │ Table │
│ users │ │ orders │ │ products │
└──────────┘ └──────────┘ └──────────┘4. Partition: A partition is a subset of the total data, identified by a partition key. Rows with the same partition key are stored together in the same partition. Cassandra distributes (hashes) partitions across nodes in the cluster.
Partition Key (e.g., user_id = 101)
↓
┌─────────────────┐
│ Partition │
│ Row 1 │
│ Row 2 │
│ Row 3 │
└─────────────────┘5. Replication Factor (RF): The replication factor defines how many copies of each partition are stored across different nodes in the cluster. Helps with fault tolerance and high availability.
Example: If RF = 3, each partition is stored on 3 different nodes.
Node 1 (Replica)
↑
┌──────┴──────┐
Node 4 │ RF = 3 │ Node 2 (Replica)
│3 copies of│
│each part. │
└──────┬──────┘
↓
Node 3 (Replica)Data Model Hierarchy:
Cluster → Keyspace → TableQ11. Explain CQL and compare it with SQL.
Answer:
CQL (Cassandra Query Language): CQL is the query language used to interact with Apache Cassandra. It is similar to SQL, but designed for distributed, scalable, NoSQL data storage.
CQL vs SQL:
| CQL (Cassandra) | SQL (Relational DB) |
|---|---|
| Keyspace | Database |
| Table | Table |
| PRIMARY KEY | Primary Key |
| Designed for distributed systems | Designed for single server |
| No JOINs | Supports JOINs |
| Eventual consistency | Strong consistency |
Basic CQL Commands:
a) Create a Keyspace:
CREATE KEYSPACE university
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 3
};b) Use a Keyspace:
USE university;c) Create a Table:
CREATE TABLE students (
student_id int,
name text,
department text,
age int,
PRIMARY KEY (student_id)
);d) Insert Data:
INSERT INTO students (student_id, name, department, age)
VALUES (1, 'Ananya', 'CSE', 20);e) Query Data:
SELECT * FROM students;
SELECT * FROM students WHERE student_id = 1;f) Update Data:
UPDATE students SET age = 21 WHERE student_id = 1;g) Delete Data:
DELETE FROM students WHERE student_id = 1;Verify Creation:
DESCRIBE KEYSPACES;
DESCRIBE TABLES;
DESCRIBE TABLE students;Tip: Always create a keyspace first and then create tables inside it.
Q12. Explain the Redis Hash data structure in detail.
Answer:
Redis Hash: A Redis Hash is a collection of field-value pairs, similar to a dictionary or a map, and is used to store structured objects.
Key Points:
- Stores field-value pairs under a single key
- Fields are unique within a hash
- Values can be strings (text, numbers, or JSON)
- Useful for storing objects like user details, product information
- Allows efficient access and update of individual fields
Structure:
Key: user:101
┌──────────┬──────────────────┐
│ Field │ Value │
├──────────┼──────────────────┤
│ name │ Ananya │
│ age │ 25 │
│ email │ ananya@gcu.edu │
│ role │ faculty │
└──────────┴──────────────────┘A single key (user:101) stores multiple related fields and values.
Example Commands:
# 1. Create a hash and add field-value pairs
127.0.0.1:6379> HSET user:101 name "Ananya" age "25" email "ananya@gcu.edu" role "faculty"
(integer) 4
# 2. Read a single field
127.0.0.1:6379> HGET user:101 name
"Ananya"
# 3. Read all fields and values
127.0.0.1:6379> HGETALL user:101
1) "name"
2) "Ananya"
3) "age"
4) "25"
5) "email"
6) "ananya@gcu.edu"
7) "role"
8) "faculty"
# 4. Update a field
127.0.0.1:6379> HSET user:101 role "professor"
(integer) 0Real-World Use Case: Store user profile information (name, age, email, role) for each user in a web application.
Useful Commands:
HGET key field— get a field valueHGETALL key— get all fieldsHSET key field value— set a fieldHINCRBY key field n— increment numeric field
Redis Hash is ideal for storing and managing structured data efficiently.
Q13. Explain the Redis List data structure in detail.
Answer:
Redis List: A List is an ordered collection of string elements. It allows insertion and removal from both ends (like a queue or stack).
Structure:
Left ← [A] [B] [C] [D] → RightKey Features:
- Maintains the order of elements
- Allows duplicates
- Useful for queues, recent activity logs, message lists
Example:
127.0.0.1:6379> LPUSH tasks "Task1" "Task2" "Task3"
(integer) 3
127.0.0.1:6379> LRANGE tasks 0 -1
1) "Task3"
2) "Task2"
3) "Task1"Common List Commands:
| Command | Purpose |
|---|---|
LPUSH key value | Add element to left |
RPUSH key value | Add element to right |
LRANGE key start stop | Get elements in a range |
LPOP key | Remove from left |
RPOP key | Remove from right |
LLEN key | Get list length |
Use Cases:
- Message Queues: LPUSH + RPOP for FIFO
- Stacks: LPUSH + LPOP for LIFO
- Activity Logs: Keep recent N items
- Notification Lists: Store user notifications
Example — Message Queue:
LPUSH queue "job1"
LPUSH queue "job2"
RPOP queue # Returns "job1" (FIFO)Example — Stack:
LPUSH stack "a"
LPUSH stack "b"
LPOP stack # Returns "b" (LIFO)Q14. Explain the Redis Set data structure in detail.
Answer:
Redis Set: A Set is an unordered collection of unique string elements (no duplicates).
Structure:
A
B CKey Features:
- Unordered collection
- No duplicate elements
- Useful for storing unique items like tags, user IDs, followers
Example:
127.0.0.1:6379> SADD tags "redis" "nosql" "database"
(integer) 3
127.0.0.1:6379> SMEMBERS tags
1) "redis"
2) "nosql"
3) "database"
127.0.0.1:6379> SADD tags "redis"
(integer) 0 # duplicate, not addedCommon Set Commands:
| Command | Purpose |
|---|---|
SADD key member | Add element |
SMEMBERS key | Get all elements |
SISMEMBER key member | Check if element exists |
SREM key member | Remove element |
SCARD key | Get number of elements |
SINTER key1 key2 | Find common members |
SUNION key1 key2 | Union of sets |
SDIFF key1 key2 | Difference of sets |
Use Cases:
- Tags: Store unique tags for a post
- Followers: Store user IDs of followers
- Unique Visitors: Track unique visitors to a page
- Common Interests: SINTER to find common interests
Example — Common Followers:
SADD user:1:followers "u2" "u3" "u4"
SADD user:2:followers "u3" "u4" "u5"
SINTER user:1:followers user:2:followers
# Returns ["u3", "u4"]Q15. Explain the Redis Sorted Set data structure in detail.
Answer:
Redis Sorted Set (ZSet): A Sorted Set is a collection of unique elements, each associated with a score. Elements are automatically ordered by their score (ascending by default).
Structure:
┌─────────┬───────┐
│ Member │ Score │
├─────────┼───────┤
│ Charlie │ 60 │
│ Bob │ 80 │
│ Alice │ 100 │
└─────────┴───────┘Key Features:
- Unique elements with an associated score
- Automatically sorted by score
- Useful for leaderboards, rankings, priority queues, recommendations
Example:
127.0.0.1:6379> ZADD leaderboard 100 "Alice" 80 "Bob" 60 "Charlie"
(integer) 3
127.0.0.1:6379> ZRANGE leaderboard 0 -1 WITHSCORES
1) "Charlie"
2) "60"
3) "Bob"
4) "80"
5) "Alice"
6) "100"Common Sorted Set Commands:
| Command | Purpose |
|---|---|
ZADD key score member | Add element with score |
ZRANGE key start stop | Get elements (low to high) |
ZREVRANGE key start stop | Get elements (high to low) |
ZSCORE key member | Get score of a member |
ZREM key member | Remove element |
ZRANK key member | Get rank (position) |
ZINCRBY key increment member | Increment score |
Use Cases:
- Leaderboards: Rank players by score
- Priority Queues: Process tasks by priority
- Trending: Rank content by views/likes
- Recommendations: Rank items by relevance
Example — Leaderboard:
ZADD game:leaderboard 1500 "Player1"
ZADD game:leaderboard 2000 "Player2"
ZADD game:leaderboard 1200 "Player3"
ZREVRANGE game:leaderboard 0 2 WITHSCORES
# Returns top 3 playersQ16. Explain Redis Streams and their use cases.
Answer:
Redis Stream: A Stream is an append-only log-like structure for events. It is designed for event sourcing, message queues, and real-time analytics.
Key Features:
- Append-only log
- Each entry has a unique ID
- Supports consumer groups
- Persistent storage
- Real-time processing
Commands:
# Add an event
XADD mystream * event "login" user "Rahul"
# Returns ID like "1687459200000-0"
# Read events
XREAD COUNT 10 STREAMS mystream 0
# Read range
XRANGE mystream - +
# Get length
XLEN mystreamStream ID Format:
<milliseconds>-<sequence>
Example: 1687459200000-0Use Cases:
- Event Sourcing: Store all events in order
- Message Queues: Producer-consumer pattern
- Activity Feeds: User activity timeline
- Real-time Analytics: Process events as they arrive
- IoT Data: Sensor readings over time
Example — Activity Feed:
XADD user:101:activity * action "login"
XADD user:101:activity * action "view_product" product "101"
XADD user:101:activity * action "add_to_cart" product "101"
XRANGE user:101:activity - +Comparison with List:
| Aspect | List | Stream |
|---|---|---|
| Order | Insertion order | Chronological |
| ID | No | Yes (auto) |
| Consumer Groups | No | Yes |
| Use Case | Simple queue | Event sourcing |
Q17. Explain Redis key expiry and TTL management.
Answer:
Key Expiry: Redis allows setting a time-to-live (TTL) for keys. After the TTL expires, the key is automatically deleted.
Commands:
1. Set Expiry (EXPIRE):
SET session:abc "token_xyz"
EXPIRE session:abc 3600 # Expires in 1 hour2. Check TTL:
TTL session:abc
# Returns remaining seconds (e.g., 3595)TTL Return Values:
| Return | Meaning |
|---|---|
| Positive number | Remaining seconds |
| -1 | Key exists but has no expiry |
| -2 | Key does not exist |
3. Set Expiry in Milliseconds (PEXPIRE):
PEXPIRE session:abc 36000004. Remove Expiry (PERSIST):
PERSIST session:abc
# Key will no longer expire5. Set with Expiry (SETEX):
SETEX session:abc 3600 "token_xyz"
# Sets key and TTL in one command6. Set with Expiry (SET with EX):
SET session:abc "token_xyz" EX 3600Use Cases:
- Session Management: Auto-expire sessions
- Cache Entries: TTL for cached data
- Rate Limiting: Expire counters
- Temporary Tokens: OTP, password reset
- Distributed Locks: Auto-release locks
Example — Rate Limiting:
INCR api:user:101:requests
EXPIRE api:user:101:requests 60
# User can make limited requests per minuteBest Practices:
- Always set TTL for cache entries
- Use appropriate TTL based on data freshness
- Monitor TTL for critical keys
- Use PERSIST for keys that should not expire
- Use SETEX for atomic set+expire
Q18. Explain the Redis MULTI/EXEC transaction with examples.
Answer:
Redis Transaction: A Redis transaction groups multiple commands into a single atomic unit. Commands are queued and executed together.
MULTI — Start a Transaction:MULTI puts Redis into transaction mode.
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET user:1 "Ananya"
QUEUED
127.0.0.1:6379(TX)> INCR login_count
QUEUED
127.0.0.1:6379(TX)> EXPIRE user:1 3600
QUEUEDEXEC — Execute All Queued Commands:EXEC executes all queued commands as a single atomic unit.
127.0.0.1:6379(TX)> EXEC
1) OK
2) (integer) 1
3) (integer) 1Important: Runtime errors do not rollback. All commands execute.
WATCH — Optimistic Locking:WATCH monitors keys for changes. If a watched key changes before EXEC, the transaction aborts.
127.0.0.1:6379> WATCH balance:100
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> DECRBY balance:100 50
QUEUED
127.0.0.1:6379(TX)> EXEC
(nil) # if balance:100 was modified by another clientDISCARD — Cancel Transaction:
127.0.0.1:6379(TX)> DISCARD
OKUse Case — Money Transfer:
WATCH account:A account:B
MULTI
DECRBY account:A 1000
INCRBY account:B 1000
EXECKey Takeaways:
- MULTI starts the transaction
- EXEC executes all queued commands
- WATCH detects changes (optimistic locking)
- DISCARD cancels the transaction
- Redis transactions provide atomicity, but no rollback on runtime errors
Q19. Explain the Cache-Aside strategy with a real-world example.
Answer:
Cache-Aside Strategy (Lazy Loading): The application manages the cache. Data is fetched from cache first; if not found, loaded from database and stored in cache.
Real-World Example — E-commerce Product Details:
When a user views a product (e.g., product ID 101):
Read Flow:
- Application checks Redis for
product:101 - Cache Hit: If found, return directly from cache (fast)
- Cache Miss: If not found:
- Fetch product from database
- Store in Redis with TTL (e.g., 5 minutes)
- Return to user
Product Details:
Product ID: 101
Name: Running Shoes
Price: ₹2,999
Stock: 50
Cached for 5 minutesWrite Flow:
- Update product in database
- Invalidate/delete cache entry (
DEL product:101) - Next read will load fresh data
Code Example (Pseudocode):
def get_product(product_id):
key = f"product:{product_id}"
# Check cache
cached = redis.get(key)
if cached:
return cached # Cache hit
# Cache miss — fetch from DB
product = db.query("SELECT * FROM products WHERE id = ?", product_id)
# Store in cache with TTL
redis.setex(key, 300, product) # 5 minutes
return product
def update_product(product_id, data):
# Update database
db.update("products", product_id, data)
# Invalidate cache
redis.delete(f"product:{product_id}")Benefits:
- Reduces database load
- Improves application performance
- Simple to implement
- Works well for read-heavy applications
- Gives control to the application
Considerations:
- First request is slower (cache miss)
- Need to handle cache invalidation
- Possibility of stale data
- Choose appropriate TTL
Q20. Explain Apache Cassandra’s data model hierarchy.
Answer:
Cassandra Data Model Hierarchy:
Cluster
↓
Keyspace
↓
Table1. Cluster: A cluster is a collection of nodes that work together. All nodes are peer-to-peer (equal).
Cassandra Cluster
┌──────┐ ┌──────┐ ┌──────┐
│Node 1│ │Node 2│ │Node 3│
└──────┘ └──────┘ └──────┘2. Keyspace: A keyspace is a top-level container (like a database). It defines replication settings.
CREATE KEYSPACE university
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 3
};Keyspace: university
┌──────────┐ ┌──────────┐
│ Table │ │ Table │
│ students │ │ courses │
└──────────┘ └──────────┘3. Table: A table stores rows of data. It is defined with a primary key.
CREATE TABLE students (
student_id int,
name text,
department text,
age int,
PRIMARY KEY (student_id)
);4. Partition: Data is divided into partitions based on the partition key. Rows with the same partition key are stored together.
Partition Key (student_id = 101)
↓
┌─────────────────┐
│ Partition │
│ Row 1 │
│ Row 2 │
└─────────────────┘5. Replication: Each partition is replicated across multiple nodes based on the replication factor.
CQL Commands:
-- Create keyspace
CREATE KEYSPACE university WITH replication = {...};
-- Use keyspace
USE university;
-- Create table
CREATE TABLE students (...);
-- Insert data
INSERT INTO students (...) VALUES (...);
-- Query data
SELECT * FROM students;
-- Describe
DESCRIBE KEYSPACES;
DESCRIBE TABLES;
DESCRIBE TABLE students;Key Points:
- Cluster → Keyspace → Table
- Keyspace defines replication
- Table has a primary key
- Partition key determines data distribution
- Replication factor determines copies
SECTION C: ANALYTICAL QUESTIONS (10)
Q1. Analyze the following Redis commands and predict the output.
SET counter 10
INCR counter
INCR counter
DECR counter
GET counterAnswer:
Output:
"11"Step-by-step:
SET counter 10→ counter = 10INCR counter→ counter = 11INCR counter→ counter = 12DECR counter→ counter = 11GET counter→ returns “11”
Key Points:
- INCR/DECR operate on numeric strings
- Returns integer result
- Atomic operations
Q2. Analyze the following Redis List commands and predict the output.
LPUSH tasks "Task1"
LPUSH tasks "Task2"
RPUSH tasks "Task3"
LRANGE tasks 0 -1
LPOP tasks
LRANGE tasks 0 -1Answer:
Output:
First LRANGE: 1) "Task2" 2) "Task1" 3) "Task3"
LPOP: "Task2"
Second LRANGE: 1) "Task1" 2) "Task3"Step-by-step:
LPUSH tasks "Task1"→ [Task1]LPUSH tasks "Task2"→ [Task2, Task1]RPUSH tasks "Task3"→ [Task2, Task1, Task3]LRANGE tasks 0 -1→ [“Task2”, “Task1”, “Task3”]LPOP tasks→ removes “Task2”, returns itLRANGE tasks 0 -1→ [“Task1”, “Task3”]
Key Points:
- LPUSH adds to left
- RPUSH adds to right
- LPOP removes from left
- LRANGE 0 -1 returns all
Q3. Analyze the following Redis Hash commands and predict the output.
HSET user:101 name "Ananya" age "25"
HGET user:101 name
HINCRBY user:101 age 1
HGETALL user:101Answer:
Output:
HSET: (integer) 2
HGET: "Ananya"
HINCRBY: (integer) 26
HGETALL: 1) "name" 2) "Ananya" 3) "age" 4) "26"Step-by-step:
HSET user:101 name "Ananya" age "25"→ creates hash with 2 fieldsHGET user:101 name→ returns “Ananya”HINCRBY user:101 age 1→ age becomes 26HGETALL user:101→ returns all fields and values
Key Points:
- HSET can set multiple fields
- HGET retrieves one field
- HINCRBY increments numeric field
- HGETALL returns all fields
Q4. Analyze the following Redis transaction and predict the output.
MULTI
SET user:1 "Ananya"
INCR login_count
EXPIRE user:1 3600
EXECAnswer:
Output:
1) OK
2) (integer) 1
3) (integer) 1Step-by-step:
MULTI→ starts transactionSET user:1 "Ananya"→ QUEUEDINCR login_count→ QUEUEDEXPIRE user:1 3600→ QUEUEDEXEC→ executes all:- SET returns OK
- INCR returns 1
- EXPIRE returns 1
Key Points:
- Commands queued after MULTI
- EXEC executes all as atomic unit
- Returns array of results
- No rollback on runtime errors
Q5. Analyze the following Redis WATCH transaction and explain when it fails.
WATCH balance:100
MULTI
DECRBY balance:100 50
EXECAnswer:
Scenario 1 — No modification:
EXEC returns: 1) (integer) 50Transaction succeeds.
Scenario 2 — Another client modifies balance:100:
EXEC returns: (nil)Transaction aborts.
-> Explanation:
- WATCH monitors
balance:100 - If another client modifies it between WATCH and EXEC
- EXEC returns nil (transaction aborted)
- This implements optimistic locking
Use Case:
WATCH account:A account:B
MULTI
DECRBY account:A 1000
INCRBY account:B 1000
EXECPrevents lost updates in money transfer.
Key Points:
- WATCH detects concurrent modifications
- EXEC returns nil if watched key changed
- Prevents lost updates
- Optimistic locking pattern
Q6. Analyze the following Redis Set commands and predict the output.
SADD tags "redis" "nosql" "database"
SADD tags "redis"
SMEMBERS tags
SISMEMBER tags "redis"
SISMEMBER tags "mysql"Answer:
Output:
SADD: (integer) 3
SADD: (integer) 0
SMEMBERS: 1) "redis" 2) "nosql" 3) "database"
SISMEMBER: (integer) 1
SISMEMBER: (integer) 0Step-by-step:
SADD tags "redis" "nosql" "database"→ adds 3 membersSADD tags "redis"→ duplicate, returns 0SMEMBERS tags→ returns all 3 membersSISMEMBER tags "redis"→ 1 (exists)SISMEMBER tags "mysql"→ 0 (does not exist)
Key Points:
- Sets store unique elements
- Duplicates ignored
- SISMEMBER returns 1/0
- SMEMBERS returns all members
Q7. Analyze the following Redis Sorted Set commands and predict the output.
ZADD leaderboard 100 "Alice"
ZADD leaderboard 80 "Bob"
ZADD leaderboard 60 "Charlie"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 1 WITHSCORES
ZSCORE leaderboard "Alice"Answer:
Output:
ZRANGE: 1) "Charlie" 2) "60" 3) "Bob" 4) "80" 5) "Alice" 6) "100"
ZREVRANGE: 1) "Alice" 2) "100" 3) "Bob" 4) "80"
ZSCORE: "100"Step-by-step:
- ZADD adds members with scores
- ZRANGE returns ascending order
- ZREVRANGE returns descending order
- ZSCORE returns Alice’s score
Key Points:
- Sorted sets order by score
- ZRANGE ascending
- ZREVRANGE descending
- WITHSCORES includes scores
Q8. Analyze the Cache-Aside flow and identify potential issues.
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached:
return cached
user = db.query(user_id)
redis.set(key, user)
return userAnswer:
Issues Identified:
- No TTL set:
redis.set(key, user)without expiry — data never expires, may become stale. - No cache invalidation on update: If user data is updated, cache is not invalidated.
- Race condition: Multiple requests may miss cache simultaneously and all query DB.
- No serialization: Object may not be JSON-serializable.
Improved Code:
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached:
return json.loads(cached)
user = db.query(user_id)
redis.setex(key, 300, json.dumps(user)) # 5 min TTL
return user
def update_user(user_id, data):
db.update(user_id, data)
redis.delete(f"user:{user_id}") # Invalidate cacheImprovements:
- Add TTL (
setex) - Invalidate cache on update
- Serialize with JSON
- Consider cache stampede mitigation (lock)
Q9. Analyze the following Cassandra CQL commands and predict the outcome.
CREATE KEYSPACE university
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 3
};
USE university;
CREATE TABLE students (
student_id int,
name text,
department text,
age int,
PRIMARY KEY (student_id)
);
INSERT INTO students (student_id, name, department, age)
VALUES (1, 'Ananya', 'CSE', 20);
SELECT * FROM students;Answer:
Outcome:
student_id | name | department | age
-----------+--------+------------+-----
1 | Ananya | CSE | 20Step-by-step:
- CREATE KEYSPACE → creates
universitywith RF=3 - USE → switches to
university - CREATE TABLE → creates
studentswithstudent_idas primary key - INSERT → adds row
- SELECT → returns all rows
Key Points:
- Keyspace must be created first
- USE switches keyspace
- PRIMARY KEY defines uniqueness
- RF=3 means 3 copies of data
Q10. Design a Redis-based caching solution for a web application’s user profile system.
Answer:
Requirements:
- Cache user profiles
- Fast reads
- Handle updates
- Avoid stale data
Solution:
1. Data Structure — Hash:
HSET user:101 name "Ananya" age "25" email "ananya@gcu.edu"2. Read Flow (Cache-Aside):
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.hgetall(key)
if cached:
return cached # Cache hit
# Cache miss
user = db.query(user_id)
redis.hset(key, mapping=user)
redis.expire(key, 300) # 5 min TTL
return user3. Write Flow:
def update_user(user_id, data):
db.update(user_id, data)
redis.delete(f"user:{user_id}") # Invalidate4. TTL Strategy:
- Short TTL (5 min) for frequently changing data
- Long TTL (1 hour) for stable data
- No TTL for immutable data
5. Handling Cache Stampede:
def get_user_safe(user_id):
key = f"user:{user_id}"
cached = redis.hgetall(key)
if cached:
return cached
# Acquire lock
lock_key = f"lock:user:{user_id}"
if redis.set(lock_key, "1", nx=True, ex=10):
user = db.query(user_id)
redis.hset(key, mapping=user)
redis.expire(key, 300)
redis.delete(lock_key)
return user
else:
time.sleep(0.1)
return get_user_safe(user_id)6. Monitoring:
- Track cache hit ratio
- Monitor Redis memory usage
- Alert on high miss rate
Architecture:
Client → Application → Redis Cache
↓
Database (on miss)Benefits:
- Fast reads (in-memory)
- Reduced DB load
- Scalable
- Simple to implement
Considerations:
- Cache invalidation
- Stale data risk
- Memory usage
- TTL tuning
SUMMARY TABLE
| Section | Count | Topics Covered |
|---|---|---|
| MCQ | 50 | Key-value stores, Redis data structures, commands, transactions, caching, column-family stores, Cassandra, CQL |
| Theory | 20 | Key-value stores, Redis data structures (String, List, Set, Hash, Sorted Set, Stream), key management, transactions, Cache-Aside, column-family stores, Cassandra architecture, CQL, TTL, MULTI/EXEC |
| Analytical | 10 | Command prediction, transaction analysis, cache flow analysis, CQL outcomes, caching solution design |