Showing posts with label Redis. Show all posts
Showing posts with label Redis. Show all posts

Thursday, December 11, 2025

Redis Interview Keypoints

Redis Interview Keypoints


Architecture & Execution

✅ 1. Redis executes commands in a single thread “Redis uses an event loop to process all client requests sequentially, ensuring atomicity without locks.”

✅ 2. Redis uses non‑blocking I/O multiplexing “Redis leverages epoll/kqueue/select to handle thousands of concurrent connections efficiently.”

✅ 3. Redis guarantees atomic operations “Because commands are executed sequentially, Redis ensures atomicity without explicit transactions.”

✅ 4. Redis supports multiple data structures “Strings, lists, sets, sorted sets, hashes, streams, bitmaps, and hyperloglogs are natively supported.”

✅ 5. Redis optimizes small collections with encodings “Structures like lists and hashes use ziplist/intset encodings to save memory.”

✅ 6. Redis supports pub/sub messaging “Clients can publish and subscribe to channels for real‑time message distribution.”

✅ 7. Redis supports Lua scripting “Lua scripts run atomically inside Redis, enabling complex operations without race conditions.”

✅ 8. Redis supports transactions with MULTI/EXEC “Commands queued in MULTI are executed atomically when EXEC is called.”

✅ 9. Redis supports pipelines “Clients can batch multiple commands to reduce round‑trip latency.”

✅ 10. Redis supports streams for event data “Streams provide append‑only log structures with consumer groups for processing.”

Persistence

✅ 11. Redis supports RDB snapshots “RDB creates point‑in‑time dumps of the dataset into dump.rdb.”

✅ 12. Redis supports AOF logging “AOF logs every write operation into appendonly.aof for durability.”

✅ 13. Redis supports hybrid persistence “RDB + AOF can be enabled together for balance between speed and durability.”

✅ 14. Redis forks child processes for persistence “On BGSAVE or BGREWRITEAOF, Redis forks a child to handle disk writes.”

✅ 15. Redis supports configurable snapshot intervals “save 900 1 means snapshot every 900 seconds if at least 1 key changed.”

✅ 16. Redis supports appendfsync policies “Options are always, everysec, or no, balancing durability vs performance.”

✅ 17. Redis supports AOF rewrite “BGREWRITEAOF compacts the log by rewriting it in the background.”

✅ 18. Redis supports truncated AOF recovery “aof-load-truncated yes allows Redis to start even if AOF is incomplete.”

✅ 19. Redis supports stop‑writes on persistence error “stop-writes-on-bgsave-error yes prevents data loss if snapshotting fails.”

✅ 20. Redis persistence files are stored in dir “Both RDB and AOF files are written to the configured data directory.”


Replication

✅ 21. Redis supports master‑replica replication “Replicas asynchronously copy data from the master.”

✅ 22. Redis supports partial resynchronization “Replicas can catch up using replication backlog without full resync.”

✅ 23. Redis supports replica promotion “SLAVEOF NO ONE promotes a replica to master.”

✅ 24. Redis supports replica authentication “masterauth config ensures replicas authenticate to the master.”

✅ 25. Redis supports min‑replicas‑to‑write “Writes only succeed if enough replicas acknowledge them.”

✅ 26. Redis supports min‑replicas‑max‑lag “Defines maximum lag allowed before writes are stopped.”

✅ 27. Redis supports diskless replication “repl-diskless-sync yes streams data directly without temporary files.”

✅ 28. Redis supports replication backlog buffer “Backlog stores recent writes for replicas to catch up after disconnects.”

✅ 29. Redis supports chained replication “Replicas can replicate from other replicas, not just the master.”

✅ 30. Redis supports replica read‑only mode “By default, replicas serve read queries but reject writes.”

High Availability (Sentinel & Cluster)

✅ 31. Redis Sentinel monitors masters “Sentinel detects failures and promotes replicas automatically.”

✅ 32. Redis Sentinel reconfigures clients “Clients are updated with new master info after failover.”

✅ 33. Redis Sentinel supports quorum “Failover requires majority agreement among Sentinels.”

✅ 34. Redis Cluster shards data “Cluster divides 16,384 hash slots across masters.”

✅ 35. Redis Cluster supports replicas per master “Each master has replicas for redundancy.”

✅ 36. Redis Cluster supports automatic rebalancing “Slots can be migrated between nodes to balance load.”

✅ 37. Redis Cluster supports resharding “Keys can be moved between slots during scaling.”

✅ 38. Redis Cluster supports gossip protocol “Nodes exchange state info via gossip messages.”

✅ 39. Redis Cluster supports failover “Replicas are promoted if a master fails.”

✅ 40. Redis Cluster requires full slot coverage “By default, cluster stops serving if slots are missing.”

Memory Management

✅ 41. Redis enforces maxmemory limits “maxmemory sets a hard RAM cap for the dataset.”

✅ 42. Redis supports eviction policies “Options include allkeys-lru, volatile-ttl, and noeviction.”

✅ 43. Redis supports maxmemory‑samples “Defines how many keys are sampled for eviction decisions.”

✅ 44. Redis supports memory fragmentation monitoring “INFO memory shows fragmentation ratio for tuning.”

✅ 45. Redis supports lazy freeing “lazyfree-lazy-eviction frees memory asynchronously.”

✅ 46. Redis supports memory allocator tuning “Redis can use jemalloc or libc malloc for memory management.”

✅ 47. Redis supports memory usage command “MEMORY USAGE key shows memory consumed by a key.”

✅ 48. Redis supports memory stats “MEMORY STATS provides allocator and fragmentation details.”

✅ 49. Redis supports memory doctor “MEMORY DOCTOR suggests fixes for memory fragmentation.”

✅ 50. Redis supports eviction notifications “Clients can subscribe to keyspace events for evictions.”



Performance & Monitoring

✅ 51. Redis supports INFO command “Provides runtime stats: memory, clients, persistence, replication, CPU, keyspace.”

✅ 52. Redis supports SLOWLOG “Captures queries slower than threshold for tuning.”

✅ 53. Redis supports latency monitor “Tracks operations exceeding configured latency thresholds.”

✅ 54. Redis supports MONITOR command “Streams all commands in real time for debugging.”

✅ 55. Redis supports CLIENT LIST “Shows connected clients with IP, state, and flags.”

✅ 56. Redis supports CLIENT KILL “Terminates misbehaving or unauthorized client connections.”

✅ 57. Redis supports CONFIG GET/SET “Allows runtime inspection and modification of config parameters.”

✅ 58. Redis supports DEBUG commands “DEBUG SEGFAULT or OBJECT commands help diagnose issues.”

✅ 59. Redis supports command stats “INFO commandstats shows per‑command call counts and latencies.”

✅ 60. Redis supports keyspace stats “INFO keyspace shows keys per DB and TTL distribution.”


Security

✅ 61. Redis supports requirepass “Enforces password authentication for clients.”

✅ 62. Redis supports ACLs (Redis 6+) “ACLs define users, commands, and key patterns allowed.”

✅ 63. Redis supports ACL WHOAMI “Shows which user is currently authenticated.”

✅ 64. Redis supports ACL LIST “Lists all ACL rules configured.”

✅ 65. Redis supports rename‑command “Disables or renames dangerous commands like FLUSHALL.”

✅ 66. Redis supports protected‑mode “Enabled by default, prevents unsafe external access.”

✅ 67. Redis supports TLS encryption “Redis can encrypt client‑server traffic with TLS.”

✅ 68. Redis supports firewall binding “bind restricts Redis to specific IP addresses.”

✅ 69. Redis supports port configuration “Default port is 6379, configurable via port.”

✅ 70. Redis supports AUTH command “Clients authenticate with password or ACL user credentials.”


Advanced Features

✅ 71. Redis supports modules “Modules extend Redis with custom data types and commands.”

✅ 72. Redis supports GEO commands “Stores and queries geospatial data using sorted sets.”

✅ 73. Redis supports BIT operations “Bitmaps allow efficient storage and manipulation of binary data.”

✅ 74. Redis supports HyperLogLog “Provides approximate cardinality estimation with low memory usage.”

✅ 75. Redis supports Bloom filters via modules “Modules like RedisBloom add probabilistic data structures.”

✅ 76. Redis supports JSON via modules “RedisJSON allows storing and querying JSON documents.”

✅ 77. Redis supports graph data via modules “RedisGraph enables graph queries using Cypher syntax.”

✅ 78. Redis supports time series via modules “RedisTimeSeries provides efficient time series storage and queries.”

✅ 79. Redis supports search via modules “RediSearch adds full‑text search and secondary indexing.”

✅ 80. Redis supports AI inference via modules “RedisAI integrates ML models for in‑database inference.”

Operational Practices


✅ 81. Redis supports online configuration changes “CONFIG SET allows parameters to be updated at runtime without restarting the server.”

✅ 82. Redis supports runtime inspection of configs “CONFIG GET retrieves current configuration values for verification.”

✅ 83. Redis supports persistence checks “INFO persistence shows last save time, AOF status, and background save progress.”

✅ 84. Redis supports backup via file copy “Copying dump.rdb or appendonly.aof provides a consistent backup snapshot.”

✅ 85. Redis supports restore by file placement “Placing RDB/AOF files back in the data directory restores the dataset on restart.”

✅ 86. Redis supports keyspace notifications “Clients can subscribe to events like set, expire, or evict for monitoring.”

✅ 87. Redis supports database selection “SELECT <db> switches between logical databases (default is DB 0).”

✅ 88. Redis supports flushing databases “FLUSHDB clears one DB, FLUSHALL clears all DBs — dangerous in production.”

✅ 89. Redis supports migration commands “MIGRATE moves keys between instances atomically with copy or replace options.”

✅ 90. Redis supports renaming keys “RENAME changes a key’s name; RENAMENX only if new name doesn’t exist.”

Advanced Administration

✅ 91. Redis supports cluster resharding tools “redis-cli --cluster reshard moves slots between nodes during scaling.”

✅ 92. Redis supports cluster health checks “redis-cli --cluster check validates slot coverage and node states.”

✅ 93. Redis supports sentinel failover testing “SENTINEL failover <master> forces a manual failover for testing.”

✅ 94. Redis supports sentinel monitoring commands “SENTINEL masters and SENTINEL slaves list monitored nodes.”

✅ 95. Redis supports client pause “CLIENT PAUSE temporarily blocks clients for controlled failover or maintenance.”

✅ 96. Redis supports command renaming for safety “Critical commands can be renamed or disabled to prevent accidental misuse.”

✅ 97. Redis supports eviction statistics “INFO stats shows key eviction counts for monitoring memory pressure.”

✅ 98. Redis supports key expiration checks “TTL key shows remaining time before a key expires.”

✅ 99. Redis supports cluster slot mapping “CLUSTER KEYSLOT key shows which slot a key belongs to.”

✅ 100. Redis supports cluster key migration “CLUSTER GETKEYSINSLOT retrieves keys in a specific slot for migration.”

Redis DBA Daily Commands

Redis DBA Daily Commands

1. Service Management

sudo systemctl start redis → Start the Redis service if it’s stopped.
sudo systemctl stop redis → Stop Redis safely (use before maintenance).
sudo systemctl restart redis → Restart Redis after config changes.
systemctl status redis → Check if Redis is running and view recent logs.

2. Connectivity & Basic Ops

redis-cli → Open the Redis command-line interface.
redis-cli ping → Quick health check; returns PONG if Redis is alive.
redis-cli SET mykey "hello" → Store a key/value pair.
redis-cli GET mykey → Retrieve the value of a key.

3. Monitoring & Health

redis-cli INFO → Full server stats (memory, clients, persistence, replication).
redis-cli INFO memory → Focused memory usage report.
redis-cli CLIENT LIST → Show all connected clients (IP, state, etc.).
redis-cli MONITOR → Stream all commands in real time (use carefully in prod).
redis-cli SLOWLOG get 10 → Show the 10 most recent slow queries.

4. Persistence & Backup

redis-cli SAVE → Force an immediate RDB snapshot (blocking).
redis-cli BGSAVE → Trigger background snapshot (non-blocking).
redis-cli INFO persistence → Check persistence status (last save, AOF enabled).

Backup files:
dump.rdb → RDB snapshot file.
appendonly.aof → AOF log file.

5. Memory & Key Management

redis-cli DBSIZE → Count how many keys are in the database.
redis-cli KEYS '*' → List all keys (avoid in large DBs, can block).
redis-cli DEL mykey → Delete a specific key.
redis-cli EXPIRE mykey 60 → Set a 60‑second TTL on a key.

6. Replication & High Availability

redis-cli INFO replication → Show replication role (master/replica) and status.
redis-cli SLAVEOF NO ONE → Promote a replica to master.
redis-cli SLAVEOF <master_ip> <master_port> → Make this node a replica of another.

7. Cluster Administration (if enabled)

redis-cli -c CLUSTER NODES → List all cluster nodes and their roles.
redis-cli -c CLUSTER INFO → Cluster health and slot coverage.
redis-cli --cluster check <ip:port> → Validate cluster configuration.

8. Security & Access

redis-cli -a <password> → Authenticate with password.
redis-cli ACL LIST → Show all ACL rules (Redis 6+).
redis-cli ACL WHOAMI → Show which user you’re logged in as.

Redis Daily Health‑Check Runbook

1. Service Status
systemctl status redis
Confirms Redis service is running and shows recent logs.

2. Connectivity
redis-cli ping
Quick test; should return PONG if Redis is alive.

3. Memory & Resource Usage
redis-cli INFO memory
Check total memory used, peak memory, fragmentation ratio.
Watch for memory close to system limits.

4. Persistence
redis-cli INFO persistence
Verify RDB/AOF status, last save time, and whether background saves are succeeding.

5. Replication / HA
redis-cli INFO replication
Shows if this node is master or replica.
Check replica lag and connected replicas.

6. Clients
redis-cli CLIENT LIST | wc -l
Count connected clients.
Useful to detect spikes or stuck connections.

7. Slow Queries
redis-cli SLOWLOG get 5
Review the last 5 slow queries.
Helps identify performance bottlenecks.

8. Keyspace Stats
redis-cli INFO keyspace
Shows number of keys per database and how many have TTLs.
Useful for monitoring growth and expiration behavior.

9. General Server Info
redis-cli INFO server
Check Redis version, uptime, and role.
Confirms you’re running the expected build.

10. Optional Cluster Checks (if enabled)
redis-cli -c CLUSTER INFO
redis-cli -c CLUSTER NODES
Verify cluster health, slot coverage, and node states.

✅ Daily Routine Summary

Service status → Is Redis running?
Ping test → Is it responsive?
Memory check → Is usage healthy?
Persistence check → Are RDB/AOF saves working?
Replication check → Are replicas in sync?
Client count → Any unusual spikes?
Slow queries → Any performance issues?
Keyspace stats → Growth and TTL behavior.
Server info → Version, uptime, role.
Cluster info → Slot coverage and node health (if clustered).

Saturday, February 17, 2024

Redis: The Leading In-Memory Database for High-Speed Data Processing

Redis: The Leading In-Memory Database for High-Speed Data Processing


In today's fast-paced world, where every microsecond counts, especially when it comes to processing vast amounts of data, in-memory databases (IMDB) have emerged as game changers. They store data in the main memory (RAM) instead of disks, enabling quicker data retrieval and processing. This speeds up applications, making them more responsive, which is vital in areas ranging from financial services to real-time analytics. Among the plethora of in-memory databases available, Redis stands out for its simplicity, efficiency, and versatility. So, let's explore this gem together, in a friendly, no-jargon manner.

Redis Database: A Friendly Introduction

Have you ever been in a situation where your application starts to lag, and users start complaining? Slow database responses are often the culprit, and this is where Redis saves the day. It's like that friend who can recall any piece of information instantly, no matter the situation.

Redis, which stands for Remote Dictionary Server, is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. What sets Redis apart is its ability to support various data structures such as strings, hashes, lists, sets, and more, making it incredibly flexible for different needs.

Key Features that Set Redis Apart

Let's delve into what makes Redis the talk of the tech town:

Speed

Imagine you are playing a video game that loads in the blink of an eye. That's Redis for you! Its in-memory datastore allows it to process data at lightning speed, significantly faster than disk-based databases.

Data Structures Support

Redis is like a Swiss Army knife for developers, offering a variety of data structures. Whether it's managing simple key-value items, lists, or complex data types, Redis handles it with ease, providing flexibility in application development.

Replication and Persistence

Just because Redis is in-memory doesn't mean it can't keep data safe. It offers options to periodically save data to disk and replicate it across multiple servers, ensuring data durability and high availability.

Easy Scalability

As your application grows, so does the amount of data. Redis makes it easy to scale up with minimal fuss, accommodating more data and users without skipping a beat.

Vibrant Community

Ever got stuck and wished for a helpful community? Redis boasts a large, active community. From detailed documentation to forums and tutorials, you'll find ample resources and support.

Personal Anecdote: Redis in Action

Let me share a quick story. Once, I was working on an application that needed a super-fast session store. We initially tried a traditional database, but the latency issues were a nightmare. That's when we gave Redis a shot. The difference was night and day! Session information loaded in milliseconds, user experience improved, and so did our sleep, knowing we had a reliable solution in place.

Redis Use Cases Galore

From caching to real-time analytics, Redis shines in multiple scenarios. Here are a few:

  • Session Caching: Keeping user sessions swift and responsive.

  • Full-page Cache (FPC): Serving entire web pages from memory for ultra-fast website loading.

  • Queue Management: Managing tasks and job queues efficiently.

  • Real-time Analytics: Providing insights and analytics in real-time, perfect for financial analysis or social media trends.

Many renowned companies rely on Redis for its top-notch performance and reliability, underlining its value in today's digital landscape.

Concluding Thoughts

Redis is not just another database; it's a reliable, fast, and versatile solution for a myriad of use cases. Its features, community support, and performance make it a standout choice in the realm of in-memory databases. Whether you're building a high-traffic web application, managing real-time data analytics, or simply need a quick, reliable caching solution, Redis is worth exploring.

Frequently Asked Questions about Redis



  1. What is Redis? 

Redis, which stands for Remote Dictionary Server, is an open-source, in-memory data structure store that can be used as a database, cache, and message broker.

  1. What does Redis do? 

Redis supports various data structures such as strings, hashes, lists, sets, and more, making it incredibly flexible for different needs.

  1. What’s the difference between Redis Enterprise and Redis Open Source? 

Redis Enterprise overcomes Redis open source’s limitations by providing scalable Redis even for dataset sizes beyond the size of the largest server.

  1. Is Redis Enterprise fully compatible with Redis open source? 

Yes, Redis Enterprise is fully compatible with Redis open source.

  1. How is Redis different from other key-value stores? 

Redis has a different evolution path in the key-value DBs where values can contain more complex data types, with atomic operations defined on those data types.

  1. What’s the Redis memory footprint?

An empty instance uses ~ 3MB of memory. 1 Million small Keys -> String Value pairs use ~ 85MB.

  1. Does Redis support transactions? 

Yes, Redis supports transactions, which means that you can execute a group of commands as a single, atomic operation.

  1. How does Redis handle persistence?

Redis offers options to periodically save data to disk and replicate it across multiple servers, ensuring data durability and high availability.

  1. What is Pub/Sub in Redis? 

Redis supports Publish/Subscribe messaging paradigms. This feature can be used to trigger actions based on specific events or updates, making it ideal for real-time applications.

  1. Does Redis support Lua scripting? 

Yes, Redis allows the execution of Lua scripts on the server side for complex computation, reducing the client-server communication overhead.

  1. What is the role of Redis in session management? 

Redis can efficiently manage user sessions, improving the performance of web applications. Its in-memory nature ensures fast session retrieval and updates, enhancing user experience.

  1. Can Redis be used for caching? 

Yes, Redis acts as a powerful caching layer between your application and the database. It stores frequently accessed data in-memory, reducing the load on the database and enhancing overall system performance.

  1. How does Redis handle security? 

Redis provides a level of security with features like command renaming and disabling, and optional password protection.

  1. Can Redis be used for real-time analytics? 

Yes, Redis’ fast data retrieval capability is perfect for real-time analytics. Store and process streaming data to gain insights and make informed decisions on the fly.