Scalability and load balancing

Mid-level Always asked 7 min

On this page

The question

What is the difference between vertical and horizontal scaling? Which do you prefer for a web service?

30-second answer

Vertical scaling gives one machine more CPU and memory; horizontal scaling adds more identical machines behind a load balancer. Vertical is simple and needs no code change, but it has a ceiling, usually a restart per resize, and stays a single point of failure. Horizontal scales almost without limit and survives an instance failure, but only if the service is stateless. For a web service I scale horizontally, and use vertical scaling for what resists it, such as a primary database.

Understand it

Traffic drives an auto-scaling group

Explore

1500 requests a second at 300 per instance: the group runs 5 identical stateless instances behind one load balancer, adding and removing them as traffic moves.

1500 req/s
View as text

A load balancer above the instances it sends traffic to, each with a bar of its CPU use against a dashed 60% target line. Horizontally, an auto-scaling group of 2 to 8 instances, each serving 500 requests a second at full CPU; vertically, one machine resized from large to 4xlarge.

Night: 250 requests a second would fit fewer, but the group keeps its minimum of 2, one per zone, so one failure leaves capacity.

Busy day: 1500 requests a second at 300 per instance: the group runs 5 identical stateless instances behind one load balancer, adding and removing them as traffic moves.

Peak, capped: 3000 requests a second need 10 instances at 300 each, but the group stops at 8: raise the maximum or every instance overloads.

One big box: 1500 requests a second fit one 4xlarge machine. Simple, but each resize restarts it, and when it fails everything fails.

Peak, one box: 3000 requests a second push even the largest size past the target. Vertical scaling has a ceiling, and every resize restarted the only instance.

A load balancer above the instances it sends traffic to, each with a bar of its CPU use against a dashed 60% target line. Horizontally, an auto-scaling group of 2 to 8 instances, each serving 500 requests a second at full CPU; vertically, one machine resized from large to 4xlarge.

Night: 250 requests a second would fit fewer, but the group keeps its minimum of 2, one per zone, so one failure leaves capacity.

Busy day: 1500 requests a second at 300 per instance: the group runs 5 identical stateless instances behind one load balancer, adding and removing them as traffic moves.

Peak, capped: 3000 requests a second need 10 instances at 300 each, but the group stops at 8: raise the maximum or every instance overloads.

One big box: 1500 requests a second fit one 4xlarge machine. Simple, but each resize restarts it, and when it fails everything fails.

Peak, one box: 3000 requests a second push even the largest size past the target. Vertical scaling has a ceiling, and every resize restarted the only instance.

Takeaway: Horizontal scaling adds identical stateless instances behind a load balancer, between a minimum and a maximum. Vertical scaling makes one machine bigger: simple, but capped, disruptive to resize and a single point of failure.

Sticky sessions when an instance dies

Predict

Three instances behind a load balancer with sticky sessions. Ana’s cart, 3 items, lives in the HTTP session in instance B’s memory. Traffic drops, and scale-in terminates B.

What does Ana see on her next request, once instance B is gone?
View as text

A load balancer above three instances, A, B and C. A cookie ties Ana to one instance, and a cart badge shows where her session lives and how many items she sees. A Redis box below the instances is used only after the fix. Three instances behind a load balancer with sticky sessions. Ana’s cart, 3 items, lives in the HTTP session in instance B’s memory. Traffic drops, and scale-in terminates B. The learner predicts what Ana sees next.

Ana’s next request goes to instance A. A has no session for her cookie, so it starts a new one: an empty cart, and perhaps a logout.

Fix the cause: keep sessions in a shared store, such as Redis. Any instance can read any session, so stickiness is no longer needed for correctness.

Now scale-in terminates B again. Ana’s request lands on A, which loads her session from Redis: still 3 items. Instances can come and go freely.

A load balancer above three instances, A, B and C. A cookie ties Ana to one instance, and a cart badge shows where her session lives and how many items she sees. A Redis box below the instances is used only after the fix. Three instances behind a load balancer with sticky sessions. Ana’s cart, 3 items, lives in the HTTP session in instance B’s memory. Traffic drops, and scale-in terminates B. The learner predicts what Ana sees next.

Ana’s next request goes to instance A. A has no session for her cookie, so it starts a new one: an empty cart, and perhaps a logout.

Fix the cause: keep sessions in a shared store, such as Redis. Any instance can read any session, so stickiness is no longer needed for correctness.

Now scale-in terminates B again. Ana’s request lands on A, which loads her session from Redis: still 3 items. Instances can come and go freely.

Takeaway: Sticky sessions hide state in one instance’s memory, so scale-in, a deploy or a crash loses it. Keep instances stateless and put sessions in a shared store; then any instance can serve any request.

Layer 4 balances connections, layer 7 reads the request and routes itA layer 7 load balancer terminates HTTP and TLS, reads the host, path, headers and cookies, and routes each request to a target group, such as orders for the shop path and payments for the pay path. A layer 4 load balancer sees only IP addresses, ports and TCP or UDP connections and forwards whole connections, which suits gRPC, databases, MQTT or very high throughput./api/orders/*pay.example.comwhole connectionsClientsLayer 7 loadbalancer:HTTP, TLS, host,path,headers, cookiesorderstarget grouppaymentstarget groupLayer 4 loadbalancer:IP, port, TCP or UDPgRPC, MQTT,databases
Layer 4 balances connections, layer 7 reads the request and routes itA layer 7 load balancer terminates HTTP and TLS, reads the host, path, headers and cookies, and routes each request to a target group, such as orders for the shop path and payments for the pay path. A layer 4 load balancer sees only IP addresses, ports and TCP or UDP connections and forwards whole connections, which suits gRPC, databases, MQTT or very high throughput./api/orders/*pay.example.comwhole connectionsClientsLayer 7 loadbalancer:HTTP, TLS, host,path,headers, cookiesorderstarget grouppaymentstarget groupLayer 4 loadbalancer:IP, port, TCP or UDPgRPC, MQTT,databases
Layer 4 balances connections; layer 7 reads the request and routes it
ConceptAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
Layer 7 load balancerALB (Application Load Balancer)Application Gateway, Front DoorApplication Load Balancer
Layer 4 load balancerNLB (Network Load Balancer)Azure Load BalancerNetwork Load Balancer
Group of identical instancesEC2 (Elastic Compute Cloud) Auto Scaling groupVirtual Machine Scale SetsManaged instance group
Shared session storeElastiCache for RedisAzure Cache for RedisMemorystore for Redis

In code

resource "aws_autoscaling_policy" "cpu_60" {
  name                   = "cpu-60"
  autoscaling_group_name = aws_autoscaling_group.orders.name
  policy_type            = "TargetTrackingScaling"
  target_tracking_configuration {
    predefined_metric_specification {
      predefined_metric_type = "ASGAverageCPUUtilization"
    }
    target_value = 60
  }
}

resource "aws_lb_target_group" "orders" {
  name                 = "orders"
  port                 = 8080
  protocol             = "HTTP"
  vpc_id               = aws_vpc.main.id
  deregistration_delay = 30
  health_check {
    path    = "/actuator/health/readiness"
    matcher = "200"
  }
}
Terraform: scale on average CPU, check readiness, drain for 30 s before removing an instance
@RestController
class CartController {
    // Wrong: the cart lives in this instance; the next request may reach another one, or this one may be gone
 Wrong     private final Map<String, Cart> carts = new ConcurrentHashMap<>();

    @PostMapping("/cart/{cartId}/items")
    void add(@PathVariable String cartId, @RequestBody Item item) {
        carts.computeIfAbsent(cartId, id -> new Cart()).add(item);
    }
}

// Right: state goes to a store every instance shares, such as Redis or the database
 Right record CartService(CartRepository carts) {
 Right     void add(String cartId, Item item) {
 Right         Cart cart = carts.findById(cartId).orElseGet(() -> new Cart(cartId));
 Right         cart.add(item);
 Right         carts.save(cart);
 Right     }
 Right }
A stateless service keeps no request state in its own memory
# With spring-session-data-redis on the classpath, every instance reads the same sessions
spring.data.redis.host=sessions.abc123.euw1.cache.amazonaws.com
spring.data.redis.ssl.enabled=true
spring.session.timeout=30m
spring.session.redis.namespace=orders
# The layer 7 balancer terminates TLS (Transport Layer Security): trust its X-Forwarded-* headers
server.forward-headers-strategy=native
Spring Session moves HttpSession to Redis; forwarded headers keep URLs right behind the balancer
Scale out, then scale in, without dropping a requestAverage CPU passes the 60 percent target, so the auto-scaling group launches an instance. The load balancer sends it traffic only after its readiness check passes. Later CPU falls, the group picks an instance to remove, the load balancer stops new requests to it and waits up to 30 seconds for open ones, then the instance is terminated.New instanceLoad balancerAuto-scaling groupMetricsaverage CPU 78%, target 60%launch from the imagereadiness check passessend a share of trafficaverage CPU 25%deregister one instanceno new requests, wait up to 30 sterminate it
Scale out, then scale in, without dropping a requestAverage CPU passes the 60 percent target, so the auto-scaling group launches an instance. The load balancer sends it traffic only after its readiness check passes. Later CPU falls, the group picks an instance to remove, the load balancer stops new requests to it and waits up to 30 seconds for open ones, then the instance is terminated.New instanceLoad balancerAuto-scaling groupMetricsaverage CPU 78%, target 60%launch from the imagereadiness check passessend a share of trafficaverage CPU 25%deregister one instanceno new requests, wait up to 30 sterminate it
Scale out, then scale in, without dropping a request

Solve it

Autoscaling is on, yet the service falls over at 10 times its traffic

An orders service runs 4 instances in an auto-scaling group, scaling on 60% average CPU up to 40 instances. At the start of a sale, traffic jumps tenfold within two minutes; latency climbs to 20 seconds and requests fail, while average CPU stays near 35% and the group adds only two instances. Each instance holds a pool of 20 database connections. Find the causes and fix them.

  1. Ask what is actually saturated. CPU stays low because threads wait on the database: requests queue in the connection pool, not in the CPU. A CPU target cannot see that, so the group barely scales.
  2. Scale on what tracks the load. Use request count per target, or latency, as the metric. Then 10 times the requests means 10 times the instances, whatever the CPU does.
  3. Count the new bottleneck before it bites. 40 instances times 20 connections is 800, above a database that allows 500. Size pools so the total fits, put a connection proxy in front, and move reads to replicas or a cache.
  4. Beat the scaling lag. New instances need minutes to boot and warm the JVM (Java Virtual Machine), longer than the spike takes to arrive. Schedule capacity ahead of a known sale, and keep a warm pool of prepared instances.
  5. Check with a load test. Replay the sale’s ramp against staging: watch request count per instance, pool wait time and database connections, and confirm that latency stays flat while the group grows.
resource "aws_autoscaling_schedule" "sale_warmup" {
  scheduled_action_name  = "sale-warmup"
  autoscaling_group_name = aws_autoscaling_group.orders.name
  start_time             = "2026-11-27T06:00:00Z"
  min_size               = 12
  max_size               = 40
  desired_capacity       = 12
}

resource "aws_autoscaling_policy" "requests_per_target" {
  name                   = "requests-per-target"
  autoscaling_group_name = aws_autoscaling_group.orders.name
  policy_type            = "TargetTrackingScaling"
  target_tracking_configuration {
    predefined_metric_specification {
      predefined_metric_type = "ALBRequestCountPerTarget"
      resource_label         = "${aws_lb.main.arn_suffix}/${aws_lb_target_group.orders.arn_suffix}"
    }
    target_value = 800
  }
}

# 40 instances x 12 connections = 480, under max_connections = 500
# spring.datasource.hikari.maximum-pool-size=12
Scale ahead of the sale and on requests per instance, not on CPU

How to answer

  • Horizontal needs stateless instances, a load balancer and health checks.
  • Autoscaling adds and removes instances between a minimum and a maximum, on a metric.
  • The bottleneck moves downstream, usually to the database, when instances multiply.
  • Databases scale vertically first, then with read replicas, caching and sharding.

Common mistakes

  • Calling horizontal scaling free, without mentioning state, sessions and downstream limits.
  • Saying vertical scaling never needs downtime.

Follow-up questions

What does it mean for a service to be stateless, and why does it matter for scaling?

A stateless service keeps nothing between requests in its own memory or disk that a later request needs: no in-memory sessions, carts, uploaded files or local caches it relies on. All such state lives in shared stores, such as a database, Redis or object storage. Then any instance can serve any request, so the load balancer can spread traffic freely and the platform can add, replace or remove instances at any time without losing data.

  • Stateless does not mean no state; it means the state lives outside the instance.
  • Local caches are fine if losing them only costs speed, not correctness.
  • Stateless instances also make rolling deploys and crash recovery trivial.

See it in the infographic: Sticky sessions when an instance dies

How does auto-scaling work, and which metric would you scale on?

An auto-scaling group keeps between a minimum and a maximum number of identical instances. A policy watches a metric and adds instances when it passes a target and removes them when it falls, with cooldowns so it does not flap. Target tracking on average CPU is the default, but for I/O-bound Java services I prefer requests per instance, queue depth for workers, or latency, because CPU can stay low while requests pile up.

  • Scaling takes minutes, so add scheduled or predictive scaling before known peaks.
  • Keep the minimum at two or more, spread over zones, for availability.
  • New instances must pass a readiness check before getting traffic.

See it in the infographic: Traffic drives an auto-scaling group

What is the difference between a layer 4 and a layer 7 load balancer?

A layer 4 load balancer works on TCP (Transmission Control Protocol) or UDP connections: it sees IP addresses and ports and forwards whole connections, so it is very fast, keeps the client IP and handles any protocol. A layer 7 load balancer terminates HTTP and TLS and reads each request: it routes by host, path, header or cookie, rewrites and redirects, and balances each request, not each connection. Web APIs usually sit behind layer 7; gRPC, databases and extreme throughput behind layer 4.

  • Layer 7 adds features, such as path routing, TLS termination, a web application firewall and sticky cookies.
  • Layer 4 balances long-lived connections once, which can leave load uneven.
  • Behind layer 7, read the client IP from X-Forwarded-For.

See it in the infographic: Traffic drives an auto-scaling group

What are sticky sessions, and why are they a problem?

Sticky sessions, or session affinity, make the load balancer send every request from one client to the same instance, usually with a cookie, so a session kept in that instance's memory keeps working. The problem is that the state still lives on one instance: scale-in, a deploy or a crash loses those sessions, load becomes uneven when heavy users stick to one instance, and new instances take traffic slowly. Prefer a shared session store or tokens.

  • Stickiness hides statefulness; it does not remove it.
  • Spring Session with Redis, or signed tokens such as JWTs (JSON Web Tokens), make instances interchangeable.
  • Use affinity only as a performance hint, never for correctness.

See it in the infographic: Sticky sessions when an instance dies

How does a load balancer decide which instance gets a request, and when to stop sending it traffic?

It sends traffic only to targets that pass health checks, a regular HTTP or TCP probe, and removes a target after several failures in a row. Among healthy targets it applies an algorithm: round robin, least outstanding requests or connections, weighted, or a hash of the client for affinity. Least outstanding requests suits services with uneven request costs. In Spring Boot, point the check at the readiness endpoint, not at a check of every dependency.

  • A deep health check that fails on a slow database removes every instance at once.
  • Slow start ramps traffic to a new instance while its JVM warms up.
  • Health checks decide traffic; the auto-scaling group decides replacement.

See it in the infographic: Traffic drives an auto-scaling group

You add instances, but throughput stops growing. Where do you look?

At the shared parts behind them: database connections and locks, a cache or queue at its limit, a rate-limited third-party API, or a lock held in one place. Adding instances only helps the tier that is saturated; measure each hop's latency and saturation, then scale or relieve that one.

Check yourself

1. Traffic triples, latency soars, but average CPU stays at 30% and the group scaling on 60% CPU adds nothing. What is the likely cause?
Show answers
  • Requests wait on the database, so CPU does not reflect the load: Correct. Waiting threads use no CPU; scale on requests per instance or latency.
  • The scaling policy is broken and must be recreated: Incorrect. It works as configured; CPU simply never reaches the target.
  • The instances are too small and need a vertical resize: Incorrect. More CPU does not help when CPU is idle and threads wait.
2. Sessions are kept in memory and the load balancer uses sticky cookies. Scale-in removes one of four instances. What happens to the users pinned to it?
Show answers
  • They are routed elsewhere and lose their sessions: Correct. The session existed only in the removed instance's memory.
  • Nothing; the load balancer copies their sessions over: Incorrect. Load balancers route requests; they never copy application memory.
  • Their requests fail until a new instance starts: Incorrect. Stickiness falls back to a healthy instance.
3. Requests to /api/orders must go to one service and /api/payments to another, behind one public address. Which load balancer can do it?
Show answers
  • A layer 7 load balancer, with path rules: Correct. Only layer 7 reads the HTTP path.
  • A layer 4 load balancer, with port rules: Incorrect. Layer 4 sees ports and addresses, not paths.
  • DNS (Domain Name System) round robin: Incorrect. DNS resolves host names, never paths.