A tale of a dying monolith: The complexity of replacing something simple
Tags: feathersjs, microservices, softwareengineering, architecturecompone
Published: 2018-09-26 02:21:07

---
title: A tale of a dying monolith: The complexity of replacing something simple
published: true
tags: feathersjs,microservices,software-engineering,architecture-compone
canonical_url: https://medium.com/@eduardoromero/a-tale-of-a-dying-monolith-7e0e0411951
---

### A tale of a dying monolith: The complexity of replacing something simple

![](https://cdn-images-1.medium.com/max/1024/1*D6ltU71DfGMyGkYGPaeBYA.jpeg)<figcaption>Photo by <a href="https://unsplash.com/photos/wgjG86EuubE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thor Alvis</a> on <a href="https://unsplash.com/@terminath0r?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

I’ve been working on Big Media for almost two years now. Two of my favorite projects were building publishing platforms. Both leveraged the Headless CMS architecture and developed a platform around it.

While the stacks were entirely different, the patterns between architectural components seemed the same.

I started to identify the same patterns in older systems I had worked with before, and I wanted to know if I could apply the same patterns to a legacy system.

A friend was building new versions of the Android and iOS Apps for an old CakePHP app in the Healthcare industry I had helped develop almost five years ago. He wanted to add new features to the apps and needed the backend to support the new features.

The CakePHP App interacted with data coming from an external system. It was the source of truth for most of the entities in the app. Both systems were tightly coupled, sharing data via database tables.

![](https://cdn-images-1.medium.com/max/1024/1*d-yytiQAYljF5Y8zoa9h6g.png)<figcaption>CakePHP Monolith tightly-coupled to an external system via the Database.</figcaption>

Data for things like product names, system ids, pricing, discounts, product status, user accounts, membership status, and stock levels come from the external system.

Doctors and practitioners would log in to the CakePHP App and add extra information to the data coming from the external system.

Models for product descriptions, pictures, calendars, procedures, locations, profiles, etc. only existed in the App, and that data was created and managed there. The App would render the content and exposed the data via a REST API to mobile and third-party apps. One big, mighty monolith from the good ole’ days.

I convinced my friend to let me start building experiments around the project. I began [_strangling_](https://www.martinfowler.com/bliki/StranglerApplication.html) the monolith. After several iterations, this is the resulting architecture:

![](https://cdn-images-1.medium.com/max/1024/1*3Rw5Hd7AFof_Uq7fOA3ACw.png)<figcaption>The New Stack — A Highly decoupled architecture with a Headless CMS, an external search engine and real-time API.</figcaption>

### The Platform — 🕸

The new Platform is an event-driven, distributed system. A FeathersJS RESTful layer in the middle of the platform. I offloaded all content related responsibilities to Prismic.io, the CMS functionality on CakePHP was deprecated. I used Algolia to power the search engine on all apps, including the API.

Based on the events of the API I can do things like index new content or remove content from the search engine, update pricing, stock levels, enable or disable content, and bake in some default data in case an entity does not exist on the CMS yet.

As a nice bonus, the mobile apps can now give notifications in real time to the users about things that are happening in other parts of the platform.

#### No shared databases — 💥

I started by removing the database dependency between systems. Now all systems integrate via RESTful API endpoints.

The coupled integration was the source of a lot of pain-points:

- **Schema changes from external updates** : Whenever the external system’s schema was updated the backend needed to be updated too. Some of those changes could tickle all the way up to the mobile apps.
- **Cascaded down-time** : Because the external system was the source of truth for things like membership status and identity when it went down for a reason it would cause partial failures on other systems. Local cache helps but only to some extent.
- **Batch syncs** : Because of the systems integrated via the database some things needed synchronization with daily jobs. Stuff like price lists, stock levels, status (i.e., discontinued items), and search indexing on Lucene all had to run every day at the end or beginning of the day.
- **Ownership** : Because there was very little visibility when something was wrong there was a lot of blame-game between maintainers of the external system and the backend.

Now the external system pushes changes via the REST API. They exposed a SOAP API for User Membership which the Feathers backend consumes and proxies as JSON API for external clients.

#### The Headless CMS — 🖋

I modeled all Content entities in Prismic. Users can now create and manage content and see it magically appear on all apps in near real-time.

I kept Cake’s frontend as is. Keeping it as the Rendering engine means that no extra effort needed in the frontend. In the future, they want to migrate the to VueJS or React.

![](https://cdn-images-1.medium.com/max/1024/1*EQuvgF_2UDjHO-HeVULang.png)<figcaption>Modeling Content in Prismic (sample data model)</figcaption>

I set up webhooks to sync that data back to CakePHP models. The content coming from Prismic will update existing models, handle external assets (backing them up locally) and update current state. Eventually, all content will exist in Prismic.

From previous experience, data migration is always a lot of work. In this case no data migration is needed.

![](https://cdn-images-1.medium.com/max/1024/1*iQzHdPP6blK8mjp8PSLCpg.png)<figcaption>JSON Response from Prismic’s API (from same model above).</figcaption>

#### The Search Engine — ️🔍

Working with Algolia is a breeze. It’s blazing fast and easy to use. Having an event-driven architecture turned out to be extremely beneficial. Events on the API use [NodeJS’ client](https://www.algolia.com/doc/api-client/javascript/getting-started/)to index the data asynchronously.

![](https://cdn-images-1.medium.com/max/1024/1*X4KslL8YmYKF3SawbqT17Q.png)<figcaption>Search response time — Blazing fast, under 10ms.</figcaption>

In a few milliseconds, the search features on all applications will reflect the changes and show (or hide) the same results. SDKs for PHP, Swift, and Java made the integration easy.

![](https://cdn-images-1.medium.com/max/1024/1*2yPg3LOAVmbuDrkwsHQ-AA.png)<figcaption>Search Operations — Averages to 88k monthly operations.</figcaption>

For other existing clients that were not updated the CakePHP search continued to work as it was before powered by algolia behind the scenes. This means that other integrations like Chrome’s Omnibox search continued to work.

#### Continuous Deployment — 🚀

Having more pieces in the architecture means that deploying new versions of the platform can no longer be done by hand. I set up pipelines on [_Buddy_](https://buddy.works/) to handle the deployments automatically.

The CakePHP app was already being deployed to an EC2 instance on AWS. I just had to automate the process (and added [atomic deployments](https://buddy.works/blog/introducing-atomic-deployments)).

![](https://cdn-images-1.medium.com/max/1024/1*pR3dB9EC9KU3wPsyfJGKTw.png)

The FeathersJS app is deployed to the cloud with Zeit’s [Now](https://zeit.co/now). A service for immutable infrastructure that makes it simple to deploy features quickly without hassle (or fear).

![](https://cdn-images-1.medium.com/max/1024/1*J1bKV4gUxhpNxCa8mdFo8w.png)<figcaption>NodeJS Deployment Pipeline with Now</figcaption>

Merging a branch will create a new container tied to a new domain name where you can do any tests you need.

If everything works as expected, the last step will alias the current deploy to the backend’s public DNS name and it will automatically start receiving live traffic. It will also automatically scale the app and make sure it’s running in all available [regions](https://zeit.co/cdn).

![](https://cdn-images-1.medium.com/max/1024/1*ytMmI0AOgDf36g9zmuXNxQ.png)<figcaption>now scale</figcaption>

The configuration for aliasing to production and scaling rules are set in the repository as code. Things like database connection, and the access keys for third-party services are set as environment variables that are injected to now from the pipeline.

MySQL database lives on Amazon’s RDS. The RethinkDB database is hosted in [_compose.io_](https://www.compose.com/databases/rethinkdb). Using a three node cluster configuration plus a proxy portal node (and automated backups).

#### Debugging and Tracing —🕵🐛

Breaking the monolith apart made the overall architecture easy to understand, easier to maintain and evolve. But at the same time made debugging very hard. Trying to figure out what’s going on when an event crosses system boundaries was very challenging.

I had already some idea about observability and traceability because of my experience with AWS Lambda, X-Ray, and IOPipe. I really like IOPipe, but it only works for lambda. I remembered reading great insight on observability via [Charity Majors](https://medium.com/u/5587d135a397)’ [twitter](https://twitter.com/mipsytipsy). I decided to try Honeycomb.io.

I instrumented the backend and the pipeline.

![](https://cdn-images-1.medium.com/max/1024/1*R902TgSBNMZ_ipuhWT69PA.png)<figcaption>Request per second (purple) and Releases from GitHub (blue).</figcaption>

Feathers uses ExpressJS under the hood, so I just had to add their [beeline for NodeJS](https://www.honeycomb.io/blog/2018/05/the-fastest-most-direct-route-to-instrumented-code-a-honeycomb-beeline/)and HTTP requests were handled out of the box.

![](https://cdn-images-1.medium.com/max/868/1*xAwhcEaIseApND9I0t4uig.png)<figcaption>NodeJS Honeycomb Beeline</figcaption>

I used _before_ and _after_ [_hooks_](https://docs.feathersjs.com/api/hooks.html) to add extra context to the tracing information. That helped get better insight into what was going on in the platform and made it easier to build meaningful queries and create visualizations with values that made sense business-wise.

There is no beeline for PHP yet. But the [Events API](https://docs.honeycomb.io/api/events/) can be used with all other languages.

I also instrumented the pipeline so all releases are marked on honeycomb (the blue combs on the image above). I used the [marker CLI](https://docs.honeycomb.io/working-with-data/markers/#honeymarker-installation) for that. With pipelines already setup to run when code is merged to master and tagged for release, it was just running one extra step with the following:

```
$ honeymarker -k $HONEYCOMB\_KEY -d feathers-ws \
    -t release \
    -m "$EXECUTION\_TAG" \
    add
```

Triggers can be leveraged to keep track of any unexpected behavior across the platform. I expect that in the future [Triggers](https://docs.honeycomb.io/api/triggers/) will be used to track behavior after an update performing roll-backs or aliasing the release automatically.

I learned a lot! The platform is robust, decoupled and scalable. It helped me validate my theory around content platforms and helped recognize reusable patterns I can apply in different projects easily.

On the other hand, it made me realize that replacing a monolith with a distributed system helps in the long run _but_ adds a lot of complexity that can be cumbersome if you don’t have the right tools support it like CI/CD, event logs and tracing.

I think observability is a key success factor when building service-oriented architectures like microservices or Lambda-based architectures. I’ll continue to dig more into it.

Finally, the team that will continue to support the platform was also delighted with the outcome. It’s now easier to add new features. Understanding the components is straightforward, more than the original codebase was. They are already thinking of what the next refactor will be — _The frontend_. The organization has less aversion to change, and new ideas are already on the pipeline, overall they are moving faster, and there’s a new sense of trust in the engineering team.

### More resources 📚

- [**How to break a Monolith**](https://martinfowler.com/articles/break-monolith-into-microservices.html) by [Zhamak Dehghani](https://medium.com/u/f2c25544d719) explains how to migrate a monolith to a microservices architecture. The folks from Nginx have a great [article series about](https://www.nginx.com/blog/introduction-to-microservices/) Microservices, [last one](https://www.nginx.com/blog/refactoring-a-monolith-into-microservices/) explains how to refactor a Monolith into Microservices.
- [**Buddy**](https://buddy.works/) is my favorite CI/CD tool. It’s easy to use and it has all the cool features like integration with GitHub, deploying to k8s (ECS, GKS), running steps in containers and ephemeral environments they call Sandboxes. Read their [guides](https://buddy.works/guides) for more information.
- [**FeathersJS**](https://docs.feathersjs.com) is a Real-time REST API framework for NodeJS. It’s my favorite framework to develop NodeJS APIs. [**NestJS**](https://nestjs.com/) is second.
- **Honeycomb’s** [**blog**](https://www.honeycomb.io/blog/) has very good pointers on Observability. They even sponsored this year’s (and first ever) o11ly con.
- [**New Relic**](https://newrelic.com/nodejs) has support for [Custom Metrics](https://docs.newrelic.com/docs/agents/nodejs-agent/supported-features/nodejs-custom-metrics) and [Distributed tracing](https://docs.newrelic.com/docs/apm/distributed-tracing/getting-started/introduction-distributed-tracing), but I haven’t tried. Seems more complicated. I will give it a try because my clients use it.
- [**Martin Fowler**](https://martinfowler.com/aboutMe.html) has [a very good post](https://martinfowler.com/articles/201701-event-driven.html) about Event-driven patterns and a [presentation](https://martinfowler.com/articles/two-stack-cms/) about “headless cms”
- [**Human Made**](https://humanmade.com/) has a good [booklet](https://gallery.mailchimp.com/afdf80ec9bf56213ada4edf20/files/7a1013d4-35da-4b5a-9082-02e317b098fb/Headless_WordPress_The_Future_CMS_1.pdf) about Headless CMS with WordPress. Concepts apply to any CMS.

_Thanks to_ [_Felipe Guizar Diaz_](https://medium.com/u/bd35c34ebe66)_,_ [_Luis Daniel_](https://medium.com/u/4517f8f364b1)_, and_ [_Miguel Lomelí_](https://medium.com/u/62df9fbbb4d8) _for helping proof-read this article._