<?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 Karthik Kottugumada on Medium]]></title>
        <description><![CDATA[Stories by Karthik Kottugumada on Medium]]></description>
        <link>https://medium.com/@karthikkottugumada?source=rss-40c3cc93522b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dxaXe8jCbBL3xpf1of9H4Q.png</url>
            <title>Stories by Karthik Kottugumada on Medium</title>
            <link>https://medium.com/@karthikkottugumada?source=rss-40c3cc93522b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:32:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthikkottugumada/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[Love It Or HATEOS It]]></title>
            <link>https://levelup.gitconnected.com/love-it-or-hateos-it-3f8d5844e736?source=rss-40c3cc93522b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f8d5844e736</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[hateoas]]></category>
            <dc:creator><![CDATA[Karthik Kottugumada]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 22:09:50 GMT</pubDate>
            <atom:updated>2021-01-04T17:37:05.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>Love It Or HATEOAS It</h3><p>Last week we had a pretty stretched out discussion about the efficacy of HATEOAS for our REST based microservice suite of applications. Long story short, the team was divided in opinion on should we or should we not build our API response model based on the “uniform interface” feature of REST.</p><p><strong>What is HATEOAS?<br></strong>Before we get there, I would ask you to challenge yourself to properly define REST. We all have that one person on our API teams who would have (at least once) commented saying that, our APIs are not truly RESTful. And for what it’s worth they could be absolutely right. Their idea could, in all probability, be based on <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Roy Fielding’s dissertation</a>. Insisting that we may understand what HTTP verbs are <a href="https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">but they are not hypertext-driven</a>. Without it being so, your REST API is just a HTTP-based interface that is RPC driven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*kybyt2qXxx87PWFWKToY_g.png" /></figure><p><strong>H</strong>ypertext <strong>A</strong>s <strong>T</strong>he <strong>E</strong>ngine <strong>O</strong>f <strong>A</strong>pplication <strong>S</strong>tate, or <em>HATEOAS </em>in simple words means that we embed enough information in the response such that the client can intelligently choose what it wants to do next. Every media type defines a default processing model, e.g. HTML defines a rendering process for hypertext and the browser behavior around each element. It has no direct dependency on the verbs GET/PUT/POST/DELETE. The interface tells the client either what method to use, e.g. fetch a user’s data, that in turn translates to a GET call.</p><p>What should the client do next translates into resource discovery, which if defined right, is there in the response hypermedia. This will allow the client to figure out what resources are available and what can be manipulated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95329674a2803ee402f6676b34b67ce7/href">https://medium.com/media/95329674a2803ee402f6676b34b67ce7/href</a></iframe><p>Assume a case where your API is being used by the end users and admins <em>via </em>the same interface. Regular users would be able to just GET /users/{​userId}​​​​​​​​​. Power Users would have PUT and PATCH /users/{​userId}​​​​​​​​​ and Admins would have privileges on DELETE. If we stopped at he Level 2 of <a href="http://martinfowler.com/articles/richardsonMaturityModel.html">Richardson Maturity Model</a>, we would have a client that would understand the types of privileges and render based on that.</p><p><strong>Sounds Fancy, Should I implement it?<br></strong>One thing that most teams do not understand is that HATEOAS is not a design principle, but it is part of an architectural constraint. Building a completely decoupled, independently scalable system is every engineer’s goal. But here is my gripe, implementing something just because you had read about it over the weekend is never the right approach.</p><p>Lets look at HATEOAS, if implemented right it would do away with the need for explicit documentation as it is <em>self-documenting. </em>But in reality, most of us wouldn’t spend time building clients that are smart enough to read <em>rel = what-this-endpoint-does</em>and figure out if it should use the PUT method or a POST method for a particular use case. I would definitely wish that it does so, thereby allowing progressive non-intrusive enhancements to my applications. But we are pretty far off on that.</p><p>Additionally, most implementations of APIs rely on providing access to it via a gateway like <a href="https://cloud.google.com/apigee">Apigee </a>or a Service Mesh, that renders HATEOAS based links pretty much non functional.</p><h3></h3><p>The reason to make a real REST API is to get evolvability ... a &quot;v1&quot; is a middle finger to your API customers, indicating RPC/HTTP (not REST)</p><p>Also, in order to make your REST API truly ready for evolvability, it might need to be <a href="https://medium.com/swlh/api-versioning-7f6f713c6b14">versioned right</a>. But this becomes borderline counterintuitive with true HATEOAS.</p><p>REST is still a phenomenal way to build APIs but I would not just attempt to implement this for a fictitious client that would somehow have a semantic understanding of my hypermedia format. Every microservices suite is different and there is no one-size-fits-all for APIs. Trying to build the ultimate response discovery engine is a good end goal to aim for. But having a rigid mindset that ultimately slows down your application’s evolvability is not a good direction for any engineering team.</p><p>References:</p><ul><li><a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven</a></li><li><a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm</a></li><li><a href="http://martinfowler.com/articles/richardsonMaturityModel.html">http://martinfowler.com/articles/richardsonMaturityModel.html</a></li><li><a href="https://en.wikipedia.org/wiki/No_Silver_Bullet">https://en.wikipedia.org/wiki/No_Silver_Bullet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f8d5844e736" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/love-it-or-hateos-it-3f8d5844e736">Love It Or HATEOS It</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apps As Clusters]]></title>
            <link>https://karthikkottugumada.medium.com/apps-as-clusters-bc52cc05d6c0?source=rss-40c3cc93522b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc52cc05d6c0</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Karthik Kottugumada]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 17:34:20 GMT</pubDate>
            <atom:updated>2020-09-17T17:34:20.921Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scaling A Nodejs App</h4><p>Scaling any app cannot be a late addition to your application development timeline. It has to be planned and introduced right when you are designing it. Most teams, like one of the teams that I had been once part of, went though this whole exercise few development cycles after the kick off. And we ended up having to refactor a huge subset of our code. Dealing with scale issues on your distributed systems is not a lot of fun especially when the entire team is bursting at the seams with the amount of work pending before the beta release. Also there is no fixed set of rules for solving this. And hence there is a lot of material online on how it has to be done. So, there is no point in churning out one more post about the horizontal <em>scale-out</em> and vertical <em>scale-up </em>or detailing the <a href="https://microservices.io/articles/scalecube.html">three axis cube solution</a>. Instead I will consolidate all the steps that we took and options we weighed in before making that decision and all the challenges we encountered while doing so.</p><p>Teams have proved time and again how cloning a large application and logically dividing the operations load greatly helps in <em>scaling out</em>, and with minimal effort. One common way to increase the throughput of the application suite is to spawn one process for each core of the hosted machine. By doing so, the already efficient “concurrency” management of requests in Node.js (<em>see. </em>“event driven, non-blocking I/O”) can be multiplied and also parallelized.<br>There are different strategies for scaling on a single machine. But the common concept is to have multiple processes running on the one same port, with some sort of internal load balancing used to distribute the incoming connections across all the processes/cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*jw4XPAqL6RH0HBfz-Y5VXg.png" /></figure><p>The strategies described below are for the standard Node.js <strong>cluster mode</strong> and the automatic, higher-level <strong>PM2 cluster</strong> functionality.</p><p><strong>Native Cluster Mode<br></strong>By default it works like this: <strong>the master process listens on a port</strong>, accepts new connections and <strong>distributes them across the workers in a round-robin fashion</strong>, with some built-in logic to avoid overloading a worker process.<br><strong>Cluster mode implementation:</strong><br>On your project entry point, require cluster mode, and spawn your application when the process is a worker. First, we require the cluster module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd648060736aad5e461391a3dcda7d4/href">https://medium.com/media/3dd648060736aad5e461391a3dcda7d4/href</a></iframe><p>Then we check if the current process is <em>master</em>. If so, we get the total amount of CPU cores and spawn worker processes. Otherwise, the current process is a <em>worker</em>, so we initialize our app at this place. Also, we are setting up a subscriber for the event <em>exit</em>. If a <em>worker </em>dies for any reason, we spawn a new one in replacement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*_hsS1Lzu8I7x301AD-vMvg.png" /><figcaption>Round Robin Leader Election</figcaption></figure><p>It is probably not a good idea to spawn processes that are more in number when compared to the number of cores, because at the lower level the OS will likely balance the CPU time between those processes.</p><p><strong>PM2 Cluster Mode<br></strong>This lets you scale the process across all the available cores without the need for the <em>cluster </em>module. The PM2 daemon covers the role of the <em>master</em> process, and it spawns processes of your application as <em>workers</em>, with load-balancing, in a round-robin fashion. So, this lets you write your application as you would for a single core process usage and PM2 takes care of scaling it out to multiple cores.<br>As a process manager PM2 also takes care of restarting a process after it crashes. And once the application is started in the cluster mode the number of instances can be adjusted using pm2 scale</p><p><strong>Use a better task scheduler</strong><br>One very common and often ignored place is the task scheduler. Most microservice suites have task schedulers. They are a quick and easy way to automate the execution of a bunch of operations. It is important that we don’t rely on setTimeoutand/or setInterval. Poorly written schedulers might be a pain to scale out horizontally, resulting in issues with duplication of cron jobs.<br>1. We switched to using <em>Azure scheduler</em>, which has greatly evolved ever since it was initially introduced.<br>2. Another approach that we tried was using cosmos and/or mongoDB to store recurring jobs. And use that as a high level queuing system to store and lock the execution every time a worker starts a job.<br>3. There is also an npm package available for the <a href="https://www.npmjs.com/package/cron">cron module</a>(with a seemingly obvious dependency on <a href="https://www.npmjs.com/package/moment-timezone">moment</a>). It lets you define cron jobs inside your node.js code, making it independent from the OS configuration. The worker process can create the cron, which invokes a function putting a new job on the queue periodically. Using the queue makes it more clean and helps you take advantage of features like priority, retries, etc. make the implementation more efficient.<br>Everything seems rosy till you have only one worker process. Which most likely might never be a production worthy case. Now because the cron function would wake app for every process at the same time, putting it on a queue creates duplicates of the same job that would be executed many times.<br>The best way to solve this problem is to identify a single worker process that will perform the cron operations. <br>We can make use of “<em>leader election</em>” offered by something like <a href="https://www.npmjs.com/package/hapi-cron-cluster">hapi cron cluster</a>. Contrary to what you might assume, <em>Leader Election </em>is a much simpler process in the software development world. If you are using hapi cron cluster, you start by providing a redis client to the cron-cluster module, which would be used by the worker processes to communicate among themselves and agree who will be the “leader”.<br>One challenge that you might face while running a cluster might be addressing cases where we need stateful communication. Since communication is not guaranteed to be always with the same worker process. A very basic example of such a scenario might be issues with user authentication. With a cluster, the request to authenticate comes to the master and via the loadbalancer moves to a worker process, which do not know whether the request is authenticated or not. <br>There are numerous ways to resolve this. One quick and simple approach could be to share the state across all the works by storing this session information on a shared database. But like in our case we couldn’t afford touching the code in so many places, without massively breaking things. A minimal invasive approach might be using something known as <em>Sticky Load Balancing</em>. Most modern load balancing solutions have this feature out of the box. At a high level, when there is a need to share data between the processes, a record of the relation is stored at the loadbalancer level. So, when the same user sends a new request to authenticate, we do a lookup in the existing records to find out which server has a their session authenticated. And keep sending the requests to that server instead of the regular distribution. This ensures that we do not need to change the existing code. But doing this means that we are not fully load balancing our calls. In this example, calls for authenticated users.</p><p><strong>Caching<br></strong>Caching goes a long way in helping us scale the apis better. If we are trying to cache with the previously discussed cluster setup, we would need to implement an exclusive entity object. And use that to record incoming and outgoing calls to that entity’s API. This could be a collection on mongoDB, any key value db or even a column based db. Contrary to what it might seem like, maintaining a separate entity for our caching needs makes decomposing the app easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*-pp5uvR9Cy_vXkqvuuOjTw.png" /></figure><p><strong>Caching the API calls<br></strong>Choosing an application level implementation of cache invalidation instead of a fixed TTL, might be more efficient.</p><p><strong>Services on AWS<br></strong>There are also some Java services that provide infrastructure support for the Node.js services:</p><p><a href="https://github.com/Netflix/eureka"><strong>Netflix Eureka</strong></a> is a service registry and discovery tool that enables services to find other services without needing to know where they’re running.</p><p><a href="https://github.com/Netflix/zuul"><strong>Netflix Zuul</strong></a> is a load balancer and dynamic routing service that gets a list of available instances of each service from Eureka, routes requests between services, and balances the load among server instances.</p><p><strong>Resources:<br></strong>I have found a huge treasure trove of information regarding the best practices, but very few instances talking about the practical challenges. In my study regarding the various dimensions of scalability, I found these really useful</p><ol><li><a href="http://book.mixu.net/distsys/single-page.html">Distributed Systems for Fun and Profit</a>, Mikito Takada</li><li><a href="https://link.springer.com/content/pdf/10.1007%2Fs00607-016-0508-7.pdf">A brief introduction to distributed systems</a>, Maarten van Steen &amp; Andrew S. Tanenbaum</li><li><a href="https://www.amazon.com/dp/1449373321/ref=cm_sw_em_r_mt_dp_fWgyFb1PSH6Y0">Designing Data-Intensive Applications</a> by Martin Kleppmann</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc52cc05d6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment Testimonials: Issues, Challenges and Architectural Orthodoxy]]></title>
            <link>https://medium.com/swlh/deployment-testimonials-issues-challenges-and-architectural-orthodoxy-95d38ccdf00b?source=rss-40c3cc93522b------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d38ccdf00b</guid>
            <category><![CDATA[observation]]></category>
            <category><![CDATA[canary-deployments]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Karthik Kottugumada]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 19:44:09 GMT</pubDate>
            <atom:updated>2020-08-25T23:38:59.836Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deployment Testimonials: Issues and Challenging the Architectural Orthodoxy</h3><p>I lead a team of immensely talented engineers maintaining a critical application that is at the nucleus of my organization’s IT map. The advantage of being in such a team is the fact that you get to gauge the impact of your changes by looking at the effect it has on other teams and consumers. A major disadvantage, if you have not already guessed, is this same dependency and the pressure it brings along and a very thin margin for error. The application that my team manages used to be a large monolith and had a single source of non-replicable data, with the downstream systems being tightly coupled to this. Breaking this down into a host of microservices was a colossal undertaking. But that would be a story for yet another fewer-meetings day.</p><p>Fast forward to a time when we are managing a suite of 60 odd, loosely coupled, context bound microservices. But effortless deployments were still a challenge that we had not fully won over. We were still relying on after-business hours releases, redundant release definitions and complex release cycles. With a super agile team and a massively dynamic workitem backlog, the need to come up with a way to upgrade our deployments was well overdue. Along with the team, I came up with a couple of options and chose to organically revamp the whole system. Putting together the details of this exercise in one place would be gross over-simplification. Here is my first attempt at doing that.</p><p><strong>Blue/Green<br></strong><em>Why?<br></em>We started with simple resource swap deployments. Where new production resources are tested on a set of servers prior to swapping the resources out in production. This process is popularly known as <em>Blue/Green </em>deployments. For those who are unfamiliar with this, essentially there are two exact copies of the application’s source code, designated “<em>Blue</em>” and “<em>Green</em>” respectively (not exactly sure why those two colors). And we started seeing really good results with this approach, pretty early on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ta9aHk-njmecCpT9EE4vWg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yasinalsbey?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yasin Alsbey</a> on <a href="https://unsplash.com/s/photos/marbles?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Advantages<br></em> One of these Blue/Green stacks is the external facing set of servers, while the other stays unavailable to the users. Essentially this second set of servers becomes a smoke test environment on top of the production stack. By using this inactive set of servers as our deployment target, we could test our application’s behavior with the new codebase prior to deploying the functionality to live users. This allowed us to reduce the downtime in deployments while also improving the overall resiliency of the application. Improvement in resiliency was achieved by the way of providing an easy fallback in the event of a sudden increase in scale or the occasional botched deployment.</p><p><em>Challenges<br></em>The <em>blue/green</em> approach can be very cost-intensive, since the core premise of this is duplication of application’s production resources. While the actual work of setting up this kind of environment is greatly eased due to advancements in cloud-resource availability, the costs of such an install are nearly double as those of a less secure option.</p><p><strong>Canary</strong></p><p>Canary deployments aim to address these issues by reducing the need for duplicate application infrastructures. With some tweaks to the application’s architecture and to the development practices, we could reduce the need for maintaining redundant stacks and deliver the same level of stability. Canary releases have always been used by development teams whenever there is a new or big change that has to be introduced. But giving our stakeholders and teammates, a surprise, at the same time might not work in everyone’s best interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5t8Dk1Am7uFQoVweyKRTjA.jpeg" /><figcaption><a href="https://staticshare.america.gov/uploads/2014/11/canary_art22.jpg"><em>State Department static images</em></a></figcaption></figure><p>I have worked on teams that have extensively used <em>feature flags</em>. Which are an ingenious way to isolate certain features. But as developers world over are growing more and more curious about the upcoming releases, it becomes more and more strenuous to manage internal releases. Especially if the changes correspond to a company that is due on releasing a new product. And thus even an innocuous miss around the code-names or dead code, might cost the company a lot in PR cover-up. Phased or incremental rollouts could be another way of gradually folding the changes in.<br><em>Canary </em>releases shift the focus from releasing entire applications to releasing individual features within an application. So, instead of releasing all of the new features at once, as part of a mammoth monthly release, we started releasing the code for new features while slowly scaling up the number of users that have access to that feature. And by employing multiple <em>canaries </em>each tagged by a different <em>feature toggle</em> across various geographical regions we were able to get early success indices. All this while, gradually updating the traffic allowed on the <em>canary</em> from under 5% to a full 100%. Another upside is that it enabled us to continuously release new features for the application without needing a specific deployment or a release window.</p><p><strong>Observability and Defining Success</strong></p><p>In the process of switching traffic to users, we had to identify the user sets. What should be the criteria for defining the target user base? We started with identifying the users that are relatively more active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*5-PisqAgsTLNXr6c-5_hFQ.png" /><figcaption>Illustration by karthik on his 90’s machine</figcaption></figure><p>Once done, we had to engage the marketing and public relations team to seek out consent and request feedback. This would help gauge the issues early on. For internal product teams dogfooding is an easier approach.<br>Choosing success metrics for such a series of releases becomes more and more critical since the numbers from each stage help in identifying any early stage issues. Increased response times for an extrapolated throughput, increased error rates or other measurable entities were some of the key metrics.</p><p><strong>Challenges</strong></p><p>One of the major challenges, we know, would be cleaning up after or managing multiple release versions and constantly reducing the number of parallel versions currently live in production. Database changes were a real challenge to work around. <em>Parallel Change</em> or <em>expand, merge and contract</em> pattern can help mitigate this to a large extent. This aspect is yet to be thoroughly explored.</p><p><em>References: <br></em><a href="https://martinfowler.com/bliki/BlueGreenDeployment.html"><em>https://martinfowler.com/</em></a><em><br></em><a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/kubernetes/deployment-strategies"><em>https://docs.microsoft.com</em></a><em>/</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d38ccdf00b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/deployment-testimonials-issues-challenges-and-architectural-orthodoxy-95d38ccdf00b">Deployment Testimonials: Issues, Challenges and Architectural Orthodoxy</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Versioning]]></title>
            <link>https://medium.com/swlh/api-versioning-7f6f713c6b14?source=rss-40c3cc93522b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6f713c6b14</guid>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[hateoas]]></category>
            <category><![CDATA[api-versioning]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Karthik Kottugumada]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 18:04:12 GMT</pubDate>
            <atom:updated>2020-08-25T18:29:28.077Z</atom:updated>
            <content:encoded><![CDATA[<p>So, you are new to this team. And in one of the bi-weekly tech leads’ meetings, one thing leads to another and you casually bring up how the error messages on all the APIs are not consistent. You hear one of the engineers telling you that their pull requests to update the core error handler have always been kept on hold and have never been merged. Before you could ask for more information, you hear a few other audible nods. All those have one thing in common, they are all breaking changes. Breaking, for the downstream systems and/or breaking for the clients that consume these resources. This discussion makes way for one of the commonly contested aspects of API development: “<em>versioning”</em>.</p><p>I think the topic of API versioning is probably as old as or older than the topic of URL design for applications themselves. And probably a discussion that most teams involved in API development get involved in. What makes it more interesting is the fact that there is no right answer or approach that fits all use cases. And thus makes up for quite an interesting conversation.</p><p><strong>Why would you need to version your APIs?<br></strong>A versioning strategy allows clients to continue using the existing API and migrate their applications to the newer API when they are ready. If you need to make breaking changes you might continue to do so and migrate to this new structure only when all the essential stakeholders are ready for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQRpiIZR1pX1yiiF_TI6iA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clay Banks</a> on <a href="https://unsplash.com/s/photos/volumes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>While certain modifications like adding new routes or route parameters shouldn’t cause any problems. Changes that could affect existing clients or downstream systems that consume your API would mean that you would need to think about a strategy for versioning thoroughly. Like most cases, we have multiple ways to approach this.</p><blockquote>“The most RESTful approach to versioning an API is to not version it at all.”</blockquote><blockquote>~(Old Asgardian Proverb)</blockquote><p><strong>Embedding API version in the URI?<br></strong>This looks like the easiest way forward. However, this would be against the HATEOAS constraint [<a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">Hypermedia As The Engine Of Application State</a>]. Adding a version number to the API would mean that the client is making an assumption of how an API would behave and would thus mean that the API is no longer opaque. If we go by the book, clients should be dynamic and only rely on the API responses [<em>see. </em>web browsers]. It might also mean that incrementing the API version would translate into branching the entire API resource.</p><pre>GET <a href="https://www.sampleresource.com/v1/foo">https://www.sampleresource.com/v1/foo</a></pre><p><strong>Through content negotiation<br></strong>Using the content negotiation strategy. This helps us by requiring only a single resource to represent the API instead or versioning the entire API and thus giving us more control over versioning. Also, we would not need to define custom routing rules, like we had to while using version as part of the URI path.</p><pre>GET /foo<br>Accept: application/ion+json;v2.0</pre><p><strong>Query Parameters<br></strong>This approach is very straightforward and is also easy to set defaults to the latest version in case of missing query parameters.</p><pre><a href="http://www.sampleresource.com/api/foo?version=1">www.sampleresource.com/api/foo?version=1</a></pre><p>Biggest challenge with this approach would be setting up routing.</p><p><strong>Custom Headers<br></strong>This is another approach which might not be very popular with teams, but does the job. Sending version number as a custom header.</p><pre>curl -H “accepts-version: 1.0”<br><a href="http://www.sampleresource.com/api/foo?version=1">www.sampleresource.com/api/foo</a></pre><p><strong>Lets talk code<br></strong>.net core like few other popular frameworks, offers versioning through content negotiation <em>via</em> custom libraries.</p><p>Add the nuget package ‘<em>Microsoft.AspNetCore.Mvc.Versioning’</em> and update the <em>startup.cs</em> accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9092bff76f70e078b96ead5434eda70c/href">https://medium.com/media/9092bff76f70e078b96ead5434eda70c/href</a></iframe><p>We can then go ahead and add a class level attribute of ‘<em>ApiVersion</em>’ on our <em>BaseController</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c0dfa8f2845f5d07415424253a8b601/href">https://medium.com/media/4c0dfa8f2845f5d07415424253a8b601/href</a></iframe><p>Now when you compile and send a request to this endpoint. You might notice a change in the headers. Something like this:</p><pre>api-supported-versions -&gt; 1.0</pre><p>Just for kicks if you send in a different header. Like this:</p><pre>curl -i -H &quot;Accept: application/json;v=2.0&quot; <br>http://www.sampleresource.com/api/foo</pre><p>You might notice that the same call might throw a ‘<em>400 Bad request</em>’, stating that the error code as ‘<em>UnsupportedApiVersion</em>’ . We don’t have an apiversion attribute corresponding to version 2.0 on this endpoint. But if we did, we would have been able to request that.</p><p><strong>Which versioning strategy to use?<br></strong>Which approach to use depends on the project and the intent. Do you want versioning that’s more explicit to clients or one that is more flexible and clean? Are you expecting the interface to be stable or have breaking changes? Planning and thinking through all the use cases for your API in advance can reduce the need to make breaking changes down the road.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f6f713c6b14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/api-versioning-7f6f713c6b14">API Versioning</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>