Building a modular monolith with Fastify

Spanish audio is available in the player settings
Rate this content
Bookmark

In my journey through Nodeland, I saw most teams struggling with the free-form nature of Node.js development: there are no guardrails for maximum flexibility. Yet, not all paths offer a smooth ride.
How to build applications that are well-organized, testable, and extendable? How could we build a codebase that would stand the test of time?
In this talk, we will explore how to avoid the trap of Singletons to create robust Node.js applications through the use of Fastify plugins: we will build a modular monolith!

FAQ

Fastify is a web framework for Node.js designed for building web applications, backends, and APIs efficiently. It offers built-in features like a logger named Pino and supports creating routes using AsyncAwait. Fastify is recommended for its ease of use and performance benefits in Node.js environments.

Fastify's encapsulation allows developers to create context within contexts, ensuring that each layer of the application does not share state with the previous one. This feature aids in structuring applications into segmented plugins, enhancing code maintainability and scalability.

The main disadvantage of using MVC systems is that they often do not scale well in terms of complexity. As applications grow, maintaining a large number of models and controllers can become cumbersome and lead to spaghetti code, making the system difficult to manage.

Instead of MVC, applications should be structured by domains or features, segmenting distinct functionalities and communicating over well-defined APIs. This approach helps in managing complexity and maintaining clear boundaries between different parts of the application.

You can follow Matteo Collina on Twitter at @MatteoCollina, subscribe to his newsletter for updates in the UK, or watch his streams on Twitch where he shares insights on software development and more.

To harness Fastify effectively, ensure you define schemas for both incoming and outgoing data. This not only secures your application but also optimizes JSON handling. Additionally, use the 'under-pressure' module to protect your service from becoming overloaded.

Matteo Collina
Matteo Collina
30 min
14 Apr, 2023

Comments

Sign in or register to post your comment.
  • Sreeharsha Raveendra
    Sreeharsha Raveendra
    I don't know if my brain travels as fast as Matteo, man was sprinting in his mind

Video Summary and Transcription

Fastify is a powerful tool for building web applications and APIs in Node.js, with millions of downloads per month. It promotes encapsulation and structuring through plugins and decorators, allowing for code and data segmentation. The talk emphasizes the importance of modularizing applications by domains and features, and showcases a demo of a typical Fastify application. The speaker also discusses the benefits of using Platformattic for refactoring and launching Fastify applications in the cloud. The Q&A section covers topics such as dependency injection and debugging, while also highlighting the importance of separating business logic from API contracts.

1. Introduction to Fastify

Short description:

Happy to be here at Node Congress. Talking about Fastify, a powerful tool for building web applications and APIs in Node.js. It has a built-in logger called Pino. Fastify is widely used with millions of downloads per month. The problem with using a model view controller system is that it doesn't scale well in complexity. Instead of building a view layer, we focus on building APIs. This can lead to a large number of models and a lengthy routes.js file.

So, happy to be to be here at Node Congress. I have been... Look, I've known about this conference for a while, and it's so great to finally be here in Berlin. It's been a long time since I came to Berlin, and I kind of missed it. So, look, I am here talking about Fastify. So, it's great to be here, and so on.

So, a couple of things about me. I have a newsletter too, and in the UK, if you don't matter, just subscribe there, or follow me on Twitter, at Matteo Collina. And I also am also streaming on Twitch, so if you like that, you can join. Also, I need to correct Liz, because since I put in the bio, it's actually 17 billion in 2022. Whatever. Like, it's so much fun.

So, okay. So, today, we are talking about Fastify. And if you don't know Fastify, you probably should, but you should probably use it if you're using Node.js, right? This is not Congress, so I don't know. You should probably use Fastify to build your web applications and backends and APIs. How do you use it? Very easy, you require import whatever. It has a logger built in. EpiDays, you want a logger in your application, right? It's called Pino. And you can use it to create your routes using AsyncAwait and all the other shenanigans that you might want. It's probably 4 billion million times per year or something, downloads per month.

So, okay. Let's talk a little bit about why you should not use Fastify or anything, or how to not use Node.js. How many of you have built a model view controller system in your career? Great. What's the problem with this system is that ultimately it doesn't scale. In what sense it doesn't scale? Well, it doesn't scale well in complexity. If you are building an application, and you're building it using following model view controllers, okay, let's start with the view. Most of the time there's no view layer anymore, we just do build API, so that's gone. So if you are writing a piece of code, it either goes into the controller or the models, and if it, you know, a 50% chance. After a bit of time you have 2000 models and a routes.js file that is 10,000 lines long.

2. Building Monoliths with Fastify

Short description:

Truth. MVC leads to Carbonara and spaghetti code. Instead, structure your application by domains and features. Avoid mixing features' databases. Fastify offers encapsulation through plugins, enabling code and data segmentation. It has no cost or overhead and supports decorators. Encapsulation allows for nested contexts without sharing data between layers.

Truth. This is actual number from real code. So it doesn't really work well in that way, and it doesn't scale well in complexity. What do you do instead? Because the question is, if model view controller is not good enough, what do you do instead? And how a lot of few major companies and a few major system can actually build monoliths, because model view controller is not good but they still ship monoliths. So there's a few article every now and then about monoliths around, and why and how, what they are doing.

Well, to be honest MVC leads to Carbonara and spaghetti code, but I like the Carbonara and not the spaghetti code. That's it. So how do you do it? You need to structure your application by domains, by feature. You need to identify what are the key features of your application and segment it. And in between those systems, you tend to communicate over well-known APIs. The important part is, do not have one set of features, read the database of the other set of features. Because the moment you start dipping into both, then you have a lot of, you don't know how you end up with your relations. Or another term to say is if in order to fetch a data, you need to do a 10, you need to join 10 tables, you probably have the wrong schema. Okay? So think about that and what you're doing and reflect on your life choices.

So what makes a domain and how do we build monolith? Like it is something that we want to do, right? It's a good thing. And well, you know, it typically, it's a specific subject that is being developed, okay? Typical cases is the catalog or the order management system or a cart or whatever you want to call it, okay? In some of the stuff that they're recently been developing, it's called, we have a domain which is the organization and the teams and other stuff is about the applications and the code that you run on our cloud. So anyway, it's domains, and you want to avoid the spaghetti code. So what does Fastify as for helping out building with this stuff? Fastify offers a concept called encapsulation. So it enables you to structure your application in a set of plugins that you can use to segment your data, to segment your code and in that way they don't share anything, essentially. Now a few few may ask but you could do this before, right? There's other techniques. Yes, but this has no cost has no overhead whatsoever. Okay, it's super fast, so you don't have anything to pay for it. And it's great. It has also concept of this called the decorator. So you can actually add stuff to your to your code and application. So how does encapsulation work? You basically can create context within context within context within this context, like kind of from a big matrioshka, and each layer does not share anything with the previous one. It's great. It's something disappeared. Okay, fun. Some missing.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
You can check the slides for James' talk here.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
Native ESM support for Node.js was a chance for the Node.js project to release official support for enhancing the module loading experience, to enable use cases such as on the fly transpilation, module stubbing, support for loading modules from HTTP, and monitoring.
While CommonJS has support for all this, it was never officially supported and was done by hacking into the Node.js runtime code. ESM has fixed all this. We will look at the architecture of ESM loading in Node.js, and discuss the loader API that supports enhancing it. We will also look into advanced features such as loader chaining and off thread execution.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
In the early years of Node.js, diagnostics and debugging were considerable pain points. Modern versions of Node have improved considerably in these areas. Features like async stack traces, heap snapshots, and CPU profiling no longer require third party modules or modifications to application source code. This talk explores the various diagnostic features that have recently been built into Node.
You can check the slides for Colin's talk here. 
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Can Deno run apps and libraries authored for Node.js? What are the tradeoffs? How does it work? What’s next?
Multithreaded Logging with Pino
JSNation Live 2021JSNation Live 2021
19 min
Multithreaded Logging with Pino
Top Content
Almost every developer thinks that adding one more log line would not decrease the performance of their server... until logging becomes the biggest bottleneck for their systems! We created one of the fastest JSON loggers for Node.js: pino. One of our key decisions was to remove all "transport" to another process (or infrastructure): it reduced both CPU and memory consumption, removing any bottleneck from logging. However, this created friction and lowered the developer experience of using Pino and in-process transports is the most asked feature our user.In the upcoming version 7, we will solve this problem and increase throughput at the same time: we are introducing pino.transport() to start a worker thread that you can use to transfer your logs safely to other destinations, without sacrificing neither performance nor the developer experience.

Workshops on related topic

Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
Building a Hyper Fast Web Server with Deno
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Matt Landers
Will Johnston
2 authors
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
GraphQL - From Zero to Hero in 3 hours
React Summit 2022React Summit 2022
164 min
GraphQL - From Zero to Hero in 3 hours
Workshop
Pawel Sawicki
Pawel Sawicki
How to build a fullstack GraphQL application (Postgres + NestJs + React) in the shortest time possible.
All beginnings are hard. Even harder than choosing the technology is often developing a suitable architecture. Especially when it comes to GraphQL.
In this workshop, you will get a variety of best practices that you would normally have to work through over a number of projects - all in just three hours.
If you've always wanted to participate in a hackathon to get something up and running in the shortest amount of time - then take an active part in this workshop, and participate in the thought processes of the trainer.
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.