Cache vs. Session Store: How we can use Redis for both?


  • 6

    Some of you may be unaware of the subtle differences between a cache and a session store. Redis, as an in-memory database, is used for both caching and session store scenarios. Let’s look at how the use cases differ.

    Cache
    An application stores data in the cache to serve future requests faster. Typically, the cache storage is located in the RAM and has sub millisecond latency. Caching has always been helpful in improving performance. Caching happens nearly everywhere

    1. RAM is in some sense a cache for hard disk/SSD
    2. L3 cache is a cache for RAM
    3. Your browser caches the web pages that you visit
    4. DNS servers cache the DNS entries for faster resolution
    5. Web servers cache the web pages that they serve
    6. Dynamic programming is also a caching

    In the data fetch lifecycle, the application first looks for the data in the cache. If there’s a hit (i.e. the data is in the cache), it serves the data instantaneously. Conversely, if there’s a miss it fetches the data from a permanent store, stores a copy in the cache, and serves the data to the consumer. For all future requests, the data is already there in the cache and is served faster. When an application updates the data, it updates both the cache and the permanent store.

    This lifecycle works well for scenarios where different consumers request the same data over a period of time. One should also note that the data is stored at the application level, and not at the user level. So the data that’s stored in the cache is shared among users. Images, videos, static HTML pages, JavaScript libraries and style sheets are examples of data that are often stored in cache.

    Session Store
    Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.

    Sessions can be very useful because the request/response cycle is stateless. The request/response cycle is considered stateless because neither the client nor the server inherently stores any information between different requests about a particular request. Therefore the lifecycle of a request/response ends when a response is made to the requesting user agent. (A user agent is the software (e.g. browser or native application) that represents you on a device (e.g. a browser tab on your computer, a smartphone application, or your refrigerator). It is associated one-to-one with a cookie or access token.)

    It helps to keep track of users and their information.For example,You have created an application that requires users to login to access certain content.Now once this user has provided you the correct user-name and password, you will have this user redirect to the page which only logged-in users can access.

    Now Imagine you have some page that displays this logged in user’s personal information, that he had earlier fed to your application. But on reaching this page, how will the server fetch this information from the database? It has no idea who this user is now. Remember: HTTP is a stateless protocol……

    So Session helps here. Once the user logs into the application, at the server you create a session for this user. Save all the necessary information into this session object.The most important of them, the user’s unique identifier.Use this ID to fetch information from the database until the user is logged in.Invalidate the session once the user logs out. Here the cycle terminates. The server no longer knows this user.

    A session-oriented application (a web application, for example) starts a session when a user logs in, and is active until the user logs out or the session times out. During this period, the application stores all session-related data either in the main memory or in a session store—a database that doesn’t lose the data when the application goes down. Session data may include user profile information, messages, personalized data and themes, recommendations, targeted promotions and discounts, etc.

    Difference between Cache and Session Store:
    The following points contrast session store from a cache:

    1. In a session store, the data is not shared between the sessions of different users. The solutions architecture must ensure the data remains isolated between users.

    2. As described in the figure above, the life cycle of the data differs between the cache and the session store. The figure shows a write-through cache that writes to both the cache and the backend data store. This lowers the throughput for write operations. On the other hand, session stores rely on reading and writing data to the in-memory database. They cannot afford to compromise on the performance for write operations.

    3. Session store data isn’t ephemeral; it’s the only source of truth when the session is live. Therefore, it needs to satisfy the data durability requirements of a true database. If the data in a cache gets lost, there’s always a copy in the permanent store.

    4. A session store requires replication, high availability, and data durability to ensure transactional data is not lost. Whereas, the high-availability requirements for caching are driven by the operational requirements and need to prevent cache stampeding.

    Using Redis for both (Cache and Session Store):

    Redis is a popular database ideal for both cache and session store use cases, delivering both the high-availability required for caching and session store scenarios as well as the durability needed for session store with in-memory replication. It’s possible to use Redis as both a cache and a session store in a single setup as shown in the picture below.

    0_1518255240628_Redis Session.png image url)

    In this design, the application layer accesses and maintains the data in the cache. Therefore, all the sessions running inside the application access the same data stored in the cache.

    In addition to the data in cache, each session holds the session-related data inside Redis. How do you ensure that the sessions don’t access each other’s data? Here’s a solution: First, each session must acquire a random session id that’s not shared with other sessions. Second, the session must append the session id to the keys. In the example below, a session stores the personal information in a Hash data structure, and the user recommendations in a Set data structure. As you may note, the keys have session ID in them. This prevents sessions from accessing the data owned by other sessions.

    session_data:(session_id):personal_info
    
        name - Shashi Bhushan
    
        email - shashibk1993@gmail.com
    
        phone - 9205834773
    
    
    
    session_data:(session_id):recommendations
    
        {“book1”, “phone1”, “book2”,.....“product n”}
    

    In conclusion, cache and session store are two different use cases. While high availability is important to a cache to prevent situations such as cache stampede, a session store requires high availability and durability to support transactional data and uninterrupted user engagement. With proper architecture and design, a single database instance of Redis can be used for both caching and session data use cases while ensuring data separation between the sessions.

    You can connect with me here: https://www.linkedin.com/in/shashi-bhushan-kumar-709a05b5/


  • 0

  • 0

    @user7513 Yes I should have given the reference to this, but I have added some extra points also.


  • 0
    E

    @shashibk11 how typical


  • 0
    R

    @shashibk11 plagiarism


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.