Skip to main contentSkip to main content
~/profileLIVE
Asad Saeed
Asad SaeedOpen to WorkSenior Software Engineer | Full Stack Developer
01

Identity

Residence
Lahore, Punjab
Nationality
Pakistani
City
Lahore
Age
26
02

Languages

  • English96%
  • Urdu100%
03

Expertise

React.js95%
Next.js95%
JavaScript / TypeScript95%
HTML5, CSS395%
Tailwind, Bootstrap, Shadcn UI95%
Material UI, SCSS, Styled Components90%
Redux Toolkit, React Query, Zustand92%
REST & GraphQL APIs92%
Git, GitHub, Bitbucket98%
Node.js, Express.js, NestJS85%
MongoDB, PostgreSQL, Prisma80%
WebSockets, Real-Time Systems82%
AI & Automation (n8n, OpenAI)78%
04

Stack

4949 technologies
ReactJSNextJSJavaScriptTypeScriptReact NativeNestJSNode.jsExpress.jsMongoDBPostgreSQLMySQLPrisma ORMFirebaseREST APIGraphQL APIApollo ClientWebSockets / Socket.ioReduxRedux ToolkitReact QueryZustandTailwind CSSShadcn UIMaterial UIBootstrapSCSSCSSModule.cssStyled ComponentsFramer MotionStripe Payment Integrationn8nOpenAI APIAWS LambdaDockerVercelNetlifyGitHub Actions (CI/CD)JestGitGitHubBitbucketPostmanSwaggerJira SoftwareStrapiSanityFigmaAdobe XD
05

Contact

Email
asadsaeed.dev@gmail.com
Phone
+92 3017631644·+92 478730644
Download Resume
HomeSkillsBackgroundPortfolioContact
Chat with Asad
All Posts
How AWS Load Balancers Work: Distributing Traffic Across Multiple EC2 Servers

How AWS Load Balancers Work: Distributing Traffic Across Multiple EC2 Servers

AWSAWS LOAD BALANCERCLOUD COMPUTINGDEVOPSASAD SAEED
November 11, 202616 min readBy Asad Saeed

Learn how AWS Load Balancers distribute traffic across multiple EC2 instances, perform health checks, handle server failures, and work with Auto Scaling for highly available applications.

Introduction

Imagine you've deployed a MERN application on a single EC2 instance.

Initially, everything works fine. Users can log in, browse products, submit forms, and interact with your APIs.

But as your application grows, traffic increases. Hundreds or thousands of users start sending requests simultaneously.

Your single server now has to handle API requests, authentication, database operations, file uploads, background processing, and multiple concurrent user sessions.

Eventually, CPU usage increases, memory becomes constrained, and response times become slower. If the server crashes, your entire application may become unavailable.

One solution is to run multiple application servers.

However, this introduces another problem:

How do users know which server to connect to?

Should every user connect to Server 1? How do we distribute traffic? What happens if Server 2 crashes? How can we add more servers without changing the frontend or API URL?

This is where AWS Elastic Load Balancing (ELB) comes in.

AWS Load Balancers provide a single entry point for incoming traffic and distribute requests across multiple registered targets, such as EC2 instances, containers, and IP addresses.

Let's understand how this works behind the scenes.

1. What Is a Load Balancer?

A load balancer is a component that receives incoming network traffic and distributes it across multiple backend servers.

Instead of allowing clients to communicate directly with individual application servers, clients communicate with the load balancer.

The load balancer then forwards traffic to an appropriate healthy backend.

              Users
                |
                v
          Application URL
                |
                v
         AWS Load Balancer
                |
       +--------+--------+
       |        |        |
       v        v        v
    Server 1 Server 2 Server 3
       |        |        |
       +--------+--------+
                |
                v
             Database

The client doesn't need to know how many backend servers exist.

It communicates with one endpoint, while the load balancer manages traffic distribution.

Why Do Applications Need Load Balancing?

High availability: If one server becomes unhealthy, the load balancer can stop routing new requests to it and use healthy targets instead.

Scalability: You can add more backend instances as application traffic increases.

Better performance: Traffic can be distributed across multiple servers instead of overwhelming one instance.

Fault isolation: A failure in one application server doesn't necessarily make the entire application unavailable.

Centralized traffic management: You can manage routing, TLS termination, health checks, and other traffic-related behavior at a central entry point.

2. What Is AWS Elastic Load Balancing?

AWS provides a managed service called Elastic Load Balancing (ELB).

Instead of installing and maintaining your own load-balancing software, AWS operates the load-balancing infrastructure.

You configure the load balancer, listeners, routing rules, and target groups. AWS manages the underlying service infrastructure.

For example, you might deploy three EC2 instances:

  • EC2 Instance 1 — Application Server

  • EC2 Instance 2 — Application Server

  • EC2 Instance 3 — Application Server

You register these instances in a target group and configure an AWS Load Balancer to forward incoming traffic to that group.

The load balancer continuously evaluates target health and routes new requests or connections according to its configured behavior.

3. Types of AWS Load Balancers

AWS provides different load balancer types for different networking requirements.

3.1 Application Load Balancer (ALB)

Layer 7 — Application Layer

The Application Load Balancer operates at the application layer.

It understands HTTP and HTTPS traffic and can make routing decisions using information such as:

  • URL paths

  • Hostnames

  • HTTP headers

  • Query strings

  • HTTP methods

  • Source IP conditions

For example:

api.example.com/users
        |
        v
Application Load Balancer
        |
        v
User Service

api.example.com/orders
        |
        v
Application Load Balancer
        |
        v
Order Service

You can configure routing rules such as:

/users/*  → User Service
/orders/* → Order Service
/admin/*  → Admin Service

You can also route traffic using different hostnames:

api.example.com     → Backend API
admin.example.com   → Admin Application

When should you use ALB?

  • React or Next.js applications with HTTP-based backend services.

  • Node.js, Express, and NestJS APIs.

  • Microservices architecture.

  • Containerized applications running on ECS or EKS.

  • Applications requiring path-based or host-based routing.

3.2 Network Load Balancer (NLB)

Layer 4 — Transport Layer

The Network Load Balancer operates at the transport layer.

It handles TCP, UDP, and TLS traffic and is designed for high-performance, low-latency network workloads.

Unlike an ALB, it doesn't inspect HTTP paths such as /users or /orders to make routing decisions.

Client
  |
  v
Network Load Balancer
  |
  +------> TCP Server 1
  |
  +------> TCP Server 2
  |
  +------> TCP Server 3

When should you use NLB?

  • High-throughput TCP or UDP applications.

  • Applications requiring static IP addresses.

  • Low-latency network services.

  • Workloads that need Layer 4 traffic handling.

  • Services that don't need HTTP-aware routing rules.

3.3 Gateway Load Balancer (GWLB)

Layer 3 — Network Layer

Gateway Load Balancer is designed to deploy, scale, and manage virtual network appliances.

These appliances can include:

  • Firewalls

  • Intrusion detection systems

  • Intrusion prevention systems

  • Deep packet inspection systems

It helps distribute network traffic across virtual appliances while integrating with AWS networking.

3.4 Classic Load Balancer (CLB)

Classic Load Balancer is an older generation of Elastic Load Balancing.

It supports basic Layer 4 and Layer 7 load balancing.

For most new application architectures, AWS recommends choosing an Application Load Balancer or Network Load Balancer based on the workload.

4. Understanding the Main Components of an ALB

Before understanding traffic distribution, let's look at the components involved.

4.1 Load Balancer

The load balancer provides the entry point for incoming traffic.

For example:

my-app-alb-123456.ap-south-1.elb.amazonaws.com

You can point your application domain to the load balancer using DNS.

api.example.com → AWS Load Balancer

The load balancer can be internet-facing or internal.

An internet-facing load balancer receives traffic from clients outside your VPC, while an internal load balancer is intended for private application traffic.

4.2 Listener

A listener checks for incoming connection requests on a configured protocol and port.

For example:

HTTP  → Port 80
HTTPS → Port 443

A listener also defines what happens when traffic arrives.

HTTPS : 443
     |
     v
Forward traffic to API Target Group

You can configure listener rules to forward, redirect, or return fixed responses.

4.3 Target Group

A target group is a collection of registered backend targets.

For example:

Target Group: production-api

EC2 Instance 1
EC2 Instance 2
EC2 Instance 3

A target group defines how the load balancer communicates with its registered targets.

It also contains health-check configuration.

Targets can include EC2 instances, IP addresses, Lambda functions (for supported ALB configurations), and other supported target types.

4.4 Health Checks

A load balancer needs to know whether a backend server is healthy before routing new traffic to it.

For an HTTP application, you might configure:

Health Check Path: /health
Protocol: HTTP
Port: Traffic port
Success Code: 200

Your Node.js API might expose this endpoint:

app.get("/health", (req, res) => {
  res.status(200).json({
    status: "healthy",
    timestamp: new Date().toISOString(),
  });
});

The load balancer periodically sends health-check requests to registered targets.

If a target fails enough consecutive checks, it becomes unhealthy.

The load balancer stops routing new requests to that unhealthy target, subject to the target group's health and routing configuration.

When the target passes the required recovery checks, it can become healthy again.

Important: A health endpoint should represent the actual readiness of your application. Returning HTTP 200 while essential dependencies are unavailable can make an unhealthy application appear healthy.

5. How AWS Load Balancer Distributes Incoming Traffic

Let's walk through the complete request lifecycle.

Suppose your application has three backend servers:

EC2-1
EC2-2
EC2-3

All three are registered in the same target group.

A user opens:

https://api.example.com/users

Here's what happens.

Step 1: DNS Resolution

The browser needs to resolve your domain.

Your DNS configuration points the domain to the AWS load balancer.

api.example.com
       |
       v
AWS Load Balancer DNS

The client connects to the load balancer rather than directly to an EC2 instance.

Step 2: The Load Balancer Receives Traffic

The load balancer accepts the incoming connection through its configured listener.

For example:

HTTPS : 443

For HTTPS traffic, the ALB can terminate TLS using a certificate configured through AWS Certificate Manager.

It can then forward traffic to the backend using the configured target group protocol and port.

Step 3: Listener Rules Are Evaluated

The listener checks the incoming request against its configured rules.

For example:

/users/*  → Users Target Group
/orders/* → Orders Target Group

If the request is:

GET /users

the listener forwards it to the Users Target Group.

Step 4: The Target Group Provides Eligible Targets

The target group contains registered backend servers.

Users Target Group

EC2-1 → Healthy
EC2-2 → Healthy
EC2-3 → Unhealthy

The load balancer considers target health when selecting destinations.

Step 5: Traffic Is Forwarded to a Backend

The ALB selects an eligible target according to its configured routing algorithm.

The default algorithm is round robin.

For example, with three healthy targets, requests may be distributed in this pattern:

Request 1 → EC2-1
Request 2 → EC2-2
Request 3 → EC2-3
Request 4 → EC2-1
Request 5 → EC2-2

This is an illustrative sequence, not a guarantee that every request will be distributed in a perfectly equal pattern.

Step 6: The Backend Processes the Request

The selected EC2 instance runs your application.

EC2-1
  |
  v
Node.js / Express API
  |
  v
Business Logic
  |
  v
MongoDB / PostgreSQL

The application processes the request and returns a response.

Step 7: The Response Returns to the Client

The response travels back through the load balancer to the client.

Client
  |
  v
Load Balancer
  |
  v
EC2 Instance
  |
  v
Load Balancer
  |
  v
Client

The client continues using the same public application endpoint. It doesn't need to know which backend instance handled the request.

6. What Happens When One Server Crashes?

This is one of the most important benefits of load balancing.

Imagine you have three application servers:

EC2-1 → Healthy
EC2-2 → Healthy
EC2-3 → Unhealthy

Suppose EC2-3 crashes because of:

  • Application errors

  • Memory exhaustion

  • High CPU usage

  • A failed deployment

  • An operating system problem

The load balancer's health checks detect that the target is no longer healthy.

After the configured failure threshold is reached, the target is marked unhealthy.

The load balancer stops sending new traffic to it and continues using the remaining healthy targets.

             Load Balancer
                   |
          +--------+--------+
          |        |        |
          v        v        v
        EC2-1    EC2-2    EC2-3
       Healthy  Healthy  Unhealthy
          |        |        X
          |        |        |
          +--------+        |
                   |
             Application
               Online

This helps your application remain available even when an individual server fails.

However, load balancing does not guarantee zero downtime. Existing connections, requests already in progress, shared dependencies, and insufficient remaining capacity can still affect users.

7. How Does AWS Decide Which Server Receives Traffic?

Load balancing isn't always a simple equal distribution.

AWS supports different routing strategies depending on the load balancer type.

For Application Load Balancers, supported routing algorithms include:

7.1 Round Robin

This is the default ALB routing algorithm.

The load balancer distributes requests across available targets in rotation.

Request 1 → Server A
Request 2 → Server B
Request 3 → Server C
Request 4 → Server A

It's useful when backend servers have relatively similar processing capacity and request workloads.

7.2 Least Outstanding Requests

With this algorithm, the ALB selects a target based on the number of requests that target is currently processing.

For example:

Server A → 10 outstanding requests
Server B → 3 outstanding requests
Server C → 6 outstanding requests

The load balancer can choose Server B because it has fewer outstanding requests.

This can be useful when requests have different processing times.

7.3 Weighted Random

Weighted random is another ALB routing algorithm.

It randomly selects targets while considering configured target weights. It also supports Automatic Target Weights, which can help identify and mitigate the impact of anomalous targets.

This can be useful in certain workloads where the default routing behavior isn't ideal.

Note: These algorithms are ALB-specific. NLB uses its own flow-based distribution behavior rather than ALB's HTTP request-routing algorithms.

8. How Does Load Balancing Work Across Multiple Availability Zones?

High availability requires more than running multiple servers.

If all your EC2 instances are deployed in one Availability Zone and that zone experiences an outage, your entire backend may become unavailable.

AWS allows load balancers to operate across multiple Availability Zones.

                 AWS ALB
                    |
          +---------+---------+
          |                   |
          v                   v
      Availability Zone A  Availability Zone B
          |                   |
       EC2-1                EC2-3
       EC2-2                EC2-4
          |                   |
          +---------+---------+
                    |
                 Database

This architecture distributes application servers across different Availability Zones.

If one zone becomes unavailable, the load balancer can route new traffic to healthy targets in the remaining enabled zones, provided sufficient healthy capacity remains.

What Is Cross-Zone Load Balancing?

Cross-zone load balancing allows a load balancer node to distribute traffic across targets in other enabled Availability Zones.

Without cross-zone load balancing, distribution can be restricted to targets in the same Availability Zone as the load balancer node.

The exact default behavior and configuration options differ by load balancer type.

For ALB, cross-zone load balancing is enabled at the load balancer level by default.

For NLB, it is configurable and has different default behavior.

9. How Does Auto Scaling Work With a Load Balancer?

A load balancer distributes traffic, but it doesn't automatically create additional EC2 instances by itself.

That's where EC2 Auto Scaling comes in.

Auto Scaling monitors configured metrics and scaling policies to determine when to add or remove instances.

Average CPU Usage > 70%
          |
          v
Auto Scaling Policy
          |
          v
Launch New EC2 Instance
          |
          v
Register Instance
in Target Group
          |
          v
Health Check
          |
          v
Healthy Instance
Receives Traffic

Suppose your application starts with two instances:

EC2-1
EC2-2

As traffic increases, CPU utilization reaches your configured scaling threshold.

Auto Scaling launches another instance:

EC2-1
EC2-2
EC2-3

When the new instance registers with the target group and passes its health checks, it can start receiving traffic.

When demand decreases, Auto Scaling can terminate instances according to its scaling policies and lifecycle behavior.

The important distinction:

  • Load Balancer distributes incoming traffic.

  • Auto Scaling adjusts the number of application instances.

  • Target Groups connect the load balancer with backend targets.

  • Health Checks help determine whether targets are ready to receive traffic.

Together, they create a scalable application architecture.

10. Sticky Sessions: What If a User Needs the Same Server?

Some applications maintain session information directly on individual backend servers.

Consider this example:

User Login → EC2-1
User Dashboard → EC2-2

If the session exists only in EC2-1's local memory, the second request might fail because EC2-2 doesn't know about that session.

AWS ALB supports sticky sessions, also called session affinity.

With stickiness enabled, the load balancer can use a cookie to route a user's subsequent requests to the same target for the configured duration.

User A → EC2-1
User A → EC2-1
User A → EC2-1

User B → EC2-2
User B → EC2-2

However, sticky sessions aren't a replacement for proper session architecture.

For scalable applications, consider storing shared session data in Redis or another centralized session store.

This allows multiple application instances to access the same session state.

11. Practical AWS Architecture for a MERN Application

Let's connect everything to a real-world MERN deployment.

Imagine you have:

  • React frontend

  • Node.js and Express backend

  • MongoDB database

  • Multiple EC2 instances

  • AWS Application Load Balancer

  • EC2 Auto Scaling Group

A possible architecture looks like this:

                 Users
                   |
                   v
             Route 53 DNS
                   |
                   v
            Application ALB
                   |
              HTTPS : 443
                   |
             Backend Target Group
                   |
          +--------+--------+
          |        |        |
          v        v        v
        EC2-1    EC2-2    EC2-3
          |        |        |
          +--------+--------+
                   |
              Node.js API
                   |
                   v
             MongoDB Database

For a production deployment, you could configure:

Frontend

  • Host the React frontend on Amazon S3.

  • Use CloudFront for content delivery.

  • Configure Route 53 for domain management.

Backend

  • Deploy Node.js APIs on EC2 instances.

  • Place instances in private subnets.

  • Use an internet-facing ALB in public subnets.

  • Register backend instances in a target group.

  • Configure health checks.

Scaling

  • Create an EC2 Auto Scaling Group.

  • Attach it to the target group.

  • Configure scaling policies based on CPU utilization or other metrics.

Security

  • Allow HTTPS traffic to the ALB.

  • Allow backend traffic only from the ALB's security group.

  • Restrict database access to the backend's security group.

  • Store credentials and secrets securely.

This architecture provides a foundation for scaling a MERN application without exposing individual backend instances directly to the internet.

12. Important Production Considerations

A load balancer improves application architecture, but it doesn't automatically solve every production problem.

12.1 Keep Application Servers Stateless

Avoid storing important user sessions or temporary shared application state only in local server memory.

When traffic moves between instances, another server should be able to process the request.

Use shared services such as Redis or a database when appropriate.

12.2 Configure Health Checks Carefully

A health check that is too aggressive can temporarily remove servers during short-lived issues.

A health check that is too relaxed can leave unhealthy instances receiving traffic for longer than necessary.

Configure the interval, timeout, healthy threshold, unhealthy threshold, and health endpoint based on your application's behavior.

12.3 Use Private Subnets for Backend Instances

For many production architectures, the ALB is public-facing while EC2 application instances are placed in private subnets.

This reduces direct exposure of backend instances.

12.4 Monitor Load Balancer Metrics

CloudWatch provides useful metrics for monitoring load balancer behavior.

Examples include:

  • RequestCount

  • TargetResponseTime

  • HTTPCode_ELB_5XX_Count

  • HTTPCode_Target_5XX_Count

  • HealthyHostCount

  • UnHealthyHostCount

These metrics help identify traffic spikes, unhealthy targets, slow responses, and application errors.

12.5 Understand Deregistration Delay

When an instance is removed from a target group, it may still have active requests.

Target group deregistration delay allows time for in-flight requests to complete before the target is fully deregistered.

This is particularly important during deployments and Auto Scaling scale-in events.

12.6 Remember That the Database Can Become the Bottleneck

Adding more backend servers increases your application's ability to process requests, but it can also increase database connections and query volume.

For example:

3 Backend Servers
       |
       v
   Database

If each server creates too many database connections, the database may become overloaded.

Use connection pooling, query optimization, caching, and database scaling strategies to avoid moving the bottleneck from your application servers to your database.

13. Load Balancer vs Auto Scaling: What's the Difference?

These services solve different problems.

FeatureLoad BalancerAuto ScalingMain responsibilityDistributes trafficAdjusts instance capacityAdds EC2 instancesNoYesRemoves EC2 instancesNoYesHealth monitoringChecks target healthUses configured health and scaling signalsTraffic routingYesNoImproves availabilityYesHelps maintain capacity

They are often used together, but neither replaces the other.

14. Final Thoughts

When an application runs on a single server, that server becomes a potential performance bottleneck and a single point of failure.

AWS Elastic Load Balancing helps solve this problem by providing a managed entry point for distributing traffic across multiple backend targets.

Understanding the responsibilities of the load balancer, listeners, target groups, health checks, Availability Zones, and Auto Scaling is essential when designing production-ready cloud applications.

For a typical MERN application, an Application Load Balancer combined with EC2 Auto Scaling, private subnets, and centralized session storage provides a strong foundation for handling growing traffic.

The real goal isn't simply to run more servers. It's to build an architecture where traffic can grow, individual servers can fail, and the application can continue serving users reliably.

About the Author

Asad Saeed | Senior Software Engineer | Full Stack Developer

I share practical insights on backend engineering, MERN Stack development, distributed systems, database architecture, cloud computing, and building reliable production applications.

Asad Saeed

Asad Saeed

Senior Software Engineer | Full Stack Developer

More posts →

Related Posts

Don't Stop Here

Docker for Full-Stack Developers: Complete Guide (2026)

Docker for Full-Stack Developers: Complete Guide (2026)

Learn Docker for full-stack development with practical examples covering Dockerfiles, images, containers, Docker Compose, networking, environment variables, volumes, and production deployment.

DOCKERDEVOPSSOFTWARE ENGINEERING
© 2026 · Asad Saeed
All Posts
How AWS Load Balancers Work: Distributing Traffic Across Multiple EC2 Servers

How AWS Load Balancers Work: Distributing Traffic Across Multiple EC2 Servers

AWSAWS LOAD BALANCERCLOUD COMPUTINGDEVOPSASAD SAEED
November 11, 202616 min readBy Asad Saeed

Learn how AWS Load Balancers distribute traffic across multiple EC2 instances, perform health checks, handle server failures, and work with Auto Scaling for highly available applications.

Introduction

Imagine you've deployed a MERN application on a single EC2 instance.

Initially, everything works fine. Users can log in, browse products, submit forms, and interact with your APIs.

But as your application grows, traffic increases. Hundreds or thousands of users start sending requests simultaneously.

Your single server now has to handle API requests, authentication, database operations, file uploads, background processing, and multiple concurrent user sessions.

Eventually, CPU usage increases, memory becomes constrained, and response times become slower. If the server crashes, your entire application may become unavailable.

One solution is to run multiple application servers.

However, this introduces another problem:

How do users know which server to connect to?

Should every user connect to Server 1? How do we distribute traffic? What happens if Server 2 crashes? How can we add more servers without changing the frontend or API URL?

This is where AWS Elastic Load Balancing (ELB) comes in.

AWS Load Balancers provide a single entry point for incoming traffic and distribute requests across multiple registered targets, such as EC2 instances, containers, and IP addresses.

Let's understand how this works behind the scenes.

1. What Is a Load Balancer?

A load balancer is a component that receives incoming network traffic and distributes it across multiple backend servers.

Instead of allowing clients to communicate directly with individual application servers, clients communicate with the load balancer.

The load balancer then forwards traffic to an appropriate healthy backend.

              Users
                |
                v
          Application URL
                |
                v
         AWS Load Balancer
                |
       +--------+--------+
       |        |        |
       v        v        v
    Server 1 Server 2 Server 3
       |        |        |
       +--------+--------+
                |
                v
             Database

The client doesn't need to know how many backend servers exist.

It communicates with one endpoint, while the load balancer manages traffic distribution.

Why Do Applications Need Load Balancing?

High availability: If one server becomes unhealthy, the load balancer can stop routing new requests to it and use healthy targets instead.

Scalability: You can add more backend instances as application traffic increases.

Better performance: Traffic can be distributed across multiple servers instead of overwhelming one instance.

Fault isolation: A failure in one application server doesn't necessarily make the entire application unavailable.

Centralized traffic management: You can manage routing, TLS termination, health checks, and other traffic-related behavior at a central entry point.

2. What Is AWS Elastic Load Balancing?

AWS provides a managed service called Elastic Load Balancing (ELB).

Instead of installing and maintaining your own load-balancing software, AWS operates the load-balancing infrastructure.

You configure the load balancer, listeners, routing rules, and target groups. AWS manages the underlying service infrastructure.

For example, you might deploy three EC2 instances:

  • EC2 Instance 1 — Application Server

  • EC2 Instance 2 — Application Server

  • EC2 Instance 3 — Application Server

You register these instances in a target group and configure an AWS Load Balancer to forward incoming traffic to that group.

The load balancer continuously evaluates target health and routes new requests or connections according to its configured behavior.

3. Types of AWS Load Balancers

AWS provides different load balancer types for different networking requirements.

3.1 Application Load Balancer (ALB)

Layer 7 — Application Layer

The Application Load Balancer operates at the application layer.

It understands HTTP and HTTPS traffic and can make routing decisions using information such as:

  • URL paths

  • Hostnames

  • HTTP headers

  • Query strings

  • HTTP methods

  • Source IP conditions

For example:

api.example.com/users
        |
        v
Application Load Balancer
        |
        v
User Service

api.example.com/orders
        |
        v
Application Load Balancer
        |
        v
Order Service

You can configure routing rules such as:

/users/*  → User Service
/orders/* → Order Service
/admin/*  → Admin Service

You can also route traffic using different hostnames:

api.example.com     → Backend API
admin.example.com   → Admin Application

When should you use ALB?

  • React or Next.js applications with HTTP-based backend services.

  • Node.js, Express, and NestJS APIs.

  • Microservices architecture.

  • Containerized applications running on ECS or EKS.

  • Applications requiring path-based or host-based routing.

3.2 Network Load Balancer (NLB)

Layer 4 — Transport Layer

The Network Load Balancer operates at the transport layer.

It handles TCP, UDP, and TLS traffic and is designed for high-performance, low-latency network workloads.

Unlike an ALB, it doesn't inspect HTTP paths such as /users or /orders to make routing decisions.

Client
  |
  v
Network Load Balancer
  |
  +------> TCP Server 1
  |
  +------> TCP Server 2
  |
  +------> TCP Server 3

When should you use NLB?

  • High-throughput TCP or UDP applications.

  • Applications requiring static IP addresses.

  • Low-latency network services.

  • Workloads that need Layer 4 traffic handling.

  • Services that don't need HTTP-aware routing rules.

3.3 Gateway Load Balancer (GWLB)

Layer 3 — Network Layer

Gateway Load Balancer is designed to deploy, scale, and manage virtual network appliances.

These appliances can include:

  • Firewalls

  • Intrusion detection systems

  • Intrusion prevention systems

  • Deep packet inspection systems

It helps distribute network traffic across virtual appliances while integrating with AWS networking.

3.4 Classic Load Balancer (CLB)

Classic Load Balancer is an older generation of Elastic Load Balancing.

It supports basic Layer 4 and Layer 7 load balancing.

For most new application architectures, AWS recommends choosing an Application Load Balancer or Network Load Balancer based on the workload.

4. Understanding the Main Components of an ALB

Before understanding traffic distribution, let's look at the components involved.

4.1 Load Balancer

The load balancer provides the entry point for incoming traffic.

For example:

my-app-alb-123456.ap-south-1.elb.amazonaws.com

You can point your application domain to the load balancer using DNS.

api.example.com → AWS Load Balancer

The load balancer can be internet-facing or internal.

An internet-facing load balancer receives traffic from clients outside your VPC, while an internal load balancer is intended for private application traffic.

4.2 Listener

A listener checks for incoming connection requests on a configured protocol and port.

For example:

HTTP  → Port 80
HTTPS → Port 443

A listener also defines what happens when traffic arrives.

HTTPS : 443
     |
     v
Forward traffic to API Target Group

You can configure listener rules to forward, redirect, or return fixed responses.

4.3 Target Group

A target group is a collection of registered backend targets.

For example:

Target Group: production-api

EC2 Instance 1
EC2 Instance 2
EC2 Instance 3

A target group defines how the load balancer communicates with its registered targets.

It also contains health-check configuration.

Targets can include EC2 instances, IP addresses, Lambda functions (for supported ALB configurations), and other supported target types.

4.4 Health Checks

A load balancer needs to know whether a backend server is healthy before routing new traffic to it.

For an HTTP application, you might configure:

Health Check Path: /health
Protocol: HTTP
Port: Traffic port
Success Code: 200

Your Node.js API might expose this endpoint:

app.get("/health", (req, res) => {
  res.status(200).json({
    status: "healthy",
    timestamp: new Date().toISOString(),
  });
});

The load balancer periodically sends health-check requests to registered targets.

If a target fails enough consecutive checks, it becomes unhealthy.

The load balancer stops routing new requests to that unhealthy target, subject to the target group's health and routing configuration.

When the target passes the required recovery checks, it can become healthy again.

Important: A health endpoint should represent the actual readiness of your application. Returning HTTP 200 while essential dependencies are unavailable can make an unhealthy application appear healthy.

5. How AWS Load Balancer Distributes Incoming Traffic

Let's walk through the complete request lifecycle.

Suppose your application has three backend servers:

EC2-1
EC2-2
EC2-3

All three are registered in the same target group.

A user opens:

https://api.example.com/users

Here's what happens.

Step 1: DNS Resolution

The browser needs to resolve your domain.

Your DNS configuration points the domain to the AWS load balancer.

api.example.com
       |
       v
AWS Load Balancer DNS

The client connects to the load balancer rather than directly to an EC2 instance.

Step 2: The Load Balancer Receives Traffic

The load balancer accepts the incoming connection through its configured listener.

For example:

HTTPS : 443

For HTTPS traffic, the ALB can terminate TLS using a certificate configured through AWS Certificate Manager.

It can then forward traffic to the backend using the configured target group protocol and port.

Step 3: Listener Rules Are Evaluated

The listener checks the incoming request against its configured rules.

For example:

/users/*  → Users Target Group
/orders/* → Orders Target Group

If the request is:

GET /users

the listener forwards it to the Users Target Group.

Step 4: The Target Group Provides Eligible Targets

The target group contains registered backend servers.

Users Target Group

EC2-1 → Healthy
EC2-2 → Healthy
EC2-3 → Unhealthy

The load balancer considers target health when selecting destinations.

Step 5: Traffic Is Forwarded to a Backend

The ALB selects an eligible target according to its configured routing algorithm.

The default algorithm is round robin.

For example, with three healthy targets, requests may be distributed in this pattern:

Request 1 → EC2-1
Request 2 → EC2-2
Request 3 → EC2-3
Request 4 → EC2-1
Request 5 → EC2-2

This is an illustrative sequence, not a guarantee that every request will be distributed in a perfectly equal pattern.

Step 6: The Backend Processes the Request

The selected EC2 instance runs your application.

EC2-1
  |
  v
Node.js / Express API
  |
  v
Business Logic
  |
  v
MongoDB / PostgreSQL

The application processes the request and returns a response.

Step 7: The Response Returns to the Client

The response travels back through the load balancer to the client.

Client
  |
  v
Load Balancer
  |
  v
EC2 Instance
  |
  v
Load Balancer
  |
  v
Client

The client continues using the same public application endpoint. It doesn't need to know which backend instance handled the request.

6. What Happens When One Server Crashes?

This is one of the most important benefits of load balancing.

Imagine you have three application servers:

EC2-1 → Healthy
EC2-2 → Healthy
EC2-3 → Unhealthy

Suppose EC2-3 crashes because of:

  • Application errors

  • Memory exhaustion

  • High CPU usage

  • A failed deployment

  • An operating system problem

The load balancer's health checks detect that the target is no longer healthy.

After the configured failure threshold is reached, the target is marked unhealthy.

The load balancer stops sending new traffic to it and continues using the remaining healthy targets.

             Load Balancer
                   |
          +--------+--------+
          |        |        |
          v        v        v
        EC2-1    EC2-2    EC2-3
       Healthy  Healthy  Unhealthy
          |        |        X
          |        |        |
          +--------+        |
                   |
             Application
               Online

This helps your application remain available even when an individual server fails.

However, load balancing does not guarantee zero downtime. Existing connections, requests already in progress, shared dependencies, and insufficient remaining capacity can still affect users.

7. How Does AWS Decide Which Server Receives Traffic?

Load balancing isn't always a simple equal distribution.

AWS supports different routing strategies depending on the load balancer type.

For Application Load Balancers, supported routing algorithms include:

7.1 Round Robin

This is the default ALB routing algorithm.

The load balancer distributes requests across available targets in rotation.

Request 1 → Server A
Request 2 → Server B
Request 3 → Server C
Request 4 → Server A

It's useful when backend servers have relatively similar processing capacity and request workloads.

7.2 Least Outstanding Requests

With this algorithm, the ALB selects a target based on the number of requests that target is currently processing.

For example:

Server A → 10 outstanding requests
Server B → 3 outstanding requests
Server C → 6 outstanding requests

The load balancer can choose Server B because it has fewer outstanding requests.

This can be useful when requests have different processing times.

7.3 Weighted Random

Weighted random is another ALB routing algorithm.

It randomly selects targets while considering configured target weights. It also supports Automatic Target Weights, which can help identify and mitigate the impact of anomalous targets.

This can be useful in certain workloads where the default routing behavior isn't ideal.

Note: These algorithms are ALB-specific. NLB uses its own flow-based distribution behavior rather than ALB's HTTP request-routing algorithms.

8. How Does Load Balancing Work Across Multiple Availability Zones?

High availability requires more than running multiple servers.

If all your EC2 instances are deployed in one Availability Zone and that zone experiences an outage, your entire backend may become unavailable.

AWS allows load balancers to operate across multiple Availability Zones.

                 AWS ALB
                    |
          +---------+---------+
          |                   |
          v                   v
      Availability Zone A  Availability Zone B
          |                   |
       EC2-1                EC2-3
       EC2-2                EC2-4
          |                   |
          +---------+---------+
                    |
                 Database

This architecture distributes application servers across different Availability Zones.

If one zone becomes unavailable, the load balancer can route new traffic to healthy targets in the remaining enabled zones, provided sufficient healthy capacity remains.

What Is Cross-Zone Load Balancing?

Cross-zone load balancing allows a load balancer node to distribute traffic across targets in other enabled Availability Zones.

Without cross-zone load balancing, distribution can be restricted to targets in the same Availability Zone as the load balancer node.

The exact default behavior and configuration options differ by load balancer type.

For ALB, cross-zone load balancing is enabled at the load balancer level by default.

For NLB, it is configurable and has different default behavior.

9. How Does Auto Scaling Work With a Load Balancer?

A load balancer distributes traffic, but it doesn't automatically create additional EC2 instances by itself.

That's where EC2 Auto Scaling comes in.

Auto Scaling monitors configured metrics and scaling policies to determine when to add or remove instances.

Average CPU Usage > 70%
          |
          v
Auto Scaling Policy
          |
          v
Launch New EC2 Instance
          |
          v
Register Instance
in Target Group
          |
          v
Health Check
          |
          v
Healthy Instance
Receives Traffic

Suppose your application starts with two instances:

EC2-1
EC2-2

As traffic increases, CPU utilization reaches your configured scaling threshold.

Auto Scaling launches another instance:

EC2-1
EC2-2
EC2-3

When the new instance registers with the target group and passes its health checks, it can start receiving traffic.

When demand decreases, Auto Scaling can terminate instances according to its scaling policies and lifecycle behavior.

The important distinction:

  • Load Balancer distributes incoming traffic.

  • Auto Scaling adjusts the number of application instances.

  • Target Groups connect the load balancer with backend targets.

  • Health Checks help determine whether targets are ready to receive traffic.

Together, they create a scalable application architecture.

10. Sticky Sessions: What If a User Needs the Same Server?

Some applications maintain session information directly on individual backend servers.

Consider this example:

User Login → EC2-1
User Dashboard → EC2-2

If the session exists only in EC2-1's local memory, the second request might fail because EC2-2 doesn't know about that session.

AWS ALB supports sticky sessions, also called session affinity.

With stickiness enabled, the load balancer can use a cookie to route a user's subsequent requests to the same target for the configured duration.

User A → EC2-1
User A → EC2-1
User A → EC2-1

User B → EC2-2
User B → EC2-2

However, sticky sessions aren't a replacement for proper session architecture.

For scalable applications, consider storing shared session data in Redis or another centralized session store.

This allows multiple application instances to access the same session state.

11. Practical AWS Architecture for a MERN Application

Let's connect everything to a real-world MERN deployment.

Imagine you have:

  • React frontend

  • Node.js and Express backend

  • MongoDB database

  • Multiple EC2 instances

  • AWS Application Load Balancer

  • EC2 Auto Scaling Group

A possible architecture looks like this:

                 Users
                   |
                   v
             Route 53 DNS
                   |
                   v
            Application ALB
                   |
              HTTPS : 443
                   |
             Backend Target Group
                   |
          +--------+--------+
          |        |        |
          v        v        v
        EC2-1    EC2-2    EC2-3
          |        |        |
          +--------+--------+
                   |
              Node.js API
                   |
                   v
             MongoDB Database

For a production deployment, you could configure:

Frontend

  • Host the React frontend on Amazon S3.

  • Use CloudFront for content delivery.

  • Configure Route 53 for domain management.

Backend

  • Deploy Node.js APIs on EC2 instances.

  • Place instances in private subnets.

  • Use an internet-facing ALB in public subnets.

  • Register backend instances in a target group.

  • Configure health checks.

Scaling

  • Create an EC2 Auto Scaling Group.

  • Attach it to the target group.

  • Configure scaling policies based on CPU utilization or other metrics.

Security

  • Allow HTTPS traffic to the ALB.

  • Allow backend traffic only from the ALB's security group.

  • Restrict database access to the backend's security group.

  • Store credentials and secrets securely.

This architecture provides a foundation for scaling a MERN application without exposing individual backend instances directly to the internet.

12. Important Production Considerations

A load balancer improves application architecture, but it doesn't automatically solve every production problem.

12.1 Keep Application Servers Stateless

Avoid storing important user sessions or temporary shared application state only in local server memory.

When traffic moves between instances, another server should be able to process the request.

Use shared services such as Redis or a database when appropriate.

12.2 Configure Health Checks Carefully

A health check that is too aggressive can temporarily remove servers during short-lived issues.

A health check that is too relaxed can leave unhealthy instances receiving traffic for longer than necessary.

Configure the interval, timeout, healthy threshold, unhealthy threshold, and health endpoint based on your application's behavior.

12.3 Use Private Subnets for Backend Instances

For many production architectures, the ALB is public-facing while EC2 application instances are placed in private subnets.

This reduces direct exposure of backend instances.

12.4 Monitor Load Balancer Metrics

CloudWatch provides useful metrics for monitoring load balancer behavior.

Examples include:

  • RequestCount

  • TargetResponseTime

  • HTTPCode_ELB_5XX_Count

  • HTTPCode_Target_5XX_Count

  • HealthyHostCount

  • UnHealthyHostCount

These metrics help identify traffic spikes, unhealthy targets, slow responses, and application errors.

12.5 Understand Deregistration Delay

When an instance is removed from a target group, it may still have active requests.

Target group deregistration delay allows time for in-flight requests to complete before the target is fully deregistered.

This is particularly important during deployments and Auto Scaling scale-in events.

12.6 Remember That the Database Can Become the Bottleneck

Adding more backend servers increases your application's ability to process requests, but it can also increase database connections and query volume.

For example:

3 Backend Servers
       |
       v
   Database

If each server creates too many database connections, the database may become overloaded.

Use connection pooling, query optimization, caching, and database scaling strategies to avoid moving the bottleneck from your application servers to your database.

13. Load Balancer vs Auto Scaling: What's the Difference?

These services solve different problems.

FeatureLoad BalancerAuto ScalingMain responsibilityDistributes trafficAdjusts instance capacityAdds EC2 instancesNoYesRemoves EC2 instancesNoYesHealth monitoringChecks target healthUses configured health and scaling signalsTraffic routingYesNoImproves availabilityYesHelps maintain capacity

They are often used together, but neither replaces the other.

14. Final Thoughts

When an application runs on a single server, that server becomes a potential performance bottleneck and a single point of failure.

AWS Elastic Load Balancing helps solve this problem by providing a managed entry point for distributing traffic across multiple backend targets.

Understanding the responsibilities of the load balancer, listeners, target groups, health checks, Availability Zones, and Auto Scaling is essential when designing production-ready cloud applications.

For a typical MERN application, an Application Load Balancer combined with EC2 Auto Scaling, private subnets, and centralized session storage provides a strong foundation for handling growing traffic.

The real goal isn't simply to run more servers. It's to build an architecture where traffic can grow, individual servers can fail, and the application can continue serving users reliably.

About the Author

Asad Saeed | Senior Software Engineer | Full Stack Developer

I share practical insights on backend engineering, MERN Stack development, distributed systems, database architecture, cloud computing, and building reliable production applications.

Asad Saeed

Asad Saeed

Senior Software Engineer | Full Stack Developer

More posts →

Related Posts

Don't Stop Here

Docker for Full-Stack Developers: Complete Guide (2026)

Docker for Full-Stack Developers: Complete Guide (2026)

Learn Docker for full-stack development with practical examples covering Dockerfiles, images, containers, Docker Compose, networking, environment variables, volumes, and production deployment.

DOCKERDEVOPSSOFTWARE ENGINEERING
© 2026 · Asad Saeed
Oct 19, 202612 min read
Read
Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Learn how Dependency Injection works in NestJS, including Providers, the IoC Container, Constructor Injection, Injection Tokens, Custom Providers, and best practices for building scalable, testable, and enterprise-ready Node.js applications.

NESTJSDEPENDENCY INJECTIONNODEJS
Oct 19, 20265 min read
Read
NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

Master the NestJS architecture by understanding Modules, Controllers, Providers, Dependency Injection, Middleware, Guards, Pipes, Interceptors, and Exception Filters. Learn the complete NestJS request lifecycle and build scalable, production-ready backend applications.

NESTJSNODEJSSOFTWARE ARCHITECTURE
Aug 5, 20266 min read
Read
F
Made with ❤️ by Asad Saeed
© 2026 · Asad Saeed
Made with ❤️ by Asad Saeed
F
Oct 19, 202612 min read
Read
Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Learn how Dependency Injection works in NestJS, including Providers, the IoC Container, Constructor Injection, Injection Tokens, Custom Providers, and best practices for building scalable, testable, and enterprise-ready Node.js applications.

NESTJSDEPENDENCY INJECTIONNODEJS
Oct 19, 20265 min read
Read
NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

Master the NestJS architecture by understanding Modules, Controllers, Providers, Dependency Injection, Middleware, Guards, Pipes, Interceptors, and Exception Filters. Learn the complete NestJS request lifecycle and build scalable, production-ready backend applications.

NESTJSNODEJSSOFTWARE ARCHITECTURE
Aug 5, 20266 min read
Read
F
Made with ❤️ by Asad Saeed
© 2026 · Asad Saeed
Made with ❤️ by Asad Saeed
F