<?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 Salim Brahim on Medium]]></title>
        <description><![CDATA[Stories by Salim Brahim on Medium]]></description>
        <link>https://medium.com/@salimbrahim?source=rss-f7dcfc45d76d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sZXA8MfyXF_1hIAc.jpg</url>
            <title>Stories by Salim Brahim on Medium</title>
            <link>https://medium.com/@salimbrahim?source=rss-f7dcfc45d76d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:37:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salimbrahim/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[Modernizing Legacy Applications with the Strangler Fig Pattern]]></title>
            <link>https://medium.com/@salimbrahim/modernizing-legacy-applications-with-the-strangler-fig-pattern-2b44d8e85494?source=rss-f7dcfc45d76d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b44d8e85494</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[strangler-fig-pattern]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Salim Brahim]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 11:51:37 GMT</pubDate>
            <atom:updated>2026-11-19T11:51:37.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PM7KpWDGT6xn55rLzx-oeg.png" /></figure><p><em>How to progressively replace a legacy system without disrupting business operations.</em></p><h3>Introduction</h3><p>Sooner or later, every long-lived application reaches the same point. The framework is outdated, the build is fragile, and nobody wants to touch certain modules. The tempting answer is: “Let’s rewrite everything.”</p><p>The rewrite then takes twice as long as planned, and the business waits the whole time.</p><p>The <strong>Strangler Fig pattern</strong> takes the opposite approach. Instead of replacing the legacy system in one go, you build new services around it and move functionality over piece by piece, until the old system has nothing left to do and can finally be switched off.</p><p>This article explores the principle, its architecture, typical use cases, and the trade-offs worth understanding before starting a migration.</p><h3>1. The Problem with Big-Bang Rewrites</h3><p>A complete rewrite might seem like the cleanest solution to an outdated architecture. However, it often introduces more risks than expected.</p><p>Three major challenges typically emerge:</p><ul><li><strong>Long delivery freeze:</strong> The old system must keep running while the new one is being developed. As a result, features are either developed twice or postponed.</li><li><strong>Late discovery of hidden behavior:</strong> Legacy applications contain years of undocumented business rules. These rules are often discovered only when the new implementation fails to reproduce existing behavior.</li><li><strong>All-or-nothing risk:</strong> A single cut-over date, one rollback plan, and very little room for error.</li></ul><h3>Architecture Before Migration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNcT56OwoSBOv2WO.png" /><figcaption><em>Figure 1: A traditional monolithic architecture where application modules are tightly coupled.</em></figcaption></figure><p>Everything is coupled. A change to one module can force a rebuild and redeployment of the entire application.</p><h3>2. Understanding the Strangler Fig Pattern</h3><p>The name comes from the strangler fig, a plant that grows around a host tree until it eventually replaces it.</p><p>In software architecture, the concept follows the same principle:</p><ol><li>Introduce a <strong>routing layer (facade)</strong> in front of the legacy system.</li><li>Build a new service for a clearly defined business domain.</li><li>Route that domain’s traffic to the new service while keeping the remaining functionality on the legacy system.</li><li>Repeat the process until the legacy system no longer handles requests and can be retired.</li></ol><h3>Architecture During Migration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i2gvGuSiDUuPpzTH.png" /><figcaption><em>Figure 2: A hybrid architecture where the routing layer distributes requests between the legacy application and newly extracted services.</em></figcaption></figure><p>During migration, both architectures coexist. New functionality is progressively transferred to independent services, while the legacy application continues handling everything that has not yet been migrated.</p><h3>Sequence of a Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ZlsyKDxcVOwAQtu.png" /><figcaption><em>Figure 3: Request routing between the client, routing facade, new service, and legacy application.</em></figcaption></figure><p>The key point is that clients do not need to know what happens behind the scenes. The external URL contract can remain unchanged while the underlying implementation evolves.</p><h3>The Migration Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*JYIrHbA1bTKkHGT8RbDrTw.png" /><figcaption><em>Figure 4: The progressive transition from a legacy monolith to an architecture based on independent services.</em></figcaption></figure><h3>Big-Bang Rewrite vs. Strangler Fig</h3><p>The main difference between these approaches is how risk and business value are distributed throughout the migration.</p><p><strong>Big-bang rewrite:</strong></p><ul><li>One major cut-over date.</li><li>High migration risk.</li><li>Rollback is difficult.</li><li>Business value is mainly delivered at the end.</li><li>Feature development may be frozen or duplicated.</li></ul><p><strong>Strangler Fig:</strong></p><ul><li>Multiple incremental migration steps.</li><li>Smaller and more manageable risks.</li><li>Individual routes can be redirected to the legacy implementation.</li><li>Business value is delivered progressively.</li><li>Existing feature development can continue throughout the migration.</li></ul><p>The second approach provides greater flexibility because each migration step can be validated before moving to the next one.</p><h3>3. Typical Use Cases</h3><p>The Strangler Fig pattern is particularly useful in several modernization scenarios.</p><p><strong>Aging technology stack</strong></p><p>An old Java Servlet application or a frontend built with an outdated framework can be progressively replaced without requiring an immediate rewrite of the entire platform.</p><p><strong>Clearly defined business domains</strong></p><p>Domains such as authentication, user management, and reporting can be good candidates for extraction when their responsibilities and boundaries are well understood.</p><p><strong>Platform modernization</strong></p><p>Moving from an older Java version to a recent LTS version, or adopting a lighter framework with faster startup times, can be achieved incrementally while keeping the existing application operational.</p><p><strong>Parallel execution</strong></p><p>Another useful technique is to send the same request to both implementations and compare their results before switching production traffic.</p><h3>Parallel Run (Shadow Traffic)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Od1KzVXzDXtLcRJC.png" /><figcaption><em>Figure 5: Shadow traffic allows the new implementation to process duplicated requests while the legacy implementation remains responsible for the actual production response.</em></figcaption></figure><p>This approach helps identify behavioral differences before the new service becomes responsible for production traffic.</p><h3>4. Advantages of the Strangler Fig Pattern</h3><p>The pattern offers several architectural and operational benefits.</p><ul><li><strong>Lower migration risk:</strong> Each step is relatively small, independently testable, and reversible.</li><li><strong>Continuous business value:</strong> Every extracted service can be deployed to production independently.</li><li><strong>Progressive learning:</strong> The first migrated domain helps the team identify architectural challenges before extracting additional domains.</li><li><strong>Independent scaling and deployment:</strong> New services can evolve according to their own deployment and scaling requirements.</li><li><strong>Measurable progress:</strong> Instead of saying “we are almost done,” teams can measure the percentage of functionality or traffic successfully migrated.</li></ul><h3>5. Drawbacks and Common Pitfalls</h3><p>Despite its advantages, the pattern introduces challenges that must be managed carefully.</p><p><strong>Operating two systems simultaneously</strong></p><p>During migration, both architectures must be maintained. This increases operational complexity and short-term costs.</p><p><strong>The shared database trap</strong></p><p>If new and legacy services continue reading and writing the same database tables, the original coupling remains. Data ownership should be defined early.</p><h3>The Shared Database Anti-Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sye4FVhT0JgYhKTv.png" /><figcaption><em>Figure 6: Sharing database tables between services can preserve dependencies that the migration was supposed to eliminate.</em></figcaption></figure><p><strong>The last 10% problem</strong></p><p>Less frequently used or difficult-to-extract modules can remain in the legacy system indefinitely. Establish clear decommissioning milestones.</p><p><strong>Routing layer as a single point of failure</strong></p><p>The facade becomes a critical component of the architecture. It must remain lightweight, highly available, and properly monitored.</p><p><strong>Insufficient automated tests</strong></p><p>Without reliable tests for the legacy application, proving behavioral equivalence becomes difficult. Characterization tests should be introduced before migration.</p><p>The right mindset is simple:</p><p><strong>Extract a domain, don’t just copy the code.</strong></p><p>Moving a poorly designed module into a modern framework does not automatically improve its architecture.</p><h3>6. A Practical Example: Building a Routing Facade</h3><p>A routing facade is responsible for deciding whether a request should be forwarded to a newly extracted service or remain on the legacy application.</p><p>Here is a minimal implementation using Node.js, Express, and http-proxy-middleware.</p><pre>const express = require(&quot;express&quot;);<br>const { createProxyMiddleware } = require(&quot;http-proxy-middleware&quot;);<br>const app = express();<br>const LEGACY = process.env.LEGACY_URL;<br>const REPORTING = process.env.REPORTING_URL;<br>const AUTH = process.env.AUTH_URL;<br>// Migrated domains go to the new services<br>app.use(<br>  &quot;/api/auth&quot;,<br>  createProxyMiddleware({<br>    target: AUTH,<br>    changeOrigin: true<br>  })<br>);<br>app.use(<br>  &quot;/api/reporting/monthly&quot;,<br>  createProxyMiddleware({<br>    target: REPORTING,<br>    changeOrigin: true<br>  })<br>);<br>// Everything else still goes to the legacy system<br>app.use(<br>  &quot;/&quot;,<br>  createProxyMiddleware({<br>    target: LEGACY,<br>    changeOrigin: true<br>  })<br>);<br>app.listen(3000);</pre><p>Migrating another domain simply means introducing a new routing rule and deploying its corresponding service.</p><p>If something goes wrong, the routing configuration can be updated to redirect traffic to the legacy implementation.</p><p>For a more controlled rollout, traffic can also be progressively redirected based on percentage or user groups:</p><ul><li>5% of traffic to the new service.</li><li>25% after successful validation.</li><li>50% during the next rollout phase.</li><li>100% once the implementation is considered stable.</li></ul><h3>Progress Over Time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QXxE353XFlUYFeID.png" /><figcaption><em>Figure 7: Progressive migration increases the percentage of traffic handled by new services until the legacy application is no longer needed.</em></figcaption></figure><h3>7. Checklist Before Starting</h3><p>Before adopting the Strangler Fig pattern, consider the following questions:</p><ul><li>Can you identify business domains with clear boundaries that can be extracted independently?</li><li>Is there a routing layer, or can one be introduced, in front of the legacy application?</li><li>Do you have enough automated tests to verify that the new implementation preserves existing behavior?</li><li>Is a data ownership strategy defined to prevent long-term database coupling?</li><li>Are monitoring, logging, and rollback mechanisms ready?</li><li>Is there a clear decommissioning strategy for the legacy application?</li></ul><p>If most answers are no, start by introducing characterization tests and a routing facade.</p><p>These two foundations make subsequent extractions significantly safer.</p><h3>Conclusion</h3><p>The Strangler Fig pattern replaces one risky architectural transformation with a sequence of smaller, reversible steps.</p><p>Its benefits are significant: continuous delivery, reduced migration risk, independent service evolution, and measurable progress.</p><p>However, these benefits come with trade-offs. Operating two systems simultaneously increases complexity, and completing the migration requires architectural discipline and a clear decommissioning strategy.</p><p>Ultimately, adopting the Strangler Fig pattern is not simply about moving to microservices or using a modern framework.</p><p>It is about <strong>evolving an existing system without interrupting its ability to deliver business value.</strong></p><p><em>What has been your experience with legacy modernization? Have you used the Strangler Fig pattern, or do you prefer a different approach? Share your thoughts in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b44d8e85494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs. GraphQL: Which API Architecture Should You Choose?]]></title>
            <link>https://medium.com/@salimbrahim/rest-vs-graphql-which-api-architecture-should-you-choose-192ca26a338c?source=rss-f7dcfc45d76d------2</link>
            <guid isPermaLink="false">https://medium.com/p/192ca26a338c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <dc:creator><![CDATA[Salim Brahim]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 11:05:45 GMT</pubDate>
            <atom:updated>2026-11-18T11:05:45.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NazPzcad9I7KX374gQrqzQ.png" /></figure><p><em>Understanding the trade-offs between REST and GraphQL to build scalable, efficient, and maintainable applications.</em></p><h3>Introduction</h3><p>APIs are at the heart of modern web and mobile applications. They define how frontend applications communicate with backend services, exchange data, and interact with business logic.</p><p>For many years, <strong>REST (Representational State Transfer)</strong> has been the standard approach for designing web APIs. Its simplicity, resource-oriented architecture, and native integration with HTTP have made it a reliable choice across enterprise applications and distributed systems.</p><p>However, as applications have become more complex, frontend requirements have evolved. Web dashboards, mobile applications, and multi-platform systems often need data from multiple resources without making numerous network requests.</p><p>This is where <strong>GraphQL</strong> comes into the picture.</p><p>Originally developed at Facebook and later open-sourced, GraphQL introduces a different approach: instead of allowing the server to define the exact response structure, clients specify the data they need.</p><p>But does GraphQL mean REST is becoming obsolete?</p><p>Not at all. Both technologies solve different problems, and choosing between them requires understanding their architectural trade-offs.</p><p>Let’s explore the differences.</p><h3>1. Understanding REST</h3><p>REST is an architectural style introduced by Roy Fielding in his 2000 doctoral dissertation. It organizes APIs around resources, each identified by a unique URI.</p><p>For example, consider an e-commerce application:</p><pre>GET    /api/v1/products<br>GET    /api/v1/products/25<br>POST   /api/v1/orders<br>PUT    /api/v1/orders/12<br>DELETE /api/v1/orders/12</pre><p>Each endpoint represents a resource or an operation on that resource.</p><p>REST uses standard HTTP methods to define interactions:</p><h3>HTTP Methods and Their Properties</h3><p><strong>GET — Retrieve a resource</strong></p><ul><li>Idempotent: Yes</li></ul><p><strong>POST — Create a resource or trigger an operation</strong></p><ul><li>Idempotent: No (generally)</li></ul><p><strong>PUT — Replace a resource</strong></p><ul><li>Idempotent: Yes</li></ul><p><strong>PATCH — Partially update a resource</strong></p><ul><li>Idempotent: Not necessarily</li></ul><p><strong>DELETE — Delete a resource</strong></p><ul><li>Idempotent: Yes</li></ul><p>One of REST’s greatest strengths is its alignment with existing HTTP infrastructure.</p><h3>Why REST remains popular</h3><p><strong>1. Simplicity and clear contracts</strong></p><p>REST endpoints are intuitive and easy to understand. Resources such as /users, /orders, and /products provide a predictable API structure.</p><p>This makes collaboration between frontend and backend teams straightforward.</p><p><strong>2. Native HTTP caching</strong></p><p>REST benefits from standard HTTP caching mechanisms.</p><p>Reverse proxies, CDNs, and browsers can cache GET responses using headers such as:</p><ul><li>Cache-Control</li><li>ETag</li><li>Last-Modified</li></ul><p>This can significantly improve application performance and reduce unnecessary backend requests.</p><p><strong>3. Mature documentation and tooling</strong></p><p>The OpenAPI Specification provides a standardized way to document REST APIs.</p><p>Tools such as Swagger UI and Redoc make it easier to explore endpoints, generate client SDKs, and automate API testing.</p><p><strong>4. Suitable for microservices</strong></p><p>REST works naturally with domain-oriented microservices. Each service can expose its own resources and evolve independently.</p><p>This makes REST a practical choice for internal service communication and public APIs.</p><h3>2. Where REST Can Become a Bottleneck</h3><p>Despite its advantages, REST has limitations, especially when frontend applications require complex and interconnected data.</p><p>Two common challenges are over-fetching and under-fetching.</p><h3>Over-fetching: Receiving more data than necessary</h3><p>Imagine a mobile application displaying a simple user profile card.</p><p>The interface only needs:</p><ul><li>First name</li><li>Profile picture</li></ul><p>However, the REST endpoint returns the complete user object:</p><pre>{<br>  &quot;id&quot;: 12,<br>  &quot;firstname&quot;: &quot;Alice&quot;,<br>  &quot;lastname&quot;: &quot;Martin&quot;,<br>  &quot;email&quot;: &quot;alice@example.com&quot;,<br>  &quot;phoneNumber&quot;: &quot;+33612345678&quot;,<br>  &quot;billingAddress&quot;: {<br>    &quot;street&quot;: &quot;123 Dev Avenue&quot;,<br>    &quot;city&quot;: &quot;Paris&quot;<br>  },<br>  &quot;createdAt&quot;: &quot;2026-01-01T10:00:00Z&quot;<br>}</pre><p>Most of this information is unnecessary for the current interface.</p><p>This is called <strong>over-fetching</strong>: the client receives more data than it actually needs.</p><p>It can increase network consumption, serialization overhead, and processing costs, particularly on mobile devices.</p><h3>Under-fetching: Making multiple requests</h3><p>Now imagine a dashboard displaying:</p><ul><li>User information</li><li>Recent orders</li><li>Order details</li><li>Payment information</li></ul><p>If the API exposes these resources through separate endpoints, the frontend may need several requests to assemble the complete view.</p><p>This is known as <strong>under-fetching</strong>.</p><p>Multiple network round-trips can increase latency and make frontend data orchestration more complicated.</p><p>These challenges become more noticeable in applications with complex dashboards and mobile interfaces.</p><h3>3. Understanding GraphQL</h3><p>GraphQL introduces a client-driven approach to API communication.</p><p>Instead of exposing multiple resource-specific endpoints, a GraphQL server typically exposes a single endpoint:</p><pre>POST /api/v1/graphql</pre><p>The client sends a query describing exactly which fields it needs, and the server returns a response matching that requested structure.</p><h3>Example: Requesting dashboard data</h3><p>Suppose a dashboard needs the user’s name and their latest order.</p><p>With GraphQL, the client can express this requirement in a single query:</p><pre>query GetDashboardData {<br>  user(id: 10) {<br>    firstname<br>    lastname<br>    orders(limit: 1) {<br>      id<br>      totalPrice<br>    }<br>  }<br>}</pre><p>The server returns:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;user&quot;: {<br>      &quot;firstname&quot;: &quot;Alice&quot;,<br>      &quot;lastname&quot;: &quot;Martin&quot;,<br>      &quot;orders&quot;: [<br>        {<br>          &quot;id&quot;: 15,<br>          &quot;totalPrice&quot;: 120<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>The response contains only the requested fields.</p><p>This approach reduces unnecessary data transfer and can combine information from multiple resources into one client operation.</p><h3>Why developers choose GraphQL</h3><p><strong>1. Client-controlled data structures</strong></p><p>Frontend developers can request exactly the fields needed by each component.</p><p>If a mobile interface no longer needs a field, it can simply be removed from the query without necessarily requiring a backend API change.</p><p><strong>2. Aggregating multiple resources</strong></p><p>GraphQL allows clients to retrieve related information through a single query.</p><p>Instead of manually coordinating multiple REST requests, the frontend can describe the required data relationships directly.</p><p><strong>3. Flexible API evolution</strong></p><p>GraphQL schemas can evolve by introducing new fields while keeping existing fields available.</p><p>Deprecated fields can be marked using the @deprecated directive, giving clients time to migrate.</p><p>This reduces the need for frequent breaking API version changes, although schema evolution still requires proper management.</p><p><strong>4. Strongly typed schema</strong></p><p>GraphQL provides a schema that describes available types, fields, queries, mutations, and relationships.</p><p>This improves discoverability and allows tools to generate documentation and strongly typed client operations.</p><h3>4. The Challenges of GraphQL</h3><p>GraphQL provides flexibility to frontend developers, but this flexibility introduces additional responsibilities on the backend.</p><h3>1. More implementation complexity</h3><p>A production-ready GraphQL application requires several components:</p><ul><li>Schema Definition Language (SDL)</li><li>Queries and mutations</li><li>Resolvers</li><li>Input validation</li><li>Authorization and access control</li><li>Subscription management when real-time communication is required</li></ul><p>This introduces a learning curve and additional maintenance responsibilities.</p><h3>2. The N+1 database query problem</h3><p>One of the most important GraphQL performance challenges is the N+1 problem.</p><p>Consider a query requesting a company, its users, and each user’s orders.</p><p>An inefficient resolver implementation might execute:</p><ol><li>One query to retrieve the company.</li><li>One query to retrieve its users.</li><li>Fifty additional queries to retrieve orders for fifty users.</li></ol><p>Instead of a few optimized database operations, the application executes dozens of queries.</p><p>A common solution is the <strong>DataLoader pattern</strong>, which batches and caches database requests.</p><p>For example, instead of querying orders individually, the backend can retrieve them using:</p><pre>SELECT *<br>FROM orders<br>WHERE user_id IN (1, 2, 3, 4, 5);</pre><p>This reduces database round-trips and improves resolver performance.</p><h3>3. More complicated caching</h3><p>REST benefits from standard HTTP caching mechanisms, particularly for GET requests.</p><p>GraphQL commonly uses POST requests against a single endpoint, making traditional URL-based caching less straightforward.</p><p>Solutions include:</p><ul><li>Persisted queries</li><li>Apollo Client caching</li><li>DataLoader caching</li><li>Application-level response caching</li><li>CDN caching with appropriate GraphQL configurations</li></ul><p>GraphQL caching is absolutely possible, but it often requires more deliberate architectural decisions.</p><h3>4. Security and query complexity</h3><p>Because clients can construct queries dynamically, poorly controlled GraphQL APIs can expose backend resources to expensive or deeply nested queries.</p><p>Production implementations should consider:</p><ul><li>Query depth limits</li><li>Query complexity analysis</li><li>Rate limiting</li><li>Field-level authorization</li><li>Pagination</li><li>Request timeouts</li></ul><p>GraphQL flexibility must be balanced with resource protection.</p><h3>5. REST vs. GraphQL: A Practical Comparison</h3><p><strong>1. Architecture</strong></p><ul><li>REST: Resource-oriented architecture.</li><li>GraphQL: Query-oriented architecture.</li></ul><p><strong>2. Endpoints</strong></p><ul><li>REST: Multiple endpoints.</li><li>GraphQL: Usually a single endpoint.</li></ul><p><strong>3. Data Selection</strong></p><ul><li>REST: Server-defined response structure.</li><li>GraphQL: Client-defined response structure.</li></ul><p><strong>4. Over-fetching</strong></p><ul><li>REST: Possible.</li><li>GraphQL: Reduced.</li></ul><p><strong>5. Under-fetching</strong></p><ul><li>REST: Possible.</li><li>GraphQL: Reduced.</li></ul><p><strong>6. HTTP Caching</strong></p><ul><li>REST: Native support.</li><li>GraphQL: Requires additional caching strategies.</li></ul><p><strong>7. Documentation</strong></p><ul><li>REST: OpenAPI / Swagger.</li><li>GraphQL: GraphQL schema.</li></ul><p><strong>8. Learning Curve</strong></p><ul><li>REST: Relatively low.</li><li>GraphQL: Moderate to high.</li></ul><p><strong>9. Backend Complexity</strong></p><ul><li>REST: Generally lower.</li><li>GraphQL: Generally higher.</li></ul><p><strong>10. Real-Time Capabilities</strong></p><ul><li>REST: Usually relies on WebSockets or Server-Sent Events (SSE).</li><li>GraphQL: Supports subscriptions.</li></ul><p><strong>11. Microservices</strong></p><ul><li>REST: Excellent fit for service APIs.</li><li>GraphQL: Useful for aggregation and federation.</li></ul><p>Neither approach is universally better. The right choice depends on the application’s requirements and the complexity of its data interactions.</p><h3>6. When Should You Choose REST ?</h3><p>REST remains an excellent default choice in many scenarios.</p><p>Consider REST when:</p><ul><li><strong>Building public APIs:</strong> Standard HTTP conventions make integration easier for third-party developers.</li><li><strong>Developing CRUD applications:</strong> Resource-oriented operations map naturally to business entities.</li><li><strong>Building internal microservices:</strong> Explicit endpoints provide clear service boundaries and straightforward communication.</li><li><strong>Prioritizing HTTP caching:</strong> Standard caching mechanisms can improve performance without additional infrastructure.</li><li><strong>Keeping backend complexity low:</strong> REST is often easier to implement, test, document, and maintain.</li></ul><p>For many enterprise applications, REST provides everything needed without introducing unnecessary architectural complexity.</p><h3>7. When Should You Choose GraphQL ?</h3><p>GraphQL becomes particularly interesting when applications have complex data requirements.</p><p>Consider GraphQL when:</p><ul><li><strong>Developing multi-platform applications:</strong> Web, mobile, and desktop clients need different data structures from the same backend.</li><li><strong>Building complex dashboards:</strong> A single interface requires information from multiple related resources.</li><li><strong>Working with highly connected data:</strong> The domain contains deeply nested relationships.</li><li><strong>Accelerating frontend development:</strong> Teams frequently modify UI requirements and need flexibility in selecting data.</li><li><strong>Optimizing mobile communication:</strong> Reducing unnecessary payloads and network round-trips is important.</li></ul><p>GraphQL is especially valuable when frontend requirements evolve rapidly and the backend needs to support multiple client experiences.</p><h3>8. The Hybrid Approach: REST and GraphQL Together</h3><p>An important architectural consideration is that REST and GraphQL are not mutually exclusive.</p><p>Modern enterprise systems can combine both approaches through a <strong>Backend-for-Frontend (BFF)</strong> or API Gateway architecture.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qi9zQq740lqgzT4r.png" /></figure><p>In this architecture:</p><ul><li>Frontend applications communicate through GraphQL.</li><li>The GraphQL gateway aggregates data from multiple backend services.</li><li>Internal microservices expose REST APIs.</li><li>Each service maintains its own business logic and responsibilities.</li></ul><p>This approach combines frontend flexibility with backend service isolation.</p><p>However, it also introduces an additional layer that must be monitored, secured, and maintained.</p><p>The hybrid model is therefore most useful when the benefits of centralized data aggregation justify its operational complexity.</p><h3>Conclusion</h3><p>REST and GraphQL represent two different approaches to API design, each with its own strengths and limitations.</p><p><strong>REST prioritizes simplicity, standardized HTTP behavior, and resource-oriented architecture.</strong> It remains a strong choice for public APIs, CRUD operations, and internal microservices.</p><p><strong>GraphQL prioritizes flexibility, precise data selection, and frontend integration efficiency.</strong> It is particularly useful for complex dashboards, mobile applications, and systems with multiple client platforms.</p><p>The most important lesson is that architectural decisions should be driven by actual requirements rather than technology trends.</p><p>Before choosing an API architecture, evaluate:</p><ul><li>The complexity of your data relationships.</li><li>The number and diversity of client applications.</li><li>Network performance requirements.</li><li>Caching and security requirements.</li><li>Your team’s technical expertise.</li><li>Long-term maintenance and operational costs.</li></ul><p>In some systems, REST is the simplest and most effective solution. In others, GraphQL provides significant value. And in complex enterprise environments, combining both can be the most practical architectural decision.</p><p><strong>The goal is not to choose the most popular technology. It is to choose the architecture that solves the right problem with the least unnecessary complexity.</strong></p><h3>Key Takeaways</h3><ul><li>REST is a reliable choice for resource-oriented APIs and microservices.</li><li>GraphQL gives clients greater control over the structure of returned data.</li><li>GraphQL reduces over-fetching and under-fetching but does not automatically guarantee better performance.</li><li>DataLoader and query optimization are important for avoiding GraphQL’s N+1 problem.</li><li>REST and GraphQL can coexist in the same enterprise architecture.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192ca26a338c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend For Frontend (BFF)]]></title>
            <link>https://medium.com/@salimbrahim/backend-for-frontend-bff-23ea7da82759?source=rss-f7dcfc45d76d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ea7da82759</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-for-frontend]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Salim Brahim]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 13:01:44 GMT</pubDate>
            <atom:updated>2026-07-20T13:03:13.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcFQ8Pix-fe-SQcafpxPqw.png" /></figure><h4>Introduction</h4><p>Once an application serves more than one type of client, a question inevitably comes up: should you expose a single generic API, or a dedicated layer per client? The <strong>Backend For Frontend (BFF)</strong> pattern addresses this by introducing an orchestration backend tailored to each frontend — mobile, web, back-office — instead of a single entry point expected to satisfy everyone.</p><p>This article covers the principle, the architecture, concrete use cases, and the trade-offs worth knowing before adopting it.</p><h3>1. The problem BFF solves</h3><p>A general-purpose API designed to serve every client at once almost always produces two classic symptoms:</p><ul><li><strong>Over-fetching</strong>: an endpoint returns 20 fields when the mobile screen only displays 3.</li><li><strong>Under-fetching</strong>: rendering a single screen requires chaining several calls to different resources.</li></ul><h3>Architecture without a BFF</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EgbLaRVhB5206ykO.png" /></figure><p>Each client orchestrates its own calls and assembles the data on the client side. The result: aggregation logic gets duplicated across every client application, and each client becomes tightly coupled to the exact shape of the internal services.</p><p><strong>Measured consequences on a typical case</strong> (a “profile + activities + notifications” screen):</p><h3>2. The BFF pattern</h3><p>The principle: instead of one shared API, <strong>each client type gets its own orchestration backend</strong>, sitting between the frontend and the internal services. This backend:</p><ul><li>exposes an API shaped exactly for its client’s needs;</li><li>orchestrates calls to internal services;</li><li>aggregates, filters, and reshapes the data before returning it.</li></ul><h3>Architecture with a BFF</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TI0MQ5DqgQQ_qXnA.png" /></figure><p>The number of connections to internal services doesn’t fundamentally change, but <strong>orchestration now happens once, server-side</strong>, in a dedicated service — not inside every client.</p><h3>Sequence of an aggregated request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*osXoqsLnlgSb6Z_W.png" /></figure><p><strong>Measured gain on the same case:</strong></p><h4>Without BFF</h4><ul><li><strong>Network calls per screen:</strong><br> A single screen may require multiple API requests (for example, fetching user data, permissions, and related resources separately).<br> → <strong>Around 3 network calls per screen</strong></li><li><strong>Estimated latency:</strong><br> Each request introduces additional network overhead, especially when calls are sequential or depend on each other.<br> → <strong>Approximately 800 ms — 1.2 seconds</strong></li><li><strong>Aggregation logic:</strong><br> The frontend becomes responsible for combining data from multiple APIs.<br> This logic is often duplicated across different clients (Web, Mobile, Desktop), increasing maintenance costs.</li></ul><h4>With BFF</h4><ul><li><strong>Network calls per screen:</strong><br> The frontend communicates with a dedicated BFF endpoint that handles the required aggregation internally.<br> → <strong>Reduced to 1 network call per screen</strong></li><li><strong>Estimated latency:</strong><br> Fewer client-server round trips lead to improved response times.<br> → <strong>Approximately 200–300 ms</strong></li><li><strong>Aggregation logic:</strong><br> Data composition is centralized on the server side, allowing each frontend to receive exactly the data it needs.</li></ul><p>The aggregation work doesn’t disappear — it moves, from the client (on a potentially unstable network) to the server (close to the data).</p><h3>3. Typical use cases</h3><p>BFF delivers real value in the following contexts:</p><ul><li><strong>Multi-client with heterogeneous needs</strong>: a battery/network-optimized mobile app, a richer web client, a back-office with complex aggregated views.</li><li><strong>Gateway over many microservices</strong>: when a screen depends on 4, 5, or 10 microservices, the client should never need to know that topology.</li><li><strong>Controlled exposure of partner APIs</strong>: a partner-bff can expose a filtered, versioned subset of data to external consumers without leaking the internal structure.</li><li><strong>Progressive migration</strong>: a BFF can absorb changes from a legacy backend while it’s being reworked, without breaking existing clients.</li><li><strong>BFF + GraphQL</strong>: nothing prevents a BFF from exposing GraphQL internally rather than REST — BFF solves <em>where</em> aggregation happens, GraphQL is one possible tool <em>for</em> doing it. The two aren’t competitors.</li></ul><blockquote><em>A </em><strong><em>partner API</em></strong><em> is </em><strong><em>a software interface shared exclusively with authorized, vetted business partners to facilitate secure data exchange and collaboration</em></strong><em>. Unlike public APIs that anyone can access, or private APIs used strictly within a company, partner APIs act as a </em><strong><em>controlled digital bridge between distinct business systems.</em></strong></blockquote><h3>4. Advantages</h3><ul><li><strong>Tailored API per client</strong>: each BFF returns exactly the data shape its client needs.</li><li><strong>Fewer network calls</strong>: especially critical on mobile (latency, battery, data cost).</li><li><strong>Decoupling frontend from internal backend</strong>: a change in an internal microservice only impacts the BFFs that depend on it, not client apps directly.</li><li><strong>Team velocity</strong>: a mobile frontend team can evolve its BFF without depending on the release cycle of an API shared by everyone.</li><li><strong>Reduced security surface</strong>: each BFF only exposes what its client actually needs, shrinking the attack surface for external clients.</li></ul><h3>5. Drawbacks and pitfalls</h3><ul><li><strong>Logic duplication</strong>: if every BFF reimplements the same business rules (status computation, formatting, validation), you recreate technical debt spread across multiple services.</li><li><strong>Service proliferation</strong>: one BFF per client is one more service to deploy, monitor, secure, and evolve — a real operational cost.</li><li><strong>Blurry boundary with business logic</strong>: without clear discipline, a BFF becomes a dumping ground for rules that should live in the underlying services.</li><li><strong>Potential added latency</strong>: an extra network hop exists (client → BFF → services); the net gain depends on how much it reduces round-trips in return.</li><li><strong>Deployment complexity</strong>: versioning and deploying several BFFs in parallel requires a CI/CD pipeline and observability up to the task.</li></ul><p><strong>The right instinct</strong>: a BFF orchestrates and adapts — it should never carry business rules that belong to the underlying services. If two BFFs need the same rule, that’s a signal it belongs in a shared service instead.</p><h3>6. Concrete example — mobile-bff in Node.js / Express</h3><pre>// mobile-bff/routes/dashboard.js<br>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const { fetchProfile, fetchActivities, fetchNotifications } = require(&quot;../clients/internal-services&quot;);<br>router.get(&quot;/dashboard/:userId&quot;, async (req, res) =&gt; {<br>  const { userId } = req.params;<br>  try {<br>    const [profile, activities, notifications] = await Promise.all([<br>      fetchProfile(userId),<br>      fetchActivities(userId),<br>      fetchNotifications(userId),<br>    ]);<br>    // Response shaped specifically for the mobile screen:<br>    // no superfluous fields, aggressive pagination, pre-computed values.<br>    res.json({<br>      profile: {<br>        name: profile.name,<br>        avatarUrl: profile.avatarUrl,<br>      },<br>      recentActivities: activities.slice(0, 5),<br>      unreadNotificationsCount: notifications.filter(n =&gt; !n.read).length,<br>    });<br>  } catch (err) {<br>    res.status(502).json({ error: &quot;Failed to aggregate dashboard data&quot; });<br>  }<br>});<br>module.exports = router;</pre><p>For comparison, a web-bff querying the same services would likely return the full activity history and detailed notifications rather than a simple count — because the web screen displays more information at once.</p><pre>// web-bff/routes/dashboard.js<br>res.json({<br>  profile,                     // full object<br>  activities,                  // full, untruncated history<br>  notifications,               // detailed list, not just a count<br>});</pre><p>That’s exactly the point of the pattern: <strong>the same source data, two different response shapes</strong>, each tailored to the screen consuming it.</p><h3>7. Checklist before adopting a BFF</h3><ul><li>Do several genuinely heterogeneous clients consume the same data (mobile, web, back-office, partners) ?</li><li>Are over-fetching or under-fetching symptoms already visible in the current codebase ?</li><li>Does the team have the operational capacity to maintain one or more additional orchestration services ?</li><li>Is there a clear discipline in place to prevent the BFF from absorbing business logic that belongs elsewhere ?</li></ul><p>If the answer is no to most of these, a well-designed single API — possibly with a few targeted aggregated endpoints — is probably still enough. BFF isn’t a universal solution: it’s a valuable pattern once the complexity of the API’s consumers genuinely justifies it.</p><h3>Conclusion</h3><p>Backend For Frontend moves the aggregation work from the client to the server, and specializes it by consumer type rather than generalizing it into a single API. The gain is real — fewer network calls, lower latency, cleaner decoupling between frontend and internal services — but it comes with an operational cost that has to be consciously accepted: more services to maintain, and constant vigilance to keep each BFF an orchestration layer rather than a repository of business rules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ea7da82759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Professional REST API]]></title>
            <link>https://medium.com/@salimbrahim/designing-a-professional-rest-api-fd4a7dd10658?source=rss-f7dcfc45d76d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4a7dd10658</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Salim Brahim]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 10:33:07 GMT</pubDate>
            <atom:updated>2026-07-16T10:34:26.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03rmdAWkoeE_r5BjrO1U0Q.png" /></figure><h3>Introduction</h3><p>In a modern application architecture, the REST API serves as the central communication hub between various components of an ecosystem:</p><ul><li><strong>Web Applications</strong> (Single Page Applications, Portals);</li><li><strong>Mobile Applications</strong> (iOS, Android);</li><li><strong>Partner Systems</strong> and third-party services;</li><li><strong>Internal Microservices</strong>;</li></ul><p>Building a functional REST API is relatively simple — a few controllers, HTTP routes, and database access are enough to expose your first endpoints.</p><p>However, a production-ready API built for enterprise standards must meet much stricter requirements: <strong>scalability, maintainability, security, performance, backward compatibility,</strong> and a <strong>clear integration contract</strong>. It should no longer be thought of as a simple gateway to a database, but rather as a durable software contract.</p><h3>1. Understanding REST Architecture</h3><p>REST (<em>Representational State Transfer</em>) is an architectural style based on manipulating <strong>resources</strong> using standardized HTTP operations and stateless protocols.</p><h3>Classic Communication Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4ItMlRWnSY3c0DY.png" /></figure><blockquote><strong><em>The Principle of Loose Coupling:</em></strong><em> The client has no knowledge of the server’s internal implementation (programming language, framework, or database type). It interacts exclusively through the contract exposed by the API.</em></blockquote><h3>Standard Transaction Example</h3><ul><li><strong>Client Request:</strong></li></ul><pre>GET /api/products/15<br>HTTP/1.1<br>Host: api.mysite.com<br>Accept: application/json</pre><ul><li><strong>Server Response (Resource Representation):</strong></li></ul><pre>{<br>  &quot;id&quot;: 15,<br>  &quot;name&quot;: &quot;Laptop&quot;,<br>  &quot;price&quot;: 1200,<br>  &quot;category&quot;: &quot;Computer&quot;<br>}</pre><h3>2. Designing the API Around Business Resources</h3><p>The most common design mistake is modeling API routes after actions or RPC-style (<em>Remote Procedure Call</em>) functions.</p><h3>RPC Approach (Avoid in REST)</h3><p>URLs describe actions, needlessly multiplying the number of endpoints:</p><ul><li>POST /createCustomer</li><li>POST /updateCustomer</li><li>GET /getCustomerList</li></ul><h3>Resource-Oriented Approach (REST Standard)</h3><p>In REST, the URL identifies the <strong>resource</strong> (always expressed as a noun, usually in the plural form) and the HTTP method determines the <strong>action</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjkCc4HyGhm23SoW.png" /></figure><h3>3. Defining a Clear HTTP Contract</h3><p>The strict, semantic use of HTTP methods ensures that your API behaves predictably.</p><p><strong>GET — Read data</strong></p><ul><li><strong>Goal:</strong> Retrieve existing resources</li><li><strong>Safe:</strong> ✅ Yes</li><li><strong>Idempotent:</strong> ✅ Yes</li><li><strong>Example:</strong><br> GET /products → Retrieve the list of products</li></ul><p><strong>POST — Create resource</strong></p><ul><li><strong>Goal:</strong> Create a new resource</li><li><strong>Safe:</strong> ❌ No</li><li><strong>Idempotent:</strong> ❌ No</li><li><strong>Example:</strong><br> POST /orders → Place a new order</li></ul><p><strong>PUT — Full replacement</strong></p><ul><li><strong>Goal:</strong> Replace an entire existing resource</li><li><strong>Safe:</strong> ❌ No</li><li><strong>Idempotent:</strong> ✅ Yes</li><li><strong>Example:</strong><br> PUT /users/10 → Replace the complete user profile</li></ul><p><strong>PATCH — Partial modification</strong></p><ul><li><strong>Goal:</strong> Update only specific fields of a resource</li><li><strong>Safe:</strong> ❌ No</li><li><strong>Idempotent:</strong> ❌ No <em>(depends on the implementation)</em></li><li><strong>Example:</strong><br> PATCH /users/10 → Change only the user&#39;s status</li></ul><p><strong>DELETE — Deletion</strong></p><ul><li><strong>Goal:</strong> Remove a resource</li><li><strong>Safe:</strong> ❌ No</li><li><strong>Idempotent:</strong> ✅ Yes</li><li><strong>Example:</strong><br> DELETE /products/15 → Delete a product</li></ul><h3>Creation Example (POST):</h3><ul><li><strong>Request:</strong> POST /orders</li></ul><pre>{<br>  &quot;customerId&quot;: 25,<br>  &quot;items&quot;: [<br>    {<br>      &quot;productId&quot;: 10,<br>      &quot;quantity&quot;: 2<br>    }<br>  ]<br>}</pre><ul><li><strong>Server Response (</strong>201 Created<strong>):</strong></li></ul><pre>{<br>  &quot;id&quot;: 1001,<br>  &quot;status&quot;: &quot;CREATED&quot;,<br>  &quot;createdAt&quot;: &quot;2026-07-15T09:59:00Z&quot;<br>}</pre><h3>4. Designing a Scalable URL Structure</h3><h3>Naming Best Practices</h3><ul><li><strong>Use nouns, never verbs:</strong> Use /users instead of /getUsers.</li><li><strong>Prefer plural forms:</strong> /payments instead of /payment.</li></ul><h3>Handling Relations and Hierarchies</h3><p>To express that a resource depends on another (e.g., a specific customer’s orders):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*28ymfYoX6JQe0_18.png" /></figure><ul><li><strong>The relational approach</strong> (/users/10/orders) is recommended for tightly coupled resources whose existence depends entirely on the parent.</li><li><strong>The filter approach</strong> (/orders?userId=10) is ideal for complex, cross-cutting search criteria.</li></ul><h3>5. Versioning Your API</h3><p>Business requirements will inevitably change, eventually leading to <em>breaking changes</em>. To prevent breaking existing client integrations, build versioning in from day one.</p><ul><li><strong>Original Version (v1):</strong> GET /api/v1/users</li><li><strong>New Version (v2):</strong> GET /api/v2/users</li></ul><blockquote><strong><em>Technical Note:</em></strong><em> URL versioning remains the most readable and straightforward approach to manage with reverse proxies. Alternatives (such as versioning via the HTTP </em><em>Accept header or custom headers) are also viable depending on your specific infrastructure constraints.</em></blockquote><h3>6. Separating Application Layers (Clean Architecture)</h3><p>A professional API applies a strict <strong>Separation of Concerns</strong>. HTTP-specific code should never directly manipulate business logic or interact with the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IdQ3_NNoRVrdkGTB.png" /></figure><ul><li><strong>Controller Layer:</strong> Handles HTTP protocol details exclusively (syntactic validation of requests, routing, HTTP status codes, JSON serialization).</li><li><strong>Service Layer:</strong> Contains the core application value and rules (calculations, business validations, orchestration).</li><li><strong>Repository Layer (DAO):</strong> Manages read/write communication with physical storage (SQL, NoSQL, external APIs).</li></ul><h3>7. Using DTOs (Data Transfer Objects)</h3><p>Exposing your database entities (tightly coupled to your ORM) directly to the client is a major architectural flaw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*B6WURr1k23W-CMOe.png" /></figure><h3>Why Isolate with DTOs?</h3><ol><li><strong>Security:</strong> Prevents leaking sensitive fields (e.g., password, salt).</li><li><strong>Performance:</strong> Avoids loading or sending heavy, nested database relationships that are unnecessary for the current client view.</li><li><strong>Flexibility:</strong> Allows you to restructure your database schema without breaking the JSON exchange contract consumed by your clients.</li></ol><h3>Transformation Example:</h3><pre>// Database Entity (Internal)<br>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;password&quot;: &quot;$2b$12$K39daF...&quot;, <br>  &quot;createdDate&quot;: &quot;2026-01-01T10:00:00Z&quot;,<br>  &quot;updatedDate&quot;: &quot;2026-07-15T09:00:00&quot;<br>}<br><br>// Client-Facing DTO (Public)<br>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;<br>}</pre><h3>8. Global Error Handling</h3><p>Never let your backend frameworks return default HTML error pages or raw stack traces (which present severe security risks). Standardize your error payloads.</p><h3>Standardized Error Payload (RFC 7807)</h3><pre>{<br>  &quot;timestamp&quot;: &quot;2026-07-14T10:00:00Z&quot;,<br>  &quot;status&quot;: 404,<br>  &quot;code&quot;: &quot;USER_NOT_FOUND&quot;,<br>  &quot;message&quot;: &quot;User with ID 42 does not exist&quot;,<br>  &quot;details&quot;: &quot;/users/42&quot;<br>}</pre><h3>9. Input Validation</h3><p>The API should act as a shield for your core system. Every incoming piece of data must be validated before it reaches the service layer.</p><p>If an email address is malformed or a required field is missing, the API should intercept the request immediately and return a clean 400 Bad Request error:</p><pre>{<br>  &quot;status&quot;: 400,<br>  &quot;code&quot;: &quot;VALIDATION_FAILED&quot;,<br>  &quot;message&quot;: &quot;The request entity contains invalid values&quot;,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;field&quot;: &quot;email&quot;,<br>      &quot;message&quot;: &quot;The email format is incorrect&quot;<br>    },<br>    {<br>      &quot;field&quot;: &quot;name&quot;,<br>      &quot;message&quot;: &quot;The name field is required&quot;<br>    }<br>  ]<br>}</pre><h3>10. Securing a REST API</h3><p>Securing an API relies on two distinct pillars:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rN001L0PUlp_Nk_x.png" /></figure><h3>Authentication (JWT / OAuth2)</h3><p>Because REST is a stateless protocol, every single request must carry its own proof of identity — typically via a <strong>JWT (JSON Web Token)</strong> passed in the security headers:</p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><h3>Authorization (RBAC / ABAC)</h3><p>Once identity is verified, the API must evaluate user privileges:</p><ul><li>GET /profile ➔ Accessible to any authenticated user.</li><li>DELETE /users/42 ➔ Restricted to users possessing the ROLE_ADMIN role.</li></ul><h3>Indispensable Production Best Practices:</h3><ul><li><strong>Enforce HTTPS:</strong> Encrypts all transit data to prevent Man-in-the-Middle (MitM) attacks.</li><li><strong>Rate Limiting:</strong> Protects your infrastructure from DDoS attacks and brute-force attempts by restricting requests per IP/user.</li><li><strong>CORS (Cross-Origin Resource Sharing):</strong> Strictly configures which domains are authorized to call your API from a browser environment.</li></ul><h3>11. Documenting with OpenAPI / Swagger</h3><p>An undocumented API is effectively non-existent to developers. Today, the OpenAPI Specification is the undisputed industry standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--MsKNKwUOg2n8mONpXq6A.png" /></figure><p>A live, interactive documentation page generated directly from your code (or designed API-First) ensures that the integration contract always reflects the real, running system.</p><h3>12. Testing a REST API</h3><p>The stability of an interface contract depends on robust test coverage:</p><ol><li><strong>Unit Tests:</strong> Verify the business logic of your services in isolation (e.g., OrderServiceTest validates discount or tax calculation logic).</li><li><strong>Integration Tests (API/End-to-End):</strong> Execute real HTTP calls (e.g., via Postman, REST Assured, or native test clients) to assert that JSON structures, redirects, and HTTP status codes behave correctly under various conditions.</li><li><strong>Contract Tests:</strong> Ensure that backend changes do not accidentally alter the data structures expected by client applications (using tools like Pact).</li></ol><h3>13. CI/CD and Maintenance (DevOps)</h3><p>A professional API must integrate into an automated Continuous Integration and Continuous Deployment (CI/CD) pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MzVal8Rx2i0_0sY6.png" /></figure><h3>Production Observability:</h3><ul><li><strong>Structured Logging:</strong> Generate logs in JSON format for easy indexing in log aggregators (e.g., Elasticsearch, Splunk).</li><li><strong>Traceability (Correlation ID):</strong> Inject a unique Correlation ID into every incoming request to trace its lifecycle across distributed microservices and database queries.</li><li><strong>APM &amp; Monitoring:</strong> Monitor key health metrics in real-time (e.g., 5xx error rates, latency, CPU/Memory utilization).</li></ul><h3>14. Production Readiness Checklist</h3><p>Before exposing your API to live users, verify that you have covered these essential points:</p><h3>Architecture &amp; Design</h3><ul><li>Endpoints are structured around resources (nouns), not actions (verbs).</li><li>Semantic HTTP methods (GET, POST, PUT, PATCH, DELETE) are strictly applied.</li><li>API Versioning is active in the URL path (e.g., /v1/).</li><li>Architecture layers (Controller, Service, Repository) are strictly separated.</li><li>Database entities are isolated; DTOs are used for all inbound/outbound exchanges.</li></ul><h3>Security</h3><ul><li>HTTPS is active and enforced globally.</li><li>Authentication (e.g., JWT) and Role-Based Access Control (RBAC) are verified.</li><li>A restrictive CORS policy is configured.</li><li>Rate Limiting is implemented to protect against traffic surges and brute force.</li><li>Input data is validated at the controller level before entering services.</li></ul><h3>Quality &amp; Testing</h3><ul><li>Happy paths and edge cases are validated by automated tests.</li><li>OpenAPI/Swagger documentation is generated, up-to-date, and accessible.</li><li>A uniform, standard payload format is configured for all API errors.</li></ul><h3>Operations &amp; Maintenance</h3><ul><li>Application secrets (connection strings, private keys) are securely injected via environment variables or secret vaults (never committed to Git).</li><li>Structured JSON logging is ready for indexing and log alerts.</li><li>Application Performance Monitoring (APM) is active to track uptime and response times.</li></ul><h3>Conclusion</h3><p>Designing a professional REST API goes far beyond simply setting up HTTP routes. It is the process of building a software product in its own right, where other developers are your end-users.</p><p>By adhering to these industry standards, you guarantee a <strong>robust, predictable, highly secure</strong>, and <strong>future-proof</strong> contract that will scale alongside your business for years to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4a7dd10658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD for .NET with GitHub Actions and Self-Hosted Runners]]></title>
            <link>https://medium.com/@salimbrahim/ci-cd-for-net-with-github-actions-and-self-hosted-runners-ab3263eba768?source=rss-f7dcfc45d76d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3263eba768</guid>
            <category><![CDATA[self-hosted-runner]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Salim Brahim]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 13:20:34 GMT</pubDate>
            <atom:updated>2025-06-19T09:48:50.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD for .NET with GitHub Actions and Self-Hosted Runners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPbQhaV2m-WRx_QUeRhoQg.png" /></figure><p><strong>Modern development workflows demand automation, consistency, and flexibility — especially when deploying .NET applications to on-premises infrastructure.</strong> While cloud-based CI/CD solutions (like GitHub-hosted runners) work well for public-facing apps, many enterprises require self-hosted runners due to security policies, compliance, or performance needs. <strong>This guide provides a step-by-step approach</strong> to setting up a <strong>self-hosted Windows runner</strong> with GitHub Actions, automating builds, and deploying to <strong>IIS</strong> — ideal for teams managing internal .NET web applications.</p><h3>Why Use a Self-Hosted Runner?</h3><p>GitHub-hosted runners are convenient, but self-hosted runners offer:</p><ul><li>Full control over the build environment</li><li>Faster builds (no queue times)</li><li>Access to internal servers (IIS, databases, on-prem resources)</li><li>Compliance with strict security policies</li></ul><h3>Step 1: Install Chocolatey on the Server</h3><p>Chocolatey simplifies package management on Windows.</p><p><strong>Installation Steps</strong></p><ol><li>Connect to the server where the application will be hosted (or local machine).</li><li>Open PowerShell as Administrator and run:</li></ol><pre>Set-ExecutionPolicy Bypass -Scope Process -Force;<br>[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072;<br>iex ((New-Object System.Net.WebClient).DownloadString(&#39;https://community.chocolatey.org/install.ps1&#39;))</pre><p>3. Verify installation:</p><pre>choco -v</pre><p><strong>Troubleshooting Tip:</strong></p><p>If Chocolatey fails to install, check:</p><ul><li>Proxy settings (if behind a corporate firewall).</li><li>PowerShell execution policy (must allow scripts).</li></ul><h3>Step 2: Install Required Build Tools</h3><p>Since we’re building a .NET app, we need:</p><ul><li>Visual Studio Build Tools (for MSBuild)</li><li>.NET SDK (if not already installed)</li></ul><p><strong>Install Build Tools via Chocolatey</strong></p><pre>choco install visualstudio2022buildtools `<br>--params &quot;&#39;--add Microsoft.VisualStudio.Workload.WebBuildTools --quiet --norestart&#39;&quot; -y</pre><p>For <strong>.NET 6+</strong>, also run:</p><pre>choco install dotnet-sdk -y</pre><p><strong>Pro Tip:</strong></p><ul><li>Check the Chocolatey packages for specific versions.</li><li>Use :</li></ul><pre>choco list -lo</pre><p>to verify installed packages.</p><h3>Step 3: Set Up a GitHub Self-Hosted Runner</h3><ol><li>Go to your GitHub repository.</li><li>Navigate to: <strong>Settings &gt; Actions &gt; Runners</strong></li><li>Click “New self-hosted runner” and follow the instructions:</li><li>Select your operating system and architecture</li><li>Run the provided shell commands on your server</li><li>(Optional) Install as a Windows service for persistence</li><li>Once completed, you should see:</li></ol><pre>√ Connected to GitHub<br>Listening for Jobs...</pre><p><strong>Verify Runner Status</strong></p><ul><li>Check GitHub Settings → Actions → Runners for a green status.</li><li>Test with a simple workflow.</li></ul><p><strong>Security Best Practices:</strong></p><ul><li>Store the runner token in GitHub Secrets.</li><li>Run the service under a least-privilege account.</li></ul><h3>Step 4: Configure IIS for Hosting the Application</h3><ol><li>Open IIS Manager (inetmgr).</li><li>Add a new website with:</li></ol><ul><li>Site Name: MyApp</li><li>Physical Path: C:\inetpub\wwwroot\MyApp</li><li>Port: 80 (or a custom port)</li></ul><ol><li>Grant permissions:</li></ol><pre>icacls &quot;C:\inetpub\wwwroot\MyApp&quot; /grant &quot;IIS_IUSRS:(OI)(CI)(F)&quot;</pre><p><strong>Important:</strong></p><ul><li>If using HTTPS, bind a certificate.</li><li>Ensure the runner service account has write access to the deployment folder.</li></ul><h3>Sample GitHub Actions Workflow (Full CI/CD Pipeline)</h3><p>Start by creating a .github/workflows/filename.yml file. This file:</p><ul><li>runs on every `push` to `main`</li><li>builds the project</li><li>Backs up the old deployment</li><li>Deploys to IIS</li></ul><pre>name: .NET CI/CD to IIS<br>on:<br>  push:<br>    branches: [ main ]<br>jobs:<br>  build-deploy:<br>    runs-on: self-hosted  # Uses your Windows runner<br>    steps:<br>      - name: Checkout Code<br>        uses: actions/checkout@v4<br>      - name: Setup .NET SDK<br>        uses: actions/setup-dotnet@v3<br>        with:<br>          dotnet-version: &#39;6.0.x&#39;<br>      - name: Restore NuGet Packages<br>        run: dotnet restore MyApp.sln<br>      - name: Backup Old Deployment (PowerShell)<br>        shell: powershell<br>        run: |<br>          $DeployPath = &quot;C:\inetpub\wwwroot\MyApp&quot;<br>          $BackupPath = &quot;C:\inetpub\wwwroot\Backups&quot;<br>          $Timestamp = Get-Date -Format &quot;yyyyMMdd_HHmmss&quot;<br>          $BackupFolder = &quot;$BackupPath\MyApp_$Timestamp&quot;<br>          if (!(Test-Path $BackupPath)) { New-Item -Path $BackupPath -ItemType Directory }<br>          Write-Host &quot;Stopping IIS...&quot;<br>          iisreset /stop<br>          if (Test-Path $DeployPath) {<br>              Move-Item -Path $DeployPath -Destination $BackupFolder<br>              Write-Host &quot;Backup saved to: $BackupFolder&quot;<br>          }<br>          New-Item -Path $DeployPath -ItemType Directory | Out-Null<br>      - name: Build &amp; Publish<br>        run: dotnet publish MyApp/MyApp.csproj -c Release -o $DeployPath<br>      - name: Restart IIS<br>        run: iisreset /start</pre><h3>Managing Secrets Securely</h3><p>Never hardcode credentials! Use GitHub Secrets:</p><pre>env:<br>  DEPLOY_USER: ${{ secrets.DEPLOY_USER }}<br>  DEPLOY_PASSWORD: ${{ secrets.DEPLOY_PASSWORD }}</pre><h3>Conclusion</h3><p>Using GitHub Actions with a self-hosted Windows runner provides a powerful, flexible pipeline for deploying .NET apps in environments where cloud runners don’t fit — like internal servers.</p><p>This setup gives you:</p><ul><li>Full control of the environment</li><li>Seamless integration with GitHub</li><li>Automation across build, test, and deployment stages</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3263eba768" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>