BTCE | 5th Sem
No-SQL SubjectUnit 3

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?

  1. A relational database with tables
  2. A NoSQL database that stores data as key-value pairs
  3. A graph database
  4. 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?

  1. Complex JOIN queries
  2. Shopping cart storage
  3. ACID transactions
  4. 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?

  1. Relational Database Server
  2. Remote Dictionary Server
  3. Rapid Data Store
  4. 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:

  1. Disk
  2. Memory (RAM)
  3. Tape
  4. 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?

  1. GET
  2. SET
  3. PUT
  4. 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?

  1. SET
  2. GET
  3. FETCH
  4. 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?

  1. ADD
  2. INCR
  3. PLUS
  4. 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?

  1. Set
  2. List
  3. Hash
  4. 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?

  1. RPUSH
  2. LPUSH
  3. LADD
  4. 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?

  1. LGET
  2. LRANGE
  3. LLIST
  4. 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?

  1. List
  2. Set
  3. Hash
  4. 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?

  1. SADD
  2. SINSERT
  3. SPUT
  4. 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?

  1. SEXISTS
  2. SISMEMBER
  3. SCHECK
  4. 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?

  1. String
  2. List
  3. Hash
  4. 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?

  1. HSET
  2. HPUT
  3. HADD
  4. 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?

  1. HGET
  2. HGETALL
  3. HALL
  4. 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?

  1. Set
  2. List
  3. Sorted Set
  4. 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?

  1. ZADD
  2. SADD
  3. ZINSERT
  4. 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?

  1. ZREVRANGE
  2. ZRANGE
  3. ZGET
  4. 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?

  1. List
  2. Stream
  3. Set
  4. 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?

  1. TTL
  2. EXPIRE
  3. TIMEOUT
  4. 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?

  1. EXPIRE
  2. TTL
  3. TIME
  4. 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?

  1. 0
  2. 1
  3. 2
  4. 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?

  1. REMOVE
  2. DELETE
  3. DEL
  4. DROP

Answer: C) DEL -> Explanation: DEL key deletes a key from Redis.


Redis Transactions

Q25. Which Redis command starts a transaction?

  1. BEGIN
  2. START
  3. MULTI
  4. 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?

  1. RUN
  2. EXEC
  3. COMMIT
  4. 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?

  1. WATCH
  2. MONITOR
  3. OBSERVE
  4. 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?

  1. OK
  2. nil
  3. Error
  4. 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?

  1. CANCEL
  2. ABORT
  3. DISCARD
  4. ROLLBACK

Answer: C) DISCARD -> Explanation: DISCARD cancels a transaction, flushing all queued commands.


Q30. Do Redis transactions rollback on runtime errors?

  1. Yes, always
  2. No, they do not rollback
  3. Only on syntax errors
  4. 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?

  1. Database
  2. Redis
  3. Application
  4. 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”?

  1. Data found in cache
  2. Data not found in cache
  3. Cache is full
  4. 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?

  1. Cache is updated
  2. Cache is invalidated/deleted
  3. Cache is ignored
  4. 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?

  1. Increases database load
  2. Reduces database load
  3. Slows application performance
  4. 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?

  1. No cache invalidation needed
  2. Possibility of stale data
  3. No TTL needed
  4. 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?

  1. A relational database
  2. A NoSQL database storing data in column families
  3. A graph database
  4. 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?

  1. MySQL
  2. PostgreSQL
  3. Apache Cassandra
  4. 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:

  1. The same fixed columns
  2. A different set of columns
  3. Only one column
  4. 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?

  1. Column-family stores support joins
  2. Column-family stores have fixed schema
  3. Column-family stores are horizontally scalable
  4. 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?

  1. SQL
  2. CQL
  3. NoSQL
  4. 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?

  1. A table
  2. A single instance of Cassandra running on a machine
  3. A database
  4. 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?

  1. A single node
  2. A group of nodes working together
  3. A table
  4. 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?

  1. A table
  2. A top-level container similar to a database
  3. A node
  4. 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?

  1. A subset of data identified by a partition key
  2. A table
  3. A node
  4. 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?

  1. The number of tables
  2. The number of copies of each partition
  3. The number of nodes
  4. 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. 1
  2. 2
  3. 3
  4. 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?

  1. Table → Keyspace → Cluster
  2. Cluster → Keyspace → Table
  3. Keyspace → Cluster → Table
  4. 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?

  1. CREATE DATABASE
  2. CREATE KEYSPACE
  3. CREATE TABLE
  4. 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?

  1. USE
  2. SELECT
  3. SWITCH
  4. CONNECT

Answer: A) USE -> Explanation: USE university; switches to the specified keyspace.


Q50. Which CQL command shows the structure of a table?

  1. SHOW TABLE
  2. DESCRIBE TABLE
  3. DISPLAY TABLE
  4. 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:

KeyValue
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:

  1. Simple model
  2. High performance
  3. Scalable
  4. Flexible
  5. 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 StructureDescriptionUse Case
StringBasic key-valueCaching, counters
ListOrdered collectionQueues, logs
SetUnordered uniqueTags, followers
HashField-value pairsUser profiles
Sorted SetUnique + scoreLeaderboards
StreamAppend-only logEvent sourcing

1. String:

SET user:101 "Ananya"
GET user:101
INCR counter

2. List:

LPUSH notifications "msg1"
RPUSH notifications "msg2"
LRANGE notifications 0 -1

3. Set:

SADD tags "redis"
SMEMBERS tags
SISMEMBER tags "redis"

4. Hash:

HSET user:101 name "Ananya"
HGET user:101 name
HGETALL user:101

5. 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 1

Example 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] → Right

Redis 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 right

Example Use Case: Maintain recent activity logs, message queues, notification lists.

Comparison:

AspectStringList
TypeSingle valueOrdered collection
OrderN/AMaintained
DuplicatesN/AAllowed
Use CaseCaching, countersQueues, 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   C

Redis 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            # Intersection

Example 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 score

Example Use Case: Leaderboards, rankings, priority queues, or scheduling.

Comparison:

AspectSetSorted Set
OrderUnorderedOrdered by score
ScoreNoYes
Use CaseTags, followersLeaderboards

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 field

Example 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:

AspectHashStream
TypeField-value pairsAppend-only log
OrderN/AChronological
Use CaseObjectsEvents

Q6. Explain Redis key management commands.

Answer:

1. Create a Key (SET):

SET username "Ananya"
# 127.0.0.1:6379> SET username "Ananya"
# OK

If 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) 1

The 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) 42

Returns the remaining time in seconds.

  • 1: key exists but has no expiry
  • 2: key does not exist

5. Common Key Commands:

CommandPurpose
SET key valueCreate/update key
GET keyRetrieve value
DEL keyDelete key
EXISTS keyCheck existence
EXPIRE key secondsSet TTL
TTL keyCheck remaining TTL
PERSIST keyRemove TTL
KEYS patternFind keys by pattern
RENAME old newRename 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
QUEUED

2. 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) 1

Important: 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 client

4. DISCARD — Cancel Transaction:

127.0.0.1:6379(TX)> DISCARD
OK

Use 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:

  1. Application checks the cache for the data.
  2. If the data is found (cache hit), return it directly from the cache.
  3. If the data is not found (cache miss), fetch it from the database.
  4. 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 client

After 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 entry

On 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 minutes

Key Benefits:

  1. Reduces database load
  2. Improves application performance
  3. Simple to implement
  4. Works well for read-heavy applications
  5. Gives control to the application

Things to Consider:

  1. First request is slower (cache miss)
  2. Need to handle cache invalidation on data updates
  3. Possibility of stale data (until invalidated)
  4. 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)nameemailagecity
u1Ananyaa@gcu.edu25Bangalore
u2Rahulr@mail.com—Delhi
u3Meera—30Chennai

Each row can have a different set of columns. Missing values are not stored (sparse storage).

Comparison with Relational Database:

FeatureColumn-Family StoreRelational Database
Data modelColumn families with flexible columnsFixed tables with rows and columns
SchemaDynamicFixed
Storage formatBy column familiesBy rows
Best forLarge-scale, distributed workloadsTransactional applications
ScalabilityHorizontally scalableVertically scalable
Query languageCQL (Cassandra)SQL
JoinsNot supportedSupported
Use casesTime-series, IoT, logsBanking, 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 → Table

Q11. 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)
KeyspaceDatabase
TableTable
PRIMARY KEYPrimary Key
Designed for distributed systemsDesigned for single server
No JOINsSupports JOINs
Eventual consistencyStrong 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) 0

Real-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 value
  • HGETALL key — get all fields
  • HSET key field value — set a field
  • HINCRBY 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] → Right

Key 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:

CommandPurpose
LPUSH key valueAdd element to left
RPUSH key valueAdd element to right
LRANGE key start stopGet elements in a range
LPOP keyRemove from left
RPOP keyRemove from right
LLEN keyGet list length

Use Cases:

  1. Message Queues: LPUSH + RPOP for FIFO
  2. Stacks: LPUSH + LPOP for LIFO
  3. Activity Logs: Keep recent N items
  4. 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   C

Key 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 added

Common Set Commands:

CommandPurpose
SADD key memberAdd element
SMEMBERS keyGet all elements
SISMEMBER key memberCheck if element exists
SREM key memberRemove element
SCARD keyGet number of elements
SINTER key1 key2Find common members
SUNION key1 key2Union of sets
SDIFF key1 key2Difference of sets

Use Cases:

  1. Tags: Store unique tags for a post
  2. Followers: Store user IDs of followers
  3. Unique Visitors: Track unique visitors to a page
  4. 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:

CommandPurpose
ZADD key score memberAdd element with score
ZRANGE key start stopGet elements (low to high)
ZREVRANGE key start stopGet elements (high to low)
ZSCORE key memberGet score of a member
ZREM key memberRemove element
ZRANK key memberGet rank (position)
ZINCRBY key increment memberIncrement score

Use Cases:

  1. Leaderboards: Rank players by score
  2. Priority Queues: Process tasks by priority
  3. Trending: Rank content by views/likes
  4. 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 players

Q16. 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 mystream

Stream ID Format:

<milliseconds>-<sequence>
Example: 1687459200000-0

Use Cases:

  1. Event Sourcing: Store all events in order
  2. Message Queues: Producer-consumer pattern
  3. Activity Feeds: User activity timeline
  4. Real-time Analytics: Process events as they arrive
  5. 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:

AspectListStream
OrderInsertion orderChronological
IDNoYes (auto)
Consumer GroupsNoYes
Use CaseSimple queueEvent 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 hour

2. Check TTL:

TTL session:abc
# Returns remaining seconds (e.g., 3595)

TTL Return Values:

ReturnMeaning
Positive numberRemaining seconds
-1Key exists but has no expiry
-2Key does not exist

3. Set Expiry in Milliseconds (PEXPIRE):

PEXPIRE session:abc 3600000

4. Remove Expiry (PERSIST):

PERSIST session:abc
# Key will no longer expire

5. Set with Expiry (SETEX):

SETEX session:abc 3600 "token_xyz"
# Sets key and TTL in one command

6. Set with Expiry (SET with EX):

SET session:abc "token_xyz" EX 3600

Use Cases:

  1. Session Management: Auto-expire sessions
  2. Cache Entries: TTL for cached data
  3. Rate Limiting: Expire counters
  4. Temporary Tokens: OTP, password reset
  5. 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 minute

Best Practices:

  1. Always set TTL for cache entries
  2. Use appropriate TTL based on data freshness
  3. Monitor TTL for critical keys
  4. Use PERSIST for keys that should not expire
  5. 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
QUEUED

EXEC — 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) 1

Important: 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 client

DISCARD — Cancel Transaction:

127.0.0.1:6379(TX)> DISCARD
OK

Use Case — Money Transfer:

WATCH account:A account:B
MULTI
DECRBY account:A 1000
INCRBY account:B 1000
EXEC

Key Takeaways:

  1. MULTI starts the transaction
  2. EXEC executes all queued commands
  3. WATCH detects changes (optimistic locking)
  4. DISCARD cancels the transaction
  5. 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:

  1. Application checks Redis for product:101
  2. Cache Hit: If found, return directly from cache (fast)
  3. 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 minutes

Write Flow:

  1. Update product in database
  2. Invalidate/delete cache entry (DEL product:101)
  3. 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:

  1. Reduces database load
  2. Improves application performance
  3. Simple to implement
  4. Works well for read-heavy applications
  5. Gives control to the application

Considerations:

  1. First request is slower (cache miss)
  2. Need to handle cache invalidation
  3. Possibility of stale data
  4. Choose appropriate TTL

Q20. Explain Apache Cassandra’s data model hierarchy.

Answer:

Cassandra Data Model Hierarchy:

Cluster
    ↓
Keyspace
    ↓
Table

1. 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:

  1. Cluster → Keyspace → Table
  2. Keyspace defines replication
  3. Table has a primary key
  4. Partition key determines data distribution
  5. 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 counter

Answer:

Output:

"11"

Step-by-step:

  1. SET counter 10 → counter = 10
  2. INCR counter → counter = 11
  3. INCR counter → counter = 12
  4. DECR counter → counter = 11
  5. GET 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 -1

Answer:

Output:

First LRANGE: 1) "Task2"  2) "Task1"  3) "Task3"
LPOP: "Task2"
Second LRANGE: 1) "Task1"  2) "Task3"

Step-by-step:

  1. LPUSH tasks "Task1" → [Task1]
  2. LPUSH tasks "Task2" → [Task2, Task1]
  3. RPUSH tasks "Task3" → [Task2, Task1, Task3]
  4. LRANGE tasks 0 -1 → [“Task2”, “Task1”, “Task3”]
  5. LPOP tasks → removes “Task2”, returns it
  6. LRANGE 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:101

Answer:

Output:

HSET: (integer) 2
HGET: "Ananya"
HINCRBY: (integer) 26
HGETALL: 1) "name"  2) "Ananya"  3) "age"  4) "26"

Step-by-step:

  1. HSET user:101 name "Ananya" age "25" → creates hash with 2 fields
  2. HGET user:101 name → returns “Ananya”
  3. HINCRBY user:101 age 1 → age becomes 26
  4. HGETALL 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
EXEC

Answer:

Output:

1) OK
2) (integer) 1
3) (integer) 1

Step-by-step:

  1. MULTI → starts transaction
  2. SET user:1 "Ananya" → QUEUED
  3. INCR login_count → QUEUED
  4. EXPIRE user:1 3600 → QUEUED
  5. EXEC → 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
EXEC

Answer:

Scenario 1 — No modification:

EXEC returns: 1) (integer) 50

Transaction 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
EXEC

Prevents 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) 0

Step-by-step:

  1. SADD tags "redis" "nosql" "database" → adds 3 members
  2. SADD tags "redis" → duplicate, returns 0
  3. SMEMBERS tags → returns all 3 members
  4. SISMEMBER tags "redis" → 1 (exists)
  5. 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:

  1. ZADD adds members with scores
  2. ZRANGE returns ascending order
  3. ZREVRANGE returns descending order
  4. 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 user

Answer:

Issues Identified:

  1. No TTL set: redis.set(key, user) without expiry — data never expires, may become stale.
  2. No cache invalidation on update: If user data is updated, cache is not invalidated.
  3. Race condition: Multiple requests may miss cache simultaneously and all query DB.
  4. 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 cache

Improvements:

  1. Add TTL (setex)
  2. Invalidate cache on update
  3. Serialize with JSON
  4. 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        | 20

Step-by-step:

  1. CREATE KEYSPACE → creates university with RF=3
  2. USE → switches to university
  3. CREATE TABLE → creates students with student_id as primary key
  4. INSERT → adds row
  5. 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 user

3. Write Flow:

def update_user(user_id, data):
    db.update(user_id, data)
    redis.delete(f"user:{user_id}")   # Invalidate

4. 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:

  1. Fast reads (in-memory)
  2. Reduced DB load
  3. Scalable
  4. Simple to implement

Considerations:

  1. Cache invalidation
  2. Stale data risk
  3. Memory usage
  4. TTL tuning

SUMMARY TABLE

SectionCountTopics Covered
MCQ50Key-value stores, Redis data structures, commands, transactions, caching, column-family stores, Cassandra, CQL
Theory20Key-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
Analytical10Command prediction, transaction analysis, cache flow analysis, CQL outcomes, caching solution design

On this page