Breaking the Monolith: Our First Microservice
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.
- Analogy: It's a single, massive restaurant. It has one huge kitchen that makes everything: Italian pasta, Mexican tacos, and Chinese noodles. There's one head chef who oversees everything.
- Pros (The Early Days): It's simple to start. Everyone is in the same kitchen, communication is easy, and you can serve your first customers quickly.
- Cons (Our Current Reality): As you get popular, the kitchen becomes chaotic. The pasta chef has to wait for the taco chef to finish using the stove. A change to the noodle recipe might accidentally use up all the salt needed for the pasta sauce. Hiring a new specialist chef is hard because they need to learn the entire, massive menu. This is exactly what we were experiencing.
Microservices: A Food Court of Specialized Stalls A microservice architecture breaks a large application into a collection of smaller, independent services.
- Analogy: It's a food court. Instead of one giant restaurant, you have a separate, independent stall for each type of cuisine. There's a pizza stall, a taco stall, and a noodle stall. Each stall has its own small kitchen, its own specialized chefs, and its own ingredients.
- Pros:
- Team Autonomy: The pizza team can change their menu, experiment with new ovens, and operate completely independently of the taco team. They can deploy updates multiple times a day without any risk of breaking the noodle stall.
- Specialized Technology: The noodle stall can use a special high-powered wok (a different programming language or database) that is perfect for their needs, while the pizza stall uses a traditional brick oven.
- Fault Isolation: If the taco stall has a fire in its kitchen, it shuts down. But the pizza and noodle stalls keep running perfectly fine. The entire food court doesn't go down.
- Cons: It's much more complex to set up and manage. How do the stalls coordinate an order for a customer who wants both a taco and a pizza? You now have to worry about network communication, service discovery, and distributed data-problems that simply don't exist in a monolith.
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.
- Analogy: You don't learn to cook by preparing the main course for a state dinner. You start by making the salad. If you mess up the salad, it's not great, but the main dinner isn't ruined.
- For Dukaan: This immediately ruled out critical, complex domains like Payments or Orders. A bug in the payment service could mean losing our users' money, which is an existential threat. That was not the place to experiment.
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.
- Analogy: Think of the monolith as a giant, tangled ball of yarn. You don't want to start by trying to pull out a single thread from the very center; you'll just make the knot tighter. You want to find a loose thread hanging off the edge and start unraveling from there.
- For Dukaan: We analyzed our code. The Orders service was a tangled nightmare; it depended on Users, Products, Payments, and Logistics. But other parts were more isolated.
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."
- Analogy: In our food court, "Pizza Stall" is a perfect bounded context. You know exactly what it does. "Miscellaneous Food Stall" is a terrible one.
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:
- Low-ish Business Criticality: This might sound counter-intuitive, but it was true. If the Storefront service went down, customers couldn't view stores. This is obviously bad, but it was not catastrophic. Sellers could still log in to their dashboards, manage products, and see their existing orders. Crucially, no data or money would be lost. We could still process payments for orders already initiated. It was the salad, not the main course.
- Few Dependencies: The Storefront was almost entirely a "read-only" service. Its main job was to fetch product and store information from our database (specifically, the read replica we built in Chapter 5) and display it prettily. It had very few dependencies on the complex "write" logic of the rest of the monolith, like order processing or payment confirmation. It was a thread hanging off the edge of the yarn ball.
- Clear Domain: Its purpose was crystal clear: "Display a public, read-only catalog of a seller's products." That's it. A perfect bounded context.
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.
- Don't rewrite the monolith all at once.
- Instead, identify one piece of functionality (a branch of the old tree).
- Build a new, independent microservice for it (plant a new vine).
- Put a "router" or "proxy" in front of the old monolith. This router is the key.
- Initially, the router just passes all traffic to the old monolith.
- Then, you configure the router to intercept calls to the specific functionality you've rebuilt and redirect that traffic to your new microservice. You can do this gradually-first for internal users, then for 1% of real users, then 10%, and so on.
- Once 100% of the traffic for that feature is being served by the new service, the old code inside the monolith is effectively dead. It's no longer being used.
- You can now safely delete that old code, making the monolith a little bit smaller.
- Repeat the process for the next piece of functionality.
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?
- How does the new order-service talk to the user-service to verify a customer's details?
- How does it talk to the payment-service to confirm a transaction?
- How do you handle a situation where a customer's payment succeeds in the payment-service, but the order-service crashes before it can create the order? This is a distributed transaction, and it is one of the hardest problems in software engineering. How do you keep your data consistent across multiple, independent services?
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.