Developers looking for a powerful and feature-rich database often turn to Redis. According to DB-Engines ranking, Redis is currently the 8th most widely used database management system and is also the most popular choice worldwide for key-value databases. Moreover, according to Stack Overflow’s 2019 research, Redis is the “favorite” database technology, ahead of alternatives such as Oracle, MySQL and Microsoft SQL Server.
So what exactly is Redis and what are its advantages and features? In this article, we’ll tell you everything you need to know about Redis so you can decide if it’s the right database technology for you.
Let’s get started!
What is Redis?
Redis – Remote Dictionary Server is an open source in-memory data store that is widely used to implement non-relational key/value databases and caches.
This distinction is important. Because Redis is technically a data structure store and not a key/value database. In traditional key-value databases, each key is an optional string associated with an uninterpreted byte array.
Data structure stores such as Redis remove this limitation. A key can be a string or a more complex data structure such as a list, set, hash, bitstream or stream. This allows developers to leverage multiple Redis use cases:
- Key-value database: Redis is commonly used to implement a non-relational key-value database, which is lightweight and efficient. For example, a database containing 1 million small keys (e.g. strings) takes about 85 megabytes of memory.
- Cache: Because it can store arbitrary data, Redis can also implement an application cache. The data is stored in memory and offers the best possible performance when reading from and writing to the cache.
- Message broker: Since version 2.0, Redis supports the publish/subscribe messaging model, allowing it to be used as a message broker.
With major tech companies like Twitter, GitHub and Pinterest all using Redis, it’s no surprise that Redis is both popular and well-liked among developers.
Redis offers sub-millisecond response times, enabling millions of requests per second for real-time applications in gaming, iOT, social networking, financial services, healthcare and ad tech. Redis is also a popular choice for caching, session management, gaming, leaderboards, real-time analytics, geolocation, geolocation, ride-hailing, chat/messaging, media streaming and pub/sub applications.
It supports data structures such as strings, hashes, lists, clusters, sorted sets with range queries, bitmaps, hyperlogs and geospatial indexes with radius queries. It has different stages of LRU eviction, Lua scripting, built-in replication, operations as well as disk persistence. It offers built-in support for high-availability solutions through Redis Sentinel or by leveraging Redis Cluster with automatic partitioning.
What are the Features of Redis?
Redis is written in ANSI C and runs on most POSIX systems such as BSD, Linux, OS X without any external dependencies. OS X and Linux are considered the two operating systems where Redis has been developed and tested the most, while Linux has been used to distribute the same. Redis can also run on systems derived from Solaris, such as SmartOS. Unfortunately, there is no official support provided for Windows builds, but Microsoft has developed and maintained a Win-64 port for Redis. Other important features of Redis are as follows:
1. High Level Data Structure
Redis offers five possible data options for values. These are hashes, lists, clusters, arrays and sorted sets.
2. Superior Performance
Due to its in-memory nature, its commitment to keeping complexity to a minimum, and the fact that it is an event-based programming model, the application has exceptional performance for reading and writing.
3. Extremely Lightweight and No Dependencies
Redis is written in ANSI C and is not limited by any external dependencies. The program works perfectly in all POSIX environments. The Windows platform is not officially supported for Redis, but an experimental build of the same has been provided by Microsoft.
4. High Availability
Redis has built-in support to ensure a high level of data availability. There is currently a high-availability solution called Redis Sentinel, which is available but is still considered an ongoing project.
How Redis Works
Redis works by storing keys that match one of five different data structures: STRINGS, LISTs, SETs, HASHs, and ZSETs (ordered sets). Some Redis commands are shared between all five of these data structures, while others are used by only one or two.
There are four major Redis versions that you can deploy to maintain the integrity of the database:
- Standalone Redis, which lacks vertical scalability and resiliency.
- Redis master-slave replication, where a single administrator replicates data to multiple slaves.
- Redis Sentinel, which monitors the master-slave system and automatically reconfigures a new master when the old one goes down.
- Redis Cluster, which uses a multi-master architecture to provide both scalability and flexibility for very large deployments
Where and When to Use Redis?
Since Redis has very high performance, it is mainly used for caching. This is where Redis shines the most as it offers a variety of types to store with its dictionary structure.
However, we can also use Redis to cache full pages with high traffic and static content. If the page itself is open to change or the content is dynamically generated, it should not be cached in any case, regardless of whether you are using Redis or Memcached. If the page contains mostly static content or the content is refreshed every x time interval, you can cache that page and have it served immediately.
Another thing Redis can be used for is storing sessions. Unlike Memcached, which has no persistence, Redis has this, and this allows session storage. Managing sessions with Redis also improves the user experience when interacting with the site.
Persistence is important for storing sessions to prevent data loss during critical parts of user interaction. For example, processing a payment, adding an item to the shopping cart, or requesting any action as an authenticated user.
Redis Use Cases
Below are some of the use cases of Redis:
- Session Cache
Many websites leverage Redis Strings to create a session cache to speed up their website experience by caching HTML fragments or pages. Since data is temporarily stored in RAM, this feature makes Redis an excellent choice as a session cache. For example, it can temporarily store user-specific data, such as items stored in a shopping cart in an online store. This is crucial so that your users don’t lose their data if they log out or lose their connection.
- Full Page Cache (FPC)
Apart from your basic session tokens, Redis provides a very easy to work with FPC platform. Magento offers a plugin to use Redis as a full page cache backend. Also, for your WordPress users, Pantheon has a great plugin called wp-redis that will help you get the fastest page loads you’ve ever seen.
- Queues
Any application that deals with congestion, messaging, data aggregation, job management or packager routing should consider a Redis Queues as it can help you manage your queue size based on the arrival and departure rate for resource allocation.
- Leaderboards/Counting
Redis is a popular choice among game developers who want to create real-time leaderboards. Simply use the Redis Sorted Set data structure, which ensures the uniqueness of items while maintaining a sorted list based on user scores. Creating a real-time ranked list is as easy as updating it every time a user’s score changes. You can also use Sorted Sets to handle time series data using timestamps as scores.
- Pub/Sub
Redis supports the use of publish and subscribe (Pub/Sub) commands, users can design high performance chat and messaging services across all their applications and services. This includes the ability to use list data structures to run atomic operations and blocking capabilities.
- Real-Time Analytics
Redis can process data with sub-millisecond latency, making it ideal for real-time analytics, online advertising campaigns and AI-driven machine learning processes.
Other uses include social networking sites, RSS Feeds, analyzing e-commerce sales, IP address tracking, inappropriate content filtering, Q&A platforms, task scheduling service, user posts and profiles, multi-storage.
Why Use Redis?
There are many reasons to use Redis. Some of these reasons are as follows:
- Fast response database
It stores data in memory instead of on a disk or solid state drive (SSD), so response time is faster than others when performing read and write operations.
- Data persistence
Redis uses persistent disk storage designed for process interruptions. Redis can persist datasets by taking regular snapshots of the data and adding changes to them as they become available. It can then be configured to create these database backups on demand or at automatic intervals to ensure database durability and integrity.
- Random data support
Data stored in Redis can be of any shape and size. Redis is secure for binary files, so it can store any type of data, from human-readable text to encoded binary files. The size of a single data item in Redis can range from 0 bytes to 0.5 GB. This allows it to cache almost any data.
- Key-based access
Redis is based on a key/value model where data is stored and retrieved from Redis by key. Key-based access allows for extremely efficient access times and this model naturally matches caching with Redis providing traditional GET and SET semantics for interacting with data.
- Data expiration time
Keys in Redis can be set with a time to validity (TTL) after which they expire. Until they expire, such keys are called “temporary” keys.
- Developer friendly
Redis is supported in most languages (with the advantage of using open source technology). Languages like JavaScript, Java, Go, C, C++, C#, Python, Objective-C, PHP and almost all well-known languages support it.
- Extensibility
Redis is an open source project supported by a vibrant community. Because Redis is based on open standards, supports open data formats, and has a rich set of clients, there is no vendor or technology lock-in.
What are the Disadvantages of Redis?
Like any resource, Redis has a few disadvantages as well as advantages. Here are some of the key challenges when using Redis:
- Basic level of security
Redis only provides basic security (such as access rights) at the cloud server level. RDBMS provides granular, per-object access control lists (also known as role management).
- Flexibility
Redis has no query language, only commands. There is also no support for relational algebra. One cannot send any ad-hoc queries. All data accesses have to be envisioned by a developer and appropriate data access paths have to be designed. This is why flexibility is believed to be lost.
- Data management
All data must fit in memory. RDBMS usually store the cache part of the information and data on disks in memory. Using an RDBMS, more data can be managed than the memory it has. This is not possible with Redis.
- Persistence
Redis has only 2 options for persistence: Normal snapshotting and append-only files. Neither of these is as secure as the actual transaction server, which offers redo/redo logging, recovery at a specific point in time, block checksumming, flashback capabilities, etc.
- Client support
Clients need to make changes to support Redis clusters. Although Redis clusters have been around for a long time, there are still some clients that do not support it.
- Support
Unlike standalone databases, Redis Clusters supports only a single database (database 0). The SELECT command is not allowed in Redis.
- Scalability
A unique Redis instance cannot be said to be scalable. It runs on only one CPU core in single-threaded mode. To achieve scalability, a number of Redis instances need to be deployed and initialized. Deployment and sharing is done client-side (a developer has to take care of these aspects). Most RDBMSs offer more scalability. It provides parallelism at the connection level. They are said to be multi-process or even multi-threaded (like MySQL, Microsoft SQL Server), taking advantage of the benefits of multi-core machines.
Comparison of Redis with Other Database and Caching Solutions
Of course, Redis is not the only database and caching solution on the market. There are also Redis alternatives such as Hazelcast, Apache Ignite and Memcached.
Both Memcached and Redis are high-performance key-value databases. However, unlike Redis, Memcached can only store data in flat string keys. Redis supports multiple storage formats for data and can automatically write data to disk in two different ways (AOF and RDB). Redis also provides more flexible control over cache extraction policies and supports data replication to improve availability and withstand unexpected crashes.
Redis is also better compared to alternatives such as Hazelcast and Apache Ignite. For example, neither Hazelcast nor Ignite have the rich array of Java distributed objects and collections that you can access with a third-party Redis Java client like Redisson.
In particular, there are important technical differences between Redis and Hazelcast. Redis is single-threaded, while Hazelcast is multi-threaded. Redis also uses the jemalloc memory allocator to efficiently manage various data types, while Hazelcast stores data on the heap, which can affect the performance of larger applications.
Can Redis Be the Best Method for Cache and Storage?
Cache is temporary storage where data is stored so that future data can be accessed faster. Caching is therefore the process of storing data in the cache. Redis is a good choice to implement a highly available in-memory cache with disk or SSD to reduce data access latency, high throughput and ease the load of the database and application. Web page caching, database query result caching, persistent session caching and caching of frequently used objects such as images, files and metadata are popular examples of caching solutions with Redis.
To summarize, once you know the areas where you can apply Redis for your business applications, you can leverage the power and speed that this technology can provide from scalability, high availability and optimal performance that can benefit your needs. Redis may not be that old compared to other existing databases, but its wide adoption and broad support by the community proves how powerful and efficient this tool can be.
Sources:
https://redis.io/
https://en.wikipedia.org/wiki/Redis