Chapter 8

Breaking the Monolith: Our First Microservice

Subhash Choudhary · 13 min read

We had conquered the major beasts of infrastructure scaling. Our servers could handle traffic, our database could handle reads, and our deployment process was safe. We had a professional engineering team, a resilient architecture, and a product that millions of people used. For the first time, it felt like we were in control.

But the nature of scale is that the bottleneck always moves. We had optimized our machines, but we had forgotten to optimize our organization. As our team grew, our single, monolithic codebase, which had been our greatest asset for speed in the beginning, was becoming our greatest liability.

The next fire wasn't started by a traffic spike. It was started by our own team, a self-inflicted wound born from the chaos of too many people trying to work in the same small kitchen.

Part 1: The Civil War

Our engineering team had grown to about ten people. We split them into two small "squads" to focus on different parts of the business. The "Growth" squad focused on the seller experience-onboarding, dashboards, and product management. The "Operations" squad focused on the nuts and bolts-payments, logistics, and order fulfillment.

It seemed like a logical split. The problem was that both squads were still working on the same, single monolithic Django application. Their code was completely intertwined.

One afternoon, the Operations squad was working on a new integration with a logistics partner. To do this, they needed to add a few new fields to our Order model in the database, like tracking_id and shipping_provider. At the same time, the Growth squad was working on a feature to allow sellers to offer discounts, which also required changes to the Order model to include a discount_code field.

Both teams worked in parallel. Both tested their features on the staging server. Everything looked fine. The logistics feature was approved first and deployed to production. An hour later, the discounts feature was also approved and deployed.

And then, chaos.

Our payment processing webhook, the critical endpoint that confirms a customer's payment has been successful, started failing for every single order. Money was being charged to customers, but the orders weren't being marked as "Paid" in our system. From a seller's perspective, orders were just vanishing after payment.

Suumit's call was immediate. This wasn't about a slow website; this was about losing our users' money. This was a five-alarm fire.

We dove into the logs. The error was cryptic. It was failing deep inside the payment confirmation logic. After a frantic half-hour of debugging, we found the cause. In the process of adding the discount_code field, the Growth squad's code had slightly changed how an Order object was saved. The logistics squad's earlier change had made an assumption about the old way of saving. The two perfectly functional, independently tested features were completely incompatible. When they were deployed together on production, they created a critical bug that no one had anticipated.

It was a civil war inside our own codebase. Two friendly teams, working towards the same goal, had accidentally sabotaged each other.

Identifying the Bottleneck: The Codebase

After we reverted the changes and calmed the storm, we held a serious post-mortem. It was clear that our problem wasn't the servers, the database, or the deployment pipeline. The pipeline had worked perfectly; it had deployed exactly what we told it to.

The bottleneck was the monolith itself.

Our application had become a giant, tangled web of dependencies. The code for payments was tightly coupled to the code for orders, which was tightly coupled to logistics, sellers, and products. It was impossible for a developer to make a change in one area without having to understand its potential impact on the entire system.

Our developer velocity-the speed at which we could safely ship new features-had plummeted. Every new feature required more meetings, more coordination, and more fear of breaking something unrelated. We were spending more time managing the complexity of the monolith than we were building for our customers. The kitchen had become too crowded.

Technical Deep Dive: The Monolith vs. Microservices Showdown

This crisis forced us to confront a major architectural decision. It was time to consider breaking up the monolith into microservices.

The Monolith: One Giant Restaurant As we've discussed, a monolith is a single application that does everything.

Microservices: A Food Court of Specialized Stalls A microservice architecture breaks a large application into a collection of smaller, independent services.

The choice was clear. The pain of the monolith had become greater than the pain of moving to microservices. We had to start breaking it apart. We had to plan our first incision.

Part 2: Planning the First Incision

We had made the terrifying, necessary decision to start breaking up our monolith. It felt like standing in front of a giant, complex machine that we had built with our own hands, knowing we now had to take it apart while it was still running.

Where do you even begin?

A surgeon doesn't just start cutting randomly. They spend hours studying X-rays and planning their first incision. That first cut is the most critical; it sets the stage for the rest of the operation. We needed a plan. We needed to choose our first microservice, the first piece we would carefully carve away from the main body of the application.

Choosing your first microservice is one of the most important decisions you'll make in this journey. If you choose a piece that is too complex or too tangled, the entire operation can fail, leaving you with a mess that is far worse than the monolith you started with.

Technical Deep Dive: How to Choose Your First Microservice

After much debate and research, we established a set of criteria for our first candidate. This is a playbook anyone can use.

Criterion 1: Low Business Criticality Your first attempt at building, deploying, and managing a microservice will be a learning experience. You will make mistakes. It's far better to make those mistakes on a part of your application that won't destroy your business if it goes down for an hour.

Criterion 2: Few and Clear Dependencies A "dependency" is any connection or communication a service has with other parts of the system. You want to choose a piece of your application that is as self-contained as possible.

Criterion 3: A Clear and Bounded Domain The service you choose should have a single, well-defined purpose. You should be able to describe what it does in one simple sentence. This is what software architects call a "bounded context."

Our Decision: The Storefront Service

After evaluating our entire monolith against these criteria, one candidate emerged as the perfect choice for our first incision: the Storefront.

The Storefront is the public-facing part of a seller's shop-the page that customers actually visit to browse products. Let's see how it stacked up against our rules:

There was one more massive advantage. The Storefront had a completely different scaling profile from the rest of the application. The seller dashboard might get thousands of visits a day, but a popular store's page could get millions. By carving it out, we could scale it independently. We could have a fleet of 20 powerful servers for the Storefront service, while keeping a smaller, more efficient fleet of 3 servers for the seller dashboard, saving us a huge amount of money.

The plan was set. We would perform surgery. We would carefully extract all the code, templates, and logic related to the public storefront and re-build it as a brand new, completely independent application: the storefront-service.

The New Problem: Inter-Service Communication

The moment we made this decision, a new class of problem that we had never faced before appeared.

As long as we had a monolith, communication was easy. If the order logic needed to get the price of a product, it would just call a getProductPrice() function. It was a direct, internal conversation within the same application.

But now, we were going to have two separate applications. The old monolith (which we now called the core-api) and the new storefront-service. They were two separate buildings. What happens when a seller logs into the core-api and updates a product's price? How does the completely separate storefront-service find out about this change?

They can't just call a function anymore. They need a way to talk to each other over a network. We needed to define a contract, a formal API (Application Programming Interface), that would allow our services to communicate.

Our food court needed a shared language. The pizza stall needed a formal way to tell the central warehouse what ingredients it needed, and the warehouse needed a way to tell the stall about price changes. We had just entered the complex world of distributed systems.

Part 3: The Strangler Fig Pattern

We had a plan. We knew which part of the monolith we wanted to carve out-the Storefront. But how do you perform surgery on a living patient without killing them? A "big bang" rewrite, where you shut everything down for months to rebuild it, was out of the question. A startup that isn't shipping is a dead startup.

We needed a strategy to replace the old system piece by piece, gradually and safely, while the rest of the application continued to run. For this, we turned to a beautiful and powerful architectural pattern named after a force of nature: the Strangler Fig Pattern.

Technical Deep Dive: The Strangler Fig Pattern

In the rainforest, a strangler fig is a vine that begins its life on an old, established tree. It starts small, sending down roots around the host tree's trunk. Over years, these roots grow thicker and stronger, creating a new, powerful lattice structure that completely envelops the old tree. Eventually, the host tree inside can die and rot away, leaving behind the strong, healthy, and perfectly formed structure of the strangler fig.

This is a perfect metaphor for replacing a legacy system.

Over months or years, the new microservices (the fig vine) grow stronger and take over more and more of the monolith's responsibilities, until the old monolith has either shrunk to a manageable size or disappeared entirely.

Our Implementation: Nginx as the Strangler

Once again, our trusty tool Nginx was perfect for the job. We were already using it as a load balancer. We could enhance its configuration to also act as this intelligent router.

We built our new, standalone storefront-service. It was a lean, fast application whose only job was to render store pages. Then, we updated the Nginx configuration on our load balancer with some new logic:


#A simplified version of our "Strangler" config
#Define our new storefront microservice

upstream storefront_service {
  server 10.132.8.12; # IP of the new service
}

#Define our old monolith
upstream monolith_service {
  server 10.132.2.31;
  server 10.132.4.55;
}

server {
  listen 80;
  server_name dukaan.app;

  location {
    #This is the strangler logic. By default, send all traffic
    #to the old monolith.
    set $target_service $monolith_service;

    #However, if the request is for a store page (e.g., dukaan.app/store/gavranmisal)
    #AND we have set a special cookie for testing...

    if ($uri ~* "^/store/" and $cookie_use_new_storefront = "true") {
      #...then send this specific request to our new microservice instead!
      set $target_service $storefront_service;
    }

    proxy_pass http://$target_service;
    #... other proxy settings
  }
}

This configuration gave us precise control. We could now give the use_new_storefront=true cookie to our internal team. We could browse the site and test the new service on live production traffic without any real users seeing it. Once we were confident, we could modify the logic to route 10% of anonymous traffic, then 50%, and finally 100% to the new service.

The first surgery was a success. The storefront-service was live, it was fast, and we had a proven, safe pattern for slowly strangling our monolith.

The New Problem: A Pandora's Box of Communication

We had successfully carved out a simple, read-only service. But in doing so, we had unleashed a host of new, complex problems that we had been shielded from in our simple monolithic world.

The communication for the storefront was easy. When a seller in the monolith updated a product, we could have the monolith's code also update the storefront's database or send a message to its cache. It was mostly a one-way street.

But what happens when we extract a more complex service, like Orders?

Our simple point-to-point communication methods wouldn't work. We had just opened Pandora's box. We were no longer just application developers; we were now forced to become distributed systems engineers.

Key Takeaways

  • Never rewrite a complex system from scratch. The risk is too high. A gradual, piece-by-piece replacement is the safer and more effective path.
  • The Strangler Fig Pattern is the gold standard for incrementally replacing a monolith. It allows you to build and validate your new services with real traffic, minimizing risk at every step.
  • Your existing reverse proxy (like Nginx) is a powerful tool for implementing the Strangler pattern. You can use it to intelligently route traffic between the old and new systems.
  • Start with a simple, low-risk, and self-contained service. A read-heavy service like a storefront or a search feature is an ideal first candidate for extraction.
  • Moving to microservices solves team scaling problems, but it introduces complex technical challenges. Be prepared to tackle difficult problems like service discovery, network latency, and distributed data consistency.