The Wayback Machine - https://web.archive.org/web/20240917160049/https://www.geeksforgeeks.org/system-scaling-optimization-trade-offs/
Open In App

System Scaling – Optimization Trade offs

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Network Load Balancer (NLB) can handle traffic spikes, handle millions of requests per second however, it doesn’t support logging, so use cloudwatch to keep all logs in centralized place. Things to ponder before horizontal scaling. 

  • Ensure thread safe code – for horizontal scaling
  • Connection pooling, no direct connection upon instantiation
  • Management of data

Various horizontal scaling options : 

  • Heroku – configure number of dynos, increase power of individual dynos.
  • HirePower – for fine grained control, power and flexibility.
  • Azure
  • Google cloud
  • AWS
  • And many more vendors

Web server concurrency setup : 

  • Puma (For Ruby/Rack)- number of workers via web_concurrency flag, number of threads.
  • NginX – for high performance, stability, rich feature set, simple configuration, low resource consumption.
  • Apache – for java web applications

Vertical Scaling : 
Scale-up a system is called vertical scaling. 
Pros – 

  • Increase the power of each server to achieve desired performance.

Cons –  

  • The expensive, practical limit to how much we can vertically scale on an instance.
  • Scaling configurations depends on balanced cost, performance, resource usage to acceptable levels.

Use cache for transactional queries : 
Before caching we need to get the answer to question Is it OK to provide eventual consistency or strong consistency of data is required. For eventual consistency – NoSQL DB. For strong consistency / critical transactions – RDBMS – example payment transactions. 

Cache – Redis /Memcached : 
Redis – 
Auto replica, snapshot. 

Memcached – 
Multithreaded architecture. 
Type of cache : 

  • Global cache – 
    Simple, effective only up to a certain scale. 
     
  • Distributed cache – 
    API Gateway, Cloudfront – Lambda @ edge.

How to choose correct cache :  

  • Is the system write heavy and reads less frequently – (time based logs).
  • Is the data written once and read many times – ( User profile).
  • Is data returned always unique – (Search engine).

Cache aside : 

  • General purpose and best for read heavy workloads. (Memcached, Redis).
  • System are resilient to cache failures.
  • Data model in cache can be different than data model in database.(Result of multiple query response stored against – request id).
  • Common write strategy is – write to DB directly. TTL is used to serve stale data until TTL expires. If data freshness required – we can either invalidate cache entry or use write through cache method.
  • Load data lazily

Read Through Cache : 

  • Sits in line with DB.
  • In case of cache miss, cache is populated by DB hit.
  • Load data lazily.
  • Best for read heavy workloads -( News story)

Cons – 
First time its always a cache miss. Warming/pre-heating cache by queries manually. Data might become inconsistent, strategy for write will be the solution. 
Difference b/w Cache aside and read through cache : 
Cache aside –  

  • Application is responsible for data fetch from db and populate cache.
  • Data model can be different.

    Read through cache –

  • Logic is supported by library or stand-alone cache provider.
  • Data model will be same as of DB.

Write through cache – Cache write policy : 
Write around – 
Data are written to DB first when first read request comes, then data written to cache. 

  • It Can combine with read-through and with cache aside as well.
  • Good performance when data written once and read less frequently or never. (Real time logs/ chat room messages)

Write through – 
Data first are written to cache, then to DB. Can be combined with read-through. 

  • Extra write latency.
  • Guarantee consistency – no need to use any cache invalidation technique (DAX – Dynamo DB accelerator).
  • DAX can be used as write around cache. Applications can write to Dynamodb and read it through DAX. Possible issue – Negative cache entry, when DAX cant find requested item in underlying dynamodb table, DAX returns an empty result to user, instead of error.

Write back – 
Write data to cache, cache acknowledges immediately, after some delay it writes the data back to database. 

  • Called write behind as well.
  • Improves performance and good for write heavy workloads.
  • When combined with read-through, works good for mixed workload where most recently updated and assessed data is always available in cache.
  • Resilient to DB failures, can tolerate some DB downtime.
  • If batching or coalescing is supported, it can reduce overall writes to the DB, decrease the load and reduce cost for DB which charge for number of requests (DynamoDB).
  • DAX is write through (so Dynamo db cost wont be reduced for write heavy applications)

Note – 
If we use Redis for both caches aside and write back to better absorb spikes during peak load – in case of cache failure, data may be permanently lost. 
Cache eviction policy : 

  • LRU – Least recently used. Mostly used every where, in search engines as well.
  • Random replacement, FIFO – not frequently used.

N+1 Queries : 
Queries that require other queries to get complete picture of data. Root cause-  architectural issue or inattention to data retrieval considerations. Solution – eager loading the related records, records fetched in initial query. 
Inefficient code 

  • Avoid doing resource intensive things.
  • Moving to faster libraries.
  • Streaming – Use streaming to upload excel or other data intensive load tasks to minimize the memory and CPU footprint.
  • Moving collection traversal to database, e.g. 
    • Calculate sum of records in RDBMS instead of doing it in code. Use single aggregate database query.
    • Avoid eager loading of entire document, when only few fields will be accessed.

Backgrounding : 
Identify and separate tasks that can be delayed for few seconds or can be handled by another system. Use queues, separate out jobs based on type – transactional, user-triggered bulk jobs, critical jobs in separate queue – SQS. 

Use read replicas for performing these non- critical tasks like – 

  • Sending Email
  • Generate reports
  • Upload configuration / documents

Asset modification : 
Ensure that all the assets were gzipped or optimized before loading them. This results in reducing load time significantly. Push compressed and zipped front end assets – webpacks to S3, using deployment script. S3 will serve to gzip by setting the content encoding and the content type. Automate deployment as much as you can – use Cloudformation by AWS, Terraform. 

Memory Leaks : 
Avoid memory leaks, they can hit swap memory (Exchanging data between real memory and virtual memory(virtual memory address, always enabled in modern CPU) is “swapping”. the swap on disk is swap space). Avoid restart server band-aid solution, try to figure out the actual cause. 

Co-location : 
Ensure all required microservices were located in one region to get low latency and speed up all queries and operations. 

References : 
Wikipedia 
Redis vs Memcached  
For more  System Design concepts



Similar Reads

Manual Scaling vs. Auto-Scaling in System Design
In system design, scaling is key to handling variable loads efficiently. Manual scaling allows engineers to adjust resources based on expected demand, offering control but requiring oversight. Auto-scaling automates this process, dynamically adapting to real-time demand, improving resource efficiency and responsiveness. This article explores both m
3 min read
Overview of Scaling: Vertical And Horizontal Scaling
Given architecture is an example of a client-server based system. In this, there is a client who sends requests to the server and then the client receives a response from the server accordingly but when the number of users/clients increases, the load on the server increases enormously which makes it difficult for the server to perform efficiently a
4 min read
Horizontal and Vertical Scaling | System Design
In today's fast-paced digital world, creating systems that can handle increasing demands is key to success. Picture this: you're hosting a big party, and more and more guests keep arriving. You need to make sure your setup can handle the crowd without slowing down or crashing. In this article, we'll break down the concepts of horizontal and vertica
8 min read
Reactive vs. Proactive Scaling in System Design
In system design, Reactive scaling adjusts resources dynamically in response to changes in demand, while proactive scaling predicts workload fluctuations. This article explores the differences between these approaches, highlighting their respective strengths and weaknesses. By understanding the concepts of reactive and proactive scaling, system arc
3 min read
Elastic Scaling in System Design
Elastic scaling in system design is a crucial approach that allows organizations to dynamically adjust computing resources based on fluctuating demand. By seamlessly scaling up or down, systems can maintain optimal performance levels, ensure high availability, and optimize cost efficiency. Important Topics for Elastic Scaling in System Design What
11 min read
Performance Optimization Techniques for System Design
The ability to design systems that are not only functional but also optimized for performance and scalability is paramount. As systems grow in complexity, the need for effective optimization techniques becomes increasingly critical. This article explores various strategies and best practices for optimizing system design, ensuring systems perform ef
9 min read
Bias-Variance Trade Off - Machine Learning
It is important to understand prediction errors (bias and variance) when it comes to accuracy in any machine-learning algorithm. There is a tradeoff between a model’s ability to minimize bias and variance which is referred to as the best solution for selecting a value of Regularization constant. A proper understanding of these errors would help to
3 min read
ML | Feature Scaling - Part 1
Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing. Working: Given a data-set with features- Age, Salary, BHK Apartment with the data size of 5000 people, each having these independent data features. Each data point is labeled as: Class1- YES (m
3 min read
What is TCP Window Scaling?
In the TCP header, the window size field is of size 16 bits. Using this field TCP users (client or server) can advertise a maximum of 216 = 65536 bytes or 64 KiB as its buffer size to its other end-user. But modern endpoint devices (e.g., phones, tabs, PCs, etc) have much more memory available in their buffers. This 16-bit field was enough during t
5 min read
Computer Graphics - 3D Scaling Transformation
Prerequisite: Computer Graphics – 3D Translation Transformation Scaling Transformation : It is performed to resize the 3D-object that is the dimension of the object can be scaled(alter) in any of the x, y, z direction through Sx, Sy, Sz scaling factors. Matrix representation of Scaling transformation Condition : [Tex]\large S[x, y, z]= \left [ \beg
3 min read
What is Auto Scaling?
In System Design, Auto Scaling is an important mechanism for optimizing cloud infrastructure. Dynamic and responsive, Auto Scaling coordinates computational resources to meet fluctuating demand seamlessly. This article dives deep into the essence of Auto Scaling, showing its transformative role in enhancing reliability, performance, and cost-effect
14 min read
Scaling Memcached
Scaling Memcached explains how to handle increased demand on the Memcached system, a tool used to speed up web applications by storing data in memory. It covers strategies to ensure Memcached can efficiently manage more users and data. Key points include distributing the load across multiple servers, using consistent hashing to evenly spread data,
10 min read
Optimization techniques for Gradient Descent
Gradient Descent is a widely used optimization algorithm for machine learning models. However, there are several optimization techniques that can be used to improve the performance of Gradient Descent. Here are some of the most popular optimization techniques for Gradient Descent: Learning Rate Scheduling: The learning rate determines the step size
4 min read
Nature-Inspired Optimization Algorithms
Optimization algorithms are the highly efficient algorithms which focus on finding solutions to highly complex optimization problems like travelling salesman problems, scheduling problems, profit maximization etc. Nature-inspired algorithms are a set of novel problem-solving methodologies and approaches derived from natural processes. Some of the p
2 min read
Interprocedural Optimization using Inline Substitution
The different scopes of code optimization include Local Optimization, Regional Optimization, Global Optimization, and Interprocedural Optimization. Local Optimization refers to optimization in a Basic Block. Regional Optimization refers to optimization in an Extended Basic Block. Global Optimization refers to the optimization of a whole procedure.
4 min read
SQL software and query optimization tools
Introduction : SQL stands for Structured Query Language. SQL is a non-procedural language, so the Optimizer is free to merge, reorganize and process in any order. It is based on statistics collected about accessed data. It is very useful to perform query and to store and manage data in RDBMS. SQL is a language to operate databases. It includes data
4 min read
Common Subexpression Elimination - Code optimization Technique in Compiler Design
Code Optimization Technique is an approach to enhance the performance of the code by either eliminating or rearranging the code lines. Code Optimization techniques are as follows: Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reductionCommon Sub-expression Elimination:The expression or sub-ex
2 min read
Basic Cache Optimization Techniques
Generally, in any device, memories that are large(in terms of capacity), fast and affordable are preferred. But all three qualities can't be achieved at the same time. The cost of the memory depends on its speed and capacity. With the Hierarchical Memory System, all three can be achieved simultaneously. The cache is a part of the hierarchy present
5 min read
Optimization of Basic Blocks
Optimization is applied to the basic blocks after the intermediate code generation phase of the compiler. Optimization is the process of transforming a program that improves the code by consuming fewer resources and delivering high speed. In optimization, high-level codes are replaced by their equivalent efficient low-level codes. Optimization of b
5 min read
Trie memory optimization using hash map
We introduced and discussed an implementation in below post. Trie | (Insert and Search) - GeeksforGeeks The implementation used in above post uses an array of alphabet size with every node. It can be made memory efficient. One way to implementing Trie is linked set of nodes, where each node contains an array of child pointers, one for each symbol i
7 min read
Design Optimization in OOAD
Object-Oriented Analysis and Design (OOAD) is a crucial phase in software development where the system requirements are analyzed and translated into a well-designed object-oriented model. Design optimization in OOAD focuses on improving the quality, performance, maintainability, and scalability of the system design. Important Topics for Design Opti
6 min read
Edge AI for Network Traffic Optimization
The edge AI for the network traffic algorithm refers to the various applications of the artificial intelligence and its algorithms and techniques at the edge of a network which are used in order to optimise and manage the network and its traffic more efficiently, So in this article we will understand what is edge AI, applications, advantages and di
9 min read
Optimization for Data Science
From a mathematical foundation viewpoint, it can be said that the three pillars for data science that we need to understand quite well are Linear Algebra , Statistics and the third pillar is Optimization which is used pretty much in all data science algorithms. And to understand the optimization concepts one needs a good fundamental understanding o
5 min read
Java System.nanoTime() vs System.currentTimeMillis
Java provides two methods to time operations, System.nanoTime() and System.currentTimeMillis(). But which one should be used in which condition? And which is more efficient? From the first look it might seem that nanoTime() should be used because it gives more precise value of time (in nano seconds, compared to milli seconds that the other method r
3 min read
Difference between Management Information System (MIS) and Decision Support System (DSS)
Decision Support System (DSS) is an interactive, flexible computer based information system or sub-system intended to help decision makers use communication technologies, data, documents to identify and solve problems, complete decision process tasks and make decision. Management Information System (MIS) consists of following three pillars: Managem
2 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
How does the process of developing a system differ from designing a system?
System Development vs. System DesignSystem DevelopmentSystem DesignHow Does The Process Of Developing A System Differ From Designing A System?ConclusionSystem DevelopmentSystem development is a structured process of designing, creating, and implementing software or hardware solutions to address specific needs or problems within an organization. It
7 min read
Design a system that counts the number of clicks on YouTube videos | System Design
Designing a Click Tracking System for YouTube Videos involves architecting a comprehensive and efficient solution to monitor and analyze user interactions with videos on the YouTube platform. Important Topics for Counting the number of Clicks on Youtube Videos System DesignRequirementsCapacity EstimationLow-Level Design (LLD)Database Design-High-Le
15+ min read
Difference between System Design and System Architecture
When it comes to software development and engineering there can be some confusion, between the two terms "System Design" and "System Architecture." Although they are related they actually refer to stages and responsibilities in creating scalable and efficient systems. It is important to grasp the differences, between System Design and System Archit
3 min read
Distributed Messaging System | System Design
In our fast-paced world, how we share information matters more than ever. Old-school messaging setups sometimes struggle to keep up with today's tech demands. That's where distributed messaging systems step in. They're like a breath of fresh air, changing the game and making sure our messages get where they need to go, no matter what. Important Top
8 min read
Practice Tags :