In the world of software development, it’s easy to get the impression that a modern application should be made up of microservices. One service for managing users, another for orders, one for payments, and another for notifications. Each component can be developed independently, deployed separately, and scaled when it actually needs to be.
On a diagram, it looks perfect. Each part of the system has its own responsibilities, teams can work in parallel, and an outage in one service shouldn’t bring the entire application to a halt.
The problem starts when the diagram meets reality. Instead of one application, the team has to maintain a dozen services, several communication mechanisms, numerous deployment processes, and additional logs, monitoring, permissions, and configurations. A simple business operation requires communication between several components. Testing becomes more difficult, and finding the cause of an error means tracing the entire flow through the system.
Does that mean microservices are a bad solution? No. Under the right conditions, they can significantly improve how large products are developed. But they are neither an automatic stage in an application’s maturity nor a guarantee of better scalability.
Good architecture isn’t the architecture with the largest number of services. It’s the one that lets you develop a product without unnecessarily increasing costs, risk, and complexity.
That’s why, before making a decision, it’s worth understanding how monoliths, modular monoliths, and microservices differ, what problems they solve, and what new responsibilities they bring.
What exactly is a monolith?
A monolith is an application whose main components are developed and deployed as a single unit. It can contain many modules, support different business processes, and use a sophisticated internal architecture. So the fact that a system is a monolith doesn’t mean that all its code is in one file or that the application is chaotic.
For example, consider a system that handles sales, customers, products, orders, payments, and reporting. All these functions can be part of a single application that uses a shared database and is deployed as one product.
This approach has some clear advantages. In many cases, it’s easier to run, test, and deploy. Calls between modules can be made directly within the application process, without sending requests over a network. Transactions spanning several areas of the system can be simpler to implement when they use a shared database.
A monolith can also reduce the number of infrastructure components that need to be managed. There’s no need to configure a separate deployment process, monitoring, and communication for every small feature.
Of course, monoliths also have limitations. If new features are added over the years without keeping dependencies in check, the code becomes increasingly difficult to understand. A change in one place can cause problems elsewhere, and deploying a small feature requires testing and releasing the entire application.
But that isn’t an inevitable characteristic of a monolith. Often, the problem isn’t how the application is deployed, but its internal structure.
Not all monoliths are the same
In discussions about architecture, all monolithic applications are often lumped together. But there’s an important difference between a system whose modules have clearly defined boundaries and an application where every component can freely depend on all the others.
The first is a well-structured system. The second can become what’s known as a big ball of mud: a system with unclear boundaries, numerous dependencies, and logic that’s difficult to untangle.
Imagine a sales application in which the customer, product, order, and payment modules each have their own responsibilities. The order module uses a defined interface exposed by the customer module, rather than relying on random parts of its internal implementation. Changes in one area shouldn’t require uncontrolled modifications throughout the system.
If, on the other hand, every module directly modifies other modules’ data, uses their internal classes, and assumes details about how they work, the application gradually loses its structure.
This is where the modular monolith comes in.
Modular monolith: a compromise worth considering
A modular monolith remains a single deployable application, but its internals are divided into clearly defined modules. Each is responsible for a specific business area, has clearly defined boundaries, and provides other parts of the system with a controlled way to interact with it.
In practice, this might mean modules responsible for customers, the product catalog, orders, billing, or notifications. Each has its own logic, and access to its internal mechanisms is restricted.
The key difference is that logical boundaries don’t have to mean infrastructure boundaries. Modules can be well separated in the code, even while the application continues to run and deploy as a whole.
This model helps clarify responsibilities, limit dependencies, and prepare the system for further development without introducing all the costs of a distributed architecture.
A modular monolith can be a particularly good solution when:
-
the product is being developed by one team or by a few teams that work closely together;
-
the system’s business boundaries are still taking shape;
-
most features use the same data and need to maintain its consistency;
-
there’s no need to scale individual areas independently;
-
the current deployment process works well enough;
-
the company wants to keep open the option of extracting selected modules later.
That last point is particularly important. Starting with a modular monolith doesn’t mean giving up the option of moving to microservices. If the module boundaries are well designed and business needs change, a specific area can be extracted into a separate service in the future.
That’s not an automatic, one-click migration, though. You need to account for data storage, dependencies, transactions, communication, and responsibility for maintaining the new component. Good modularity can make this process much easier, however.
Microservices: what do they really offer?
A microservices architecture divides an application into smaller services that handle specific business functions and can be developed and deployed independently. Services communicate with one another through defined interfaces, often via APIs, messages, or events.
This allows the team to change one service without having to deploy the entire application. Individual components can also use different technologies or be scaled independently if their workloads and requirements genuinely differ.
For example, an e-commerce platform may have a separate product search service whose workload grows much faster than that of the user account management module. In a microservices architecture, you can increase the resources allocated to the search service without scaling every other part of the system.
A similar situation can arise when one area of a product requires particularly frequent deployments, another has distinct availability requirements, and yet another is developed by an independent team.
Microservices can therefore help in several specific areas:
Independent deployments. A change to one service does not have to require releases of all the other components, provided their contracts remain compatible.
Independent scaling. You can increase the resources of only the services that need them, rather than scaling the entire system.
Distinct team responsibilities. Teams can develop specific areas of a product independently, provided the boundaries of responsibility are genuinely well designed.
Isolation of some failures. A well-designed service can limit the impact of certain failures on the rest of the system. However, this does not happen automatically. If the other components cannot operate without an unavailable service, the problem may still affect a substantial part of the application.
Technology flexibility. Individual services can be tailored to different technical needs, although maintaining multiple technologies also increases costs.
It is worth noting that none of these benefits comes solely from the number of services. They require appropriate architectural boundaries, automation, monitoring, testing processes, and team expertise.
The cost of splitting up a system: what lies beyond the diagram?
The biggest mistake when planning microservices is comparing them solely on the basis of code structure. Splitting an application changes not only how it is implemented, but also how it is run, tested, deployed, and troubleshot.
In a monolith, one function can call another within the same process. In a distributed system, communication between services often involves network traffic, which can be delayed, fail, or be interrupted at an unexpected moment.
New questions arise. What should you do if service A performs an operation but service B does not receive a response? Will retrying the request cause the same operation to be performed twice? What happens if part of a process succeeds but the remaining components do not record the change?
These are not rare, theoretical problems. In systems that handle payments, orders, reservations, or inventory, they can lead to real business inconsistencies.
There are also maintenance costs:
-
more components to monitor;
-
separate configurations and deployment processes;
-
the need to trace requests that pass through multiple services;
-
additional communication and error-handling mechanisms;
-
integration and contract tests;
-
API version management;
-
access control between components;
-
a larger number of potential failure points;
-
the need for expertise in distributed systems.
This does not mean that microservices are always more expensive over their entire lifecycle. In a sufficiently large system, they can reduce coordination costs and accelerate development. However, the initial operational cost is real and should be factored into the decision.
If a company lacks deployment automation, good monitoring, and incident response procedures, splitting up an application may increase complexity faster than it delivers benefits.
When do microservices start to make sense?
There is no single universal number of users, requests, or developers after which you should switch to microservices. The decision depends on the type of product, its workload, the organizational structure, and the actual limitations of the current architecture.
However, there are situations in which it is worth seriously considering splitting off parts of the system.
1. Different areas have clearly different workload profiles.
If one function requires significantly more computing power than the others, independent scaling can bring tangible benefits. However, you should first confirm that the problem cannot be solved with simpler methods, such as query optimization, caching, a job queue, or increasing the resources of the entire application.
2. Teams need to develop different areas independently.
In a large organization, a shared codebase and a single release process can make it harder for multiple teams to work. Separating responsibilities can improve autonomy, provided the services have stable boundaries and clearly defined contracts.
3. Different functions have different availability requirements.
Some areas of a product may require particular resilience to failures, while others may be temporarily unavailable without halting the most important processes. Independent services make it possible to tailor scaling, deployment, and recovery strategies to each area.
4. One module requires a different technology or processing approach.
Sometimes a particular task has justified requirements that would be inefficient to meet in the main application. Splitting it off can then limit the impact of those requirements on the rest of the product. However, it is worth remembering that an additional technology stack also means additional maintenance responsibilities.
5. Business boundaries are already well understood.
If it is clear where one area's responsibilities end and another's begin, it is easier to design independent services. When boundaries are unclear and frequently change, defining them prematurely can lead to costly dependencies and constant interface changes.
The most important principle is: split off a service because it solves a specific problem, not because another box on the diagram looks modern.
When is a modular monolith a better choice?
A modular monolith often wins when a company needs to organize its application but there is not yet a good reason to distribute it across many independent services.
This may be the case with a new product whose business model is still evolving. At the outset, it is difficult to predict which features will become the most heavily loaded, which will require independent deployments, and where the boundaries of responsibility will ultimately lie.
The same applies to a medium-sized business system in which most operations involve shared data. Splitting the logic into several services can introduce additional problems with data consistency and transactions without providing enough independence in return.
Vale la pena prendere in considerazione un monolite modulare anche quando l'azienda dispone di risorse operative limitate. Un unico processo di rilascio e un modello di monitoraggio più semplice possono essere una soluzione più ragionevole rispetto alla gestione di una dozzina di servizi, ciascuno con una propria configurazione e procedure.
Ciò non significa lasciare tutto in un'unica applicazione senza un piano per il futuro. Un monolite modulare ben progettato richiede disciplina: confini chiari tra i moduli, accesso controllato ai dati e limitazione delle dipendenze non necessarie.
Se questi principi vengono rispettati, l'azienda può beneficiare di un modello di rilascio più semplice, preparando al contempo il sistema all'eventuale separazione di alcune funzionalità in futuro.
La scalabilità non è solo una questione di numero di server
Uno degli argomenti più frequenti a favore dei microservizi è la scalabilità. È tuttavia opportuno distinguere due questioni diverse: la scalabilità tecnica e la capacità dell'organizzazione di sviluppare il prodotto.
La scalabilità tecnica indica la possibilità di gestire un carico maggiore. In molti casi è possibile eseguire un'applicazione monolitica su più istanze, utilizzare il bilanciamento del carico, la cache, le code di attività e un database progettato adeguatamente. Un sistema del genere può gestire un traffico significativo senza doverlo suddividere in decine di servizi.
Naturalmente, non è possibile scalare qualsiasi monolite in ogni modo. I problemi possono derivare dalla memorizzazione dello stato nella memoria del processo, da un database condiviso, da operazioni sincrone costose o dai limiti di un determinato componente. Prima di tutto, però, vale la pena stabilire cosa rappresenti davvero il collo di bottiglia.
La scalabilità organizzativa è una questione diversa. Se molti team lavorano sul prodotto e si bloccano regolarmente a vicenda durante le modifiche e i rilasci, suddividere le responsabilità può essere vantaggioso anche quando le prestazioni del sistema sono sufficienti.
In pratica, è quindi opportuno basare la decisione su misurazioni. L'applicazione ha problemi di prestazioni? I rilasci richiedono troppo tempo? I team devono concordare ogni modifica? Una funzionalità specifica ha bisogno di risorse diverse? I guasti di un modulo influiscono sugli altri?
Le risposte permettono di distinguere un problema architetturale da un problema di infrastruttura, qualità del codice o organizzazione del lavoro.
Migrazione ai microservizi: perché non conviene suddividere tutto in una volta?
Se l'applicazione attuale inizia davvero a limitare lo sviluppo del prodotto, la migrazione ai microservizi non deve necessariamente comportare una riscrittura completa del sistema in un'unica soluzione.
Un approccio più sicuro può consistere nel separare gradualmente aree specifiche. Per prima cosa occorre stabilire quale modulo abbia una responsabilità sufficientemente chiara, quali dati gestisca e in che modo collabori con le altre parti dell'applicazione.
Successivamente è possibile progettare il confine di comunicazione, preparare i test e trasferire gradualmente la responsabilità al nuovo servizio. In questo modo è possibile verificare le ipotesi in un ambito limitato, prima che l'azienda decida di apportare ulteriori modifiche.
Per esempio, un sistema di vendita può inizialmente includere un modulo per la generazione di report che grava pesantemente sul database e rallenta le operazioni degli utenti. Invece di suddividere l'intero sistema, si può prima valutare se sia possibile trasferire la reportistica a un processo o servizio separato, eventualmente utilizzando dati preparati in modo asincrono.
Questa separazione ha senso se riduce davvero il carico sull'applicazione principale o consente di sviluppare e scalare la reportistica in modo indipendente. Se invece i report sono semplici e il loro carico è contenuto, un servizio aggiuntivo potrebbe essere superfluo.
Proprio per questo la migrazione dovrebbe partire dal problema e dal risultato atteso, non dall'ipotesi che tutti i moduli debbano prima o poi diventare microservizi.
È inoltre importante ricordare che separare un servizio non significa soltanto spostare il codice. Occorre risolvere le questioni relative ai dati, alla comunicazione, all'autorizzazione, al monitoraggio, ai rilasci, ai test e alla responsabilità in caso di guasti. Solo allora il nuovo componente diventa un elemento realmente indipendente dell'architettura.
Come prendere una decisione? Una lista pratica di domande
Prima di scegliere un'architettura, vale la pena rispondere ad alcune domande. Non sostituiranno un'analisi tecnica, ma aiuteranno a fare chiarezza sulla decisione.
1. Quale problema specifico vogliamo risolvere? Si tratta di prestazioni, tempi di rilascio, dipendenze tra i team, disponibilità o difficoltà di manutenzione del codice? Se non sappiamo indicare il problema, è difficile valutare se i microservizi siano la soluzione giusta.
2. Il problema dipende davvero dall'architettura? Un'applicazione lenta potrebbe richiedere l'ottimizzazione delle query, mentre i rilasci difficili potrebbero dipendere dalla mancanza di test e automazione. Un cambiamento architetturale non sostituisce questi interventi.
3. I confini aziendali sono sufficientemente chiari? Se i moduli utilizzano continuamente i dati e le regole interne gli uni degli altri, separarli in servizi indipendenti potrebbe consolidare una suddivisione errata.
4. Abbiamo bisogno di scalare o rilasciare in modo indipendente? Se tutte le parti del sistema vengono modificate e sottoposte a carico in modo simile, il vantaggio dell'indipendenza potrebbe essere limitato.
5. Disponiamo degli strumenti e delle competenze necessari per gestire un sistema distribuito? Il monitoraggio, i log, la tracciabilità delle richieste, i rilasci automatizzati e le procedure di gestione dei guasti sono elementi importanti di questa decisione.
6. Come verranno gestiti i dati e le transazioni? Separare un servizio può rendere più difficile mantenere l'atomicità delle operazioni che coinvolgono più aree. È necessario pianificare cosa accadrà se una parte del processo va a buon fine e un'altra no.
7. I vantaggi giustificano il costo totale? È opportuno considerare non solo il costo di implementazione, ma anche l'infrastruttura, il monitoraggio, la sicurezza, i test, la manutenzione e lo sviluppo delle competenze.
8. Possiamo iniziare con una modifica più contenuta? A volte è sufficiente riordinare i moduli, separare un processo asincrono o migliorare l'automazione dei rilasci. La modifica minima che risolve efficacemente il problema può essere il miglior punto di partenza.
Gli errori più frequenti nella scelta dell'architettura
Il primo errore è identificare la modernità con il numero di servizi. I microservizi sono un modo specifico di organizzare un sistema, non un fine in sé.
Il secondo è progettare l'architettura sulla base di previsioni che non sono ancora state confermate dal funzionamento effettivo del prodotto. È opportuno mantenere la possibilità di evolversi e separare altri elementi quando emerge una necessità giustificata.
Il terzo è suddividere il sistema senza definire i confini aziendali. Se i servizi dipendono fortemente gli uni dagli altri, si crea un'architettura distribuita che conserva i problemi del monolite, aggiungendo però i costi della comunicazione di rete.
Il quarto è trascurare gli aspetti operativi della soluzione. Ogni nuovo servizio deve essere rilasciato, monitorato, protetto e sottoposto a diagnosi. Senza processi adeguati, un numero crescente di componenti può ridurre l'affidabilità anziché migliorarla.
Il quinto è cercare di risolvere i problemi organizzativi con la sola tecnologia. I microservizi possono favorire l'autonomia dei team, ma non sostituiscono una chiara ripartizione delle responsabilità, la comunicazione e una buona gestione del prodotto.
Il sesto errore è considerare il monolite modulare una soluzione temporanea da abbandonare il prima possibile. Un'applicazione monolitica ben progettata può rimanere la scelta giusta per molti anni. Non c'è bisogno di complicarne l'architettura senza un vantaggio concreto.
L'architettura dovrebbe evolversi insieme al prodotto
Non esiste un'unica architettura che sia la migliore per ogni applicazione. Un piccolo prodotto sviluppato da un team di poche persone ha esigenze diverse da una piattaforma che supporta molti domini aziendali indipendenti ed è sviluppata da una dozzina di team.
Un monolite può offrire semplicità di distribuzione e una gestione operativa più facile. Un monolite modulare permette di organizzare la struttura dell'applicazione mantenendo questa semplicità. I microservizi, invece, possono garantire indipendenza nello sviluppo, nella distribuzione e nella scalabilità, se il prodotto e l'organizzazione hanno davvero bisogno di questo modello.
La cosa più importante è capire quale problema sta affrontando l'azienda. Non vale la pena introdurre una dozzina di servizi solo perché l'architettura delle piattaforme più diffuse è fatta così. Allo stesso modo, non conviene aggrapparsi a un monolite se i suoi limiti frenano lo sviluppo del prodotto e si possono individuare vantaggi concreti nel separare alcune parti del sistema.
Una buona decisione architetturale non consiste nel prevedere ogni esigenza futura. Consiste nel realizzare una soluzione che risponda ai requisiti di oggi senza precludere cambiamenti ragionevoli in futuro.
Prima di suddividere un'applicazione in microservizi, verifica se hai davvero bisogno di servizi indipendenti o se ti serve soprattutto un sistema organizzato meglio. Questa differenza può determinare non solo l'architettura, ma anche i costi e il ritmo di sviluppo del prodotto.
Fonti e approfondimenti
-
AWS Well-Architected Framework: Choose how to segment your workload - compromessi tra architettura monolitica e a microservizi.
-
Microsoft Azure Architecture Center: Microservices architecture - complessità, comunicazione, test e gestione dei dati nei sistemi distribuiti.
-
microservices.io: How modular can your monolith go? - organizzare un monolite attorno ai domini aziendali.
Articoli correlati di Web24
-
La tua applicazione ha 5 anni. È ancora adatta a essere sviluppata?
-
Perché una nuova funzionalità in una vecchia applicazione costa sempre di più?
-
La tua applicazione funziona. Ma è possibile distribuirla in sicurezza 100 volte al giorno?
I link qui sopra rimandano ad articoli che trattano temi legati alla modernizzazione, ai costi di sviluppo e ai processi di distribuzione. Non sostituiscono un'analisi specifica della scelta dell'architettura.
Buona lettura.
