Advertisement

Information Technology

Redis Interview Questions & Answers

In-memory data structure store used heavily as system level cache engines.

40topics 280questions last updated
Advertisement

Caching Patterns

All 7 questions
  1. In the cache aside pattern, your application first checks Redis for the data it needs, and if the data is not found, it fetches it from the primary database, stores a copy in Redis…

  2. In the write through pattern, every time data is written to the database, it is also immediately written to Redis at the same time, keeping the cache always up to date, unlike cach…

  3. In the write behind pattern, data is written to Redis immediately and then asynchronously written to the database a short time later, which improves write speed since the applicati…

  4. In read through caching, the caching layer itself is responsible for fetching data from the database when it is missing from the cache, meaning the application always just asks the…

  5. You can use a distributed lock so only one request regenerates the expired value while others wait briefly or serve a slightly stale version, or use a technique like probabilistic…

Cluster Sharding & Hash Slots

All 7 questions
  1. Sharding splits your data across multiple Redis nodes instead of storing everything on a single server, letting you scale beyond the memory and processing limits of one machine by…

  2. Redis Cluster divides its entire key space into sixteen thousand three hundred and eighty four hash slots, and every key is assigned to exactly one of these slots based on a hash c…

  3. Redis Cluster applies a hashing algorithm called CRC16 to the key, then takes the result modulo sixteen thousand three hundred eighty four to determine the specific hash slot, ensu…

  4. A hash tag is a portion of a key wrapped in curly braces, and when present, Redis Cluster only uses that specific portion for the hash slot calculation rather than the entire key,…

  5. You add the new node to the cluster, then use a resharding tool or command to move a portion of hash slots, and the keys within them, from existing nodes to the new node, carefully…

  1. Redis Cluster is a way to run Redis across multiple connected nodes that automatically share data between them, solving the problem of a single Redis instance being limited by one…

  2. A master node owns a specific range of hash slots and handles both read and write operations for the keys in those slots, while a replica node keeps a synchronized copy of a specif…

  3. When enough nodes in the cluster agree that a specific master has become unreachable, one of that master's replicas is automatically promoted to become the new master, taking over…

  4. Redis Cluster does not support multi key operations across keys that live on different nodes unless you use hash tags to force them onto the same slot, has limited support for sele…

  5. You would choose a number of master nodes sufficient to spread your data and traffic appropriately, add at least one replica per master for failover protection, place replicas in d…

Connection Pooling & Client Libraries

All 7 questions
  1. Connection pooling maintains a set of already established connections to Redis that your application can reuse, rather than opening and closing a brand new connection for every sin…

  2. Popular Redis client libraries include redis-py for Python, node-redis and ioredis for Node.js, Jedis and Lettuce for Java, and StackExchange.Redis for C#, each providing a way for…

  3. Most well designed client libraries automatically detect a dropped connection and attempt to reconnect, often using a retry strategy with increasing delays between attempts, lettin…

  4. A cluster aware client understands the cluster's hash slot mapping and automatically routes each command directly to the correct node responsible for that key, while a regular clie…

  5. You would size your connection pool based on your application's expected concurrency needs and the Redis server's capacity, monitor actual pool utilization to identify if you need…

  1. Redis supports strings for simple text or numeric values, hashes for storing objects with multiple fields, lists for ordered collections that support fast additions at either end,…

  2. Using the appropriate data type gives you access to specialized, efficient operations designed for that structure, such as incrementing a counter atomically, adding to a list witho…

  3. A set stores unique, unordered values and is ideal for membership checks like determining if an item exists in a collection, while a sorted set also stores unique values but each o…

  4. A hash stores multiple field value pairs under a single key, similar to a small object or dictionary, and is often more memory efficient than storing each field as its own separate…

  5. You could use a set for each user storing the ids of users they follow, and a separate set for each user storing the ids of their followers, letting you efficiently check if one us…

Distributed Locks with Redis

All 7 questions
  1. A distributed lock ensures that only one process or server, out of potentially many running the same application, can perform a specific action at a time, which is important when m…

  2. You use the SET command with the NX option, which only sets the value if the key does not already exist, combined with the EX option to set an automatic expiration time, ensuring t…

  3. If you simply delete the lock key without checking first, you risk accidentally releasing a lock that was actually acquired by a different client after your own lock expired, so yo…

  4. This is exactly why a distributed lock should always be set with an expiration time, ensuring that even if the holding process crashes, hangs, or otherwise never explicitly release…

  5. The Redlock algorithm acquires a lock across a majority of several independent Redis instances rather than relying on just one, aiming to provide stronger guarantees against a sing…

Expiration & Eviction

All 7 questions
  1. You can set an expiration time when creating a key using SET with the EX option for seconds or PX for milliseconds, or apply it to an already existing key using the EXPIRE command,…

  2. EXPIRE sets a countdown timer on a key after which it will be automatically deleted, TTL checks how much time remains before that countdown reaches zero, and PERSIST removes any ex…

  3. Redis offers several eviction policies including noeviction, which rejects new writes once memory is full, allkeys-lru and volatile-lru, which remove the least recently used keys,…

  4. LRU, meaning least recently used, evicts the key that has not been accessed for the longest time, while LFU, meaning least frequently used, evicts the key that has been accessed th…

  5. You would check the current maxmemory setting and eviction policy, review which keys are consuming the most memory, determine whether you actually need more available memory or a d…

Geospatial Data in Redis

All 7 questions
  1. Redis lets you store geographic coordinates, meaning longitude and latitude, associated with a member name using the GEOADD command, which internally stores this location data usin…

  2. You use the GEODIST command, specifying the two member names whose distance you want to calculate along with an optional unit like meters, kilometers, or miles, and Redis returns t…

  3. You use the GEOSEARCH command, specifying a center point either by coordinates or by an existing member's name, along with a radius and unit, and Redis returns all members within t…

  4. You use the GEOPOS command, specifying the member name whose coordinates you want to retrieve, and Redis returns the longitude and latitude values that were originally stored for t…

  5. You would use GEOADD to continuously update each vehicle's current location as it moves, use GEOSEARCH to find the nearest available vehicles to a new delivery request, and combine…

Hashes in Redis

All 7 questions
  1. A Redis hash lets you store several field value pairs under a single key, similar to a small dictionary or object, using the HSET command to set one or more fields at once, which i…

  2. You use HGET with a specific field name to retrieve just that one value, or HGETALL to retrieve every field and value pair stored in the hash at once, letting you either fetch a sp…

  3. You use the HINCRBY command, specifying the hash key, the field name, and the amount to increase it by, which atomically updates that specific field's numeric value, making it safe…

  4. You use HEXISTS to check whether a specific field is present in a hash, returning a simple true or false style result, and HDEL to remove one or more specific fields from a hash, l…

  5. You would generally prefer a native hash when your application frequently needs to read or update individual fields independently, since hashes let you avoid retrieving and rewriti…

HyperLogLog in Redis

All 7 questions
  1. A HyperLogLog is a probabilistic data structure used to estimate the number of unique items in a very large collection using a tiny, fixed amount of memory, solving the problem of…

  2. You use PFADD to add one or more items to a HyperLogLog structure, and PFCOUNT to retrieve the current estimated number of unique items that have been added, with Redis automatical…

  3. A Redis HyperLogLog typically has a standard error of about zero point eight one percent, meaning the estimated count will usually be very close to the true value, and this small i…

  4. You use the PFMERGE command, specifying a destination key and the source HyperLogLog keys you want to combine, which creates a new HyperLogLog representing the union of all unique…

  5. You would create a separate HyperLogLog for each day, add visitor identifiers to the appropriate day's structure as they occur, and then use PFMERGE to combine the relevant daily s…

Keyspace Notifications

All 7 questions
  1. Keyspace notifications let Redis publish events whenever certain operations happen to keys, such as a key being set, deleted, or expiring, letting other parts of your application s…

  2. You enable keyspace notifications using the CONFIG SET command on the notify-keyspace-events setting, combining character flags where K enables keyspace events, E enables keyevent…

  3. You subscribe to the special channel named __keyevent@0__:expired, where zero represents the database number, using a regular Pub/Sub SUBSCRIBE command, and your application then r…

  4. Keyspace notifications are delivered using Redis's Pub/Sub mechanism, which does not guarantee delivery, meaning if a subscribing client is disconnected or too slow to keep up when…

  5. You would use keyspace notifications as a fast, best effort mechanism to quickly invalidate related cache entries, but combine it with a periodic reconciliation process that indepe…

Leaderboards with Sorted Sets

All 7 questions
  1. A sorted set automatically keeps its members ordered by their associated score, meaning as you add or update a player's score, Redis automatically maintains the correct ranking ord…

  2. You use the ZREVRANGE command, specifying the sorted set key and a range from zero to nine, which returns the ten members with the highest scores in descending order, since ZREVRAN…

  3. You use the ZREVRANK command to find a specific player's zero based rank position in descending score order, and then use ZREVRANGE around that rank position to retrieve the player…

  4. You use the ZINCRBY command, specifying the leaderboard key, the amount to add, and the player's name, which atomically increases that player's existing score by the specified amou…

  5. You would create a new sorted set key for each period, such as including the week number in the key name, letting the current week's leaderboard start fresh while previous weeks' c…

Lists in Redis

All 7 questions
  1. A Redis list is an ordered collection of values that maintains the order items were added, and you use LPUSH to add an item to the left, meaning the beginning, of the list, or RPUS…

  2. You use the LRANGE command, specifying the list key along with a starting and ending index, which returns the items within that range without removing them from the list, letting y…

  3. You use RPUSH to add new items to the end of the list, representing new work being added to the queue, and LPOP to remove and retrieve the item from the beginning of the list, repr…

  4. BLPOP works like LPOP but blocks and waits if the list is currently empty, up to a specified timeout, instead of immediately returning nothing, which lets a worker process efficien…

  5. You use the RPOPLPUSH or the newer LMOVE command to atomically move a task from the main queue into a separate processing list at the same time it is retrieved, so if a worker cras…

Lua Scripting

All 7 questions
  1. A Lua script runs entirely on the Redis server as a single atomic operation, meaning no other client's commands can run in between the individual steps of your script, which both g…

  2. You specify the actual key names as a group after the script text, preceded by a count of how many keys you are passing, followed by any additional argument values, and within the…

  3. EVAL sends the full text of the Lua script to Redis every single time it runs, while EVALSHA sends only a hash identifier of a script that has already been loaded and cached on the…

  4. You call other Redis commands from within a Lua script using the redis.call or redis.pcall functions, passing the command name and its arguments, and while you have access to most…

  5. You write a script that increments a counter for the specific rate limited key, sets an expiration on it only if this is the very first request within the current time window, chec…

Persistence (RDB/AOF)

All 7 questions
  1. RDB persistence periodically saves a complete point in time snapshot of your entire dataset to a single compact file on disk, based on configured save rules, such as saving automat…

  2. AOF persistence logs every write operation to a file as it happens, rather than periodically saving the entire dataset at once like RDB, meaning it can offer much better durability…

  3. The always option writes and flushes to disk after every single write command, providing the strongest durability but the slowest performance, everysec flushes to disk once per sec…

  4. AOF rewriting compacts the append only file by rebuilding it from the current in memory dataset rather than the full history of every write command ever issued, removing redundant…

  5. You would enable both RDB snapshots for fast, compact full backups useful for quick restores and off site backup storage, and AOF for stronger durability during normal operation, c…

  1. Pub/Sub lets one client publish a message to a named channel, and any other clients currently subscribed to that same channel instantly receive the message, providing a simple way…

  2. You use the SUBSCRIBE command with a channel name to start listening for messages on that channel, and the PUBLISH command with a channel name and message content from a different…

  3. PSUBSCRIBE lets you subscribe to multiple channels at once that match a specified wildcard pattern, rather than needing to individually subscribe to each specific channel name, whi…

  4. If no client is currently subscribed to a channel when a message is published, that message is simply lost forever and never delivered to anyone, since Redis Pub/Sub does not store…

  5. You would use Pub/Sub for the fast, real time delivery portion of the system, but also persist important notifications to a database or a Redis Stream as the source of truth, so if…

Rate Limiting with Redis

All 7 questions
  1. Rate limiting restricts how many times a specific action, such as an API call, can happen within a given time period, and Redis is well suited for this because its fast, atomic cou…

  2. You increment a counter key representing the current time window each time a request comes in, and set an expiration on that key only the first time it is created, so the counter a…

  3. The sliding window log algorithm stores a timestamp for every single request in a sorted set, removes timestamps older than the allowed window before checking the current count, an…

  4. The token bucket algorithm maintains a bucket that refills with tokens at a steady rate up to a maximum capacity, with each request consuming one token, allowing short bursts of tr…

  5. You centralize all rate limit counting in Redis rather than in each individual application server's local memory, using an atomic Lua script to check and increment the shared count…

Redis Architecture & Installation

All 7 questions
  1. Redis stores all of its data in memory rather than on disk, which is dramatically faster to read and write than traditional disk based databases, and it processes commands using a…

  2. You can install Redis using your operating system's package manager, or by downloading and compiling the source code directly, and once installed, you start the Redis server proces…

  3. You should configure an appropriate maxmemory limit and eviction policy to control memory usage, set up a persistence strategy using RDB, AOF, or both based on your durability need…

  4. Redis uses an event driven, non blocking input and output model, meaning while only one command is actually being processed by the main thread at any given moment, the server can s…

  5. You would size available memory generously beyond your expected dataset size to account for growth and internal overhead like replication buffers, choose fast, reliable storage for…

Redis as a Message Queue

All 7 questions
  1. Redis offers simple lists combined with LPUSH and BRPOP for a basic first in first out queue, Pub/Sub for real time fire and forget messaging without persistence, and Streams for a…

  2. You have producers add new tasks to the queue using RPUSH, and have multiple worker processes each call BRPOP on the same queue key, with Redis guaranteeing that each individual ta…

  3. A plain list based queue does not retain any history of processed messages, offers no built-in way to acknowledge that a message was successfully processed, and provides no way to…

  4. You can use a sorted set instead of a plain list, storing each task with a score representing its priority, and have workers retrieve the highest or lowest priority task using ZPOP…

  5. You use a sorted set where the score represents the timestamp at which each task should become due, with a background process periodically checking for and moving any tasks whose d…

Redis Backup & Disaster Recovery

All 7 questions
  1. You use the SAVE command to synchronously create an RDB snapshot file, or the BGSAVE command to create the same snapshot in the background without blocking other operations, and th…

  2. You stop the Redis server, replace its current data file with the backup RDB file you want to restore, ensuring it is placed in the directory and with the filename Redis expects ba…

  3. A reasonable approach often includes taking frequent RDB snapshots, such as every few hours, retaining daily backups for a few weeks and weekly backups for several months, storing…

  4. You would maintain replicas or a full standby Redis Cluster in a geographically separate location, regularly synchronize or ship backups to that separate location, document and per…

  5. You would simulate a realistic failure scenario, such as intentionally taking down your primary Redis instance in a controlled test environment, have your team follow their documen…

Redis CLI & Basic Commands

All 7 questions
  1. redis-cli is the official command line tool for connecting directly to a Redis server, letting you run commands interactively and see their results immediately, which is useful for…

  2. SET stores a value under a specified key, GET retrieves the current value stored under a specified key, and DEL removes one or more keys entirely from Redis, together forming the f…

  3. You can use the KEYS command with a wildcard pattern to find matching key names, but it is generally discouraged in production because it scans the entire keyspace in a single bloc…

  4. You use the TYPE command to see what kind of data type a key holds, such as string, list, or hash, and the TTL command to see how many seconds remain before the key automatically e…

  5. You could use the MONITOR command to see a live stream of every command being processed by the server, though carefully since it adds overhead and should be used briefly, the SLOWL…

Redis Memory Optimization

All 7 questions
  1. Since Redis stores all of its data directly in memory rather than on disk, the total amount of data you can store is limited by the amount of RAM available on your server, making i…

  2. You use the MEMORY USAGE command with the specific key name, which returns the approximate number of bytes that key and its associated value are currently consuming, helping you id…

  3. Since Redis stores the key name itself alongside every value, using shorter, more concise key naming conventions can add up to meaningful savings across millions of keys, and choos…

  4. MEMORY DOCTOR analyzes your current Redis instance and provides plain language suggestions for potential memory related issues, while MEMORY STATS gives a detailed, granular breakd…

  5. Memory fragmentation happens when the memory allocator used by Redis leaves gaps between allocated pieces of memory that cannot be efficiently reused, causing Redis's actual memory…

Redis Modules Overview

All 7 questions
  1. Redis modules are dynamically loadable extensions that add entirely new commands and data types to Redis, letting you gain specialized capabilities like full text search, native JS…

  2. RedisJSON adds native support for storing and querying JSON documents, RedisSearch adds full text search and secondary indexing capabilities, RedisTimeSeries adds specialized suppo…

  3. You use the MODULE LIST command to see all currently loaded modules along with their versions, and load a new module either by specifying it as a startup parameter when launching t…

  4. Redis Stack is a distribution that bundles Redis together with several of the most popular official modules, including RedisJSON, RedisSearch, RedisTimeSeries, and RedisBloom, alre…

  5. You would weigh the development time saved by using a purpose built module against the added operational complexity of managing that module, consider whether your use case genuinel…

Redis Monitoring & Observability

All 7 questions
  1. You should regularly monitor memory usage relative to your configured maximum, the number of currently connected clients, hit and miss ratio for cache workloads, replication status…

  2. You check the keyspace_hits and keyspace_misses values from the INFO command, calculating the ratio between them, which tells you what percentage of read requests are being success…

  3. The slow log automatically records any command that takes longer than a configured threshold to execute, and you review it using the SLOWLOG GET command, which shows you the specif…

  4. Popular tools include Prometheus combined with the Redis Exporter for collecting and storing metrics over time, Grafana for building visual dashboards from that collected data, and…

  5. You would configure alerts for conditions like memory usage approaching your configured maximum, replication lag exceeding an acceptable threshold, connection counts approaching yo…

Redis Performance Tuning & Benchmarking

All 7 questions
  1. Redis includes a command line tool called redis-benchmark that simulates many simultaneous clients sending requests to a Redis server, letting you measure how many operations per s…

  2. Pipelining lets you send multiple commands to Redis together without waiting for a response after each individual one, dramatically reducing the impact of network round trip time w…

  3. You should avoid the KEYS command in favor of SCAN, avoid retrieving an entire very large collection at once when only a portion is actually needed, avoid storing extremely large i…

  4. Extremely large individual values take longer to transfer over the network, consume more memory, and can block the single Redis thread for a noticeably longer time during operation…

  5. You would define a realistic workload that closely matches your actual production traffic patterns, run redis-benchmark or a custom benchmarking tool against both configurations un…

Redis Replication

All 7 questions
  1. Redis replication lets you create one or more replica servers that maintain a continuously synchronized copy of a primary server's data, providing a backup that can take over if th…

  2. You use the REPLICAOF command, specifying the hostname and port of the primary server you want to replicate from, either as a runtime command or as a configuration file setting, af…

  3. Replication lag is the delay between when a write happens on the primary and when that same change is actually reflected on a replica, which can be caused by network latency betwee…

  4. Full resynchronization requires the replica to receive an entirely new complete copy of the primary's dataset, which can be slow and resource intensive for large datasets, while pa…

  5. You would add multiple replicas and distribute read traffic across them using a client side or proxy based load balancing approach, carefully monitor each replica's lag to ensure r…

Redis Security & ACL

All 7 questions
  1. You set the requirepass configuration option to a strong password value, after which any client attempting to connect must first successfully authenticate using the AUTH command wi…

  2. Redis ACL, short for access control list, lets you create multiple distinct users, each with their own password and a specifically defined set of permissions controlling which comm…

  3. You use the ACL SETUSER command, specifying the username, enabling the user, setting a password, and then defining exactly which key patterns they can access using the tilde symbol…

  4. ACL categories group related commands together under a single named category, such as read, write, or dangerous, letting you grant or deny an entire category of commands with one r…

  5. You would create a distinct user for each application or team with the minimum permissions they actually need, using key pattern restrictions to prevent one application from accide…

Redis Sentinel & High Availability

All 7 questions
  1. Redis Sentinel is a separate monitoring system that continuously watches your primary and replica Redis instances, and if it detects the primary has failed, it automatically coordi…

  2. Running multiple Sentinel instances allows them to reach a quorum, meaning a majority agreement, before deciding a primary has actually failed and triggering a failover, which prev…

  3. Rather than connecting directly to a specific server address, a Sentinel aware client library asks one of the Sentinel instances for the current address of the primary, and after a…

  4. The quorum setting specifies the minimum number of Sentinel instances that must agree the primary is actually unreachable before a failover process begins, providing protection aga…

  5. You would spread your Sentinel instances and your primary and replica Redis servers across different physical locations or availability zones, ensuring that a failure affecting one…

Redis vs Memcached

All 7 questions
  1. Redis supports a wide variety of rich data structures like hashes, lists, sets, and sorted sets, along with features like persistence, replication, and Pub/Sub, while Memcached is…

  2. No, Memcached is purely an in memory cache with no built-in persistence mechanism, meaning all data is permanently lost if the Memcached process restarts or the server reboots, unl…

  3. Redis primarily processes commands using a single main thread, relying on an efficient event driven model to handle many connections, while Memcached uses a genuinely multi threade…

  4. Redis offers rich data structures like sorted sets and streams, Pub/Sub messaging, Lua scripting for atomic multi step operations, built-in replication and clustering for high avai…

  5. You would benchmark both under a realistic workload closely matching your actual traffic patterns, weigh Memcached's potentially higher raw throughput for simple operations against…

Redis with Docker & Kubernetes

All 7 questions
  1. You use the docker run command with the official Redis image, optionally mapping the container's port to a port on your host machine, letting you quickly start a working Redis inst…

  2. You mount a Docker volume to the directory where Redis stores its persistence files, ensuring that even if the container is stopped, removed, and recreated, the underlying data fil…

  3. A StatefulSet is used instead of a regular Deployment because Redis needs stable network identities and persistent storage tied to each specific pod, ensuring that if a pod restart…

  4. You typically need a Service to provide a stable network endpoint that other applications can connect to, a ConfigMap to manage Redis configuration settings separately from the con…

  5. You would deploy the Redis primary and replicas as a StatefulSet with appropriate persistent volumes, deploy a separate set of Sentinel pods configured to monitor the Redis deploym…

RedisBloom (Probabilistic Data Structures)

All 7 questions
  1. A Bloom filter is a highly memory efficient probabilistic data structure that can quickly tell you whether an item is definitely not in a set or possibly in a set, and RedisBloom a…

  2. You use BF.ADD to add an item to a Bloom filter, automatically creating the filter if it does not already exist, and BF.EXISTS to check whether an item has possibly already been ad…

  3. A standard Bloom filter works by setting several bits shared across multiple items based on hash calculations, meaning you cannot safely clear those bits for one specific item with…

  4. A lower configured false positive rate makes the Bloom filter more accurate at correctly identifying items that were never actually added, but requires more memory to achieve that…

  5. You would populate a Bloom filter with all the identifiers of items that are known to actually exist in your database, and before performing an expensive database lookup for a requ…

  1. RedisJSON is a module that adds native support for storing, retrieving, and modifying JSON documents directly within Redis, letting you access and update specific fields deep withi…

  2. You use JSON.SET or JSON.GET along with a JSONPath expression that identifies the specific field you want to target, using a dollar sign to represent the document's root and dot no…

  3. You use JSON.ARRAPPEND to add one or more new items to the end of an existing array at a specified path within your JSON document, letting you efficiently grow an array, such as a…

  4. You create a search index using RedisSearch that specifically defines certain fields within your JSON documents as searchable, and RedisSearch then automatically indexes those fiel…

  5. You would structure your data as nested JSON documents that closely match how your application naturally thinks about its entities, use RedisJSON's path based commands to efficient…

RedisTimeSeries

All 7 questions
  1. RedisTimeSeries is a module specifically designed for efficiently storing and querying time stamped data, such as sensor readings, application metrics, or stock prices, providing s…

  2. You use TS.ADD to add a new value with either a specific timestamp or an asterisk to automatically use the current time, and TS.RANGE to retrieve all data points falling within a s…

  3. You create a compaction rule using TS.CREATERULE, specifying a source time series, a destination time series, an aggregation type like average or maximum, and a bucket duration, wh…

  4. You set a retention period, specified in milliseconds, either when creating the time series or by altering it afterward, and Redis automatically removes any data points older than…

  5. You would configure a short retention period for high frequency raw data optimized for immediate alerting and detailed recent analysis, set up multiple compaction rules creating pr…

Session Management with Redis

All 7 questions
  1. Redis offers extremely fast read and write access needed for checking a user's session on nearly every request, supports automatic expiration so sessions can time out naturally aft…

  2. You call the EXPIRE command with a fresh expiration duration each time a user makes a request, effectively resetting their session's countdown timer, ensuring an actively browsing…

  3. You could use a Redis hash to store multiple related fields for a single session under one key, such as the user id, login timestamp, and a reference to their cart, or use RedisJSO…

  4. You maintain a set that tracks all the active session identifiers associated with a specific user, and when you need to force a logout across all their devices, you retrieve that s…

  5. You would maintain two separate expiration mechanisms, extending a sliding expiration key on every user request to keep active sessions alive, while also checking a separate absolu…

Sets & Sorted Sets in Redis

All 7 questions
  1. A Redis set stores an unordered collection of unique values, automatically preventing any duplicate from being added twice, which makes it a natural fit for tracking things like un…

  2. You use SISMEMBER to check whether a specific value is currently a member of a set, returning a simple true or false style result, and SREM to remove one or more specific values fr…

  3. You use SINTER to find items that exist in every specified set, SUNION to find items that exist in at least one of the specified sets, and SDIFF to find items that exist in the fir…

  4. A sorted set also guarantees unique members like a regular set, but additionally associates a numeric score with each member, which Redis uses to automatically maintain the members…

  5. You could store each piece of content's tags in a set, and to find similar content, calculate the intersection between a target item's tag set and the tag sets of other candidate i…

  1. A Redis Stream is an append only log data structure specifically designed for messaging, where every added entry receives a unique id and remains stored in the stream even after be…

  2. You use XADD to add a new entry, providing a set of field value pairs representing the message data, and XRANGE to read a range of entries from the stream, specifying starting and…

  3. A consumer group lets multiple different consumers share the workload of processing a single stream, with Redis ensuring each message is only delivered to one consumer within that…

  4. You use the XACK command, specifying the stream, the consumer group, and the specific message id, which marks that message as successfully processed for that group, removing it fro…

  5. You use the XPENDING command to identify messages that have been delivered but not yet acknowledged, and XCLAIM to transfer ownership of a specific pending message to a different,…

Strings & Bitmaps in Redis

All 7 questions
  1. A Redis string can store text, numbers, or even binary data up to five hundred twelve megabytes in size, making it the most basic and flexible data type in Redis, commonly used for…

  2. You use INCR to atomically increase a numeric string value by one, DECR to atomically decrease it by one, or INCRBY and DECRBY to change it by a specific custom amount, all guarant…

  3. A Redis bitmap is not actually a separate data type but rather a way of treating a regular string as a sequence of individual bits, letting you use commands like SETBIT and GETBIT…

  4. You use the BITCOUNT command, which returns the total number of bits set to one within the specified range of a string, letting you efficiently calculate things like how many uniqu…

  5. You use BITOP with the AND operation to combine two bitmaps into a new one where only bits set in both original bitmaps remain set, and then run BITCOUNT on that resulting combined…

TLS & Encryption in Redis

All 7 questions
  1. TLS encryption protects data as it travels between clients and the Redis server, preventing attackers on the network from reading or tampering with sensitive information like passw…

  2. You generally need a server certificate and its matching private key to identify and authenticate the Redis server itself, plus a certificate authority file used to verify the iden…

  3. Standard TLS only verifies the identity of the server to the client, while mutual TLS additionally requires the client to present its own valid certificate, which the server verifi…

  4. You pass connection parameters that specify the TLS scheme along with paths to the client certificate, private key, and certificate authority file, allowing the client library to e…

  5. TLS introduces some additional CPU overhead for encrypting and decrypting traffic and a small amount of latency for the initial handshake, so on very high throughput systems it hel…

Transactions

All 7 questions
  1. A Redis transaction lets you group a series of commands together so they are executed sequentially and atomically as a single unit, starting the group with MULTI, queuing each comm…

  2. You use the DISCARD command, which cancels the current transaction and clears all commands that were queued after MULTI was called, returning the connection to its normal state wit…

  3. WATCH lets you monitor one or more keys for changes made by other clients before your transaction executes, and if any watched key is modified between calling WATCH and calling EXE…

  4. Unlike a relational database, Redis does not roll back earlier successful commands within a transaction if a later command in the same transaction fails at runtime, since Redis tre…

  5. A Lua script is often a better choice when your atomic operation needs conditional logic based on values read partway through, since the entire script runs as a single atomic unit…