<?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 Gopal on Medium]]></title>
        <description><![CDATA[Stories by Gopal on Medium]]></description>
        <link>https://medium.com/@gopalsays108?source=rss-2636be64d4be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jIAlMcP70LG3sofZe-NX0A.jpeg</url>
            <title>Stories by Gopal on Medium</title>
            <link>https://medium.com/@gopalsays108?source=rss-2636be64d4be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:41:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gopalsays108/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[Monolith vs Microservices: When Should You Actually Split a System]]></title>
            <link>https://medium.com/@gopalsays108/monolith-vs-microservices-when-should-you-actually-split-a-system-033d1af19fe3?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/033d1af19fe3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 15:42:36 GMT</pubDate>
            <atom:updated>2026-10-20T15:43:43.346Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://www.youtube.com/@ExplainBroTech/videos">Explain Bro</a>: System Design Foundations · Guide #03</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kEslseHK9WSjX26mJvozg.png" /></figure><h3>One Application, How Many Services?</h3><p>Suppose we’re building the photo-sharing app from our previous guide.</p><p>Users can create accounts, upload photos, follow other users, and receive notifications. We could build these features inside one application. Or we could create separate services for accounts, uploads, feeds, and notifications.</p><p>Separate services sound flexible. Each could have its own deployment and scale independently.</p><p>But now a simple action might involve several network calls. <br>We need to handle <strong>timeouts</strong>, <strong>coordinate changes</strong>, and investigate <strong>failures </strong>across different processes.</p><p>Should we take on that complexity immediately?</p><p>To answer that, let’s compare three approaches</p><ol><li><strong>A</strong> <strong>monolith</strong></li><li><strong>A modular</strong> <strong>monolith</strong></li><li><strong>A microservices</strong></li></ol><blockquote><strong><em>Want to see these architectures in action?</em></strong><em> Explore the </em><a href="https://gopal-os.vercel.app/labs/monolith-vs-microservices"><em>interactive architecture guide</em></a><em>. Switch between monolith, modular monolith, and microservices to compare their structure, code, and deployment.</em></blockquote><h3>Monolith: One Application Deployed Together</h3><p>Monolithic architecture is a traditional model of building software as a single indivisible unit. All components, from the user interfaces to business logic to the data access layer, are built, deployed, and scaled as a single unit.</p><p>Its primary benefits include</p><ol><li><strong>Simplicity in building</strong>: A unified codebase in a single repo. Makes it easier to set up, write code, and test.</li><li><strong>Ease of deployment</strong>: The entire application can be deployed as a single artifact.</li><li><strong>Easy Debugging</strong>: Since all code runs in a single process, tracing a request or a bug doesn’t include inter-service communication, which simplifies debugging compared to a distributed system.</li></ol><p>However, as the application grows, this simplicity gives rise to new challenges. The most common issue is tight coupling.</p><p>Our photo-sharing application might contain account management, uploads, feeds, and notifications. These capabilities can live in different modules while still being released together.</p><p><strong>A monolith describes a deployment boundary. It does not automatically mean messy code.</strong></p><p>The trade-off is that the deployment remains shared. A change to notifications ships with the rest of the application. If image processing consumes excessive resources in the same runtime, it can affect other features.</p><p>A monolith can also scale horizontally by running multiple application instances. However, replicating the whole application may be inefficient when only one capability needs additional capacity.</p><p>The question is whether that limitation is causing a meaningful problem for this application.</p><h3>Modular Monolith: Clear Boundaries Inside One Deployment</h3><p>A modular monolith is an evolution of the traditional monolith.<br>A modular monolith organizes the application around clear responsibilities, while retaining the single deployment unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlFsVtflQR3kDwqF4ktfpw.png" /></figure><p>Key advantages over a classic monolith include:</p><ol><li><strong>Improved codebase organization</strong>: The codebase is now easier to navigate and understand, as code related to specific features is grouped together.</li><li><strong>Better team scaling</strong>: Modules can be divided easily according to the team or for better collaboration.</li><li><strong>Easier testing</strong>: Modules can be tested in isolation.</li><li><strong>Space for the microservice</strong>: If needed, a well-defined module can be easily extracted and turned into an independent microservice.</li></ol><p>Our photo-sharing app could have these modules:</p><ul><li><strong>Accounts:</strong> profiles and account-related operations.</li><li><strong>Photos:</strong> upload metadata and photo lifecycle.</li><li><strong>Feeds:</strong> deciding which posts users see.</li><li><strong>Notifications:</strong> preparing and sending updates.</li></ul><p>Each module has a defined responsibility, if handled by a separate team. Other modules use those interfaces instead of reaching into its implementation.</p><p>For example, the feed module could request visible photos through the photos module’s interface. It should not quietly depend on that module’s internal table layout.</p><blockquote>A shared database may still be used, but data ownership should remain explicit</blockquote><p>However, the modules still share a deployment and commonly a runtime. Their release schedules and some failure risks remain connected.</p><h3>Microservices: Separate Deployment Boundaries</h3><p>In a microservices architecture, an application is broken down into collections of small autonomous services.</p><p>Each service runs independently and communicates with the others via the network, commonly via APIs.</p><p>Key advantages of the modular monolith are</p><ol><li><strong>Independent deployment</strong>: Teams can deploy their service on their own schedules, without needing to coordinate with other teams.</li><li><strong>Technology freedom</strong>: Each service can be built with the programming language and DB best suited for the task.</li><li><strong>Improved fault isolation</strong>: A failure in one service does not necessarily bring down the entire application.</li><li><strong>Granular scalability</strong>: Individual services can be scaled independently</li></ol><p>However, these benefits come with complexity. Moving from a single server to a network of systems introduces a new set of challenges that must be addressed, such as</p><ol><li><strong>Inter-service communication</strong>: Services require a reliable method of communication</li><li><strong>Data management</strong>: Maintaining data consistency across the distributed system is a complex task</li><li><strong>Operational overhead</strong>: Deploying, monitoring, and debugging in a distributed system requires complex tools and expertise.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzsRDUDEsGBBmmW4e5I1Yg.png" /></figure><p>For our application, image processing could become a separate service. It could receive jobs, generate thumbnails, and report results without being deployed alongside the main application.</p><p>That gives us a useful boundary if image processing has different capacity needs or changes on a different schedule.</p><p>But we now need to answer additional questions:</p><ul><li>What happens when the service is unavailable?</li><li>How long should callers wait?</li><li>Can a job be delivered more than once?</li><li>How do we follow an operation across services?</li><li>How do we change a message format without breaking consumers?</li></ul><h3>What Microservices Make Harder</h3><p>Consider a user uploading a photo.</p><p>The application stores the original image and schedules thumbnail generation. The worker finishes processing, but its acknowledgement is lost. The same job arrives again.</p><p>The worker must handle that repeated job safely.</p><p>Now suppose processing succeeds, but the photo’s status is not updated. We need a way to detect and recover from the incomplete workflow.</p><p>These are examples of partial failure: one part succeeds while another fails or becomes unreachable.</p><p>Microservices require deliberate handling of timeouts, failures, compatibility, and operations. Fowler’s discussion of their trade-offs emphasizes both the benefits of independent deployment and the additional complexity introduced by distribution. Microservice Trade-Offs</p><blockquote><strong>Explain Bro Bytes:</strong> One of the most common System Design mistakes is premature optimization. Adopting microservices too early can cripple a startup with operational overhead before it even finds product-market fit.</blockquote><h3>When Would I Actually Split the Application?</h3><p>For our photo-sharing example, I would look for a specific problem that a service boundary could address.</p><p>Suppose measurements show that image processing consumes substantial CPU during upload peaks, while ordinary browsing remains relatively lightweight. Suppose its processing logic also changes frequently.</p><p>That gives us a concrete candidate for separation.</p><p>Before extracting it, I would ask:</p><ol><li><strong>Is the bottleneck understood?</strong><br>Splitting a service will not fix an inefficient query or algorithm by itself.</li><li><strong>Is the responsibility clear?</strong><br>Image processing should have a defined input, output, and ownership boundary.</li><li><strong>Will independence provide a real benefit?</strong><br>We should be able to explain the capacity, deployment, or ownership problem it solves.</li><li><strong>Can we operate it reliably? </strong><br>Someone must own monitoring, deployments, failures, and recovery.</li><li><strong>Can its data and dependencies be separated?</strong><br>Constant access to the main application’s private tables would weaken the boundary.</li></ol><p>If those answers support extraction, we can move image processing while leaving accounts, feeds, and other capabilities together.</p><blockquote>We do not have to convert the whole application at once.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhKOWyyYvbyHHirKIUXZtA.png" /></figure><h3>What I Would Choose for a New Product</h3><p>Choosing the right architecture involves balancing tradeoffs based on the specific context.</p><p>There is no universal <strong>“best”</strong> architecture.</p><p>When choosing an architecture, consider these criteria.</p><ul><li><strong>Team size and structure:</strong> A small team can move quickly with a monolith. Larger organizations may benefit from the autonomy that microservices provide.</li><li><strong>Business stage:</strong> An early-stage startup needs to iterate and ship features fast; a monolith is often the right choice. A mature company with a complex product and large scale might need the flexibility of microservices.</li><li><strong>Scaling needs:</strong> If different parts of an application have vastly different scaling requirements, microservices can be a more cost-effective solution.</li><li><strong>Operational maturity:</strong> Do you have the infrastructure, tooling, and expertise to manage a distributed system?</li></ul><h3>What to Take Away</h3><p>Monoliths, modular monoliths, and microservices offer different ways to manage deployment and dependencies.</p><p>A monolith keeps deployment simpler. A modular monolith adds explicit internal boundaries. Microservices introduce independent deployment boundaries alongside the challenges of communication and coordination across a network.</p><p>The useful question is:</p><blockquote><strong><em>What problem would splitting this capability solve, and is that benefit worth the additional complexity?</em></strong></blockquote><p>If we cannot answer that clearly, improving the existing application’s boundaries may be the better next step.</p><h3>Next: What Are We Designing For?</h3><p>Before choosing databases, services, or architectural patterns, we need to understand the problem.</p><p>“Users can upload photos” describes a <strong>capability</strong>.<br>“Uploads should remain responsive during peak traffic” introduces an <strong>expectation</strong> about how that capability behaves.</p><p>In the next guide, we’ll explore <strong>functional and non-functional requirements: what the system must do, and how well it must do it.</strong></p><p>If image-processing logic is already separated from request handling, moving it into a worker may be easier. If that logic is tightly mixed with HTTP requests and database operations, the move will require more restructuring.</p><p><strong>Clear software boundaries can make system changes easier, while system requirements can reveal where better software boundaries are needed.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033d1af19fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design vs Software Architecture: What’s the Difference?]]></title>
            <link>https://medium.com/@gopalsays108/system-design-vs-software-architecture-whats-the-difference-0ba805900aa2?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ba805900aa2</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 03:01:02 GMT</pubDate>
            <atom:updated>2026-10-18T14:00:23.786Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://www.youtube.com/@ExplainBroTech/videos">Explain Bro</a>: <strong>System Design Foundations</strong> · Guide #02</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfQQq0fpfZPXJJXsz1h8kQ.png" /></figure><h3>One App, Two Design Perspectives</h3><p>Suppose you are building a photo-sharing app. We need to decide where photos will be stored, how the user will log in, how the codebase will be organized, and how the app will handle the growing traffic.<br>All of these are design decisions, but which belong to system design and which belong to software architecture?</p><p>Let’s explore both by following the same application, from a user uploading a photo to someone else viewing it.</p><h3><strong>System Design: How the Pieces Work Together</strong></h3><p>System design is the process of defining the <strong>components</strong>, <strong>interfaces</strong>, <strong>modules</strong>, and <strong>data</strong> for a system to meet its requirements. It often gives a high-level view of the <strong>network</strong>, <strong>hardware</strong>, and <strong>services</strong> that connect them.</p><p>For our app sharing app, user should be able to able the photos and view it later. That sounds very straightforward but leaves many critical decisions open.</p><ol><li>Where do the photo files live?</li><li>Where do we store the caption, owner&#39;s details, and other metadata?</li><li>How do we deliver images quickly?</li><li>How to handle failures such as photo upload failure?</li><li>How do we make the app respond quickly irrespective of the user&#39;s geographical location?</li></ol><p>An initial design decision would be to store the photo file in object storage and keep the metadata in the database.</p><p><strong>System design connects the requirements to components, communication flows, and operational trade-offs.</strong></p><p>It isn’t simply a diagram containing a load balancer, database, and cache. The important part is explaining why those pieces are needed.</p><h3>Software Architecture: How the Software Is Structured</h3><p>It is a subset of System Design. It focuses on the internal structure of the software itself. It includes optimizing code in modules, defining how they will interact, and choosing the right architectural pattern.</p><p>Within our photo-sharing application, we might separate responsibilities like this</p><ol><li>An <strong>API layer</strong> receives requests and returns responses.</li><li>An <strong>upload workflow</strong> coordinates validation, storage, and metadata creation.</li><li>A <strong>storage interface</strong> defines how the application saves and retrieves files.</li></ol><p>However, the software architecture is more than choosing how to organize code and folders. I can also cover boundary relationships between different services</p><h3>Following a Photo Upload Through Both Perspectives</h3><p>A user selects a photo and presses upload. For this, assume the application receives the photo before saving it to the object storage.</p><p>From a System design perspective, we might propose this flow</p><ol><li>The application receives the photos</li><li>It saves the original photo in the object storage</li><li>It saves the metadata in the database</li><li>It schedules thumbnail generation</li></ol><p>Now we have questions about coordination and failure.</p><p>What happens if the file is stored but the metadata write fails? What if a processing job runs twice? How does the user know whether the photo is ready?</p><p>Those questions influence the overall design.</p><p>From a <strong>software-architecture perspective</strong>, we examine how the software implements that flow.</p><p>Which component checks the file type and size? Which component owns the upload workflow? How does it call storage? Where are processing-state transitions defined? Can the thumbnail logic be tested without starting the entire application?</p><p>The same upload raises both kinds of questions. One perspective examines the end-to-end behavior; the other examines the responsibilities and dependencies that make that behavior possible.</p><h3>Comparing the Decisions Side by Side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bt3hSr8gpfjCRIEEtzjQcA.png" /></figure><h3>Where the Two Influence Each Other</h3><p>Suppose thumbnail generation becomes slow enough to delay uploads. We decide to move it into background workers.</p><p>That decision changes the system: we now need a way to schedule work, run workers, track progress, and handle failures.</p><p>It also changes the software: the upload workflow can no longer assume that the thumbnail exists when the request finishes. We need explicit processing states and code that handles them.</p><p>The influence also works in the other direction.</p><p>If image-processing logic is already separated from request handling, moving it into a worker may be easier. If that logic is tightly mixed with HTTP requests and database operations, the move will require more restructuring.</p><p><strong>Clear software boundaries can make system changes easier, while system requirements can reveal where better software boundaries are needed.</strong></p><p>Both perspectives affect qualities such as performance, reliability, security, and maintainability. These qualities don’t belong exclusively to one discipline.</p><h3>What to Take Away</h3><p>When approaching a design, I find these two questions useful:</p><blockquote><strong><em>How will the complete system behave?<br>How should the software’s responsibilities and dependencies be organized to support that behavior?</em></strong></blockquote><p>The first encourages us to think about components, data movement, capacity, and failures. <br>The second encourages us to think about interfaces, ownership, coupling, and change.</p><p>Neither perspective is sufficient on their own.</p><h3>Next: Monolith vs Microservices — When Should You Split a System?</h3><p>Understanding system design and software architecture leads to another practical question: should our application run as one deployable unit or as several independent services?</p><p>In the next guide, we’ll explore <strong>monoliths, modular monoliths, and microservices</strong> — how they differ, what trade-offs they introduce, and when splitting a system is worth the added complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ba805900aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Questions to Answer Before You Start Learning System Design]]></title>
            <link>https://medium.com/@gopalsays108/questions-to-answer-before-you-start-learning-system-design-7267138eea50?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7267138eea50</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[code-vs-system-design]]></category>
            <category><![CDATA[distributed-system-design]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 03:01:02 GMT</pubDate>
            <atom:updated>2026-10-17T13:35:27.599Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://www.youtube.com/@ExplainBroTech/videos">Explain Bro</a>: <strong>System Design Foundations</strong> · Guide #01</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgfjSXnEZd0oDP2aV7ltVA.png" /></figure><h3>What You’ll Learn in This Blog</h3><ol><li>What Is System Design?</li><li>Why Does System Design Matter?</li><li>System design v/s coding</li><li>System Design Across Software Roles</li></ol><h3>What Is System Design</h3><p>System design is the discipline of <strong>planning </strong>how a software product will work end-to-end in real-world conditions.</p><p>System design involves describing the various parts of a software system.</p><p>1. <strong>What building blocks does the system need</strong>?<br>We decide which components are required to build the system, such as databases, caches, CDNs, application servers, and services.</p><p><strong>2. How will these building blocks communicate</strong>, <br>We define how different components interact with each other. This includes APIs, communication patterns, data flows, and interactions between services.</p><p>3. <strong>What happens during failure.<br></strong> Read world system experience the failure and failures are inevitable. A server might crash, a database might become unresponsive, or traffic might suddenly increase<br>We need to think about how the system would react in these situations and continue to operate in such conditions whenever possible.</p><p>4. <strong>What trade-offs are we willing to accept</strong><br> Design decisions come with trade-offs. For example:</p><ul><li><strong>Cost vs. Reliability:</strong> How much are we willing to spend to make the system more reliable?</li><li><strong>Availability vs. Latency:</strong> How do we balance keeping the system available with delivering responses quickly?</li></ul><h3>Why System Design Matters</h3><p>Every major tech company faces challenges as its systems scale. Without thoughtful system design, systems that work well for 1,000 users may struggle or even fail when the user base grows to 100,000.</p><p>Thoughtful design anticipates these challenges and addresses complex problems before they impact the system. This is achieved by focusing on the core concepts of system design.</p><ol><li><strong>Scalability: </strong>The ability of a system to handle massive user load by distributing it to the different server, preventing any single server from becoming overwhelmed.</li><li><strong>Availability: </strong>The ability of a system remain operational and responsive if if one of its component get failed or crashed.</li><li><strong>Low latency: </strong>The ability to respond to user query fast irrespective of the user geographical locaiton.</li><li><strong>Consistency: </strong>The ability of a system to ensure that data remains accurate and that updates are reflected across distributed components according to the system’s consistency guarantees.</li></ol><p>Without the solid system system design the engineer often find themsleves in a reactive cycle of fixing the production bottlenecks and managing outages.</p><blockquote><strong>⚡ Explain Bro Bytes: </strong><a href="https://github.blog/news-insights/company-news/oct21-post-incident-analysis/"><strong>GitHub’s 43-Second Network Failure (2018)</strong></a><strong><br></strong>On October 21, 2018, a brief network partition disrupted GitHub, triggering database failovers and hours of recovery.<br><strong>💡 Lesson:</strong> Distributed systems need reliable replication, consistency mechanisms, and carefully planned disaster recovery.</blockquote><p>A well served system serves as a stable foundation upon which new features can be added without much hassle and breaking changes.</p><h3>System Design v/s Coding</h3><p>While coding and system design are closely realted but they function at differnt level of abstraction.</p><p>Think of building a car.</p><p><strong>System design is the blueprint.</strong> It defines the car’s overall structure, how powerful the engine needs to be, where the wiring should go, and how all the components will work together.</p><p><strong>Coding is the process of bringing that blueprint to life</strong> by implementing the engine, wiring, and other components, along with details such as the interior and user-facing features.</p><p>Similarly, in software engineering, system design defines how the different components fit together, while coding implements those decisions.</p><p>Coding is a act of implemting a solution in a programming language.</p><ol><li>Writing function, classes and modules.</li><li>Writing algorithm, bussiness logics.</li><li>Handling edge cases and error</li><li>Testing and Debugging behabiour at code level</li><li>Readability and refractoring</li></ol><blockquote>Coding Ask: How do I implement this feature<br>System Design Ask: How to make entire system to act fast, realiable, and correct when reality hit.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSKea0eoygWkxMWvPEiSJQ.png" /></figure><h3>System Design across software roles</h3><p>System design is not exclusive to the “architect” role. It is the collaborative process that involved engineer and different stakeholders accross differnt functions. Each role bring unique perspective and set of responsibility.</p><ol><li><strong>Backend Engineers</strong>: They focus of creating the APIs, data models, bussiness logic, and. making the system secure and fast in the large distributed system.</li><li><strong>Frontend Engineers: </strong>They ensure the client-facing of the system remain efficient, reliable, fast and secure. Thier choice of rendering (e.i server-side or client-side ), affect the data model and APIs and give shape to backend design overall. This might help to reduce the user percieved latency</li><li><strong>System Architect:</strong> These individuals focus on end-to-end architecture.</li><li><strong>SREs</strong>: They bring operational perspective and advocate the features like monitoring, automatic failover and disaster recovery planning.</li><li><strong>Product engineer:</strong> They connect technical decisions with user needs and business goals. User feedback, product requirements, and usage patterns help inform architectural trade-offs, such as choosing between strong consistency and eventual consistency when the application allows that choice.</li></ol><blockquote><strong>Note:</strong> The concept of, <strong><em>You build it</em></strong><em>, </em><strong><em>you run it</em></strong><em>,</em> is increasingly common. This empowers development teams to own the entire lifecycle of their services, from design and implementation to deployment and operations, blurring the traditional lines between roles.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Lp-KkmCaYQcCChx4PvzIQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>System design is the process of translating business requirements into scalable, reliable, and efficient software systems.</p><p>It shifts the focus from writing individual lines of code to making high-level decisions about system components, their interactions, data flow, and the trade-offs involved in building a robust application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7267138eea50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Powerplay Drive: The Low-Level Design Behind Millions of Construction Documents]]></title>
            <link>https://medium.com/getpowerplay/inside-powerplay-drive-the-low-level-design-behind-millions-of-construction-documents-ada14c1885ab?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada14c1885ab</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[file-management-system]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-07-25T02:31:01.759Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Building Powerplay Drive · Part 2 of a series</strong></p><p>In <a href="https://medium.com/getpowerplay/how-we-engineered-a-file-system-to-handle-millions-of-construction-documents-7f0ac20b7a0c"><strong>Part 1</strong></a>, I showed you the architecture of Powerplay Drive at 10,000 feet. Now let’s zoom all the way in — and follow a single file from the moment our API receives it to the moment it becomes searchable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TGAwskX9NLK8NK7sLo2YQ.png" /></figure><h4><strong>A Quick Recap</strong></h4><p>In <a href="https://medium.com/getpowerplay/how-we-engineered-a-file-system-to-handle-millions-of-construction-documents-7f0ac20b7a0c">Part 1</a>, we covered <strong>why</strong> we built Powerplay Drive and <strong>what</strong> the system looks like: an <strong>event-driven</strong>, <strong>fully asynchronous</strong> file management system built on <strong>S3</strong>, <strong>DynamoDB</strong>, <strong>Elasticsearch</strong>, <strong>SQS</strong>, and <strong>AWS Lambda</strong>. If you haven’t read it, start there — this post assumes you know the high-level shape.</p><p>This time we go one layer deeper. We’ll trace a single request end-to-end.</p><p>- How is a request <strong>received</strong>, <strong>validated</strong>, and <strong>processed</strong> by the backend?<br>- How is data <strong>persisted</strong> in DynamoDB?<br>- How does a file become <strong>searchable</strong> through Elasticsearch?</p><p><em>Let see the engineering decisions</em> behind each stage.</p><blockquote>🧭 <strong>This post comes with an interactive companion — </strong>step through this exact flow yourself — <a href="https://gopal-os.vercel.app/labs/drive-backend-explorer">Drive Backend Explorer</a> →</blockquote><h3>The four principles behind the design</h3><p>Before we trace a request, here are the four rules that shaped every decision in this post. Keep them in mind — every section below is one of these rules playing out:</p><ol><li><strong>The synchronous path does as little as possible.</strong> Anything slow or failure-prone runs behind a queue. The user should never wait on work they can’t see.</li><li><strong>Strong consistency for metadata, eventual consistency for search.</strong> Your file list must never lie to you. Your search index is allowed to be a few seconds behind.</li><li><strong>Failures must stay small.</strong> One overloaded workload — or one failing dependency — must never take down an unrelated one. In system-design terms: <strong>small, isolated failure domains</strong>.</li><li><strong>Security is structural, not procedural.</strong> Access control should fall out of <em>how data is keyed and how URLs are issued</em>, not out of a hundred if checks scattered through the code.</li></ol><h3><strong>A surprise: there isn’t one upload path. There are two</strong></h3><p>When we designed Drive, we realized files enter the system in two very different ways:</p><p><strong>Path A — a user uploads a file directly in the Drive UI.</strong> A site engineer uploads a foundation drawing. They are <em>waiting</em>. This path is <strong>latency-sensitive</strong>: it must be fast, and it must give correct, immediate feedback. Here, we favor <strong>consistency</strong> — when the API says “saved,” it is saved.</p><p><strong>Path B — another module generates a file.</strong> A worker attaches a photo to a Task, an Indent gets a supporting document. The user never opened Drive — they were doing something else. This path is <strong>availability-sensitive</strong>: Drive ingestion must <strong>never slow down or break the feature the user was actually using</strong>. Here, we favor <strong>availability</strong> — the Task update always succeeds, even if Drive ingestion is having a bad day</p><p>These two paths have opposite requirements, so we built them differently. One <strong>synchronous</strong> and <strong>minimal</strong>, one fully <strong>asynchronous</strong> and <strong>fire-and-forget</strong>.</p><pre>PATH A (user in Drive UI)                 PATH B (system-generated)<br><br>Client ──▶ S3 (direct upload)             TaskService / IndentService / ...<br>   │                                              │<br>   ▼                                              ▼<br>POST /drive/file (metadata only)          DriveFileUploadService<br>   │                                              │ (publish message)<br>   ▼                                              ▼<br>DriveService ─▶ DriveRepository ─▶ DynamoDB     SQS queue<br>   │                                              │<br>   ▼                                              ▼<br>DriveSyncService ─▶ SQS ─▶ Lambda ─▶ ES        2 Lambda ─▶ DynamoDB + ES</pre><blockquote>One rule holds on both paths: file bytes never pass through our backend</blockquote><h3>Path A, Stage 0 — Pre-signed URLs: performance and security in one move</h3><p>The naive upload API is: client sends the file to your server, your server forwards it to S3. That doubles your bandwidth bill, ties up a server process for the full duration of every upload, makes your API the throughput bottleneck — and hands your backend a stream of untrusted bytes to hold in memory. Every one of those is a problem at scale.</p><p>So we don’t do it. The upload is a three-step dance:</p><ol><li>The client asks our API for a <strong>presigned S3 URL</strong> — generated by S3 itself, valid for <strong>exactly one object, </strong>expiring after a fixed window..</li><li>The client PUTs the file bytes <strong>directly to S3</strong> using that URL. Our backend is not involved at all.</li><li>The client calls POST /drive/file with <strong>metadata only</strong>: name, size, mime type, parent folder, and the <strong>S3 key</strong> it just uploaded to.</li></ol><p>A presigned URL is what security people call a <strong>capability</strong>: possessing the URL <em>is</em> the permission, and the permission is <strong>narrow</strong> (one object) and <strong>temporary</strong> (it expires).</p><p>It also shrinks our <strong>attack surface</strong>: our API never parses, buffers, or stores untrusted file content. The most dangerous thing a client can send our Drive backend is a JSON document a few hundred bytes long.</p><p>The same idea runs in reverse on download. We <strong>never return raw S3 keys or bucket names to clients</strong>. Every read response swaps the stored S3 location for a fresh, short-lived <strong>presigned GET URL</strong>, generated per request.</p><h3>Stage 1 — Validate and fail fast: the cheapest failure is an early one</h3><p>The metadata request now hits two validation layers, in order. Think of them as defense in depth: each layer catches what the previous one can’t.</p><p><strong>Layer 1: The schema validator (Joi).</strong> Before any business code runs, the request body is checked against a strict schema. The interesting part is the mime-type <strong>whitelist</strong> — photos, videos, PDFs, CAD drawings, spreadsheets — and each mime type must agree with the media category the client claims. <em>You cannot tell us a </em><em>.exe is a photo</em>.</p><p><strong>Layer 2: Business rules in DriveService.</strong> Once the shape is valid, the service checks the things a schema can’t:</p><pre>async createFile(fileData) {<br>  this.assertNameIsValid(fileData.item_name);       // at least 4 characters<br>  this.assertParentIsWritable(fileData.parent_id);  // users can&#39;t write into system folders<br>  const parent = await this.getParentFolder(fileData);  // parent must exist and be active<br>  // ...only now do we touch the database<br>}</pre><ul><li><strong>System folders are write-protected.</strong> Drive auto-maintains folders like “<strong>Uploaded in Tasks</strong>” and “<strong>Uploaded in Attendance</strong>” that only the system (<strong>Path B</strong>) may fill. The guard lives in the service layer — the one chokepoint every request must pass — not in the UI.</li></ul><blockquote>Rule of thumb: <em>the client is a convenience, the server is the authority.</em></blockquote><ul><li><strong>The parent folder must exist and be active.</strong> In a key-value store there are no foreign keys — referential integrity is our job. We pay one cheap indexed read up front so we never persist an orphan.</li></ul><p>Why be this strict this early? Because <strong>the cheapest error is the one you catch before doing any work</strong>. A bad request rejected here never touches DynamoDB, never enqueues an SQS message, never wakes a Lambda.<br>Fail-fast isn’t just correctness hygiene — at millions of requests, it’s also <strong>cost control</strong> and <strong>overload protection</strong> for <strong>everything downstream</strong>.</p><h3>Stage 2 — DriveRepository: persistence, and where we refuse to be “eventual”</h3><p>Once a request is valid, <strong>DriveRepository</strong> takes over. The service layer knows business rules; the repository knows DynamoDB. Nothing above it ever sees a key expression or an index name — if we ever changed the storage engine again (we’ve done it once; that story is the next post), the blast radius stops at this layer.</p><p>Everything in Drive — <strong>folders, files, and file versions</strong> — lives in <strong>one DynamoDB table</strong> (a single-table design). <br>Every entity gets a prefixed ID so you can tell what you’re holding at a glance: <br>1. Folders are FOL… <br>2. Files are FIL…<br>3. File versions are FIV…</p><p>Here’s what a real file item looks like (values anonymized):</p><pre>{<br>  &quot;project_id&quot;: &quot;PRJ4XK92MD&quot;,<br>  &quot;item_type_id&quot;: &quot;ITEM#1#STATUS#true#FILA8C3QZ7X&quot;,<br><br>  &quot;_id&quot;: &quot;FILA8C3QZ7X&quot;,<br>  &quot;item_type&quot;: 1,<br>  &quot;item_name&quot;: &quot;foundation-drawing-v3.pdf&quot;,<br>  &quot;parent_id&quot;: &quot;FOL9TR2WQ8L&quot;,<br>  &quot;org_id&quot;: &quot;ORG7Y2BKQ&quot;,<br>  &quot;is_active&quot;: true,<br><br>  &quot;version_count&quot;: 3,<br>  &quot;current_version_id&quot;: &quot;VC#3&quot;,<br><br>  &quot;file_info&quot;: {<br>    &quot;size&quot;: 2048,<br>    &quot;extension&quot;: &quot;pdf&quot;,<br>    &quot;mime_type&quot;: &quot;application/pdf&quot;,<br>    &quot;file_category&quot;: 2<br>  },<br>  &quot;storage_info&quot;: {<br>    &quot;bucket_name&quot;: &quot;&lt;drive-bucket&gt;&quot;,<br>    &quot;key&quot;: &quot;&lt;s3-object-key&gt;&quot;<br>  },<br><br>  &quot;created_at&quot;: 1751023456789,<br>  &quot;updated_at&quot;: 1751109876543,<br><br>  &quot;folder_content_pk&quot;: &quot;ORG7Y2BKQ#PRJ4XK92MD#FOL9TR2WQ8L&quot;,<br>  &quot;folder_content_sk&quot;: &quot;STATUS#true#ITEM#1#TS#1751109876543&quot;,<br>  &quot;project_items_timestamp_pk&quot;: &quot;ORG7Y2BKQ&quot;,<br>  &quot;project_items_timestamp_sk&quot;: &quot;PRJ4XK92MD#STATUS#true#ITEM#1#TS#1751109876543&quot;<br>}</pre><p>Look at the keys — they’re doing a lot of work:</p><ul><li><strong>Partition key</strong> (project_id): the raw project ID. All of a project&#39;s drive items live together.</li><li><strong>Sort key</strong> (item_type_id): a composite string, ITEM#&lt;type&gt;#STATUS#&lt;active&gt;#&lt;id&gt; — the item&#39;s type, its active/deleted status, and its ID, all encoded into one sortable string.</li></ul><p>DynamoDB doesn’t give you WHERE clauses — it gives you key prefix matching. So instead of filtering rows, we <strong>design the keys so the query is the filter</strong>. &quot;Active files in this project&quot; is a single prefix query: everything starting with ITEM#1#STATUS#true#.</p><p>The two <strong>GSIs</strong> (Global Secondary Indexes — alternate sorted views of the table that DynamoDB maintains automatically) follow the same idea:</p><ul><li><strong>folder_content</strong> — partition key org#project#parentFolder, sort key ending in TS#&lt;timestamp&gt;. One query answers <em>&quot;list everything in this folder, newest first&quot;</em> — the index behind every folder screen in the app.</li><li><strong>project_items_timestamp</strong> — partitioned by org, time-sorted. One query answers <em>&quot;show the most recent items in this project&quot;</em> — the Recents feed.</li></ul><p>There’s a quiet security property here too. Notice that the tenant identifiers — project on the base table, org + project on the indexes — are <strong>inside the partition keys themselves</strong>. A query physically cannot cross a tenant boundary, because the boundary <em>is</em> the partition. That’s what “<strong>security is structural</strong>” means: multi-tenant isolation enforced by data layout, with request validation as the second layer on top — not the only layer.</p><h4>The consistency decision</h4><p>Now the important trade-off. A file and its first version are <strong>two separate items</strong>, and we write them with a single <strong>TransactWriteItems</strong> — DynamoDB&#39;s atomic multi-item transaction. Either both exist or neither does. There is no window, not even a millisecond, where a file exists without a version.</p><p>Version switching goes further, using <strong>optimistic concurrency control</strong>. When we promote version 3 to “current,” the transaction carries <strong>condition expressions</strong>: demote the old version <em>only if</em> it is still marked latest, promote the new one <em>only if</em> it is not. <br>If two users race — or a retry fires twice — DynamoDB rejects the losing transaction instead of silently corrupting state, and tells us <em>which</em> condition failed so we can return a precise error (“this version is already active”) rather than a mystery 500.</p><p>This is us choosing <strong>consistency</strong> deliberately: metadata is small, writes are cheap, and a wrong answer here (“which version of this drawing is current?”) could literally put the wrong drawing in a contractor’s hands. Some things should never be eventual.</p><h3>Stage 3 — DriveSyncService: choosing availability, on purpose</h3><p>A file that isn’t searchable barely exists to the user. But DynamoDB has no full-text search — so we maintain a copy of each item’s search metadata in <strong>Elasticsearch</strong>.</p><p>Here’s where a less careful design goes wrong: write to Elasticsearch inline, right after the DynamoDB write. Now your write path is <strong>coupled</strong> to a second datastore — your upload availability becomes availability(DynamoDB) × availability(Elasticsearch). Two systems that must both be up is strictly worse than one. <br>A slow ES cluster means slow uploads; <br>A down ES cluster means failed uploads.<br>You&#39;ve imported someone else&#39;s outage into your critical path.</p><p>So <strong>DriveSyncService</strong> decouples them. After every successful DynamoDB write, it publishes a small message — <em>operation</em> (create / update / delete), the item’s ID, and the changed fields — onto the <strong>drive_sync_elastic_search</strong> SQS queue. A Lambda consumes the queue and applies the change to the index.</p><pre>DriveRepository writes to DynamoDB     ← source of truth, strongly consistent<br>        │<br>        ▼<br>DriveSyncService publishes {operation, id, data} → SQS   ← non-blocking<br>        │<br>        ▼<br>Lambda consumes → applies the change to Elasticsearch<br>        │<br>        ▼<br>File is now searchable</pre><p>This is the <strong>availability side</strong> of the trade-off, chosen just as deliberately as the consistency side in Stage 2. If Elasticsearch is slow or briefly unavailable, uploads still succeed — the messages wait in the queue and the index catches up. The queue acts as a <strong>shock absorber</strong>: it converts “ES is down for five minutes” from an outage into a five-minute indexing lag that users never notice. That’s <strong>graceful degradation</strong> — the system loses a little freshness instead of losing a feature.</p><p>Search is <strong>eventually consistent</strong> with the source of truth, and we accepted that because a few seconds of index lag is invisible — nobody uploads a file and searches for it in the same breath. And for the rare message that’s lost anyway, we keep a <strong>reconciliation job</strong> that can re-sync the index from DynamoDB — the standard companion to any best-effort pipeline: eventual consistency needs an “eventually” you can force.</p><p>One more design detail closes the loop: <strong>search results never serve stale data.</strong> Elasticsearch returns only matching <em>IDs</em>. We then fetch each item fresh from DynamoDB — live metadata, newly presigned URLs — before responding. Elasticsearch decides <em>what matches</em>; DynamoDB decides <em>what’s true</em>. A lagging index can affect which results appear, never the correctness of what you see. The blast radius of staleness is contained to relevance.</p><p>Keeping two datastores in sync is genuinely hard — drift, ordering, reconciliation — and it gets its own post later in this series.<br>We will see in upcoming blogs how we managed retry mechanism in the Lamda for the upload.</p><h3>Path B — DriveFileUploadService: fault tolerance as a feature</h3><p>Now the second path. Remember the worker attaching a photo to a Task? The constraint that shaped everything: I<strong>f Drive ingestion fails, the Task update must still succeed.</strong> A file-sync hiccup must never block a construction workflow.</p><p>So <strong>DriveFileUploadService</strong> does almost nothing — by design. It’s a pure message publisher:</p><ol><li>Validate the payload, and resolve the <strong>destination system folder</strong> from the source module — task photos land in “Uploaded in Tasks / Task Logs,” indent documents in “Uploaded in Material / Indent” — driven by a mapping table, not scattered if-else.</li><li>Publish one message to the <strong>drive_file_upload</strong> SQS queue.</li><li>Return. No S3 call, no DynamoDB call.</li></ol><p>A dedicated Lambda consumes the queue and does the real work — creating the DynamoDB items in the right system folder and indexing them into Elasticsearch — entirely off the request path.</p><p>Three deliberate engineering choices here:</p><ul><li><strong>IDs are generated <em>before</em> enqueueing.</strong> The API mints the FIL…/FIV… IDs and ships them inside the message. The file has a stable identity from the instant the message is sent, even though its database row will only exist once the Lambda processes it. Anyone downstream can already reference it.</li><li><strong>Failure is silent on purpose.</strong> If validation fails or SQS is unreachable, we log and move on — the parent Task write is never rolled back. This is a conscious <strong>availability-over-consistency</strong> call: we accepted a rare missing drive entry over ever failing a site workflow. The wrong version of this decision is the <em>accidental</em> one; <br>Ours is written down, logged, and monitored.</li><li><strong>The queue does load leveling.</strong> Morning shift starts, and thousands of site photos arrive in a burst. The API’s cost per photo is one SQS publish — nearly constant — while the Lambda drains the queue at its own pace. Traffic spikes become queue depth, not latency. The system <strong>degrades gracefully under load instead of falling over</strong>: ingestion lag grows for a while; nothing times out, nothing 500s.</li></ul><h3>Four queues, four failure domains</h3><p>Across both paths, Drive runs on 4 SQS queues, each consumed by its own Lambda</p><p>QueueJob drive_file_uploadIngest system-generated files from other modules, drive_deleteRecursive folder deletion — a folder tree can hold thousands of items, so the API deletes just the folder and hands the subtree to a Lambda drive_sync_elastic_search keep the search index currentdrive_approvalsThe async document-approval workflow (e.g., stamping the approval matrix onto approved PDFs)</p><p>Why four queues instead of one? This is the <strong>bulkhead pattern</strong> — named after the watertight compartments in a ship’s hull. One flooded compartment doesn’t sink the ship; one backed-up workload doesn’t starve the others. Each queue has its own consumer, its own scaling behavior, its own failure mode. A backlog of PDF stamping can’t delay search indexing; a spike in task-photo uploads can’t block folder deletes. One shared queue would mean one shared failure domain — and a poison message or slow consumer in <em>any</em> workload would become everyone’s problem.</p><p>Note the wording throughout this post: the API never <em>invokes</em> a Lambda. It only ever <em>publishes a message</em>. The queue is the contract. The Lambdas behind it can be rewritten, redeployed, scaled, or paused without the API knowing anything changed — <strong>loose coupling</strong> in the most literal sense.</p><blockquote>The tax you pay for all this resilience: SQS guarantees at-least-once delivery, so a consumer can occasionally receive the same message twice — after a timeout, a retry, a redelivery. Every handler must therefore be <strong>idempotent</strong>: processing a message twice must produce the same result as processing it once. Pre-generated IDs help here (re-creating item FILA8C3QZ7X is an overwrite, not a duplicate). Idempotency in event-driven systems deserves its own post, and it&#39;ll get one later in this series.</blockquote><h3>The trade-off map</h3><p>One table to summarize where we landed, operation by operation — because “consistency vs availability” is never one decision, it’s a decision <em>per operation</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Jny-ho_5uqOqw4ve_YWTQ.png" /><figcaption>trade-off map</figcaption></figure><p>If you take one thing from this post, take this table. Every row is the same question — <em>“what breaks, and who notices, if this is stale or unavailable?”</em> — answered honestly for one operation at a time.</p><h3>Security recap: the layers</h3><p>Because security decisions were scattered through the stages above, here they are in one place, ordered from outermost to innermost:</p><ol><li><strong>No untrusted bytes on the backend</strong> — uploads and downloads go client↔S3 via presigned URLs; the API handles only small JSON payloads.</li><li><strong>Capability-style, expiring URLs</strong> — one object, one operation, limited time; possession is permission, expiry is revocation; raw bucket/key names never leave the backend.</li><li><strong>Whitelist input validation</strong> — strict schemas, mime-type allow-list with category cross-checks; unknown types rejected, never defaulted.</li><li><strong>Server-side authorization at the chokepoint</strong> — system-folder write protection and parent checks live in the service layer, where they can’t be bypassed by a custom client.</li><li><strong>Structural tenant isolation</strong> — project and org identifiers are part of the partition keys, so queries are physically scoped to a tenant before any application logic runs.</li></ol><p>None of these layers is exotic. The point is that they’re <strong>layers</strong> — each one assumes the one before it can fail.</p><h3>Putting it all together</h3><p>The full journey of a direct upload:</p><ol><li>Client gets a <strong>presigned URL</strong> and puts the bytes straight into S3 — our backend never touches them.</li><li>POST /drive/file carries metadata only → <strong>schema validation</strong>, then <strong>business validation</strong>. Bad requests die here, having cost almost nothing.</li><li><strong>DriveRepository</strong> writes the file + its first version <strong>atomically</strong> into a single DynamoDB table, with composite keys engineered so every screen in the app is one indexed query — and tenant boundaries baked into the keys themselves.</li><li><strong>DriveSyncService</strong> publishes a sync message; a Lambda indexes the item into <strong>Elasticsearch</strong>. If search is down, uploads don’t care.</li><li>The user gets a fast, <em>truthful</em> response; everything slow happens behind a queue, in its own failure domain.</li></ol><p>And the system-generated path collapses to: <em>validate → publish → done</em>, with a Lambda doing all the writing off the critical path, at whatever pace the traffic allows.</p><p>Strong consistency where a wrong answer costs real money. Eventual consistency where a late answer costs nothing. Bulkheads between every workload. Least privilege enforced by the storage layer itself. That’s what lets Drive stay fast, correct, and calm while handling millions of construction documents.</p><p>Here’s that same journey one level lower — every hop, at code level:</p><pre>CLIENT                        DRIVE API (backend)                        AWS<br>   │<br>   │  1. GET signed-url<br>   │──────────────────────────▶ │  sign a PutObjectCommand<br>   │ ◀── presigned PUT URL ──── │  (one object, short expiry)<br>   │<br>   │  2. PUT file bytes ───────────────────────────────────────────▶     S3<br>   │ ◀──────────────────────────────────────────────── 200 OK ──────     S3<br>   │<br>   │  3. POST /drive/file  { file_info, storage_info }   ← metadata only<br>   │──────────────────────────▶ │<br>   │                   ┌────────┴─────────┐<br>   │                   │  DriveValidator  │  Joi schema · MIME whitelist<br>   │                   └────────┬─────────┘<br>   │                   ┌────────┴─────────┐<br>   │                   │  DriveService    │  name ≥ 4 · system-folder guard<br>   │                   │  .createFile     │  parent exists? ─▶ DynamoDB (1 read)<br>   │                   │                  │  mint FIL… + FIV… ids<br>   │                   └────────┬─────────┘<br>   │                   ┌────────┴─────────┐<br>   │                   │ DriveRepository  │  TransactWriteItems ──────▶ DynamoDB<br>   │                   │                  │  file + version · ATOMIC<br>   │                   └────────┬─────────┘<br>   │                   ┌────────┴─────────┐<br>   │                   │ DriveSyncService │  {operation, id, data}<br>   │                   │                  │ ──▶ SQS (search-sync queue)<br>   │                   └────────┬─────────┘  non-blocking · failures logged<br>   │ ◀── 200 + presigned GET ── │<br>   │<br>   │        ── async, after the response ──────────────────────────────<br>   │<br>   │              SQS ──▶ Lambdas ──▶ Elasticsearch (upsert)<br>   │              retries until success · eventually consistent</pre><blockquote><strong>Want to see all of it move?</strong> The interactive explorer walks both flows end-to-end — play/pause, step forward and back, change speed, and click any box to read its responsibilities, failure modes, and payload shapes:</blockquote><blockquote>👉 <a href="https://gopal-os.vercel.app/labs/drive-backend-explorer">Drive Backend Explorer — step through the architecture</a></blockquote><h3>What’s next</h3><p>In the next post, we go deep on the piece everything here rests on: <strong>DynamoDB single-table design in production</strong> — why we chose it over MongoDB (Drive v1 ran on Mongo, and the scars taught us a lot), how folders, files, and versions share one table, how soft-delete works when your status flag lives <em>inside</em> the sort key, and how the GSIs are engineered to avoid hot partitions.</p><p>Thanks for reading. If you have questions about any part of this design, drop a comment — I’ll answer to the best of my knowledge.</p><p>Follow me on <a href="https://www.linkedin.com/in/gopalsays108/">LinkedIn</a>, <a href="https://medium.com/@gopalsays108">Medium</a>, and <a href="https://github.com/gopalsays108/">GitHub</a> ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada14c1885ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/inside-powerplay-drive-the-low-level-design-behind-millions-of-construction-documents-ada14c1885ab">Inside Powerplay Drive: The Low-Level Design Behind Millions of Construction Documents</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Engineered a File System to Handle Millions of Construction Documents]]></title>
            <link>https://medium.com/getpowerplay/how-we-engineered-a-file-system-to-handle-millions-of-construction-documents-7f0ac20b7a0c?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f0ac20b7a0c</guid>
            <category><![CDATA[file-storage]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[engeering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 09:18:59 GMT</pubDate>
            <atom:updated>2025-09-26T09:23:57.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*aeTbz3OI2qTHU8XZmjLskw.png" /></figure><h3>Why We Built Powerplay Drive (File Management System)</h3><p>At <strong>Powerplay</strong>, we’re building the <strong>operating system</strong> for construction helping teams collaborate seamlessly across projects of every scale. Every day, thousands of files move through our platform <strong>drawings</strong>, <strong>site images</strong>, <strong>contracts</strong>, etc. That keep projects running. But managing these files in construction isn’t straightforward. Google Drive or Dropbox are generic file management which often fell short in providing better UI experience for construction sector especially in organisation of documents based on project sites, easy version management and navigation between them, discussion threads etc</p><p>To solve this, we built <strong>Powerplay Drive</strong> — a scalable, secure, and search-friendly storage system designed for real-world construction workflows. In this blog, we’ll share how we engineered it, the challenges we faced, and what we learned along the way.</p><h3>Challenges &amp; Requirements</h3><p>When we set out to build Powerplay Drive, we focused on solving problems unique to construction workflows and to us at Powerplay.</p><ul><li><strong>Automatic File Organization</strong> → With multiple modules (<strong>Tasks</strong>, <strong>Material</strong>, <strong>Attendance</strong>, <strong>Issues</strong>, <strong>etc</strong>) generating photos and attachments daily, managing them was becoming messy. Now, Drive automatically places files into their respective system folders, keeping everything organized from day one.</li><li><strong>Version Management &amp; Approvals</strong> → Every file can now have multiple versions. Switch between versions anytime, and track history.</li><li><strong>Comments on Files</strong> → Team members can leave feedback directly on file</li></ul><p>But we didn’t stop there. For new <strong>Drive V2</strong>, we introduced features that bring even more control and discoverability:</p><ul><li><strong>Powerful Search</strong> → Find files instantly by name, type, or metadata.</li><li><strong>Granular Permissions</strong> → Access must be flexible: project-level, role-based, or via shareable links.</li><li><strong>Intuitive Project-Centric Interface →</strong> Designed specifically for construction workflows with clear project-site hierarchies, visual file previews, and simplified navigation so users can move between versions, discussions, and documents effortlessly.</li></ul><h3>High Level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85BR5kyW24KzojZ14UoOyA.png" /></figure><p>This provides a bird’s-eye view of how the Drive works end-to-end. It shows how different modules like client applications, backend APIs, storage systems, and asynchronous workflows interact to deliver a seamless file management experience.</p><h4>Key Components of the Architecture</h4><ol><li><strong>Client Applications (Web &amp; Mobile)<br></strong>This is the entry point for all users interactions. It intiates requests for file &amp; folders CRUD operations.</li><li><strong>Backend System &amp; Core Services <br></strong>The backend is designed to be <strong>fully event-driven</strong> and <strong>asynchronous</strong>, ensuring that API responses remain <strong>fast, scalable, and reliable</strong> even under heavy workloads. It implements the following core services:</li></ol><ul><li><strong>DriveService<br></strong> — Performs <strong>initial data validation</strong> and <strong>sanity checks to </strong>returns errors asap, preventing unnecessary downstream processing.</li><li><strong>DriveRepository <br> — </strong>Responsible for <strong>item creation and persistence</strong>.<br> — Converts requests into the appropriate <strong>DynamoDB JSON format</strong>.<br> — Interacts directly with the <strong>DynamoDB provider</strong> for database operations.</li><li><strong>DriveFileUploadService<br> — </strong>Manages the <strong>file upload synchronization process</strong> from various modules to the Drive.<br> — Uses <strong>SQS</strong> to enqueue upload tasks for asynchronous processing.</li><li><strong>DriveSyncService<br> — </strong>Handles <strong>data synchronization</strong> with <strong>Elasticsearch (ES)</strong>.<br> — Enqueues sync tasks into <strong>SQS</strong> to ensure eventual consistency between DynamoDB and ES.</li></ul><p><strong>3. Asynchronous Processing Workflows<br> — </strong>Implemented using <strong>Amazon SQS</strong> and <strong>AWS Lambda</strong>.<br> — Time-consuming tasks like <strong>metadata synchronization</strong>, <strong>file &amp; folder operations</strong>, and <strong>search indexing</strong> are offloaded to asynchronous workflows.<br> — Four dedicated SQS queues handle specific tasks, each with a <strong>Lambda trigger</strong> for automated processing:</p><ul><li><strong>drive_delete_folder</strong> — Handles folder deletion asynchronously.</li><li><strong>drive_file_upload_queue</strong> — Manages file upload processing tasks.</li><li><strong>drive_sync_elastic_search</strong> — Keeps search indexes updated in near real-time.</li><li><strong>drive-pdf-approval</strong>— Processes PDF approvals asynchronously.</li></ul><p><strong>4. Data Storage and Indexing</strong></p><ul><li><strong>AWS S3</strong> for file storage.</li><li><strong>DynamoDB</strong> for metadata, version history, and folder hierarchy.</li><li><strong>Elasticsearch</strong> for powerful search and indexing capabilities.</li><li><strong>AWS SES</strong> sends email notifications to approvers whenever necessary.</li></ul><h4>Data Modeling &amp; Storage Design</h4><p>Drive V2 leverages <strong>DynamoDB</strong> with a <a href="https://www.alexdebrie.com/posts/dynamodb-single-table/"><strong>single-table design</strong></a> to store folders, files, and file versions efficiently. This design allows us to handle high-volume operations, maintain strong consistency, and perform complex queries while keeping latency low.</p><p>We chose <strong>DynamoDB over MongoDB</strong> because:</p><ul><li><strong>Scalability:</strong> DynamoDB scales horizontally and handles millions of requests per second.</li><li><strong>Single-table efficiency:</strong> All entities — folders, files, file versions — are stored in one table, reducing complex joins.</li><li><strong>Transactional writes:</strong> Updates across multiple entities (like creating a new file version while updating the main file) can be done atomically.</li><li><strong>Low-latency access:</strong> Key-value access patterns ensure sub-millisecond response times.</li></ul><p>If we had taken the MongoDB approach, there were two main architectural challenges:</p><ol><li><strong>Using MongoDB Change Streams with Kafka</strong></li></ol><ul><li>We would need to consume change streams from multiple MongoDB collections, process them through Kafka, and then write the processed data back to MongoDB.</li><li>This approach would significantly increase CPU utilization on our primary MongoDB cluster, as MongoDB would be serving both our transactional workloads and the additional read/write operations required for change stream processing.</li><li>Since MongoDB is also our primary database, this added overhead could have impacted its stability and performance</li></ul><p>2. <strong>Using SQS → Lambda → MongoDB without Kafka</strong></p><ul><li>In this design, each SQS event would trigger a Lambda function, and each Lambda invocation would need to establish a new connection to MongoDB.</li><li>Given that Lambda can scale rapidly and invoke a large number of concurrent executions, this could lead to <strong>connection storms</strong>, <strong>connection pool exhaustion</strong>, and <strong>increased latency</strong> on MongoDB.</li><li>These connection spikes could overwhelm the database, causing performance degradation or even outages during traffic surges.</li></ul><p>By contrast, <strong>DynamoDB</strong> natively integrates with <strong>Lambda</strong>, providing a <strong>serverless, event-driven architecture</strong> with virtually <strong>no operational overhead</strong> and <strong>no risk of overwhelming the database</strong> during high-concurrency scenarios.</p><h4>Data Modeling and Indexing</h4><p>DynamoDB lives and dies by its key and index patterns. The schema is engineered to minimize <strong>hot partition risk</strong>, maximize <strong>query efficiency</strong>, and provide access patterns for listing, recency, and status filtering.</p><pre>PRIMARY_PK : projectId,<br>PRIMARY_SK : &#39;item_type_id&#39;<br><br>// GSI 1<br>FOLDER_CONTENT_PK : &#39;folder_content_pk&#39;,<br>FOLDER_CONTENT_SK : &#39;folder_content_sk&#39;,<br><br>// GSI 2<br>PROJECT_ITEMS_TIMESTAMP_PK : &#39;project_items_timestamp_pk&#39;,<br>PROJECT_ITEMS_TIMESTAMP_SK : &#39;project_items_timestamp_sk&#39;,</pre><ul><li><strong>GSI1 (Folder Content Index):</strong> Helps us quickly fetch all items inside a specific folder.</li><li><strong>GSI2 (Recent Items Index):</strong> Lets us retrieve the most recently added items in a project, irrespective of folders.</li></ul><p>In this part, we examined the <strong>high-level design of the File Management System</strong>, exploring how it integrates with various modules, manages files and folders, and ensures smooth and consistent operation across the platform.</p><p>In the next part, we will deep dive into the <strong>low-level implementation details</strong>, including how requests are received, validated, and processed by backend APIs, how data is persisted in DynamoDB, and how search indexing is handled via Elasticsearch. This will provide a deeper understanding of the <strong>end-to-end workflow behind Drive V2</strong>.</p><p>Thank you for reading this post, I hope this was helpful to you.</p><p>Leave a comment below if you have any questions I will try to answer them to the best of my knowledge.</p><p>Follow me on <a href="https://www.linkedin.com/in/gopalsays108/">LinkedIn</a>, <a href="https://medium.com/@gopalsays108"><em>Medium</em></a>,<em> and </em><a href="https://github.com/gopalsays108/"><em>Github</em></a>✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f0ac20b7a0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/how-we-engineered-a-file-system-to-handle-millions-of-construction-documents-7f0ac20b7a0c">How We Engineered a File System to Handle Millions of Construction Documents</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Notification — Everything You Need To Know | By Gopal]]></title>
            <link>https://medium.com/getpowerplay/android-notification-everything-you-need-to-know-by-gopal-d5af80dffdfd?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5af80dffdfd</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 20:36:17 GMT</pubDate>
            <atom:updated>2025-03-29T19:55:13.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Notification — Everything You Need To Know | By Gopal | Part-1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aOo-FNDoa43RePCcSGHmg.png" /></figure><p>Notifications are one of the faster and easiest ways to increase interactivity and engagement with our Application.</p><h3>What is Notification?</h3><p>A Notification is a message that Android displays outside our App to the user. It helps to provide the user with timely reminders, communication from other people, or information from our app. Users can tap the notification to open your app or take an action directly from the notification.</p><p>Like in WhatsApp, we get message notifications if the user taps on the notification we open a chat window or we can simply type our message in the notification. and send it.</p><h3>Notification Appearances and Types</h3><p>Notifications appear in different locations and formats to the user.</p><p>When we create a notification, it is first visible as an icon in the Status bar. Users can swipe down on the status bar to open the notification drawer, where they can view more details and take action with the notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*STxyHAXEi35wFq4R0BnGsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eNm4WiKwmjocWfXmM3apqA.png" /></figure><p>Starting from <strong>Android</strong> <strong>5.0</strong>, notifications are also visible on the lock screen. We can programmatically set whether our notifications should appear on the lock screen, if yes we can even control the visibility of it.</p><p>Starting with Android 8.0, users can disable or enable lock screen notifications for each notification channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Q8NutTonviH_cAr2VMzHgw.png" /><figcaption>Lock Screen Notification</figcaption></figure><h4>App icon badge</h4><p>Starting from Android 8.0 (API level 26) and higher, app icons indicate new notifications with a colored <strong><em>badge</em></strong> known as a <strong><em>notification dot</em></strong> on the app launcher icon.</p><p>Users can touch &amp; hold an app icon to see the notifications for that app. Users can dismiss or act on notifications from that menu, similar to the notification drawer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ehZxEk_aeyCVdve8lTpBHw.png" /></figure><h4>Heads Up Notification</h4><p>Starting from Android 5.0, notifications can appear in a floating window called a <strong><em>heads-up notification</em></strong><em>.</em></p><p>This behavior is only intended for important notifications that users need to know about immediately, such as messages. It only appears when the device is unlocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*0s5KdgRB-47-a3-_z_0QGQ.png" /><figcaption>Heads Up Notification appears in front of the foreground app.</figcaption></figure><h3>Notification Structure</h3><p>The design of a notification is determined by the Android <strong>System</strong> <strong>Templates </strong>and we just define the content of each portion of the template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DUFSfcKGhoQDb8yTjnuhA.png" /></figure><ol><li><strong>Small Icon</strong>, is required, we can set it using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setSmallIcon(int)"><strong>setSmallIcon</strong></a>()</li><li><strong>App name</strong>: It is provided by the system.</li><li><strong>Timestamp</strong> which is provided by the system, but we can override it by using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setWhen(long)">setWhen()</a> or hide it using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setShowWhen(boolean)">setShowWhen(false).</a></li><li>Large icon: optional; usually used only for contact photos. Don’t use it for your app icon. Set using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setLargeIcon(android.graphics.Bitmap)">setLargeIcon()</a>.</li><li>Next, we can see the <strong>Content Title</strong> which is also an <strong>optional </strong>element and we can set it using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentTitle(java.lang.CharSequence)">setContentTitle()</a>.</li><li>Next, we can see the <strong>Content Text</strong> which is an <strong>optional </strong>element and we can set it by using <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentText(java.lang.CharSequence)">setContentText()</a>.</li><li>Finally, there is a notification button that is called an <strong>Action Button</strong><br>which is an <strong>optional </strong>element as well. It’s optimal to have a maximum of<br><strong>three</strong> action buttons per notification, so be sure to remember that.</li></ol><h3>Notification Channels</h3><p>Starting in <strong>Android 8.0</strong> (<strong>API level 26</strong>), all notifications must be assigned to a channel or they will not appear. This allows users to disable any specific notification channel of our app instead of disabling all notifications.</p><p>In Android developer terminology we use the word <strong><em>‘channel’</em></strong> while the actual users in their system settings see the word <strong><em>‘category’</em> </strong>or <strong>categories</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6R28vks5rx_n5iiEeSO0A.jpeg" /></figure><h3>Notification importance</h3><p>Android uses the importance of notifications to determine how much the notification should interrupt the user visually and audibly. The higher the importance of a notification is, the more interrupted the notification will be.</p><h3>Post limits</h3><p>Starting from Android 8.1 ( API level 27 ), the app can’t make a notification sound more than once per second. If our app posts multiple notifications in 1 second, they all appear as expected, but only the first notification per second makes a sound</p><p>Android also applies a rate limit while updating a notification. If you post updates to a single notification too frequently, such as many in less than one second, the system might drop updates.</p><p>Thank you for reading this post, I hope this was helpful to you.</p><p>Leave a comment below if you have any questions I will try to answer them to the best of my knowledge.</p><p>Follow me on <a href="https://www.linkedin.com/in/gopalsays108/">LinkedIn</a>, <a href="https://medium.com/@gopalsays108"><em>Medium</em></a>,<em> and </em><a href="https://github.com/gopalsays108/"><em>Github</em></a>✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5af80dffdfd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/android-notification-everything-you-need-to-know-by-gopal-d5af80dffdfd">Android Notification — Everything You Need To Know | By Gopal</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Gradle Version Catalog | By Gopal]]></title>
            <link>https://medium.com/getpowerplay/android-gradle-version-catalog-by-gopal-cf459e90fb92?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf459e90fb92</guid>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-gradle]]></category>
            <category><![CDATA[version-catalog]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Sat, 23 Dec 2023 05:15:52 GMT</pubDate>
            <atom:updated>2025-09-26T09:23:22.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDzpgLUPV4o4OgYj8rkgPQ.png" /></figure><p>As our projects grow, managing dependencies becomes a challenge. Consistency and avoiding version conflicts are crucial for stable builds. Gradle Version Catalogs — a solution to simplify this task.</p><p>In this article, we’ll explore what Gradle Version Catalogs are, why they’re essential, how to set them up, and their use in other projects.</p><h3>What is a Version Catalog</h3><p>Introduced in Gradle 7.0 by the Gradle team, the <a href="https://developer.android.com/build/migrate-to-catalogs">Android Gradle Version Catalog</a> enables you to add and maintain dependencies and plugins in a scalable way. Using Gradle version catalogs makes managing dependencies and plugins easier when you have multiple modules.</p><p>Instead of hardcoding dependency names and versions in individual build files and updating each entry whenever you need to upgrade a dependency, you can create a central version catalog of dependencies that various modules can reference in a type-safe way with Android Studio assistance.</p><blockquote><strong>💡 Update: </strong>Android Version Catalog has become default for new project since Android Studio Hedgehog. If you want a sample Version Catalog template, just create a new project, and you will have it.</blockquote><h3>Benefits of Android Version Catalogs</h3><ol><li><strong>Centralized Management</strong>: All the dependencies and their versions are kept in one place, making it easier to manage and update them.</li><li><strong>Consistency</strong> <strong>Across Projects</strong>: By sharing the same version catalog, all projects can ensure they are using the same versions of dependencies, reducing the likelihood of conflicts.</li><li><strong>Conflict-free dependencies</strong><br>Version catalog eradicates the conflict between the dependencies which is consumed across the modules</li><li><strong>Type-safe dependency declarations<br></strong>When you declare dependencies in a version catalog, you can use type-safe syntax. This helps to prevent errors and makes it easier to read and understand your build scripts.</li><li><strong>Support for bundles<br></strong>A version catalog can also support bundles, which allow you to group a set of dependencies. This can be useful for organizing your dependencies and making it easier to upgrade them.</li><li><strong>Scalability<br></strong>Scales effectively with larger projects and multiple modules.</li><li><strong>Library version Update Hints</strong><br>It gives you a hint if there is any update available in any library.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3pkpxP4_ELH9_s9j1gkRA.png" /></figure><h3>How to Set Up a Gradle Version Catalog</h3><ol><li>Since the Version catalog became stable in Gradle version <strong>7.4</strong>+, upgrade your Gradle version to <strong>7.4</strong>+ to access the stability and benefits of the Version Catalog introduced in this release.</li><li>Create <strong>libs.versions.toml </strong>under <strong>gradle/wrapper</strong> directory. Gradle looks for the catalog in the <strong>libs.versions.toml</strong> file by <a href="https://docs.gradle.org/current/userguide/platforms.html#sub:conventional-dependencies-toml">default</a>, so it is recommended to use this default name.<br> The .<strong>toml</strong> file extension indicates that the file is written in the <a href="https://toml.io/en/">TOML</a> (<a href="https://toml.io/en/">Tom&#39;s Obvious, Minimal Language</a>) format, which is easy to read and write.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*AAsBsK4rTvHtoHGlM4uOGQ.png" /></figure><h3>Version Catalog File and Structuring</h3><p>In your <strong>libs.versions.toml</strong> file, add these 4 sections</p><pre>[versions]<br><br>[libraries]<br><br>[bundles]<br><br>[plugins]</pre><p>1. [<strong>versions</strong>]: This section is used to define version numbers for your dependencies and plugins. By defining versions here, you can easily update them in one place when needed.</p><p>2. [<strong>libraries</strong>]: Here, you define your project&#39;s dependencies. Instead of specifying the version directly, you reference the version defined in the [versions] section.</p><p>3. [<strong>plugins</strong>]: Similar to the [libraries] section, this section is for defining your project&#39;s plugins, referencing the versions from the [versions] section.</p><p>4. [<strong>bundles</strong>]: This section allows you to group several dependencies. This is useful when multiple dependencies are used together frequently.</p><blockquote>Note: If names in .<strong>toml </strong>file is in <a href="https://developer.mozilla.org/en-US/docs/Glossary/Kebab_case">kebab-case</a> or <a href="https://developer.mozilla.org/en-US/docs/Glossary/Snake_case">snake_case</a> , when we refer them in our Gradle build scripts, they all get normalised to . so we have to change them to . there. For example, if we definecompose-ui , it will become <strong>libs.compose.ui</strong> when we call it.</blockquote><pre>[versions]<br>agp = &quot;8.1.4&quot;<br>org-jetbrains-kotlin-android = &quot;1.8.10&quot;<br>core-ktx = &quot;1.9.0&quot;<br>junit = &quot;4.13.2&quot;<br>androidx-test-ext-junit = &quot;1.1.5&quot;<br>activity-compose = &quot;1.8.1&quot;<br>rxJava = &#39;2.2.21&#39;<br>rxAndroid = &#39;2.1.1&#39;<br><br>[libraries]<br>core-ktx = { group = &quot;androidx.core&quot;, name = &quot;core-ktx&quot;, version.ref = &quot;core-ktx&quot; }<br>junit = { group = &quot;junit&quot;, name = &quot;junit&quot;, version.ref = &quot;junit&quot; }<br>androidx-test-ext-junit = { group = &quot;androidx.test.ext&quot;, name = &quot;junit&quot;, version.ref = &quot;androidx-test-ext-junit&quot; }<br>reactivex-rxjava2-rxjava = { module = &quot;io.reactivex.rxjava2:rxjava&quot;, version.ref = &quot;rxJava&quot; }<br>reactivex-rxjava2-rxandroid = { module = &quot;io.reactivex.rxjava2:rxandroid&quot;, version.ref = &quot;rxAndroid&quot; }<br><br>[plugins]<br>com-android-application = { id = &quot;com.android.application&quot;, version.ref = &quot;agp&quot; }<br>org-jetbrains-kotlin-android = { id = &quot;org.jetbrains.kotlin.android&quot;, version.ref = &quot;org-jetbrains-kotlin-android&quot; }<br><br>[bundles]<br>rxjava = [&quot;reactivex-rxjava2-rxandroid&quot;, &quot;reactivex-rxjava2-rxjava&quot;]</pre><p>Here’s how you can incorporate the TOML file into any module of your choice.</p><pre>@Suppress(&quot;DSL_SCOPE_VIOLATION&quot;)<br>plugins {<br>    alias(libs.plugins.com.android.application)<br>    alias(libs.plugins.org.jetbrains.kotlin.android)<br>}<br><br>android {<br>    namespace = &quot;com.example.versioncataloguetest&quot;<br>    compileSdk = libs.versions.compileSdkVersion.get().toInt()<br><br>    defaultConfig {<br>        applicationId = &quot;com.example.versioncataloguetest&quot;<br>        minSdk = libs.versions.minSdkVersion.get().toInt()<br>        targetSdk =libs.versions.targetSdkVersion.get().toInt()<br>        versionCode = 1<br>        ...<br>    }<br>}<br><br>dependencies {<br>    implementation(libs.core.ktx)<br>    implementation(libs.lifecycle.runtime.ktx)<br>    implementation(libs.activity.compose)<br><br>    //Including bundles<br>    implementation(libs.bundles.rxjava)<br>    debugImplementation(libs.ui.test.manifest)<br>}</pre><p>Now to include the plugin correctly, in your project&#39;s module you have to define each plugin in project level gradle file as apply false.</p><p>The apply false suffix is used to prevent the plugin from being applied to the current module. This is useful when you want to apply a plugin to a specific module, but not to the entire project.</p><blockquote><strong><em>Note:</em></strong><em> If you are using a version of Gradle below 8.1, you need to annotate the </em><strong><em>plugins{}</em></strong><em> block with </em><strong><em>@Suppress(&quot;DSL_SCOPE_VIOLATION&quot;)</em></strong><em> when using version catalogs. Refer to </em><a href="https://github.com/gradle/gradle/issues/22797"><em>issue #22797</em></a><em> or </em><a href="https://developer.android.com/studio/preview/features#gradle-version-catalogs-known-issues"><em>Known Bugs</em></a><em> for more info.</em></blockquote><pre>@Suppress(&quot;DSL_SCOPE_VIOLATION&quot;)<br>plugins {<br>    alias(libs.plugins.com.android.application) apply false<br>    alias(libs.plugins.org.jetbrains.kotlin.android) apply false<br>}</pre><h3>Extended Usage</h3><ol><li>We can also move the <strong>minSdk</strong> and <strong>targetSdk</strong> to version catalog, like we did in the above example.</li><li>Receive project update suggestions in the Android Studio Project Structure tab, allowing for effortless modification of dependencies.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvxsC_WN2JF2lmoWtinZTw.png" /></figure><p>You can find an example of this <a href="https://github.com/gopalsays108/android_version_catalog">code in my GitHub Repository</a></p><h3><strong>Conclusion</strong></h3><p>Developers might question the choice between version catalogs and buildSrc, which relies on Kotlin for managing Gradle scripts. The distinction arises because, with buildSrc, updating a dependency initiates a complete project build, resulting in extended build times — particularly noticeable in projects with numerous modules. On the other hand, version catalogs facilitate updating dependencies without necessitating a complete project rerun.</p><p>However, it is important to note that using Gradle Version Catalog doesn’t limit you to this approach alone. You can still directly specify versions of dependencies and plugins if needed for your project.</p><p>Additionally, version catalogs are shareable with other projects, which simplifies dependency management when starting new projects and saves development time.</p><p>Thank you for reading this post, I hope this was helpful to you, you can view all the code from my <a href="https://github.com/gopalsays108/android_version_catalog">GitHub Repository.</a></p><p>Leave a comment below if you have any questions I will try to answer them to the best of my knowledge.</p><p>Follow me on <a href="https://www.linkedin.com/in/gopalsays108/">LinkedIn</a>, <a href="https://medium.com/@gopalsays108"><em>Medium</em></a>,<em> and </em><a href="https://github.com/gopalsays108/"><em>Github</em></a>✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf459e90fb92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/android-gradle-version-catalog-by-gopal-cf459e90fb92">Android Gradle Version Catalog | By Gopal</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom lint checks in Android | Part 2 | By Gopal]]></title>
            <link>https://medium.com/getpowerplay/custom-lint-checks-in-android-part-2-by-gopal-c9c6ea5c95fd?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c6ea5c95fd</guid>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[android-lint]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 10:43:57 GMT</pubDate>
            <atom:updated>2025-09-26T09:23:45.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HGq9yhKNrHXsdbwki1fLQ.png" /></figure><h3>TL;DR</h3><p>In the <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-by-gopal-226e211c743e">1st section</a> of the article, we explored the fundamentals of linting in the context of Android development. Our focus was on understanding various types of lint in Android and exploring diverse methods to employ and configure lint within Android Studio.</p><p>Moving forward in this blog, we will dive into the intriguing process of crafting custom lint from the ground up.</p><p>Please make sure to read <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-by-gopal-226e211c743e">Part 1</a> before diving into Part 2 for a comprehensive understanding.</p><h3>Motivation</h3><p>In my case, I often found myself frustrated with formatting-related comments on pull requests. There were instances when I would forget to include the @AndroidEntryPoint annotation on an activity/fragment, especially when using Dagger. Other times, I would overlook the need to utilize a specific view/utility according to our organization&#39;s standards, among various other challenges that tend to slip through the cracks during development. These experiences led me to realize the importance of a more proactive approach in addressing such issues and inspired me to explore the world of Android linting.</p><p>By developing this custom lint rule, our goal is not only to streamline the development workflow but also to foster a coding environment where attention to detail becomes second nature. Let’s start this journey to enhance code quality, eliminate common pitfalls, and empower ourselves to tackle more complex coding challenges with confidence.</p><h3>How can we solve this Problem?</h3><p>We can use Ktlint for Kotlin and Checkstyle for Java, but we prefer using Android Lint (which is not just for Android) because it lets us write custom lint rules that work for both Kotlin and Java at the same time. This makes more sense because sometimes we use both languages, and we don’t want to create and handle separate lint rules for each. Plus, integrating these rules would also need to be done twice, making it more complicated. Choosing Android Lint helps us keep things simple and efficient, making our code easier to manage in both languages.</p><p>You can read <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-by-gopal-226e211c743e">Part 1</a> of this article to understand how lint works in Android for both Java and kotlin at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zz2puH0liZpJ2eqbvgr3dw.png" /></figure><h3><strong>Why do we still need to care about Java?</strong></h3><p>While it’s true that Kotlin is gaining popularity and becoming our preferred choice over Java in our code, it might not be the case for larger projects already in use. So, it’s not practical to completely disregard Java just yet. To ensure our code looks good and follows the same standards in both Java and Kotlin, it’s crucial to maintain this rule for both languages. This way, regardless of the language, we can still enjoy well-organized and readable code.</p><h3>Writing Your first Lint check</h3><ol><li><strong>Create a new Java or Kotlin Library module.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fmi4DQGif7kPo4LXp_GZxw.png" /></figure><p>2. <strong>Now add dependencies in your lint module’s build.gradle.</strong></p><pre>plugins {<br>    id(&quot;java-library&quot;)<br>    id(&quot;org.jetbrains.kotlin.jvm&quot;)<br>}<br><br>java {<br>    sourceCompatibility = JavaVersion.VERSION_17<br>    targetCompatibility = JavaVersion.VERSION_17<br>}<br><br>dependencies {<br>    compileOnly(&quot;com.android.tools.lint:lint-api:30.1.0-alpha03&quot;) // = agp + 23.0.0<br>    testImplementation(&quot;com.android.tools.lint:lint-tests:30.1.0-alpha03&quot;)<br>}</pre><p>To decide lint library version there is a rule of thumb as stated by Google developers (<a href="https://youtu.be/jCmJWOkjbM0?t=92">https://youtu.be/jCmJWOkjbM0?t=92</a>) add 23.0.0 to your Android Gradle plugin ( AGP ) version</p><p>3. <strong>Make your lint rules visible to other modules</strong></p><p>To include this lint rule in your other module we can either use lintPublish or lintChecks. The difference between these two is that lintChecks makes that lint rule available only for that module whereas lintPublish makes it available to all upstream modules as well. This is how I used it.</p><pre>android {<br>   ...<br>}<br>dependencies {<br>    ...<br>     lintChecks(project(&quot;:lint-checks&quot;))<br>}</pre><p>Now Sync your project once before moving to the next step.</p><p>4. <strong>Define Issue Registry<br></strong>Now in the next step, we need to define our <strong>Issue Registry, </strong>where we list all the issues we want to detect. Android lint discovers it using a service locator pattern.</p><blockquote>In software design, a service locator is a pattern that centralizes the process of obtaining a service or component within a system. In this context, the “service” is the Issue Registry, and the service locator pattern helps Android lint locate and use it effectively. It’s a mechanism that abstracts the process of locating and obtaining services, providing a centralized point for managing dependencies.</blockquote><p>To Define an issue Registry we need to extend our class from IssueRegistry() abstract class and return all the issues(which we will define below) we want to detect.</p><p>This is what our issue registry looks like (suppress annotation is added as all lint APIs are in beta)</p><pre>package gopal.lint_checks<br><br>import com.android.tools.lint.client.api.IssueRegistry<br>import com.android.tools.lint.detector.api.CURRENT_API<br><br>@Suppress(&quot;UnstableApiUsage&quot;)<br>class MyIssueRegistry: IssueRegistry() {<br><br>    override val issues = listOf() // Add your all Issues<br><br>    override val api: Int<br>        get() = CURRENT_API<br><br>    override val minApi: Int<br>        get() = 8<br>}</pre><p>Now we need to ensure this registry is visible to Lint for that we create a file with the name com.android.tools.lint.client.api.IssueRegistry at the location “resources/META-INF/services/” and define our registry like this.</p><pre>gopal.lint_checks.MyIssueRegistry</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QW9xil3yo5RaL8oesHoEQ.png" /></figure><p>5. <strong>Let’s understand custom lint class terms “Visitor,” “Issue,” and “Detector”</strong></p><p>5.1 Visitor: A visitor is a design pattern used to traverse and analyze the Abstract Syntax Tree (AST) of the source code. Think of it as a code explorer that looks at different parts of the code, such as classes, methods, and statements. It helps you navigate through the code’s layout and do specific tasks or checks on each piece</p><p>5.2 Issue: An issue represents a specific problem or rule violation that you want to detect in the codebase. It is like a big red flag pointing out a specific problem or mistake in code. It comes with details like an ID, a brief description, and a priority level. Each issue can also have special settings, like how severe it is or any extra options, so you can customize how it works.</p><p>5.3 Detector: A detector is responsible for implementing the logic to identify and report issues in the codebase. It is the brains behind finding and reporting code issues. It’s like a code inspector that defines methods to check different parts of the code structure. When certain conditions are met, it raises issues. The detector teams up with the lint framework and, during analysis, gets called by the visitor to inspect every nook and cranny of the code structure</p><p>6. <strong>Creating your first Issue</strong>.</p><p>In this example, we will be creating a custom lint rule to check whether an Activity or Fragment has been annotated with @AndroidEntryPoint, a requirement for Dagger Hilt projects.</p><p>Our Issue Class</p><pre>package gopal.lint_checks.checks<br><br>import com.android.tools.lint.detector.api.Category<br>import com.android.tools.lint.detector.api.Implementation<br>import com.android.tools.lint.detector.api.Issue<br>import com.android.tools.lint.detector.api.Scope<br>import com.android.tools.lint.detector.api.Severity<br>import gopal.lint_checks.detector.AndroidEntryPointDetector<br><br>@Suppress(&quot;UnstableApiUsage&quot;)<br>object AndroidEntryPointIssue {<br>    /**<br>     * The fixed id of the issue, IDs are also used to suppress any lint<br>     */<br>    private const val ID = &quot;AndroidEntryPointImplementationIssue&quot;<br><br>    /**<br>     * The priority, a number from 1 to 10 with 10 being most important/severe<br>     */<br>    private const val PRIORITY = 7<br><br>    /**<br>     * Description short summary (typically 5-6 words or less), typically describing<br>     * the problem rather than the fix (e.g. &quot;Missing minSdkVersion&quot;)<br>     */<br>    private const val DESCRIPTION = &quot;Use @AndroidEntryPoint before running the app&quot;<br><br>    /**<br>     * A full explanation of the issue, with suggestions for how to fix it<br>     */<br>    private const val EXPLANATION = &quot;&quot;&quot;<br>        Class is not contain @AndroidEntryPoint Annotation,<br>        Use @AndroidEntryPoint before running the app<br>    &quot;&quot;&quot;<br><br>    /**<br>     * The associated category, if any @see [Category]<br>     */<br>    private val CATEGORY = Category.CORRECTNESS<br><br>    /**<br>     * The default severity of the issue<br>     */<br>    private val SEVERITY = Severity.INFORMATIONAL<br><br>    val ISSUE = Issue.create(<br>        ID,<br>        DESCRIPTION,<br>        EXPLANATION,<br>        CATEGORY,<br>        PRIORITY,<br>        SEVERITY,<br>        Implementation(<br>            AndroidEntryPointDetector::class.java,<br>            Scope.JAVA_FILE_SCOPE<br>        )<br>    )<br>}</pre><p>The final parameter, IMPLEMENTATION, holds the utmost importance, while the other arguments are self-explanatory. Within IMPLEMENTATION, the scope specifies the type of files we aim to analyze — in this case, it includes both Java and Kotlin files. The initial argument is the detector class responsible for identifying the particular issue.</p><p><strong>Writing our detector Class</strong></p><p>The Detector class is required to extend from the Detector class and implement one of the following interfaces based on the file type we want to examine. Lint simplifies the process by providing callback-style APIs, eliminating the need for manual file scanning. We can specify the elements we’re interested in, and Lint will provide callbacks for them based on the chosen file type:</p><ul><li>SourceCodeScanner -&gt; Java or Kotlin files</li><li>ClassScanner -&gt; Bytecode/compiled class files</li><li>BinaryResourceScanner -&gt; Binary resource files</li><li>ResourceFolderScanner -&gt; Resource folders directory, not the files within it</li><li>XmlScanner -&gt; All XML files</li><li>GradleScanner -&gt; Gradle files</li><li>OtherFileScanner -&gt; All other files</li></ul><p>Now, let’s delve into the code.</p><pre>package gopal.lint_checks.detector<br><br>import com.android.tools.lint.client.api.UElementHandler<br>import com.android.tools.lint.detector.api.Detector<br>import com.android.tools.lint.detector.api.JavaContext<br>import com.android.tools.lint.detector.api.SourceCodeScanner<br>import gopal.lint_checks.visitor.AndroidEntryPointVisitor<br>import org.jetbrains.uast.UClass<br>import org.jetbrains.uast.UElement<br><br>@Suppress(&quot;UnstableApiUsage&quot;)<br>class AndroidEntryPointDetector : Detector(), SourceCodeScanner {<br>    override fun getApplicableUastTypes(): List&lt;Class&lt;out UElement&gt;&gt;? =<br>        listOf(UClass::class.java)<br><br>    override fun createUastHandler(context: JavaContext): UElementHandler =<br>        AndroidEntryPointVisitor(context)<br>}</pre><p>We extend from the Detector class to implement SourceCodeScanner as we want to scan Java and kotlin files</p><p><strong>Writing our Visitor Class</strong></p><pre>package gopal.lint_checks.visitor<br><br>import com.android.tools.lint.client.api.UElementHandler<br>import com.android.tools.lint.detector.api.JavaContext<br>import gopal.lint_checks.checks.AndroidEntryPointIssue<br>import org.jetbrains.uast.UClass<br><br>@Suppress(&quot;UnstableApiUsage&quot;)<br>class AndroidEntryPointVisitor(private val context: JavaContext) : UElementHandler() {<br><br>    private val superClassQualifiedNameFragment =<br>        &quot;androidx.appcompat.app.AppCompatActivity&quot;<br><br>    override fun visitClass(node: UClass) {<br>        if (node.javaPsi.superClass?.qualifiedName == superClassQualifiedNameFragment &amp;&amp;<br>            !node.hasAnnotation(&quot;dagger.hilt.android.AndroidEntryPoint&quot;)<br>        ) {<br>            reportIssue(node)<br>        }<br>    }<br><br>    private fun reportIssue(node: UClass) {<br>        context.report(<br>            issue = AndroidEntryPointIssue.ISSUE,<br>            scopeClass = node,<br>            location = context.getNameLocation(node),<br>            &quot;Use @AndroidEntryPoint before running the app, Hurray Your First Lint&quot;,<br>        )<br>    }<br>}</pre><p>Now register your issue in your IssueRegsitry class.</p><pre>class MyIssueRegistry: IssueRegistry() {<br><br>    ....<br>    override val issues = listOf(AndroidEntryPointIssue.ISSUE)<br>    ....<br>}</pre><p>Now only write “./gradlew lint” in the Android Studio terminal or you can execute a gradle lint task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eZ2smPdpwlnCufWobf8Jw.png" /></figure><p>After all the above steps you just need to rebuild your project and you can see your Lint in action.</p><p>Congratulations on your first custom lint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75QQ_fybdC5KN8UFXvnYYw.png" /></figure><p>PS: If the above step did not work for you due to any reason you also try adding this line in your lint-check module build gradle. ( Change the path ) and then rebuild your project or you even try to invalidate and restart.</p><pre>jar {<br>    manifest {<br>        attributes(&#39;Lint-Registry-v2&#39;: &#39;gopal.lint_checks.MyIssueRegistry&#39;)<br>    }<br>}</pre><p>Thank you for reading this post, I hope this was helpful to you, you can view all the code from my <a href="https://github.com/gopalsays108/android_custom_lint">GitHub Repository</a>.</p><p>Leave a comment below if you have any questions I will try to answer them to the best of my knowledge.</p><p>Follow me on <a href="https://www.linkedin.com/in/gopalsays108/">LinkedIn</a><em> and </em><a href="https://medium.com/@gopalsays108"><em>Medium</em></a><em> </em>✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c6ea5c95fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/custom-lint-checks-in-android-part-2-by-gopal-c9c6ea5c95fd">Custom lint checks in Android | Part 2 | By Gopal</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom lint checks in Android | By Gopal]]></title>
            <link>https://medium.com/getpowerplay/custom-lint-checks-in-android-by-gopal-226e211c743e?source=rss-2636be64d4be------2</link>
            <guid isPermaLink="false">https://medium.com/p/226e211c743e</guid>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[android-lint]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Gopal]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 17:02:20 GMT</pubDate>
            <atom:updated>2023-12-28T10:18:06.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZRT7e50jXjoblZgIVfsdA.jpeg" /></figure><h3><strong>What is Lint</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LZ-xXtMBzC-vVeBIxsChg.png" /></figure><p>Lint in Android is a very powerful tool. The <a href="http://developer.android.com/tools/help/lint.html">Android lint</a> is a static code<br>analysis tool that checks your project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.</p><p>The Android Lint API allows users to create custom lint checks. For example, if you are the author of an Android library project and your library project has certain usage requirements, you can write<br>additional lint rules to check that your library is used correctly, and then you can distribute those extra lint rules for users of the library. Similarly, you may have company-local rules you’d like to enforce.</p><blockquote>Note: That while Android Lint has the name “<strong>Android</strong>” in it, it is no longer an Android-specific static analysis tool; it’s a general static analysis tool, and inside Google for example it is run to analyze server-side Java and Kotlin code.</blockquote><h3>Ways to use Lint</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2xwc_3Wq1om7kDP7FXt4g.png" /></figure><p>Let&#39;s dive into some ways to use Android Lint.</p><p><strong>Using Android Studio</strong></p><ol><li>On-the-fly: It is one of the easiest and simplest ways to see your lint on Android. It will show the error message as you start typing in Android Studio. For Eg: When you write the incorrect variable name or wrong ID in XML.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zor4kFwgLAtrjWH1Q59Igw.png" /></figure><p>2. Inspect Code: This is an action in Android Studio, where we can run a batch analysis of our project. It&#39;s a great way to audit our project for common errors. Eg: There is an action called <strong>Run Inspection by Name </strong>which will check the whole project for the specific error we want. <br><strong>To try</strong>: Just press <strong>Shift twice</strong> and enter the <strong>Run inspection name </strong>and then your inspection name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dVoSNVSeTVA0DrYjmD2eQ.png" /></figure><p><strong>Using the Command line</strong></p><p>We can also run lint in the command line with gradle. For eg: <strong>./gradlew lintDebug </strong>will also do the batch analysis for the enitre project and it will also create an HTML and XML report where we can see our errors.</p><h3>Getting the most out of Android Lint</h3><p>We are now going to talk about some ways to set up lint, use cases, and understand how lint works under the hood. <br>We will learn how to write custom lint rules in Android in <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-part-2-by-gopal-c9c6ea5c95fd">Part 2</a>, but I suggest reading and understanding Part 1 before reading <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-part-2-by-gopal-c9c6ea5c95fd">Part 2</a>. I will try to make it as simple as I can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*mxhQ4uCwc2zZz6eqTfz4-w.png" /><figcaption>The topic we are going to cover in this Android lint series</figcaption></figure><h3>Configuration</h3><p>Android Studio comes with a great tool ( <strong>Inspection</strong> ) to configure your lint in Android. You can perform several tasks using this option in Android Studio. Let&#39;s explore one by one. Path to open <strong>Inspection</strong> tool in Android Studio.</p><blockquote>Android Studio Setting &gt; Editor &gt; Inspection</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh6RbEKn52grzDsY45aStA.png" /></figure><p>Android Inspection option comes with around 400+ inbuild checks. Most of them are enabled by default. I would like you guys to take a look at the disabled lint because some of these might apply to your project. With this Inspection option, you can perform several tasks over lint such as.</p><ol><li>Change the Scope of the lint</li><li>Change Severity of the lint</li><li>Change the Highlighting option of your lint</li></ol><p>Apart from these basic functions inspection tools come with. You can also add a new check from the inspection tool itself. Enable/Disable your lints and much more.</p><blockquote>All you custom lint that you will be writing will appear here also.</blockquote><h3><a href="https://developer.android.com/studio/write/annotations">Annotations</a></h3><p>Annotations let you provide hints to code inspection tools, such as lint, to help detect more subtle code problems. Annotations are added as metadata tags that you attach to variables, parameters, and return values to inspect method return values, passed parameters, local variables, and fields. When used with code inspection tools, annotations can help you detect problems such as null pointer exceptions and resource type conflicts.</p><p>For Ex: Android resource IDs, for example, use an int to identify strings, graphics, colors, and other resource types, so inspection tools can&#39;t tell when you have specified a string resource where you should have specified a color resource.</p><p>Some Annotation examples are</p><ol><li>@NonNull &amp; @Nullable These are specific to Java</li><li>@RequirePermission(Manifest.Permission.SET_WALLPAPER)</li><li><a href="https://developer.android.com/studio/write/annotations#thread-annotations">@MainThread , </a><a href="https://developer.android.com/studio/write/annotations#thread-annotations">@UiThread , </a><a href="https://developer.android.com/studio/write/annotations#thread-annotations">@WorkerThread, etc.</a></li></ol><p>Let&#39;s understand some above Thread annotation.</p><p>If we have to do any Network request, we do it in a background thread because if we do it in the UI thread, the UI thread will be blocked it will freeze the the UI. Users will be frustrated. We might not even see a crash report. It is also one of the causes of ANRs.</p><p>So to tackle these problems we have these thread annotations, which tell that this method should only be called on the background thread or UI thread. If we try to call any method that is annotated with @WorkerThread on UI thread, it will throw an error. For Ex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxV3smsUYxq27xbNQ8b9Ww.png" /></figure><p>So in the above example, we can clearly see that any method that is annotation @WorkerThread can not be called from any UI thread. So this annotation helps us to avoid such laggy apps.</p><p>Now you must be thinking that in real-world apps we usually don&#39;t call network requests directly. There are many layers between the UI and the network. Will it work in this scenario? See the below photo for clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9KgUKjEdokApsZjyQQDsQ.png" /></figure><p>Android Lint can not directly find the error in this case. But what we can do is run an inspection by name to find wrong thread (Interprocedural) problems in the app. So after running this inspection, all wrong thread calls in our get identified.</p><h3>Lint Internals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdAW0zPUSNPf2SjTdXffug.png" /></figure><p>So the way Lint works is it starts out parsing the source file, like Java and Kotlin codes in our project. Then the Lint Wrap them around UAST ( Universal Abstract syntax tree )<br>This step is really important, because due to this UAST wrapping of our Java and Kotlin code, whenever we write Lint in our code. We have to write it only once and It works in both Java and Kotlin.</p><p>Now whenever we write any Lint Analysis that means we are directly operating in UAST. We write checks on source code, method calls we are interested in UAST.</p><p>Lint works on All types of files. We can write our custom lints on XML files like manifest, resources, layouts, or Gradle files.</p><blockquote>Lint check doesn&#39;t simply mean that we are directly looking at any plain text ( java, kotlin code ), but we also have type information available for each file like file type, class hierarchy, etc. It is really important to prevent false positives and just write powerful lint checks.</blockquote><h4><strong>How Android Lint and other static code analysis tools work</strong></h4><p>Originally, Android Lint was developed with the primary purpose of identifying issues specific to Android within Java code. To analyze Java code, Android Lint creates a Java-specific Abstract Syntax Tree (AST), a hierarchical/tree representation of the source code.</p><p>Similar static code analysis tools adopt language-specific ASTs for their analyses; for instance, Checkstyle for Java, ktlint for Kotlin. These tools navigate through the AST, identifying errors by examining its nodes and associated attributes.</p><h3><strong>Bonus Read</strong></h3><h4><strong>How Android Lint can check two languages at once</strong></h4><p>The difference between <strong>Android Lint</strong> and other tools is that as Kotlin also became a supported language for Android, Android Lint started to support Kotlin as well regarding the rules we already had for Java. For this, they introduced the so-called <strong>Universal Abstract Syntax Tree</strong> which provides a tree representation of the code that can be applied for both Kotlin and Java languages at the same time, so it’s on a higher abstraction level than a language-specific AST.<br>Both UAST and AST give high-level details about the source code. They don’t contain information about whitespaces or braces, but it is usually enough for the Android-specific rules.</p><h4><a href="https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi.html">PSI</a> Tree (Program Structure Interface Tree)</h4><p>The PSI tree is built on the top of UAST for Android Lint by JetBrains. In the case of other linting tools, it is built on the language-specific AST. PSI contains more details about the structure of the code, such as whitespaces, braces, and other similar elements.</p><p>In Android Lint, PSI Expressions are included in the implementation of the UAST Expressions, which are the nodes of the UAST.</p><p>There is even a handy intelliJ plugin: <a href="https://github.com/JetBrains/psiviewer/"><strong>PsiViewer</strong></a> that can ease the debugging of PSI tree-based code analysis rules.</p><p>We need both UAST and PSI Tree to create our linting formatting rule because UAST is great for filtering and visiting nodes that we are interested in for both languages at once, but as I mentioned it doesn’t provide formatting information, eg. whitespace information. UAST rather focuses on a higher abstraction level, so primarily it isn’t for creating formatting rules.</p><p>We will be writing custom lint checks for our project in <a href="https://medium.com/@gopalsays108/custom-lint-checks-in-android-part-2-by-gopal-c9c6ea5c95fd">Part 2</a> of this article. Where we will have practical examples with source code. <br>I hope you like Part 1 where we discussed some basics about custom lint check in Android.</p><p>Join me on <a href="https://www.linkedin.com/in/gopalsays108/"><strong>LinkedIn</strong></a><strong>, </strong>for a rollercoaster of insights, laughs, and maybe a meme or two.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=226e211c743e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getpowerplay/custom-lint-checks-in-android-by-gopal-226e211c743e">Custom lint checks in Android | By Gopal</a> was originally published in <a href="https://medium.com/getpowerplay">Powerplay</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>