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!

This talk has been presented at Node Congress 2023, check out the latest edition of this JavaScript Conference.

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.

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.

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.

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.

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.

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
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
ESM Loaders enhance module loading in Node.js by resolving URLs and reading files from the disk. Module loaders can override modules and change how they are found. Enhancing the loading phase involves loading directly from HTTP and loading TypeScript code without building it. The loader in the module URL handles URL resolution and uses fetch to fetch the source code. Loaders can be chained together to load from different sources, transform source code, and resolve URLs differently. The future of module loading enhancements is promising and simple to use.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
This talk covers various techniques for getting diagnostics information out of Node.js, including debugging with environment variables, handling warnings and deprecations, tracing uncaught exceptions and process exit, using the v8 inspector and dev tools, and generating diagnostic reports. The speaker also mentions areas for improvement in Node.js diagnostics and provides resources for learning and contributing. Additionally, the responsibilities of the Technical Steering Committee in the TS community are discussed.
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Deno aims to provide Node.js compatibility to make migration smoother and easier. While Deno can run apps and libraries offered for Node.js, not all are supported yet. There are trade-offs to consider, such as incompatible APIs and a less ideal developer experience. Deno is working on improving compatibility and the transition process. Efforts include porting Node.js modules, exploring a superset approach, and transparent package installation from npm.
Multithreaded Logging with Pino
JSNation Live 2021JSNation Live 2021
19 min
Multithreaded Logging with Pino
Top Content
Today's Talk is about logging with Pino, one of the fastest loggers for Node.js. Pino's speed and performance are achieved by avoiding expensive logging and optimizing event loop processing. It offers advanced features like async mode and distributed logging. The use of Worker Threads and Threadstream allows for efficient data processing. Pino.Transport enables log processing in a worker thread with various options for log destinations. The Talk concludes with a demonstration of logging output and an invitation to reach out for job opportunities.

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.
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.
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
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.