<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ali CANLI on Medium]]></title>
        <description><![CDATA[Stories by Ali CANLI on Medium]]></description>
        <link>https://medium.com/@alicanli1995?source=rss-a06c725b2a0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R7iqmo_rO7GduWyZi2YogQ.jpeg</url>
            <title>Stories by Ali CANLI on Medium</title>
            <link>https://medium.com/@alicanli1995?source=rss-a06c725b2a0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:35:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alicanli1995/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 6(Message Queue)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-6-message-queue-ffcd02643454?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcd02643454</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 19:51:39 GMT</pubDate>
            <atom:updated>2023-08-01T19:51:39.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 6(Message Queue)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*80PvuITl4bRg0RY1" /></figure><p>Introduction: Message queuing is an essential component in modern applications, enabling asynchronous and reliable processing of data and workload management. Redis, with its fast and flexible in-memory data storage, provides an excellent solution for implementing message queues. In this article, we will explore how Redis and Message Queue can be used together to achieve high-performance, scalable message queuing and discuss the advantages it offers.</p><ol><li>Redis Message Queue Usage: Redis provides basic message queue functionality with its simple queue data structure and fast data access. Redis commands like LPUSH and RPOP allow enqueueing (adding) and dequeueing (removing) data to and from queues. These fundamental features enable straightforward message queuing scenarios.</li><li>Configuring the Message Queue: For full-fledged message queue usage, more complex configurations may be required. Redis’ LIST, PUB/SUB, or Redis Streams data structures and commands enable more advanced and powerful message queuing scenarios. These configurations allow specifying targets for message processing, filtering messages, and implementing retry mechanisms.</li><li>Asynchronous Processing and Workload Balancing: Message Queue facilitates easy management of asynchronous processing in your application. Tasked with processing messages independent of the main application flow, tasks are added to the queue and processed asynchronously. This enhances the performance and responsiveness of your application, even during high-demand periods. Additionally, using message queues to balance the workload in parallel boosts the scalability of your application.</li><li>Processing Reliability: One significant advantage of the Message Queue is ensuring reliable processing of messages. It supports retry mechanisms to handle processing failures. If a process fails, the relevant message is automatically re-enqueued and retried after a specified time, preventing data loss and improving the reliability of your application.</li><li>Application Scenarios: The combination of Redis and Message Queue can be applied in various application scenarios. For instance, it can be used for email sending, report generation, data processing, and executing long-running tasks. Additionally, it is an ideal solution for offline transaction support, sequential data streams, and event-driven systems.</li></ol><p><strong><em>Now let’s see how we can apply what we have learned in real life in a spring boot based project.</em></strong></p><p>In this example, we’ll create a Message Queue using Redis and implement a Spring Boot application to enqueue and dequeue messages from the queue.</p><ol><li>RedisConfiguration.java:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*V5XLtnK5CfRx7vNM6R_giw.png" /></figure><ol><li>RedisMessagePublisher.java:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*v_okdokhjloIEnVRO1x2nw.png" /></figure><ol><li>RedisMessageSubscriber.java:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*BL-el4OrsX_agRJsCVonag.png" /></figure><p>MessageQueueController.java:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*i5B7XyhzTI64VDnLKRigyA.png" /></figure><p>In this example, the RedisConfiguration class sets up the Redis connection and Message Queue configuration. RedisTemplate is used for communicating with Redis. RedisMessagePublisher is responsible for adding messages to the queue. RedisMessageSubscriber is used to dequeue messages from the queue and print them to the console.</p><p>The MessageQueueController class contains the /publish endpoint, which is used to enqueue messages to the queue. The enqueued messages are listened to by RedisMessageSubscriber, and then they are printed to the console.</p><p>This way, we have implemented the usage of Redis and Message Queue with Spring Boot. By enqueuing and dequeuing messages, you can achieve asynchronous messaging and ensure secure data processing in your application.</p><blockquote><em>Conclusion: The combination of Redis and Message Queue offers an effective solution for high-performance, scalable, and reliable message queuing. With Redis’ fast data storage and advanced message queuing capabilities, it caters to the demands of modern applications. By leveraging Redis and Message Queue together, you can enhance your application’s performance, balance workload, and ensure reliable processing of tasks, resulting in a more scalable and high-performing application.</em></blockquote><p>Thanks for reading, you can access the github repository link from the link : <a href="https://github.com/alicanli1995/redis-deep-dive/tree/main/dive-6-message-queue">click and gooo</a></p><p>Next dive is -&gt; Inventory management</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcd02643454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 5(Session Store)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-5-session-store-3ae1bdd7a6e0?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae1bdd7a6e0</guid>
            <category><![CDATA[sessionstorage]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java17]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 21:34:34 GMT</pubDate>
            <atom:updated>2023-08-01T19:52:06.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 5(Session Store)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ibBiFzzrfvwSVku.png" /></figure><p>Introduction, Session management is a crucial aspect of web application development, ensuring that user data is securely stored and accessible across multiple requests. Redis, with its fast in-memory data storage and advanced features, provides an excellent solution for session management. In this article, we will explore how to leverage Redis as a session store to achieve scalability, distributed session management, and improved performance.</p><ol><li>Understanding Session Management: Before diving into Redis as a session store, let’s briefly review session management. Sessions are used to store user-specific data between requests. Typically, a unique session ID is generated and stored in a user’s browser as a cookie. The session ID is then used to retrieve session data from the server.</li><li>Redis as a Session Store: Redis provides several key advantages for session management. Its in-memory data storage allows for quick access to session data, resulting in improved performance. Redis also supports data persistence, ensuring session data is not lost even during server restarts. Additionally, Redis offers advanced data structures and operations that can enhance session management capabilities.</li><li>Storing and Retrieving Session Data: To use Redis as a session store, you can store session data as key-value pairs in Redis. The session ID can serve as the key, while the session data can be serialized and stored as the value. Redis commands such as SET, GET, EXPIRE, and DEL can be utilized to store, retrieve, set expiration, and delete session data.</li><li>Distributed Session Management: Redis’s distributed nature makes it an ideal choice for managing sessions across multiple application instances or servers. By using Redis Sentinel or Redis Cluster, you can ensure session data is available and consistent across a cluster of Redis nodes. This allows for seamless horizontal scaling and high availability.</li><li>Session Expiration and Revocation: Redis provides built-in features for session expiration and revocation. You can leverage Redis’s EXPIRE command to set a timeout for session data, ensuring sessions automatically expire after a certain period of inactivity. Additionally, Redis offers the ability to invalidate or revoke sessions by deleting the corresponding session data.</li><li>Handling Session Security: When using Redis as a session store, it’s crucial to implement proper security measures. This includes securing session data during transmission by using encryption (e.g., HTTPS) and implementing safeguards to prevent session hijacking or tampering. Redis itself provides options for secure connections and authentication, which should be enabled for production environments.</li></ol><p><strong><em>Now let’s see how we can apply what we have learned in real life in a spring boot based project.</em></strong></p><p>First of all , we need to configure our redis for session management using;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*wUhD0N5ghn4AujaAEMgnWQ.png" /></figure><p>Then we can create our controller and service layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*iWzT3z5ml_LTLwHXJP1rTA.png" /></figure><p>and service layer,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*0UbOUn4s5n0xCYIKoj5QGQ.png" /></figure><p>In this example, we have the UserController and UserService classes representing the controller and service layers, respectively.</p><p>The UserController class defines three endpoints: /login, /user, and /logout. The /login endpoint takes a username parameter, and the UserService&#39;s login method is called to handle the login process. The /user endpoint retrieves the user&#39;s session information from Redis using the sessionRepository and returns the logged-in username if available. The /logout endpoint deletes the user&#39;s session from Redis using the sessionRepository.</p><p>The UserService class provides the login method, which retrieves the session using the sessionRepository and sets the username attribute to the session. The session is then saved back to Redis using the sessionRepository.</p><p>By using these controller and service classes, you can implement the logic for user login, retrieval of user information, and logout using Redis as the session store.</p><blockquote>Conclusion: By using Redis as a session store, you can achieve scalable and distributed session management for your web applications. Redis’s fast in-memory data storage, advanced features, and support for distributed environments make it a powerful choice for session management.</blockquote><p><em>When implementing Redis as a session store, ensure proper security measures are in place and consider the specific needs of your application, such as session expiration, revocation, and distributed session management. By leveraging Redis’s capabilities, you can enhance the performance, scalability, and reliability of your session management infrastructure.</em></p><blockquote>Remember to handle session data serialization and deserialization correctly, considering the requirements and constraints of your programming language or framework. Regular monitoring, performance optimizations, and proper Redis configuration will help ensure a robust and efficient session management solution.</blockquote><p>Thanks for reading, you can access the github repository link from the link : <a href="https://github.com/alicanli1995/redis-deep-dive/tree/main/dive-5-sesion-store">click and gooo</a></p><p>Next dive is -&gt; <a href="https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-6-message-queue-ffcd02643454">Message Queue</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae1bdd7a6e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 4(LeaderBoard)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-4-leaderboard-7975f2e71b7c?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7975f2e71b7c</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[leaderboard]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 11:44:15 GMT</pubDate>
            <atom:updated>2023-07-08T21:35:13.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 4(LeaderBoard)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w58yBNswpeo-5xNV.jpg" /></figure><p>Introduction: Leaderboards are a common feature in many applications, allowing users to compete and compare their rankings. Redis, with its fast in-memory data store and powerful data structures, provides an excellent solution for implementing a scalable leaderboard. In this article, we will explore how to leverage Redis to build a leaderboard system that can handle millions of users and real-time updates.</p><ol><li>Understanding the Data Model: To create a leaderboard, we need to decide on the data model and the key components. Redis provides the Sorted Set data structure, which is ideal for ranking and sorting. Each user will be represented as a member in the Sorted Set, with their score serving as the basis for ranking. The score can be any numeric value, such as points, levels, or ratings.</li><li>Storing User Scores: When a user performs an action that affects their score, we use Redis commands to update the leaderboard. For example, to add or update a user’s score, we can use the ZADD command to add the user with their score to the Sorted Set. If the user already exists, their score will be updated.</li><li>Retrieving Leaderboard Rankings: To display the leaderboard rankings, we can use Redis commands such as ZREVRANGE or ZREVRANK to fetch a specific range of users or their ranks. We can also retrieve additional information, such as the user&#39;s score, by using commands like ZSCORE.</li><li>Pagination and Pagination: When dealing with large leaderboards, it’s important to implement pagination and caching strategies. Redis provides commands like ZREVRANGE with offset and limit parameters to fetch a specific page of leaderboard results. Caching popular leaderboard pages can help reduce the load on Redis and improve performance.</li><li>Real-time Updates: To handle real-time updates, Redis offers the Pub/Sub messaging system. Whenever a user’s score changes, we can publish a message to a specific channel, indicating the score update. Subscribers, such as connected clients or backend services, can listen to the channel and update the leaderboard in real-time.</li><li>Handling Ties and Additional Ranking Factors: Redis Sorted Sets handle ties naturally. Users with the same score will be ranked based on the lexicographical order of their member names. If you need to consider additional factors for ranking, such as timestamps or secondary scores, you can use a combination of Redis data structures or additional Sorted Sets.</li></ol><blockquote><strong>Now let’s take a look at the use case with a spring boot project.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*VEiOOIsceoOfEm9ahQLlLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1Ls3VXeJ9YL0CVHCSnMyA.png" /></figure><p>The updateScore endpoint uses the zadd command of Redis to update the user&#39;s score and add the user to the Sorted Set named &quot;leaderboard&quot;. The getLeaderboard endpoint retrieves the leaderboard within the specified range using the zrevrangeWithScores command of Redis and prints the result to the console.</p><p>Inside the main method, there is a sample usage scenario. First, we update the scores of some users, and then we retrieve the leaderboard. In this example, the getLeaderboard method is used to retrieve the top 3 users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*PyMaA5qwnFuZ70BBQ4ZZXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5jY4uIkyl82wkDUALI9Xg.png" /></figure><p>The Jedis library used in this example is a popular Redis client library for Java, used for communication between Redis and Java. When the example is executed, the top three positions in the leaderboard will be printed to the console.</p><p>You can customize and adapt this example to create your own leaderboard using Redis by updating it with your Redis connection details and modifying it according to your specific needs.</p><p><em>Conclusion: By leveraging Redis and its powerful Sorted Set data structure, we can easily implement a scalable and real-time leaderboard system. Redis provides efficient commands for storing, retrieving, and updating leaderboard data, making it an excellent choice for handling millions of users and frequent score updates.</em></p><p>When building a leaderboard with Redis, consider the specific requirements of your application, such as pagination, caching, and real-time updates. By tailoring the implementation to your needs, you can create a highly performant and engaging leaderboard experience for your users.</p><blockquote>Remember to fine-tune your Redis configuration and consider strategies for handling concurrent updates and maintaining data consistency. Regular monitoring and optimizations will help ensure the smooth operation of your Redis-powered leaderboard.</blockquote><p>Thanks for reading, you can access the github repository link from the link :<a href="https://github.com/alicanli1995/redis-deep-dive/tree/main/dive-4-leaderboard/leaderboard"> click and gooo</a></p><p>Next dive is -&gt; <a href="https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-5-session-store-3ae1bdd7a6e0">Session store</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7975f2e71b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 3 (Rate Limitting)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-3-rate-limitting-96799659f710?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/96799659f710</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 11:28:42 GMT</pubDate>
            <atom:updated>2023-06-30T11:44:33.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 3 (Rate Limitting)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MCsm0_-FBsIpOE_k.png" /></figure><p>Introduction: Rate limiting is a common technique used to control the number of requests or actions that can be performed within a given time frame. Redis, with its fast and efficient operations, provides an excellent solution for implementing rate limiting in your applications. In this article, we will explore how to use Redis to create a rate limiter and prevent abuse or excessive resource consumption.</p><ol><li>Setting Up Redis: Before implementing rate limiting with Redis, you need to have Redis installed and running on your machine or server. You can follow the official Redis documentation for installation instructions. Once Redis is up and running, you can proceed with implementing the rate limiter.</li><li>Implementing the Rate Limiter: To implement a rate limiter with Redis, we will utilize the Token Bucket algorithm. The Token Bucket algorithm allows a specified number of tokens (representing requests) to be consumed within a given time period. Redis provides the necessary data structures and commands to implement this algorithm effectively.</li></ol><ul><li>Step 1: Determine the rate limit parameters: Decide on the maximum number of requests allowed per second (or any desired time unit) and the number of tokens (requests) to replenish within that time frame.</li><li>Step 2: Initializing the rate limiter: Use Redis’ SET command to initialize a counter for each user or client, representing the number of available tokens. Set an expiration time for the counter to reset it automatically after the desired time frame.</li><li>Step 3: Consuming tokens: When a request is made, check if the counter for the user or client has sufficient tokens available. If tokens are available, decrement the counter by one and proceed with the request. If there are no tokens available, reject or throttle the request.</li><li>Step 4: Token replenishment: Use Redis’ INCRBY command to replenish the token counter at a predefined rate. Execute this command periodically to ensure a continuous supply of tokens.</li></ul><p>3. Integration with your application: Integrate the rate limiter logic into the relevant parts of your application. For example, you can add the rate limiting check to your API endpoints or request processing pipelines.</p><p>4 . Handling rate-limited requests: When a request exceeds the rate limit, you can respond with an appropriate HTTP status code (e.g., 429 Too Many Requests) or a custom error message. Additionally, you can provide headers in the response indicating the number of remaining tokens and the time until the rate limit resets.</p><p><strong><em>The project showcases the following key components and features:</em></strong></p><ol><li>Redis Integration: The project demonstrates how to configure the Redis connection in a Spring Boot application using the Spring Data Redis library. It sets up the necessary dependencies and provides the Redis connection details, including the host and port, in the application configuration.</li><li>Rate Limiter Service: The “RateLimiterService” class encapsulates the rate limiting logic. It utilizes Redis as a backend storage to enforce rate limits based on the number of requests per specified time frame. The service uses Redis atomic operations to ensure thread-safe increments and expires the counters automatically.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*0iw0li78XSIz4TL__4C2Aw.png" /></figure><ol><li>Rate Limiting Configuration: The project illustrates how to configure the rate limiting parameters in the application. It includes properties such as the maximum number of requests allowed per minute, the duration of the time frame, and the Redis key prefix for rate limiting.</li><li>Integration with Controller: The example project integrates the rate limiter service with a Spring MVC controller. It showcases how to annotate specific endpoints or controller methods with rate limiting annotations, enabling automatic rate limiting enforcement.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yroNPExUqPWaa9rXIxxIUA.png" /></figure><ol><li>Response Handling: The project demonstrates how to handle rate-limited requests by returning appropriate HTTP responses. When a request exceeds the rate limit, the controller responds with an HTTP status code of 429 (Too Many Requests) and includes relevant headers indicating the rate limit details, such as the number of remaining requests and the time until the rate limit resets.</li></ol><p>This example project serves as a practical guide for implementing rate limiting using Redis in a Spring Boot application. It emphasizes the simplicity and effectiveness of Redis as a high-performance data store for rate limiting purposes. By leveraging Redis’ features and the integration with Spring Boot, developers can easily incorporate rate limiting capabilities to protect their APIs and ensure fair resource allocation.</p><p><em>Please note that the example project provides detailed source code, including the necessary configuration files and sample code snippets, to help you understand and implement rate limiting with Redis in your Spring Boot applications effectively.</em></p><blockquote>Conclusion: Implementing rate limiting with Redis allows you to protect your applications from abuse, ensure fair resource allocation, and maintain system stability. By utilizing Redis’ data structures and commands, you can easily implement a scalable and efficient rate limiter. Redis’ speed and atomic operations make it a reliable choice for handling rate limiting requirements in various use cases.</blockquote><p>Remember to fine-tune your rate limit parameters based on your application’s needs and traffic patterns. Regular monitoring and adjustments will help you maintain an optimal rate limiting strategy.</p><p>By following the steps outlined in this article, you can successfully implement a rate limiter using Redis and enhance the reliability and security of your applications.</p><p>Thanks for reading, you can access the github repository link from the link : <a href="https://github.com/alicanli1995/redis-deep-dive/tree/main/dive-3-rate-limit">click and gooo</a></p><p>Next dive is -&gt; <a href="https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-4-leaderboard-7975f2e71b7c">Leaderboards</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96799659f710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 2 (Counter Usage)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-2-counter-usage-9b4d3eeaccc0?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b4d3eeaccc0</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[counter]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 07:46:17 GMT</pubDate>
            <atom:updated>2023-06-29T11:28:54.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 2 (Counter Usage)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*jdy7howCt9f7yMUd.jpg" /></figure><blockquote>Introduction: Redis is an in-memory key-value store that is widely used as a distributed database. With its flexibility and speed, Redis can be utilized in various scenarios. In this article, we will focus on how Redis can be used as a counter. Redis is optimized for fast counting operations and provides several useful commands.</blockquote><ol><li>Installation and Connection: Before getting started with using Redis, you need to have Redis installed on your machine or server. You can follow the download and installation instructions from the official Redis website. Once the installation is complete, you will need a client to connect to Redis. For example, you can use Jedis or Lettuce libraries for Java.</li><li>Incrementing the Counter Value: The fundamental operation of using Redis as a counter is to increment the counter value. Redis provides the INCR command for this purpose. Using this command through the client, you can increment the counter value. For example, you can perform a counter increment operation as shown below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*i0F_HmIdaB3t9ZVmQ0qCbg.png" /></figure><p>In this example, a counter named my_counter is created, and its value is incremented by 1. The incr command increments the counter value and returns the new value.</p><p>3. Decrementing the Counter Value: Redis also provides a command for decrementing the counter value. The DECR command decreases the counter value by 1 and returns the new value. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*oVs3Gj-9qTj1V9_jseKM1Q.png" /></figure><p>In this example, the value of a counter named my_counter is decreased by 1.</p><p>4. Resetting the Counter Value: When you want to reset the counter value, you can use the SET command. This command sets the value of the specified key. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*88Z20FDmRiWYbyF8J-s_4g.png" /></figure><p>In this example, the value of a counter named my_counter is set to 0. Then return value is ‘OK’.</p><blockquote>Conclusion:</blockquote><blockquote>Redis provides a simple yet powerful mechanism for using it as a counter. By utilizing the INCR, DECR, and SET commands, you can easily implement counting functionalities in your applications. Whether it&#39;s tracking page views, incrementing scores, or any other counting scenario, Redis proves to be an efficient and reliable solution.</blockquote><h4>What’s the use cases for increment , decrement …</h4><ol><li>Real-Time Analytics: Redis can be used as a counter to track and analyze real-time data in various analytics scenarios. By incrementing counters for specific events or actions, you can collect metrics and gain insights into user behavior, system performance, or application usage patterns.</li></ol><p><em>Use case: Counting the number of page views, clicks, or user interactions in real-time to generate live analytics dashboards or personalized recommendations.</em></p><p>2. Social Media Metrics: Redis can serve as a counter for tracking social media metrics such as likes, shares, or followers. By incrementing counters associated with specific posts, users, or hashtags, you can measure engagement levels and identify popular content.</p><p><em>Use case: Keeping track of the number of likes, comments, and shares on social media posts to determine trending topics or influential users.</em></p><p>3. Queuing Systems: Redis counters can be employed as a simple and efficient way to manage task queues or message queues. By using counters to assign unique IDs or sequence numbers to incoming tasks or messages, you can ensure proper ordering and processing of queued items.</p><p><em>Use case: Implementing a job queue where each task is assigned a unique ID using Redis counters, allowing workers to process tasks in a coordinated manner.</em></p><p>4. Inventory Management: Redis counters can be utilized to manage and track inventory levels of products or resources. By incrementing or decrementing counters based on incoming orders or stock changes, you can monitor stock availability in real-time.</p><p><em>Use case: Tracking the stock levels of products in an e-commerce store to prevent overselling or automate reordering processes.</em></p><p>5. User Activity Tracking: Redis counters can be employed to monitor and measure user activity within an application. By incrementing counters associated with specific actions or events, you can analyze user behavior patterns, identify trends, and personalize user experiences.</p><p><em>Use case: Counting the number of logins, searches, or purchases made by individual users to generate personalized recommendations or identify power users.</em></p><p>6. Gaming Scoreboards: Redis counters can power gaming scoreboards and leaderboards by tracking and updating player scores. By incrementing counters associated with player scores, you can maintain real-time rankings and provide a competitive environment.</p><p><em>Use case: Building a leaderboard for an online game where player scores are continuously updated using Redis counters, allowing players to compete and compare their achievements.</em></p><blockquote>These are just a few examples of how Redis as a counter can be applied in different use cases. By leveraging Redis’ fast and atomic increment/decrement operations, you can efficiently track and manage various metrics, activities, and real-time data in your applications.</blockquote><p>Thanks for reading, you can access the github repository link from the link : <a href="https://github.com/alicanli1995/redis-deep-dive/tree/main/dive-2-counter/counter">click and gooo</a></p><p>Next dive is -&gt; <a href="https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-3-rate-limitting-96799659f710">Rate Limiter with redis.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b4d3eeaccc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s deep dive Redis, except cache usage … Step 1 (Distributed Locks)]]></title>
            <link>https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-1-distributed-locks-53d03983ba17?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/53d03983ba17</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 20:38:22 GMT</pubDate>
            <atom:updated>2023-06-29T07:47:09.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s deep dive Redis, except cache usage … Step 1 (Distributed Locks)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZAPEO5AO1XSN0EJ2Ql4jg.png" /></figure><p>In this medium article, we will cover Redis with its different features, except cache usage.</p><p>First we will talk about the Distributed locks mechanism,</p><p>First of all, what are Distributed locks ?</p><p>Distributed locks are a mechanism used in distributed systems to coordinate access to shared resources by multiple processes or nodes. In a distributed system, multiple processes or nodes may need to access the same resource simultaneously, which can lead to conflicts and inconsistencies if proper coordination is not established.</p><p>A distributed lock allows processes or nodes to coordinate access to a shared resource by acquiring a lock on that resource. When a process or node acquires a lock, it gains exclusive access to the resource, and no other process or node can modify it until the lock is released.</p><p><strong>Now that we understand exactly what it is, let’s take a look at how it relates to Redis,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*mSlbDdzqChCLq3vn.png" /></figure><blockquote>Redis is a popular in-memory data store that supports distributed locks as one of its core features. Redis provides a robust implementation of distributed locks using the “SETNX” (set if not exists) command, which allows a client to acquire a lock on a resource if and only if the resource is not already locked by another client.</blockquote><p>To acquire a lock, a client sends a “SETNX” command to Redis with a unique lock identifier as the key and a unique value as the value. If the key does not already exist, Redis sets the key-value pair and returns a success response, indicating that the client has acquired the lock. If the key already exists, Redis returns a failure response, indicating that the lock is currently held by another client.</p><p>To release the lock, the client sends a “DEL” (delete) command to Redis with the lock identifier as the key. Redis deletes the key-value pair, releasing the lock and allowing other clients to acquire it.</p><p>Redis distributed locks are particularly useful for implementing distributed systems that require exclusive access to shared resources, such as distributed job queues or distributed caching systems. By using Redis distributed locks, developers can ensure that concurrent processes or nodes do not interfere with each other, thereby preventing data inconsistencies and ensuring data integrity.</p><p><strong>We have talked about enough book knowledge, now it’s time to apply it!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*NZDboVnn2jn8cTEoOEB3HQ.png" /></figure><p>1. Process 1 wants to access a resource, but the resource might be undergoing mass updates or being used by others.</p><p>2. Process 1 sends a request to Redis and tries to acquire a lock. If process 1 can’t acquire the lock, it waits to access the resource.</p><p>3. Process 2 also wants to access the same resource, but the resource might be in use by process 1 or undergoing mass updates.</p><p>4. Process 2 sends a request to Redis and tries to acquire the same lock. If process 2 acquires the lock while it’s still open, process 1 waits to access the resource.</p><p>5. Process 3 also wants to access the same resource, but the resource might be in use by process 1 or process 2.</p><p>6. Process 3 sends a request to Redis and tries to acquire the same lock. If process 3 acquires the lock while it’s still open to process 1 and process 2, process 3 waits to access the resource.</p><p>7. Process 1 completes its task after acquiring the lock to access the resource, and it sends a request to Redis to release the lock.</p><p>8. Redis detects the release of the lock and processes the requests from process 2 and process 3. Redis allows one of the waiting processes to acquire the lock.</p><p>9. Either process 2 or process 3 tries to acquire the lock and is successful.</p><p>10. The successful process uses the resource and sends a request to Redis to release the lock.</p><p>Thus, Redis Distributed Locks helps to manage interactions of multiple processes working on the same resource and provides sequential access to the resource.</p><blockquote><strong><em>Let’s doing example this explain more with real life example ,</em></strong></blockquote><p>Now, let’s assume we are using a financial application and we have the wallet information in redis cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHbQTjxDuZNlwZcOf9tBYw.png" /></figure><p>How did we avoid this problem as described in the picture? <br>For example, we have locked the data when the client adds balance and automatically unlocked this data when it is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC1zzRQmt0z2b2gwJNw1Jg.png" /></figure><p>You can access the source code of the project and the rest of the code from this link : <a href="https://github.com/alicanli1995/redis-deep-dive">Click for repo !</a></p><p>Next deep dive is counter : <a href="https://medium.com/@alicanli1995/lets-deep-dive-redis-except-cache-usage-step-2-counter-usage-9b4d3eeaccc0">Click and gooo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53d03983ba17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAGA Pattern & Outbox Pattern With Spring Boot Event Driven Project]]></title>
            <link>https://medium.com/@alicanli1995/saga-pattern-outbox-pattern-with-spring-boot-event-driven-project-2ad1dddfce54?source=rss-a06c725b2a0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad1dddfce54</guid>
            <dc:creator><![CDATA[Ali CANLI]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 12:27:08 GMT</pubDate>
            <atom:updated>2023-03-19T12:45:09.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*DTwOk8oO0Nbj0SE0_30L9A.png" /></figure><blockquote>The Saga pattern is a design pattern used in distributed systems to manage and coordinate long-running transactions. It is used to maintain consistency between multiple services that participate in a complex transaction. The Saga pattern is an alternative to the two-phase commit protocol, which is not always practical in distributed systems due to its blocking nature.</blockquote><p>In a Saga pattern, a transaction is divided into a sequence of smaller, loosely coupled transactions, known as saga steps. Each saga step represents a single service or operation in the overall transaction. Each step of the Saga updates its own database and publishes an event to signal that it has completed. If a step fails, the Saga initiates a compensating transaction to undo the effects of the previous steps.</p><p><strong><em>Advantages of Saga Pattern:</em></strong></p><ul><li>Decentralization: The Saga pattern allows for each service to be responsible for its own transaction, making the system more decentralized and less reliant on a central coordinator.</li><li>Scalability: Because Saga steps can be performed asynchronously, the pattern is highly scalable.</li><li>Resiliency: The Saga pattern provides resiliency against failures by allowing compensating transactions to be executed in case of a failure.</li></ul><p><strong><em>Disadvantages of Saga Pattern:</em></strong></p><ul><li>Complexity: Implementing a Saga pattern can be complex as it requires coordination between multiple services, and each step must be implemented with a compensating transaction in case of a failure.</li><li>Consistency: The Saga pattern relies on eventual consistency, which means that updates to the system may not be immediately visible to all services participating in the transaction.</li><li>Durability: Since Saga transactions can be long-running, ensuring durability in the face of failures can be challenging.</li></ul><p>The Saga pattern is commonly used in microservices architectures, where multiple services may need to coordinate to perform a complex transaction. It is also used in event-driven architectures where services communicate through events.</p><p>In summary, the Saga pattern provides an alternative approach to managing long-running distributed transactions in a way that is scalable, resilient, and decentralized. However, it can also introduce complexity and eventual consistency issues, and it may not be suitable for all use cases. As with any design pattern, it is important to carefully consider the advantages and disadvantages before adopting it in a system.</p><p><strong><em>There are two types of saga patterns:</em></strong></p><ol><li><strong><em>Choreography-based Saga Pattern:</em></strong> In this pattern, each service publishes events to communicate with other services. Each service subscribes to events from other services and reacts to them. When a service receives an event, it updates its state and publishes events for other services to react to. This pattern relies on the event-driven architecture to coordinate transactions across services. There is no centralized coordinator, and each service has its own local transaction manager.</li><li><strong><em>Orchestration-based Saga Pattern</em></strong>: In this pattern, there is a centralized orchestrator that coordinates the transactions across services. The orchestrator sends commands to the services to initiate transactions and receives responses from them. It also sends compensating commands to undo transactions in case of failures. The orchestrator has a global view of the transaction and decides which services to invoke and in what order. This pattern is more suitable for complex transactions with many steps.</li></ol><p>The working logic of a Saga pattern is to break a long-running transaction into smaller sub-transactions. Each sub-transaction is executed in a separate service, and the entire transaction is coordinated through a saga. A saga is a long-running transaction that manages the sequence of sub-transactions and compensates for failures. If a sub-transaction fails, the saga undoes the completed sub-transactions by invoking their compensating transactions. This ensures that the transaction remains consistent even in the face of failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9AyMO93aXcKqwOxe7h86Xw.png" /></figure><blockquote>The Outbox pattern is a design pattern used in distributed systems to ensure reliable event-driven communication between microservices. The pattern is used to address the issue of atomicity and consistency when publishing messages/events to an external messaging system, such as Kafka or RabbitMQ.</blockquote><p>In traditional microservice architecture, when a service generates an event, it publishes the event to the messaging system and updates its own database. However, in the event of a failure, the message could be published, but the database update could fail, leading to data inconsistency. The Outbox pattern solves this problem by separating the transaction for updating the database and publishing the message.</p><p>The Outbox pattern works by using a separate database table called the “Outbox” to store the events that need to be published. When a service generates an event, instead of publishing it directly, it stores the event in the Outbox table within the same transaction that updates its own database. A separate process or thread called the “event processor” reads the events from the Outbox table and publishes them to the messaging system.</p><p><strong><em>Advantages of the Outbox pattern include:</em></strong></p><ol><li>Atomicity: The pattern ensures that the database update and the publishing of the message are performed atomically, preventing any data inconsistencies.</li><li>Reliability: The pattern ensures that all events are reliably published, even in the case of failures.</li><li>Scalability: The pattern allows for independent scaling of the event processor, as it can be run on a separate server or cluster.</li></ol><p><strong><em>Disadvantages of the Outbox pattern include:</em></strong></p><ol><li>Complexity: The pattern adds complexity to the system by introducing a new database table and an event processor.</li><li>Latency: The pattern introduces additional latency in the system, as the events need to be processed and published separately.</li></ol><p>The Outbox pattern is commonly used in systems that rely on event-driven communication, such as microservices architectures and event sourcing systems. It is also commonly used in conjunction with other patterns, such as the Saga pattern, to ensure consistent and reliable communication between services.</p><p><strong><em>Now we will continue with the example…</em></strong></p><p>The repo for the example is at <a href="https://github.com/alicanli1995/uber-api-saga-outbox-event-driven-microservices">here</a>. The project is designed using orchestration-based saga. Our overall goal in the project is to make a taxi hailing application. All processes here are managed with events, local transactions are handled with outbox pattern while transactions between microservices are handled with saga.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oDV_x_-7r_tlozwd.png" /></figure><p>In this project, the customer microservice acts as the entry point for the entire saga process. The customer raises an event to call a taxi, and a PaymentRequestEvent goes to the payment service first. The payment service handles this event internally and changes the status of the ongoing transaction, then fires a new event. The user service captures this event and, if there are no issues, sends an event to the driver service. The driver service consumes this event, handles it according to the happy path, changes the saga status, and fires a new event. Finally, the customer service consumes this event, and the saga transaction ends. Each service uses separate transactions when handling events within their own services, and these transactions are managed through outbox tables. In case of an error in any step of the transactions, compensable transactions are responsible for throwing rollbacks to the whole process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*7ABO6VrULvLw8Mho.png" /></figure><p><strong><em>Summary</em></strong><em>:</em></p><p><em>Thanks to the patterns used in the project, we achieved a highly consistent application by preventing possible transactional losses. You can access the entire codebase and front-end application of the project from the</em><a href="https://github.com/alicanli1995/uber-api-saga-outbox-event-driven-microservices"><em> </em><strong><em>project link.</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad1dddfce54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>