Comments are now enabled. Click here to add yours.
A common problem is for a company to have a software service that is starting to show scaling issues.
Ideally, your website should give every user a pleasant and fast experience, regardless of whether there are 10 or 10 million other users. During peak times, such as 9 a.m. when a large number of users simultaneously login, a system can show signs of strain. A user may notice a longer than normal wait for pages to load and this gives the user an incentive to leave to find an alternative. And they may never come back.
Modern architectures can be described as either monolithic or microservice-based. If your monolithic system is showing signs of poor scale, there are plenty of options to consider before committing to a move to microservices.
But, fundamentally, the solution to scaling your monolith system depends on the nature of the issue.
This article presents a deep-dive into the scalng options that do not require a costly and disruptive move to microservices.
We first of all consider why your organisation's structure may be contributing to your system's lack of scale. We then address the technical detail of what may be limiting scale, considering improving data performance, before putting into place other ways of scaling a monolith without a move to microservices.
Organisational structure
One reason for your monolith's lack of scale may be the structure of your organisation.
Imagine a team of 20 engineers and a single codebase that supports nine features:
- Orders
- Payments
- Products
- Search
- Pricing
- Logistics
- Tax
- Promotions
- Analytics
Problems will emerge over time as those twenty engineers attempt to coordinate their activities across the nine major product features.
Changes in one area may adversely affect others, updates to code may conflict, release of the whole will take significant coordination, and testing cycles will grow.
At run-time, this single codebase (a monolith) may start to show signs it can no longer scale elegantly.
With a monolith, every instance contains every feature. If Search becomes busy, you must scale all nine features.
As your team grows beyond 20 people, the coordination required to maintain the monolith becomes more of a challenge, making applying any of the following more difficult than it needs to be.
One advantage of breaking up a monolith into separate services is that separate services can be maintained by separate teams, so team autonomy is increased. The use of microservices is partly a response to how companies are structured.
The costs involved in such a change are the time it takes teams to adjust while continuing to deliver features. A risk is that changes do not make collaboration easier - however, reading the whole article will help address this as their are technical approaches that deliver some microservice benefts without a full-scale move.
Technical limits to scale
In a monolithic system that defines the nine features and which supports hundreds or millions of simultaneous users, the system will always be running each feature, possibly with users waiting.
Users are more likely to be kept waiting as the machine the monolith is running on reaches the following limits:
| Limit | What Eventually Breaks |
|---|---|
| CPU | Computation capacity exhausted leading to queued tasks, introducing delay |
| Memory | Data working set no longer fits into memory, causing data access delays |
| Storage input/output | Disk read/write throughput is maxed out, resulting in storage delay |
| Network bandwidth | Data transfer is saturated causing network data delay |
| Database writes | Volume of data writes show that single-writer constraints emerge, causing write delays |
| Database contention | Locking and transaction conflicts cause data update delays |
| Cache capacity | Due to data volume, often used data no longer fits in cache, causing data access delays |
| Coordination | Replicated data consistency costs increase, causing delays |
| Latency | Physical distance between user and monolith imposes minimum wait times |
| Availability | Failure probability increases with complexity |
There is simply too much to be done and not enough CPU, memory, storage, network, database and cache to do it efficiently. As a result, delays start to dominate, queues lengthen and scaling stops.
However, automatically moving a monolith to a microservice-based solution could be a mistake.
What is first required is an analysis to understand what is not scaling.
If this is not done, the risk is that one poorly scaling monolith is replaced by nine poorly-scaling services.
Understanding what is not scaling
To understand what is not scaling, attention must be paid to the meta-data available from operating systems and tooling that shows how resources are currently being consumed.
Linux \(ps\), Amazon Web Services, Google Cloud Platform, and Microsoft's Azure Monitor all provide data on resource usage. Values such as CPU utilisation, memory use, and storage load are relevant. Database vendors make available tools to analyse database traffic volumes, and data access and contention patterns.
Typically, scaling issues cannot be determined by only looking at the code. The issue is the aggregate behaviour that code causes over time as available resources are consumed. The code is working as requested. It is the delay loop created by the increasing scarcity of resources that contributes to scaling issues.
One key area of application performance is how it handles its data.
We take a deep dive into that below before considering other changes that can be put into place that do not involve a move to microservices.
Data performance scaling
When a single user logs into a system, the following may occur:
- The system receives login request from a web browser
- Validate credentials. Is their username email address in the correct format?
- Lookup user account via a database access
- Verify credentials. Is the submitted password correct?
- Perform any multi-factor authentication (MFA) that is required
- Check account status. Is it ongoing or has it been suspended?
- Retrieve roles and permissions. Get access to what this user can legally do
- Create session or token. Track that they are logged in via the browser
- Execute security and risk checks. Is the web browser on the approved list?
- Record audit log entry. Record when and from where the user logged in
- Load user profile. Access registered information provided by the user
- Initialize application context. Define the current work context for the user
- Load startup and personal data. Access the webpage last seen by the user.
- Redirect to last page seen
Points 3, 5, 7, 11 and 13 are likely to require a database read.
Any update to credentials or the user's profile is likely to require a database write.
Logging in 2,000 users
To login a single user requires five database reads. To login 2,000 users will require a total of 10,000 reads, some of which will overlap as a read at the end of the login sequence, to load startup and personal data (point 13), will occur at the same time when a new user initiates a fresh login sequence, and a read is started at point 3, the lookup of the user account.
For a well-resourced database, that has well-sized working memory, good CPU provision and physical RAM, logging in 2,000 users should not present a problem.
However, issues even at this level can occur when traffic types start to become mixed.
Mixing traffic types
All of the 2,000 users above cause 10,000 data reads. If 1,000 of the logged in users subsequently update their profile before logging out, the database will see 10,000 reads plus multiple thousand writes.
In general, a database write is more time consuming than a read because writes must preserve data durability, consistency and recoverability.
The database will experience a mixed stream of reads and writes that are intermingled with one another.
This will add additional load to the database, and any write before a read may lead to the read taking longer than expected.
If a write takes a while - because the amount of data written grows over time as a user's profile stores more data to support additional features - a subsequent read will also take longer as it waits for the database to complete the write.
Over time, the performance of a database that worked well for 2,000 logins, will degrade as its workload increases and the traffic types become ever more mixed. As the number of users increases, delays will become worse because there is more work to do, and because the amount of delay-inducing intermingling of work increases.
Centralisation of the database
In any architecture, if there is a single database that all components rely on for persistence support, that database - over time - may cause the entire product to slow down.
This is because most, if not all, user activity visits the same database. Any long-lived database operation (such as setting up a new user) will delay all user operations that come immediately after it as they are likely to have to wait.
As a diagram, the database is at the centre with all components surrounding it, their operations travelling via the single database at some point.
What can be done
Once the database, the machine that it is running on, and the network environment have been inspected, and run-time load data has been gathered to inform which remediation will likely work, the options are:
- Optimise queries and code
- Add caching
- Tune the database
- Vertical scale
- Separate workloads
- Introduce asynchronous processing
- Add replicas
- Partition services and data
- Shard
- Redesign the architecture
The above fall into three distinct types of work - optimise, rearchitect, redesign - that have increasing amounts of change and disruption.
Optimise
Optimising the database is the easiest and least disruptive.
The database can be made more efficient by analysing query run-times to see if the addition of table indexes would reduce query times.
Caching in the application can improve performance and reduce load on the database. If data is cached in the application, a call to the database is not required.
However, adding caching to an application requires a firm understanding of application behaviour. The risk is code will read out-of-date data from the cache, introducing subtle programming bugs.
Tuning a database involves attention to how the database is used. For example, databases define an internal buffer pool - a form of in-memory cache inside the database.
If a User table is 20GB and the databases buffer pool is 4GB, many User records will not be in the database's main memory. In this case, the database will have to access data from disk.
Disk access can be approximately 100 times slower than reading data from RAM. Therefore, holding more User records in RAM, in the buffer pool, is likely to improve performance.
The exact nature of the improvement will depend on how often the User table needs to be accessed and whether having it all in a buffer pool represents good memory usage relative to other database tables and their usage patterns.
In short, tuning a database requires trial and error.
Rearchitect
Rearchitecting the database requires more work and would typically be undertaken to improve data performance once the techniques above are showing signs of exhaustion.
Vertical scaling
Vertical scaling involves improving the machine's resources that hosts the database. By increasing the machine's RAM, the number of CPU cores, and the speed of any hard-disk, such as a move from a SATA SDD to an NVMe SSD, the database will more likely be operating from memory. This will enable the database to return results more quickly, without having to spend time retriving data too often from disk.
If this is done, the database's caches and buffers should be adjusted to take advantage of the more capable machine. Again, this will require trial and error.
Separating workloads
Separating workloads can be an effective way to improve performance. If a database demonstrates 95% reads, and 5% writes, then the read traffic consumes CPU, memory, and disk input and output, slowing down write operations, such as order creation.
One solution is to define a primary database and a number of read replicas. All database operations that alter the database contents (insert, update and delete) go via the primary. A database replication operation is then performed into a number of read replicas that are separate databases running on different host machines that handle all read-only database operations (e.g., SQL SELECTS).
However, be warned: this approach introduces eventual consistency because replication is never instantaneous when the primary is updated. Each read replica will always be running slightly behind what is stored in the primary, and this gap may get larger over time as there is more data to replicate.
However, for certain types of solution such as:
- Catalog browsing
- Product searches
- News feeds
- Analytics dashboards
working with slightly out-of-date data can be tolerated.
Asynchronous processing
In an ecommerce system, when the user clicks Place Order, the following might occur:
- Save Order
- Take Payment
- Update Inventory
- Generate Invoice PDF
- Send Email
- Notify Warehouse
- Update Analytics
- Update the interface for the user
If each stage is completed before the next is started (all stages are synchronous), and assuming generating the invoice PDF takes 2 seconds, and generating and sending the email takes another second, the user will experience at least three seconds of delay before their screen is updated after clicking Place Order.
At a busy time of year, a user will see a noticeable slow-down as more users place orders and the delay may reach 5 seconds or more.
In moving to an asynchronous approach, only the critical work is performed immediately, before the user's screen is updated, possibly within 100 milliseconds:
- Save Order
- Take Payment
- Publish OrderPlaced event
Meanwhile, the other steps will occur in the background, having been started by the OrderPlaced event being generated.
In this way, the bulk of the time-consuming work (PDF and email sending) is not experienced by the user clicking the Place Order button. The work is done asynchronously (at a later time) with respect to saving the order and taking payment.
Partition services and data
Partitioning services and data means sub-dividing a large system and database into smaller, independent parts so that each part can be developed, deployed, scaled, and stored separately.
For example, a single database might store tables for Customer, Orders, Inventory and Payments. One that is partitioned would consist of multiple databases, where each one is dedicated to a single table, and its operations.
Shard
Imagine a Customer database table has reached 1 billion rows. Any operation on that table is likely to be inefficient due to its sheer size.
An alternative is to shard the data, placing 100 million customer records in each of ten separate databases and tables.
Application code would then interact with the appropriate table, typically calculating which database to use based on a calculation of a customer ID, for example:
\(database\_id = customer\_id\ \%\ 10\)
And database_id will be in the inclusive range 0 to 9.
Redesign
Redesigning is the most costly and disruptive.
All of the solutions above require increasing knowledge about the aggregate behaviour of the application with respect to how its persistent data is handled.
As an application scales, this global behaviour may change such that the engineering tradeoffs that once worked are now showing signs of strain.
The techniques above can help - but if they have been applied and data performance is still showing signs of poor performance, a redesign may be necessary.
Such an update would typically require designing a data management layer that supported the observed behaviour of the application. For example, if 95% of data access is read and 5% is write, the redesign would reflect that, likely focusing on caching.
Other changes to address scaling issues
The changes above are focussed on improving data performance. Others are possible.
Recall we have a single codebase and run-time system that implements these nine major features:
- Orders
- Payments
- Products
- Search
- Pricing
- Logistics
- Tax
- Promotions
- Analytics
A monolith that is struggling to scale can benefit from these changes that do not require a move to microservices.
- Scaled monolith
- Modular monolith
- Database decomposition
- Event-driven monolith
- Extract specific services
- Microservices
Scaled monolith
To scale the monolith as is, it might be possible to create multiple instances of it. This is called horizontal scaling as we do not improve the machine the monolith is running on (vertical scaling) but we create multiple monoliths, each on running on a separate machine. But they all use a single database.
When a user operation arrives from a webpage that needs support from one of the nine major features, a load balancer is used to route the operation to one of the monoliths. This monolith then works just as the single one did.
This approach requires that the monoliths are stateless. This is crucial. If the incoming call uses a specific monolith that retains any state (any data), a subsequent incoming call would have to use that same monolith. A load balancer should not typically be aware of this need.
This approach is one reason why a single database is used. A single database is the record of truth, but each monolith needs to be stateless, reading and writing all data on behalf of the user to the single database.
Modular monolith
The monolith remains deployed as one application, but internally, it is divided into clear modules, typically along the lines of its major features.
There are well-defined interfaces between modules, limited cross-module dependencies, and separate team ownership of each module.
This will give easier team development scaling and realises some of the separation benefits that microservices can deliver, without the expensive move to such an approach.
This is unlikely to improve scale at run-time so more customers can simultaneously use a single monolith, but it improves the company's ability to manage and maintain the codebase while addressing run-time scale through the other initiatives described in this article.
Database decomposition
As discussed above in data performance, how the database is used based on the monolith's aggregate data behaviour is key to scaling a single application. Read replicas, sharding and partitioning are all relevant techniques.
Event-driven monolith
The monolith remains but the modules are further decoupled by exchanging events internally: rather than the Order module being directly invoked, an event with the order data in its payload is published that the Order module receives as it is listening for OrderEvents.
This reduces dependencies between modules, improving team autonomy per module, and aiding future extensibility.
Extract specific services
Extracting specific hotspots to run on a separate machine would help the monolith scale as more compute is being used to deliver the nine major features.
This is a first step towards microservices; however, not every feature would be turned into a service. Only those that are showing signs of struggle, possibly starting with search or analytics, that tend to be memory and CPU intensive.
Microservices
Only once all other options have been both considered and shown to be exhausted should be move to microservices be analysed.
The reason for this is that moving to microservices is highly disruptive and will require major planning. New hardware will have to be made available for each service, requiring the behaviour of the application to be well enough understood to ensure and efficient and applicable new hardware estate to be put into place.
How to transition from the monolith to microservices will have to be analysed and agreed, to ensure disruption is kept to a minimum.
In short, moving to microservices from a monolith is non-trivial and should not be undertaken lightly.
Conclusions
It is not automatic that a move from a monolithic design to microservices will improve system scale.
The overall behaviour of the monolithic application must be understood so that everyone involved is aware of what remediations are most appropriate.
A plan must be drawn up so that the goal is agreed and a shared path to it is understood by all involved. Such a path must also consider how to perform any change with minimum disruption to the monolith that is currently being used.
As we have seen above, paying attention to how the application uses data in aggregate can inform any scaling decision. An application that is 95% reads and 5% writes will benefit from attention to caching and read replicas before any microservice approach will help.
Read next Build or buy: a POB-CRA analysis
When deciding whether to build or buy a capability, cost and value must be considered. This is why the default decision should usually be buy unless building attracts significant value.
Your Comments
Please enter a nickname. You do not need to register. A nickname is only required the first time you comment.