<?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 Rahul soni on Medium]]></title>
        <description><![CDATA[Stories by Rahul soni on Medium]]></description>
        <link>https://medium.com/@rahuldsoni2001?source=rss-968e65a55b93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*tnmSKe5MV52eEp_VcUxyLw.jpeg</url>
            <title>Stories by Rahul soni on Medium</title>
            <link>https://medium.com/@rahuldsoni2001?source=rss-968e65a55b93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:41:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahuldsoni2001/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[Making Distributed Cache — 1]]></title>
            <link>https://medium.com/@rahuldsoni2001/making-distributed-cache-1-adf69e920dcb?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf69e920dcb</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 09:53:47 GMT</pubDate>
            <atom:updated>2026-03-01T09:53:47.135Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about building a distributed cache like Redis and learning the concepts around it.</p><p>Things we will cover</p><ul><li>RESP protocol communication</li><li>Client interface to interact with Redis</li><li>Handling load</li><li>Persistence in both modes, just like Redis: append-only file and RDB file</li><li>Crash recovery</li><li>Replication (in next part)</li><li>Master / Replica architecture (in next part)</li></ul><p>Lets dive in.</p><p>First and foremost, the most essential part is communication between the client and server. A cache does not work well with an HTTP-based protocol because we need to establish a connection with every request this takes time at scale, following the three-way handshake, then the payload exchange, and then freeing the resource, which is too slow.</p><p>We will proceed with WebSockets and reuse the already established connection channel, which will help conserve resources at scale.</p><p>Redis works using the RESP protocol, so I created a small implementation of this protocol for parsing and transferring bytes over the channel. Redis docs for <a href="https://redis.io/docs/latest/develop/reference/protocol-spec/">RESP</a> and <a href="https://github.com/r4hu1s0n7/DistributedCacheServer/blob/master/DistributedCacheServer/RESP.cs">my implementation here</a> for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCasS6XgcG998FN6JuX0vg.jpeg" /><figcaption>basic client server based cache architecture</figcaption></figure><p>Whenever the client receives a command, it establishes a connection with the server. The commands are serialized and converted into bytes, then transferred to the server, which deserializes them and sends them to the command parser module.</p><p>I have kept only the essential commands that serve the purpose of a cache: GET, SET with expiry, and a batch SET to simulate how load is handled when multiple commands hit the server.</p><h3># Client Side</h3><ol><li><a href="https://github.com/r4hu1s0n7/DistributedCacheClient/blob/master/DistributedCache/Program.cs">Command Interface file</a></li><li><a href="https://github.com/r4hu1s0n7/DistributedCacheClient/blob/master/DistributedCache/PersistentConnectionManager.cs">Connection Manager file</a></li><li><a href="https://github.com/r4hu1s0n7/DistributedCacheClient/blob/master/DistributedCache/RESP.cs">RESP file</a>, <a href="https://github.com/r4hu1s0n7/DistributedCacheClient/blob/master/DistributedCache/appsettings.json">Config file</a></li></ol><p>The main point of focus here is the Connection Manager, which is essential. What it does is reuse the socket connection if the next command arrives within the timeout window, defaulting to 5 seconds.</p><p>So when we are under bulk load, the Connection Manager reuses the already established connection to avoid the handshake overhead, saving both time and resources. Additionally, the call to the server is non-blocking as soon as one command is sent, we can send another without the thread waiting for the IO to complete. When the server sends back the response, the thread resumes.</p><h3># Server Side</h3><p>The server receives raw bytes, converts them into RESP format, deserializes them, and then passes them to the command parser.</p><h4>## Command</h4><p>It makes sense of each piece, finds the command type, keys, values, and other parameters, and then executes it. The code here misses many things in terms of separation of responsibility this was made a year ago.</p><p>The architecture should be structured as follows: a stateless Command Parser that returns a Command object, a Command itself as just a data object, and a ProcessCommand module to execute it and perform the operation. This should be followed by the Command Pattern for each command, which can be inherited to implement the specific operation.</p><p><a href="https://github.com/r4hu1s0n7/DistributedCacheServer/blob/master/DistributedCacheServer/Command.cs">Command file</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7hn25MFGMrv9VNk-bzgsw.png" /></figure><h4>## Storage</h4><p>This class is my access point to all the in-memory key-value pairs. It stores and fetches key-based objects, and that’s it. One additional thing it does is make a copy of the entire memory map.</p><p><a href="https://github.com/r4hu1s0n7/DistributedCacheServer/blob/master/DistributedCacheServer/Command.cs">Storage file</a></p><h4>## Persistence</h4><p>Persistence in Redis is handled in 2 main ways: keeping a snapshot file which is a snapshot of the memory state, and the other is a log of all write commands.</p><p>### RDB Snapshot</p><p>In this method, I have created a scheduler that runs every x minutes and takes a copy of memory and saves it to a file. Files are saved in FIFO order, so the oldest file is removed and the latest is added, keeping at least 5 files saved in the directory — depending on which version of the snapshot the program wants to restore.</p><p>The file is stored with a checksum to validate that the file data is not corrupted.</p><p>In Redis, this is performed by creating a fork of the current process. Since Windows does not have the option of forking, I created a deep copy instead, so the RDB operation does not conflict with the ongoing transactions of the main memory space.<a href="https://github.com/r4hu1s0n7/DistributedCacheServer/blob/master/DistributedCacheServer/RDBOperations.cs">RDB file</a></p><p>### Append Only File</p><p>In this method, every write command or related command is kept in a log file. This is written instantly, and in my project, asynchronously. RDB loses some data that is created between two snapshots, but this method loses no data it records every modification and addition to memory.</p><p>To restore, just replay the file and it will restore the memory state as it was. There is also a compaction process that stops the file from growing infinitely, but I have not added that in this project.</p><p><a href="https://github.com/r4hu1s0n7/DistributedCacheServer/blob/master/DistributedCacheServer/AOFOperations.cs">AOF file</a></p><p>Which one to choose?</p><p>Choose both, based on the scenario. No data loss is a requirement for most use cases, but transferring the AOF file to a secondary replica is not the correct approach since it can get too large. That’s where snapshots come in — they also take less time to restore since we don’t have to replay everything from the start.</p><p>This project allows you to select one or both persistence methods and lets you choose the restoration method.</p><p>In the next part, I will be adding Master/Slave replication along with state sync among replicas.</p><p>Thanks for reading.</p><p>feel free to connect with me on <a href="https://rahul-soni.com/">rahul-soni.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf69e920dcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Memcached at Facebook]]></title>
            <link>https://medium.com/@rahuldsoni2001/understanding-memcached-at-facebook-db8985734b1b?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/db8985734b1b</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[scaling]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 07:01:41 GMT</pubDate>
            <atom:updated>2025-04-29T07:01:41.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Simple Guide to High-Performance Caching</h3><p>If you’ve ever wondered how Facebook handles millions of users fetching data at lightning speed, it’s possible because of systems like Memcache. It is a network cache that helps Facebook serve data quickly while keeping things reliable. Main purpose of memcache is to provide frequently accessed data fast and save time in computing redundant information. Let’s look at how Facebook modified Memcache to operate at their massive scale and solve real-world challenges, based on their paper _”<a href="https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf">Scaling Memcache at Facebook.</a>”</p><p>But first, a quick look at:</p><h3>How Memcache Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZITxNSraZJUiPE1VwaVZQw.png" /></figure><p>The basic process is simple:</p><p><strong>For Reading Data:</strong></p><ol><li>Web server checks the cache first</li><li>If the data is there, it’s returned right away</li><li>If not, the server gets it from the database</li><li>The server saves this data in the cache before sending it back</li></ol><p><strong>For Writing Data:</strong></p><ol><li>The system just deletes the cached key instead of updating it</li><li>Deletion can happen multiple times without causing problems since it is idempotent operation</li><li>Fresh data gets added to the cache when needed next</li></ol><h3>Reducing Latency: Making Data Fetching Lightning Fast</h3><p>To fetch anything, server to server communication and server to cache communication is very common. The requested item can contain multiple parts retrieved from multiple services and different data sources, a single user request can consist of multiple back and forth trips across the cache, so reducing latency is big factor in serving overall request.</p><p>Facebook added few functionality around this to overcome this:</p><ol><li>Parallel Requests and Batching: instead of calling cache server for single item, application can batch multiple requests of keys and send it to Memcache for retrieval.</li><li>No Server to Server communication: so each Memcache server only cares about the keys it has, they don’t know if other Memcache server exist, so no need to preserve state. this helps simplifying logic and architecture overall.</li><li>UDP vs TCP usage: UDP is used for get requests to reduce latency (20% reduction compared to TCP) and TCP is used for set and delete operations for reliability. Web servers avoid inserting entries after errors to prevent overloading High memory demands of TCP connections make it expensive to maintain connections between every thread and server</li><li>Congestion Control for requests: Clients implement a sliding window mechanism, window increase of request are passing and shrinks as requests are failing</li></ol><p>Another key component Facebook introduced is <strong>Mcrouter</strong>, a proxy for Memcache servers. Instead of each application request creating its own connection to Memcache, Mcrouter acts as a middle layer. Applications can either use a client library or route requests through Mcrouter, which maintains a persistent connection pool to the Memcache servers. This approach reduces memory usage and connection overhead, making it the standard and preferred way to interact with Memcache at scale.</p><p>All the above approach reduce latency by either cutting down network trips i.e. through batching and Mcrouter, and connection overhead through no server-to-server communication, UDP. Also saving overloads through congestion control.</p><h3>Reducing Load: Avoiding Database Overload</h3><p>The main purpose of a cache is to reduce the load on the database by avoiding repeated fetching of the same data. However, in some scenarios, cache misses themselves become the reason for increased database calls. This not only affects performance and latency but also has a cascading impact on database load.</p><h4><strong>Stale State</strong></h4><p>This occurs when multiple servers try to write a value to a certain key, but due to being out of order, they end up overwriting each other’s updates, resulting in a value that’s not the latest.<br>For example, when Server A reads a key from cache and finds a miss, it queries the database for the value. Meanwhile, Server B encounters the same scenario — cache miss and DB query. If Server B gets the new value and writes it first, and then Server A writes its (now stale) value, we end up in an inconsistent or stale state.</p><p><strong>How it’s solved</strong></p><ul><li>Server A requests “user_score” (100), gets a cache miss, and receives a 64-bit <strong>lease</strong> token from Memcached.</li><li>Server B requests the same key, but since A has the lease, B gets a “wait” notification instead of a token.</li><li>Server A calculates the new score (110), uses its lease token to set it, and Memcached accepts it.</li><li>Server B retries after a short delay, sees the updated 110, and proceeds without overwriting — making the operation atomic.</li></ul><h4>Thundering Herd</h4><p>This problem occurs when a key is requested by many clients at the same time, leading all those requests to hit a cache miss and go straight to the database.</p><p><strong>How it’s solved</strong></p><ul><li>Memcached limits token issuing to once every 10 seconds per key by slightly modifying the lease approach, we can solve this problem too.</li><li>Subsequent requests within this period receive a “wait” notification.</li><li>Since the token holder typically sets data within milliseconds, waiting clients usually find the data in cache when they retry.</li></ul><h4><strong>Replication Within Pools</strong></h4><p>Whenever some keys which rise in demand and the load becomes too much for 1 server to handle, Memcache instead of splitting the keys between 2 servers to reduce the load, they choose replicating all these keys in 2 servers. The difference in overhead for retrieving 100 keys per request instead of 1 key is small.</p><p>For example each server stores 100 keys and each server can handle 500k requests/sec:</p><p>How to Scale Up to <strong>1M requests/sec</strong>?</p><p><strong>Option 1: Split Key Space</strong></p><ul><li>Add another server.</li><li>Each server holds <strong>half the keys</strong> (50 keys each).</li><li>Now, for every client request (asking 100 keys):</li><li>Client must <strong>split the request into 2 parts</strong> (50 keys to server A, 50 keys to server B).</li><li><strong>Each server still handles 1M small requests</strong> overall → no real load reduction.</li></ul><p><strong>Option 2: Replicate Keys</strong></p><ul><li>Instead of splitting keys, <strong>copy all 100 items to both servers</strong>.</li><li>Now, <strong>each server has the full set</strong>.</li><li>A client can <strong>send the full request</strong> (for 100 keys) to <strong>any one server</strong>.</li><li><strong>Load gets divided</strong> → each server handles only <strong>500k requests/sec</strong>.</li></ul><h4>Handling Failures</h4><p>Memcache failures, even on a small scale, can lead to serious backend overload and cascading system failures, especially if retrying requests overwhelms the database. To handle this, a small set of dedicated servers called <strong>Gutter</strong> (about 1% of the Memcache cluster) temporarily take over the role of failed servers. When a Memcache request fails, the client retries it through the Gutter pool. If the data isn’t found there, the client queries the database and stores the result in Gutter. These entries expire quickly, reducing complexity and ensuring stale data doesn’t linger.</p><p>This approach is preferred over rehashing keys to other Memcache servers, which risks overloading them — especially if some keys are accessed much more frequently than others. By redirecting failed requests to idle Gutter servers, the system prevents load spikes, protects backend systems, and helps maintain system stability even during partial outages.</p><h3>Performance Improvements</h3><h4>Dynamic Hashtable</h4><p><strong>Original Problem:</strong> The original memcached used a fixed-size hash table. As more data was added, hash collisions would increase, causing lookup times to degrade toward O(n) complexity (linear search through collision chains).</p><p><strong>Implementation:</strong> They modified memcached to automatically resize the hash table as the data volume grew. This meant:</p><ul><li>The system could detect when the hash table was becoming too densely populated</li><li>It would allocate a larger hash table when needed</li><li>Keys would be rehashed into the new, larger table</li><li>This maintained O(1) lookup performance regardless of data size</li></ul><p>This optimization ensures consistent performance even as the cache grows to hold millions of records</p><h4>Global Lock and multi-thread access</h4><p><strong>Original Problem:</strong> The original Memcache was single-threaded, which couldn’t fully utilize modern multi-core servers and limited throughput.</p><p><strong>Implementation:</strong> They modified memcached to:</p><ul><li>Create multiple worker threads to handle requests in parallel</li><li>Implement a global lock to protect shared data structures from concurrent access</li><li>Allow threads to process different requests simultaneously when not accessing shared data</li></ul><h4>Per-thread UDP Ports</h4><p><strong>Original Problem:</strong> In the multi-threaded version, threads would contend for network resources when sending replies, creating a bottleneck.</p><p><strong>Implementation:</strong> They assigned each thread its own dedicated UDP port:</p><ul><li>Each thread exclusively owns one UDP port for sending responses</li><li>This eliminates contention between threads when transmitting data</li><li>It distributes interrupt processing overhead across CPU cores</li><li>Network packet handling becomes more efficient</li></ul><p>This optimization reduced thread contention at the network layer and improved overall throughput, particularly for UDP traffic.</p><h3>New Adaptive Slab Allocation System</h3><p>Memcache had fixed slab allocation system which was not very useful when usage pattern changed</p><ul><li>If item sizes shifted (e.g., more small items, fewer large items)</li><li>Memory remained locked in slab classes that no longer needed it</li><li>Other slab classes could be constantly evicting items despite available memory elsewhere</li><li>This resulted in poor hit rates</li></ul><h4>New Adaptive Solution</h4><p>Facebook made an algorithm that redistribute the memory among needy servers and avoids memory fragmentation which they otherwise have to deal with shifting keys and background processes.</p><p>Memcached organizes memory into “slab classes” — groups of uniformly sized chunks designed to store items efficiently</p><ol><li><strong>Identifying Needy Slab Classes</strong>:</li></ol><ul><li>The system looks for classes that are actively evicting items</li><li>The next item to be evicted must be at least 20% more recently used than the average of the least recently used items in other slab classes</li></ul><p><strong>2. Memory Transfer Mechanism</strong>:</p><ul><li>When a needy class is found, the system identifies the slab class with the least recently used item</li><li>It frees that slab (1MB) from the “donor” class</li><li>It transfers that memory to the “needy” class</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwnYnx5Fl6qbADUghJmZOQ.png" /></figure><p>Chunk sizes increase by a factor of 1.25 ( So given the smallest chunk size being 80 bytes means the next size is 100 bytes, and then 128 bytes). So what are the benefits and overheads of this technique? Well the first is that memory never fragments in memcached. As such there is no need to compact it, and as such there are no background processes needed to rearrange items store. In addition there is no need to ever clean memory, you can just overwrite the existing slab. There are some negatives. There is some overhead involved in managing this process and another is a slab items will never be fixed size so there will be some space still left inside the slabs, but on global level the whole slab can be reassigned and reused.</p><p>Thanks for reading, I hope you found this insightful.</p><p><em>You reach out to me for any suggestion or queries on </em><a href="/service/mailto:rahuldsoni@gmail.com"><em>rahuldsoni@gmail.com</em></a><em> or </em><a href="https://x.com/ssoonniiii"><em>https://x.com/ssoonniiii</em></a><em> or visit </em><a href="https://rahul-soni.com/"><em>https://rahul-soni.com/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8985734b1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Uber to 1000 Services: Insights and Learnings]]></title>
            <link>https://medium.com/cloud-native-daily/scaling-uber-to-1000-services-insights-and-regrets-8ffcbef6af91?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ffcbef6af91</guid>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Sun, 28 May 2023 04:04:11 GMT</pubDate>
            <atom:updated>2023-05-29T11:26:54.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*seU61vAbhzf623s-WvM8lA.png" /></figure><h4>This post is based on a few things that you should be prepared for while moving toward microservices.</h4><p><a href="https://www.linkedin.com/in/mranney/">Matt Ranney</a>, Chief System Architect at Uber, talked about the scale near 2015 that they had achieved, they were growing rapidly fast, before he joined Uber they had ~200 engineers, and in the next 1.5 years, it went to 2000. that’s a huge scale because they were expanding to other countries like China and India.</p><p>Interestingly, he points out the normal behavior we all possess: if you were to ask yourself to advise your younger self, your younger self is too naïve to take it and thinks they are in control. However, there are still a few things we all learn the hard way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Eq7-Ndi4cUmTOh3igZG29A.jpeg" /></figure><p><strong>But why microservices?</strong></p><p>Microservices allow teams to move and deploy quickly, without dependencies. Additionally, everyone is the owner and responsible for their service.</p><p>It is such a nice concept; you get to scale your part of the system, and the system scales well with each team focusing on their end.</p><p>Microservices come with complexity and expense. Everyone is aware of costs like how hard it is to debug in a distributed environment, but…</p><h3><strong>Let&#39;s talk about Less Obvious costs</strong></h3><ul><li><strong>Everything is a trade-off;</strong> you gain some, you lose some. There is always an opportunity cost. Whatever you do, it will have consequences. You just have to check if they matter to you.</li><li><strong>Build around problems:</strong> Sometimes, people choose to build something new rather than fix an old one. Because who wants to read old code? It makes people sick. Engineers would rather choose to create new solutions, rather than fix current ones.</li><li><strong>Talking to people:</strong> If you want to fix something, you must communicate with the teams responsible for maintaining it. But Engineers are like… Oh, so you’re saying I, the TechnoGod, should go and talk to people… with words? Let me mentally prepare myself for that.</li><li><strong>Keep your own biases: </strong>People love building things with their own biases. If there is scope for discussion then the team will decide something you might not be in favor of and to avoid that, Engineers build things with their biased framework and practice. And then defend why it&#39;s the best.</li></ul><p>Now all of this might not lead in favor of org though but still happens.</p><h3>Some other costs</h3><ul><li><strong>Too many languages:</strong> You have the flexibility to code in any of them, and a few quarters down (and maybe before that), you have N languages circulating. This leads to a hard time when reorganizing teams because people have achieved specialization, and if you want to unplug them and put them somewhere else, you have to give them time to learn, which maybe the organization can afford or maybe not.</li><li><strong>Language bias is also an issue:</strong> Python users consider themselves superior to Node, and X is better than Y, and things like that. This breaks the organization into fragments, and people play Node vs Flask on the foosball table.</li></ul><h3>Operations</h3><p>Since everything is disconnected, if Service A is blocked due to some issue/requirement unsatisfied, they have to wait. Either the other service stops their task and gives Service A priority, or they finish theirs first and then help Service A.</p><p>The other way around is for Service A people themselves to go and fix the problem. But what if they don’t know the framework Service B uses? What if their deployment is broken and needs some particular configuration to deploy, etc.?</p><p>Disconnecting is easy as it will help you grow, but you won’t be able to help others because you are… Disconnected.</p><h3>Performance</h3><ul><li>When everyone is using a different framework, measuring performance can become challenging because things vary from framework to framework.</li></ul><p>Teams create dashboards as per their convenience, which can cause confusion among teams.</p><p>Uber decided to have at least a common set of metrics that will be configured for every service, so you can monitor the stats of other services you are related to even if you are not working on it. To maintain some scale of uniformity among variable environments.</p><ul><li>There is a certain culture that always says you don&#39;t have to optimize that much on design or code, optimize for dev velocity instead, they say getting a machine will solve the optimization problem rather than hiring an engineer.</li></ul><p>This becomes hard to control with time, and one-day cloud bill will shoot up or any service will go down so, you need to have at least somewhat performant service.</p><p>Uber solved this problem by having minimal passing performance criteria for all services, that will be deployed. So you can have a safety net. Even if your service is not the most efficient but you have a track of stats that this service can handle. Pre-mature optimization is considered bad, but having some optimization is a must.</p><p>So maybe “good” is not required, but you at least “know” where you stand, which will eventually help.</p><h3>Tracing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*KkNKbmcNifJ5SXfR1YgnMw.png" /></figure><p>Here we have a simple tracing waterfall of the request cycle, it is easy to identify which part of the service request is causing the delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*Ph7sN29WmE31ZtxW8v0GXw.png" /></figure><p>This is now a different scenario, the single request here is doing many DB tasks, yes all DB calls are fast but why are there so many, here DB team will report yes each request is being served fast, and as per them DB is fine up and running, but there are thousands of DB calls each request, that&#39;s a N+1 case to DB call.</p><p>Things like these go untraced but because tracing tools help you can analyze this kind of scenario. Of course, you should prioritize these, otherwise keeping on making microservices gives instant gratification but at this kind of cost.</p><h3>Logging</h3><p>People tend to dump a variety of things in different capacities and formats whenever they see an opportunity. This may lead to inconsistency due to a lack of standardization, especially since logging comes free. some individuals tend to overload the system by logging every minor detail. This makes it hard to analyze the logs with tools like Hadoop or Elastic Search.</p><p>Here you have noticed that the pattern is standardization, yes scale is achievable but many things need to be standardized to some extent and I guess this is how orgs achieve scalability.</p><p>they built ZAP for logging. <a href="https://medium.com/codex/level-based-logging-in-go-with-uber-zap-a8a90aa40672">https://medium.com/codex/level-based-logging-in-go-with-uber-zap-a8a90aa40672</a></p><p>Twitter faced a similar issue, you can learn about it in this video by <a href="https://youtu.be/dOyCq_mMtdI">Arpit Bhayani</a> for that.</p><h3>Migration</h3><p>Everyone is always migrating something somewhere. As you grow you think you will migrate in non-peak time but again at the global level somewhere it is peak time in another part of the world, so be comfortable with migrations. Code level, data level, etc. for security and compliance reasons, just like there is always a release note of “bug fixes and performance improvements”.</p><h3>Load Testing</h3><p>Don’t get sad, once you are told oh you’ve built it and it took whole 3 sprints now we are going Load Testing, gonna push your service to peak and kill it with chaos monkey. This kind of scares people but this is how it operates in the real world, so accept the fact and be ready for these scenarios.</p><h3>Emotion as a Service</h3><p>Today you build something, any infra tool or anything to help your org, and initially it worked well, you and everyone were happy, but then 6 months later you find out Amazon released that as a new service at a low cost. This can make anyone sad now you have to defend your baby.</p><p>Be prepared for scenarios like that, there is always a high chance something better will come up, don&#39;t get sad. Pre-grief on it.</p><p>These are a few things that you should know or at least be aware of that will happen once your organization will scale, so you are prepared for and it doesn’t come as a surprise. Few problems are solved, and others are waiting for better solutions, maybe you can come up with one, there will always be good problems to solve.</p><p>This is the main talk that I referenced, I encourage you to watch it because this blog is just a glimpse of it. You will learn a lot.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fkb-m2fasdDY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dkb-m2fasdDY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fkb-m2fasdDY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/791e8a276ae784297fd56f061af2d74d/href">https://medium.com/media/791e8a276ae784297fd56f061af2d74d/href</a></iframe><p>I have recently started writing about my system design learnings and will be sharing them along the way.</p><p>Let’s connect over <a href="https://twitter.com/ssoonniiii">Twitter</a>, <a href="https://twitter.com/ssoonniiii">Peerlist</a>, or <a href="https://www.linkedin.com/in/rahul-d-soni/">LinkedIn</a></p><h4>Further Reading:</h4><ul><li><a href="https://gethelios.dev/blog/5-microservices-challenges-and-blindspots-for-developers/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">5 Microservices Challenges and Blindspots for Developers</a></li><li><a href="https://gethelios.dev/blog/cut-engineering-costs-save-time-helios/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Microservices Monitoring: Cutting Engineering Costs and Saving Time</a></li><li><a href="https://gethelios.dev/blog/testing-microservices-with-helios/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Testing Microservices - Trace Based Integration Testing Example</a></li><li><a href="https://gethelios.dev/blog/microservices-or-a-monolith-which-one-are-you/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Microservices or a monolith - which one are you?</a></li><li><a href="https://gethelios.dev/blog/opentelemetry-tracing/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">OpenTelemetry Tracing: Everything you need to know</a></li><li><a href="https://python.plainenglish.io/top-11-tools-for-microservices-backend-development-in-2023-3d9cdd61ef10">Top 11 Tools for Microservices Backend Development in 2023</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ffcbef6af91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloud-native-daily/scaling-uber-to-1000-services-insights-and-regrets-8ffcbef6af91">Scaling Uber to 1000 Services: Insights and Learnings</a> was originally published in <a href="https://medium.com/cloud-native-daily">Cloud Native Daily</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Netflix: guide to microservices]]></title>
            <link>https://medium.com/@rahuldsoni2001/netflix-guide-to-microservices-16bbc59d1533?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/16bbc59d1533</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[scaling]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Fri, 26 May 2023 13:50:59 GMT</pubDate>
            <atom:updated>2023-05-26T13:50:59.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*IvJjm_Cd8zxvbEfnLszCgg.png" /></figure><p>Netflix’s Microservice talk is one of the best if you want to learn about how systems scale.</p><p>You can easily draw a picture of how an organization might have scaled along with technology and how to deal with problems that come along. Out of many, below I will be sharing a few learnings.</p><p>Why did they go microservice? In the initial days, they had a monolith, which of course everyone has, but the way they were shipping and dealing with an increasing customer base, they had problems with the monolith, like it was hard to debug what went wrong, what caused the outage, and so on.</p><p>What does a typical microservice contain? Well, it has a logic layer, a database, to save DB calls you add cache, and an application layer to access the service, so these 4 are the basic components required. Of course, you can add or remove based on needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*FLxnZwvMHP15fah6.png" /></figure><p>Usually, there are 4 areas that you should take care of while building towards microservice: Dependency, Scale, Variance, and Change.</p><p>Lets zoom into each</p><h3>Dependency</h3><p><strong>a. Inter-service communication:</strong> If 2 services are communicating, there could be a possibility of network latency, hardware failure, or anything that could affect communication, and poor service that became a victim could go down, leading to cascading failures.</p><p>They made Hystrix an internal tool to check service health. <a href="https://netflixtechblog.com/introducing-hystrix-for-resilience-engineering-13531c1ab362">https://netflixtechblog.com/introducing-hystrix-for-resilience-engineering-13531c1ab362</a></p><p><strong>b. Testing:</strong> How will you test for each service? Let’s say you have 2 today, and tomorrow it could be 10. You won’t be doing N permutations for each release. The solution is to have an identified set of critical services that should be up in any case, allowing users to at least do the basic tasks that should be tested. That’s the basic need here.</p><p>In Netflix’s case, it was provided just the basic set of recommendations and popular movies and the User should be able to play it, that’s the minimal requirement.</p><p><strong>c. Client Libraries</strong>: Since we talked about the 4 components of microservices, there is usually common code at the application layer but is modified for required service usage. Now you have 2 options to either keep that part redundant or every service have one common point like monolith there were many discussions and no ideal answer but they decided to keep monolith with minimum code required, so it does not heat up i.e. get overloaded.</p><p><strong>d. Persistence:</strong> a simple eventually consistent model. The reason I suppose they are read-heavy is that movies, recommendations, and users’ data can be later eventually synced. CAP theorem reference 👆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*JGcgiQ1euJ5Vmywq.png" /></figure><h3>Scale</h3><p><strong>a. Stateless Service</strong></p><ul><li>they don’t have db or cache to store their own data</li><li>they can access config or metadata</li><li>very short span of user service</li><li>they can go down and can be replaced with other one in no time.</li></ul><p>use autoscaling to manage their automation of these kind of services.</p><p>with chaos monkey, they got super comfortable with service going down, not an issue for them.</p><p><a href="https://netflixtechblog.com/netflix-chaos-monkey-upgraded-1d679429be5d">https://netflixtechblog.com/netflix-chaos-monkey-upgraded-1d679429be5d</a></p><p><strong>b. StateFul Service</strong></p><ul><li>they have database and cache</li><li>If node goes down, everything is gone, critical service.</li></ul><p>Once they had an outage when their dependency was in one zone, US East 1, leading to an outage in the North America and Canada regions during the holiday season. They couldn’t recover from it because of cached data took long time to refill.</p><p>They made EVcache, which works on a simple principle: <strong>write</strong> to each zone for redundancy and <strong>read</strong> from the current zone for a fast response, of course, in case of unavailability then from neighbours.</p><p><a href="https://netflixtechblog.com/announcing-evcache-distributed-in-memory-datastore-for-cloud-c26a698c27f7">https://netflixtechblog.com/announcing-evcache-distributed-in-memory-datastore-for-cloud-c26a698c27f7</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*_a6J-e2npyF_v__g.png" /></figure><p><strong>c. Hybrid Service</strong></p><p>Mix and match of both.</p><p>Once they had one EVcache layer going down, the solution in the previous case became a problem here. This led to the enhancement of the system in three ways:</p><ul><li>Workload partition: that is, don’t make real-time calls and batch calls on the same service. It will get overloaded.</li><li>Request-level caching</li><li>Secure-token fallback: here, you can provide enough data inside the token so that when the service dies, you can have enough data to keep the app running or keep recommendation data in the token for some time so it can fetch available data like videos instead of frequently hitting it dead service, in this case, videos is different service, which is up and running.</li></ul><p>This above strategy has many use cases apart from Netflix’s like you can store users’ topics inside token, in the case of social media, so they get feed generated from DB directly.</p><h3>Variance</h3><p><strong>a. Operational Drift:</strong> Things change over time, such as response fallbacks, thresholds, or best practices and formats across organizations, which can unintentionally change and keep other parts out of synced. They have automated these kinds of mundane tasks to keep them uniform and have created internal tools for monitoring them.</p><p>Like you can make a linting tool that is automated with each PR so now everyone’s code has best practices implemented without developer keeping track of it.</p><p><strong>b. Polyglot and Containers</strong>: Different services will be using different languages. You cannot restrict use cases based on scenarios to maintain norms as norms. Using containers was the solution, but there are still non-technical things to address, such as why this is the best solution and what is the impact of this. People should know about this so that they don’t conflict when certain changes are required by someone else or when teams change, etc.</p><h3>Change</h3><p>Deployments often cause outages. They are usually done on weekdays and in the morning, which is the opposite of their peak time.</p><p>To continue delivering Spinnaker, which allows for tweaking deployments, such as checking if the stats for the current code are better than others, did new code improve latency or any other stats, using canary, etc., a workflow can be created based on their deployment checklist, which varies org to org. This will help on deployments without much chaos.</p><p><a href="https://netflixtechblog.com/global-continuous-delivery-with-spinnaker-2a6896c23ba7">https://netflixtechblog.com/global-continuous-delivery-with-spinnaker-2a6896c23ba7</a></p><p>This is the main talk that I referenced, I encourage you to read it because this blog is just a glimpse of it. You will learn a lot.</p><p>I have recently started writing about my system design learnings and will be sharing them along the way.</p><p>let’s connect over <a href="https://twitter.com/ssoonniiii">Twitter</a>, <a href="https://twitter.com/ssoonniiii">Peerlist</a> or <a href="https://www.linkedin.com/in/rahul-d-soni/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16bbc59d1533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[python manage.py HowDjangoWorks]]></title>
            <link>https://medium.com/@rahuldsoni2001/python-manage-py-howdjangoworks-dc23d97729f7?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc23d97729f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Sat, 20 May 2023 10:21:04 GMT</pubDate>
            <atom:updated>2023-05-20T10:21:04.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81qzGcNs7O4NDVnQ" /></figure><p>Have you ever wondered how Django works and what components lie behind and what is happening when you run the application? You probably go to documentation or listen to good but lengthy talks given by core members of Django Framework.</p><p>I wanted to study what is happening behind the scenes of Django and came across the amazing talk by <a href="https://twitter.com/ubernostrum">James Bennett</a> at PyCon 2015. After learning lots of things from that I will give here a quick overview of how the application works and If you are interested in an in-depth picture then refer to the <a href="https://www.youtube.com/watch?v=tkwZ1jG3XgA">talk</a>.</p><p>So we start our application by typing the command ‘py <a href="http://manage.py/">manage.py</a> runserver’ what it does here is passing the runserver parameter to <a href="http://manage.py/">manage.py</a> file which has all the commands that we use while working with django, commands like startapp, createsuperuser, and so on.</p><p>On starting server, we see messages on the prompt that server in running to a port usually localhost:8000. Now django application starting point is <a href="http://wsgi.py/">wsgi.py</a> file WSGI stands for Web Server Gateway Interface. It is readable and will load the settings of projects. If you look carefully <a href="http://settings.py/">settings.py</a> file is also not complicated it is just a list and variables. After settings are loaded the application is started. First, it will direct to the default URL that is ‘/’.</p><p>You can specify from where to start and you can also direct the ‘/’ to respond with the home page. So when you request URL, it is searched with regex in urlpatterns list of <a href="http://urls.py/">urls.py</a> file and first value that is matched with URL then associated view is returned. These views are mapped in <a href="http://urls.py/">urls.py</a> file with function name from <a href="http://views.py/">views.py</a> and URL that you want for that view and pass it path() function that will be part of the list.</p><h3>Views</h3><p>To qualify as view block of code</p><ul><li>must be callable</li><li>must take accept the HTTP request</li><li>must return a response or raise an exception</li></ul><p>We also pass variables in response from views and that data is showed using templates. Now few things regarding the template, django has its own but if you want you can plugin the template of your choice. It works this way there are lexers and parsers, data from any source is received like variable or database. Using regex the template is selected from string, like this is a pattern of comment and this is a pattern of variable then the token is extracted later sent to parser returns the node and nodelist based on the output generated from token then it is sent further to render() method and name suggest what it does. views are wrapped and made into transactions so either it is executed or rollback if an error occurs. views could be class-based or function-based and depending on scenario choose your format, the class base provides feature like inheritance and oops, while function based don’t look scary on day one.</p><p>Now that we touched the source like a database that leads us to discuss few more topics related to it like orm, models and forms. let’s discuss each.</p><h3>ORM</h3><p>ORM stands for object relation mapping, it helps us perform database operations without writing SQL queries provides us with functions that make it easy to use, and helps us focus on writing logic rather than thinking about database statement structure. Django has its own and it has evolved over the years and has become very useful to manage small to the medium level databases. You can write raw SQL queries also if you want to.</p><p>Each server different purpose and you can refer documentation or talk mentioned above to see in-depth but for a quick overview, Database backend deals with understanding what database it has to connect with it is database dependent, after that, it understands the types that the database supports an operator to commands conversions is also made possible by the backend. It has many supporting modules like database Wrapper and database Operation, it also has now a very useful thing called introspect what it does is creates a Model for you if you specify the database to be attached. So we do not need to look into the database and write a Model by mapping every column to Feild. ORM does that for us, so here reverse mapping goes from Database columns to Model fields.</p><p>SQLCompiler does translate django queries to SQL statements and each part of the query is constructed then sent to SQL for execution and we can use signals here if we want to use triggers that SQL provides.</p><h3>Models</h3><p>Now, let’s discuss Models, they are data Table representations in-class format. The table name is Model name, Table Columns are Model fields and we can also set up foreign key constraint and other conditions as well we can override the default behavior by creating Meta class. There is the conversion of data in python from Model field to Table Columns supporter data types, django takes care of that for us. That conversion happens on every transaction.</p><h3>Forms</h3><p>The model allows us to create forms and they work closely that does not mean that ORM, Models, and Form have to exist together. There would be some use-case where you only need form but do not want to make database transactions. Forms are made of widgets, widgets correspond to each HTML form tag and then data is extracted. From also gives the option to create a custom validator or use the basics provided by django.</p><p>These were few facts regarding django framework and basic understanding of things that go behind the scenes.</p><p><em>Originally published at </em><a href="https://r4hu1s0n7.hashnode.dev/python-managepy-howdjangoworks"><em>https://r4hu1s0n7.hashnode.dev</em></a><em>.</em></p><p>Lets connect over <a href="https://twitter.com/ssoonniiii">twitter</a>, <a href="https://peerlist.io/rahulsoni">peerlist </a>or <a href="https://peerlist.io/rahulsoni">linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc23d97729f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things to keep track on while Developing.]]></title>
            <link>https://medium.com/@rahuldsoni2001/things-to-keep-track-on-while-developing-35c4ad2090b2?source=rss-968e65a55b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c4ad2090b2</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-tips]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Rahul soni]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 04:59:31 GMT</pubDate>
            <atom:updated>2020-04-13T04:59:31.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpXsoPWujEpZUr4HtacBtQ.jpeg" /></figure><p>In this article i will share few things, which help developers, specially beginners to keep track on developing and avoid silly mistakes which later affect quality of work as well as output.</p><h3>Conventions</h3><p>As code grows, it is not easy to maintain track of which function does what and what value will variable hold also type of it so follow convention while writing identifiers, create custom convention like first few letters telling which group identifier belongs etc.</p><p>Try writing what will function do also what will be output at end of function, what is returns etc. Dividing function into small function and making max <em>Line of Count to </em>10 to 15 will also help with readability and management.</p><p><em>Comments don’t take much space but save lots of time.</em></p><h3>User Interface / User Experience</h3><p>Be flexible with UI / UX don’t hesitate to change it any state of developing. Practice sample UI with having features in mind. Sure you can find templates but use it for practice not to copy.</p><p>User Experience is what make 5 year old capable enough to use phone, kid is not that smart it’s engineer who makes it that simple. Simple UI with necessary colors and features automatically leads to good UX in most cases. You get to realize about UX while testing of Software.</p><p><em>UI / UX are as necessary as fork with noodles.</em></p><h3>Modules</h3><p>Of course! Dividing software into modules will help you to keep sharing with teammates, and prevents redundancy for common tasks. It is good to have few finished modules than many unfinished tasks.</p><h3>Suggestions</h3><p>Below are few random suggestions which are not big enough to write paragraph about but useful enough to be mentioned.</p><ol><li>Prevention of few states is good sometimes.</li><li>Keep also track of dependencies.</li><li>Take breaks to think of different approaches.</li><li>You’ll learn so much from your project, so keep track of it like i did by publishing this article.</li><li>Don’t forget to celebrate after submission, self-rewarding is good thing.</li></ol><p><em>Have a good day. Happy Coding</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c4ad2090b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>