System Design Part 2 From one machine to many

Vertical Scaling, Horizontal Scaling, and Stateless Services: Where Sessions, Files, Scheduled Jobs, and Local State Should Go

Bill.Lin 19 min read

System Design series Part 2-1 | Previous: Napkin Math for Capacity Estimates | Next: Load Balancing in Depth | Series map

Read first: Part 1-2 Latency, Throughput, and p99.

Scenario and problem

In the load test before the 11.11 sale, one 8-core Spring Boot server is already at 85% CPU at peak. You add a second one, put a Load Balancer in front, and figure that doubles your capacity. On launch night, one thing after another shows up:

  1. Users log in, refresh, and sometimes find themselves logged out
  2. A product image that was just uploaded sometimes shows up and sometimes returns 404
  3. The daily reconciliation job in the early morning runs twice, and customers get two notification emails
  4. The “one per person” check built with synchronized stops working, and some people get two
  5. The same product shows a different price on each of the two servers
Five oddities after adding a second server1 / 6
Five oddities after adding a second serverUserLoad BalancerServer 1Server 2UserLoad BalancerServer 1Server 2peak traffichalfhalfLoad BalancerServer 1Server 2log inrefreshsession in local memoryno session foundLoad BalancerServer 1Server 2upload imageread imagesaved to local disk404Server 1Server 2User02:00 reconcile02:00 reconcile, tootwo emails receivedUserLoad BalancerServer 1Server 2clicks twicerequest 1request 2synchronized: local onlypasses the check tooUserLoad BalancerServer 1Server 2view productlocal cache: NT$990local cache: NT$1,290
  1. One more server, double the capacity?One 8-core server is already at 85% CPU at peak. You add a second one with a Load Balancer in front, requests are split evenly between the two, and capacity seems to double.
  2. Refresh, and you are logged outAt login the request lands on server 1, and the session lives in its memory. On refresh the request goes to server 2, which does not have that session, so it treats you as not logged in.
  3. Images come and goThe uploaded image is stored on server 1's local disk. If the request to read it goes to server 2, it gets a 404.
  4. The job runs twiceThe daily early-morning reconciliation job is written into the application, so each server triggers it once, and customers get two notification emails.
  5. The one-per-person limit fails"One per person" is checked with synchronized, but that only locks its own JVM. The same person's two requests go to two servers, and both pass the check.
  6. Two servers, two pricesEach server has its own local cache. After a price change, the two caches update at different times, so the same product shows a different price on each server.

All five problems have the same root cause: the application keeps state on itself. With one machine, all that state happens to be in one place, so nothing goes wrong; add a second machine and the state splits in two.

The simplest approach and its limits: vertical scaling

Before adding machines, first ask whether you can switch to a bigger machine. The benefits of vertical scaling (scale up) are often underrated:

  • No code changes at all, and no distributed-systems problems
  • All the data lives in one memory space, so latency is as low as it gets
  • Operations are simplest: one machine, one log, one thing to monitor

It has three limits:

  1. There is a ceiling: once you have picked the largest instance size in the cloud there is no next step, and upgrading the size usually needs a restart
  2. Single point of failure: however big the machine, when it dies everything stops. Even if one machine can handle the traffic, you need at least two for availability
  3. The program cannot always use more cores: Amdahl’s law says that the part of a program that cannot run in parallel sets the upper bound on the speedup

Amdahl’s law: speedup = 1 ÷ (serial fraction + (parallel fraction ÷ number of cores)). Suppose 95% of the program can run in parallel and 5% must run serially (for example, contending for the same lock or writing to the same file):

Cores Theoretical speedup
8 5.9x
16 9.1x
64 15.4x
Infinite 20x

Going from 16 to 64 cores costs 4 times as much and buys less than 2 times the speedup. At that point, rather than buying ever bigger machines, you are better off spreading the work across many machines: horizontal scaling (scale out). But horizontal scaling has a precondition: the application must be stateless.

Core mechanism: where state hides and where it should go

“Stateless” does not mean the system has no state. It means state does not travel with the instance: any instance can be shut down, replaced, or copied at any time, and whichever instance a request reaches, the result is the same. State has to be pushed down into something all instances share.

flowchart LR
    subgraph before["Stateful: state split into copies"]
        LB1[Load Balancer] --> A1["App A<br/>Session, uploads, scheduled jobs, local locks"]
        LB1 --> B1["App B<br/>Session, uploads, scheduled jobs, local locks"]
    end
    subgraph after["Stateless: state lives in shared components"]
        LB2[Load Balancer] --> A2[App A]
        LB2 --> B2[App B]
        LB2 --> C2[App C]
        A2 & B2 & C2 --> R[(Redis<br/>Session, counters)]
        A2 & B2 & C2 --> M[(MySQL<br/>data, scheduler locks)]
        A2 & B2 & C2 --> S[(Object storage<br/>files)]
    end

List every piece of state hidden in the application:

State Where it lives on one machine Problem once there are several Where it should go
HttpSession Tomcat memory A request on another instance looks logged out Redis (Spring Session) or a token (JWT)
Uploaded files Local disk Other instances cannot read them; the files vanish when the instance is rebuilt Object storage (S3 and similar)
@Scheduled jobs Each instance triggers them on its own The same job runs N times A scheduler lock (ShedLock), a dedicated worker, an external scheduler
synchronized, ReentrantLock Inside the JVM Only locks its own instance Conditional updates in the database, unique keys, distributed locks
Local cache (HashMap, Caffeine) JVM memory Data differs between instances Accept brief inconsistency plus a TTL, or a central cache plus invalidation messages (Caching in Depth)
In-memory counters (rate limiting, stats) JVM memory The total limit becomes N times larger Atomic counters in Redis (Part 6 Rate Limiting)
WebSocket connections Tied to one instance A push has to find the instance holding the connection Broadcast to every instance with pub/sub (Part 5)
Local log files Local disk Tracing one request means logging in to every instance Centralized collection (Part 6 Observability)

There is a consequence here that is easy to miss: when you push state down, the bottleneck moves down with it. You can add as many application servers as you like, but they all share the same Redis and the same MySQL. So the next step after horizontal scaling is always scaling the shared storage layer, which is what Part 3 and Part 4 are about.

Files: presigned URLs keep files away from the application servers

Once files are in object storage, you can go one step further: let the client upload straight to object storage, and have the application server only “grant permission”.

sequenceDiagram
    participant C as Client
    participant A as App (any instance)
    participant S as S3
    participant D as MySQL
    C->>A: Request an upload (file type)
    A->>A: Check permissions, generate the object key
    A-->>C: presigned PUT URL (valid for 10 minutes)
    C->>S: PUT the file content
    C->>A: Upload done (object key)
    A->>S: HEAD to confirm the file exists and check its size
    A->>D: Write the file record

The application servers no longer carry the file’s bandwidth or memory. Any instance can issue the URL, and none of them needs to know where the file ends up.

Graceful shutdown: instances you can replace at any time

The other half of statelessness is disposability: an instance has to start fast and also shut down safely. If shutdown just cuts everything off, the requests in progress fail, and every rolling deploy produces a batch of 502s. The right shutdown order:

sequenceDiagram
    participant K as Kubernetes / deploy tool
    participant L as Load Balancer
    participant A as App
    K->>A: Start shutting down (preStop)
    K->>L: Remove this instance from the backends
    Note over L: The removal takes a few seconds to take effect
    A->>A: preStop waits a few seconds first, still serving requests
    K->>A: SIGTERM
    A->>A: Stop accepting new requests, wait for in-flight ones to finish
    A->>A: Close the connection pool and other resources
    A-->>K: Exit

The key is the third step: there is a delay between “telling the LB to remove the instance” and “the LB actually stops sending requests”. If the instance shuts down as soon as it is notified, the requests that arrive during that window fail, so it has to wait a little first.

Comparing options

Vertical scaling vs horizontal scaling

Vertical scaling Horizontal scaling
Code changes? None It has to become stateless first
Capacity limit Limited by the largest single machine No limit in theory; the bottleneck moves to shared storage
Availability Single point of failure If one dies, the others carry on
Cost curve Worse value the bigger it gets (cannot use more cores) Roughly linear, but adds the LB and shared components
Deploys Upgrades usually need downtime Rolling deploys, zero downtime
Good for Database primaries, early products, stateful services that are hard to split Stateless application tiers, services that need elastic scaling

Three ways to handle sessions

Sticky session Centralized session (Redis) Token (JWT)
How The LB uses a cookie to always send the same user to the same instance Sessions are stored in Redis, readable from every instance State is signed and handed to the client; the server only verifies it
One instance dies All of its users are logged out Unaffected Unaffected
Rolling deploy Every instance deployed kicks out a batch of users Unaffected Unaffected
Load distribution Can be uneven (heavy users stick to one instance) Even Even
Forced logout Delete the session Delete the Redis key, effective immediately Hard; needs a denylist or a shorter expiry (see the JWT post)
Extra dependency None Redis, and it must be highly available Key management and rotation
Cost per request None One Redis read (about 0.5 ms) One signature check (CPU)

For a typical web application, use a centralized session: revocation is simple, and it behaves the same as on a single machine. Use tokens only for cross-domain cases, mobile apps, and service-to-service calls. Sticky sessions are only good as a stopgap, because they hide the fact that the application is stateful until a machine dies and it blows up.

Scheduled jobs

Approach How it works Pros Cons
ShedLock Grabs a lock row in the database before running Smallest change: one annotation Once the lock times out the job may run again, so the job itself still has to be idempotent
Dedicated worker Only one instance has scheduling enabled (for example, controlled by a profile) Simple That instance is a single point of failure
External scheduler Kubernetes CronJob, Quartz in cluster mode Retries, history, monitoring One more component to operate
Hand it to an MQ The scheduler only sends a message; a consumer does the work The work can be spread across instances in parallel The most complex architecture

Whichever you use, design scheduled jobs to be idempotent. “Guaranteed to run exactly once” is hard to achieve in a distributed environment; a more realistic goal is “may run more than once, but the result is the same as running once”.

In Java

The examples use Spring Boot 3.x (the rest of the series targets Spring Boot 4.1; where Boot 4 differs, the text says so).

1. Spring Session + Redis

groovy
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.session:spring-session-data-redis'
properties
spring.data.redis.host=redis.internal
spring.session.timeout=30m

With Spring Session’s Redis module on the classpath, Spring Boot automatically stores HttpSession in Redis, and session.getAttribute() in your code does not change at all.

The default serialization is Java Serialization, which plants a landmine for deploys: as soon as a class you put in the session changes its fields, the new version fails to deserialize old sessions, and every logged-in user is logged out at once. Switch to JSON instead:

java
@Configuration
public class SessionConfig {

    // The bean must be named springSessionDefaultRedisSerializer for Spring Session to use it
    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer(ObjectMapper objectMapper) {
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }
}

Switching to JSON has a trap: a session attribute’s type is Object, and JSON itself does not record the original Java type, so Jackson can only guess when restoring it. Here are three values written out with Jackson 2.15 and read back:

text
Long       -> Integer
String     -> String
Cart       -> LinkedHashMap

You write a Long and read back an Integer, and (Long) session.getAttribute("userId") throws ClassCastException. Even if you enable DefaultTyping.NON_FINAL as the comment in the Spring Session docs suggests, Long is a final class, so it still carries no type information. So:

  • Keep only a little data with simple types in the session: store userId as a String, or always convert with ((Number) value).longValue() when reading it. Data that grows, like a shopping cart, belongs in the database or in a separate entry keyed by userId, which also keeps the amount of data read from Redis on every request small
  • When you use Spring Security: the SecurityContext is stored in the session too, so the ObjectMapper has to register SecurityJackson2Modules.getModules(classLoader). It enables type information limited by an allowlist, which is what lets Security’s objects be restored; the Spring Session docs have a full example

Spring Boot 4 moves to Jackson 3, and the matching serializer class is JacksonJsonRedisSerializer.

2. Scheduled jobs: ShedLock

java
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
public class SchedulingConfig {

    @Bean
    public LockProvider lockProvider(DataSource dataSource) {
        return new JdbcTemplateLockProvider(
                JdbcTemplateLockProvider.Configuration.builder()
                        .withJdbcTemplate(new JdbcTemplate(dataSource))
                        .usingDbTime()   // Use the database's clock to decide whether a lock has expired, so clock skew between instances does not matter
                        .build());
    }
}
java
@Component
public class ReconciliationJob {

    @Scheduled(cron = "0 0 3 * * *", zone = "Asia/Taipei")
    @SchedulerLock(name = "daily-reconciliation", lockAtMostFor = "30m", lockAtLeastFor = "1m")
    public void reconcile() {
        // At 3 a.m. every day, only the instance that gets the lock runs this, across the whole cluster
    }
}
sql
CREATE TABLE shedlock (
    name       VARCHAR(64)  NOT NULL PRIMARY KEY,
    lock_until TIMESTAMP    NOT NULL,
    locked_at  TIMESTAMP    NOT NULL,
    locked_by  VARCHAR(255) NOT NULL
);

Two parameters decide how safe it is:

  • lockAtMostFor: if the instance holding the lock crashes partway through, the longest the lock stays held. It must be longer than the job’s longest run time; otherwise the lock expires before the job finishes, and another instance runs it again
  • lockAtLeastFor: even if the job finishes quickly, the lock is kept at least this long. This stops another instance whose clock is slightly off from triggering the job again right after it ends

3. Files: S3 presigned URLs

java
@Service
public class UploadService {

    private final S3Presigner presigner;

    public UploadService(S3Presigner presigner) {
        this.presigner = presigner;
    }

    public UploadTicket issueUploadUrl(long memberId, String contentType) {
        String key = "uploads/%d/%s".formatted(memberId, UUID.randomUUID());

        PutObjectRequest objectRequest = PutObjectRequest.builder()
                .bucket("shop-product-images")
                .key(key)
                .contentType(contentType)
                .build();

        PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
                .signatureDuration(Duration.ofMinutes(10))   // The URL expires after 10 minutes
                .putObjectRequest(objectRequest)
                .build();

        PresignedPutObjectRequest presigned = presigner.presignPutObject(presignRequest);
        return new UploadTicket(key, presigned.url().toString());
    }

    public record UploadTicket(String objectKey, String uploadUrl) {}
}

Note that contentType becomes part of the signature: the client must send exactly the same Content-Type header when it uploads, or S3 returns SignatureDoesNotMatch. That is actually a good thing: it stops users from taking a URL requested for an image and using it to upload some other type of file. S3Presigner holds HTTP and credential resources and has to be close()d when you are done with it. Declaring it as a shared Spring singleton bean is enough; Spring calls its close() automatically on shutdown.

4. Graceful shutdown and Kubernetes

yaml
server:
  shutdown: graceful                    # The default since Spring Boot 3.4
spring:
  lifecycle:
    timeout-per-shutdown-phase: 30s     # Wait up to 30 seconds for in-flight requests
management:
  endpoint:
    health:
      probes:
        enabled: true                   # Exposes /actuator/health/readiness and liveness
yaml
spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: app
      lifecycle:
        preStop:
          exec:
            command: ["sh", "-c", "sleep 10"]   # Wait for the LB to remove this instance
      readinessProbe:
        httpGet:
          path: /actuator/health/readiness
          port: 8080

The timing has to add up: terminationGracePeriodSeconds is the total time limit counted from the start of shutdown, and it includes both the 10 seconds of preStop and Spring’s 30 seconds, so set it above 10 + 30. If the pod has not finished when time runs out, Kubernetes sends SIGKILL right away.

5. Count total connections before scaling out

The thing most often forgotten when scaling out is that connections multiply:

text
total database connections = number of instances × pool size per instance

MySQL’s default max_connections is 151. HikariCP defaults to 10 connections per instance and opens them all at startup: 15 instances is exactly 150 connections, and when autoscaling adds a 16th, the new instance gets Too many connections as soon as it starts. The fix is to shrink each instance’s pool to the size it really needs, using Little’s Law, or to put a connection proxy in between (for example ProxySQL or RDS Proxy).

Pitfalls and gotchas

  • Using sticky sessions to hide statefulness: everything looks fine day to day, until a machine dies or a rolling deploy runs, and all of that machine’s users are logged out
  • Java Serialization for sessions: change a class’s fields, and after the deploy every user is logged out
  • Casting directly after switching sessions to JSON: a Long comes back as an Integer, and a custom object comes back as a LinkedHashMap
  • Stuffing large objects into the session: every request reads and writes it in Redis, so the bigger the object, the higher the latency and the network traffic
  • Thinking synchronized prevents duplicates: it only locks within one JVM. Mutual exclusion across machines belongs to conditional updates in the database, unique keys, or distributed locks
  • ShedLock’s lockAtMostFor set too short: the lock expires before the job finishes, and another instance runs it again
  • Saving generated reports locally and letting users download them: the LB sends the download request to another instance, and the file is gone
  • Not counting total database connections when scaling out: scaling out the application tier ends up taking down the database
  • Autoscaling on CPU when the bottleneck is the database: the CPU is high because of waiting on the database, retries, and queuing. Adding machines then only adds concurrent load on the database and makes things worse. Scaling conditions have to take downstream health into account too
  • Shutting down without draining: every rolling deploy produces a batch of 502s

Security

  • A session cookie without Secure: by default, Spring Session uses request.isSecure() to decide whether to add Secure to the cookie. TLS terminates at the LB, so the application receives HTTP, the cookie goes out without Secure, and the browser sends it over any HTTP connection. Set server.forward-headers-strategy (see Load Balancing in Depth) so the application knows the original request was HTTPS, or declare your own DefaultCookieSerializer and call setUseSecureCookie(true)
  • A hand-written login that does not change the session ID: an attacker first gets a session ID and then gets the victim to log in with it; after login, that ID is in a logged-in state (session fixation). Spring Security calls changeSessionId() by default on a successful login to replace the ID; a login flow that bypasses Spring Security and does its own session.setAttribute("userId", ...) has no such protection
  • The permission boundary of presigned URLs: a URL can be reused while it is valid, anyone who has it can upload, and a presigned PUT has no “maximum size” condition you can set. Have the server generate the object key and bind it to the user, and never let the client choose the path; keep the expiry as short as you can; after the upload, use HEAD to check the size and type, and delete the object if they do not match. When you need to limit the size at upload time, use a presigned POST instead, which supports the content-length-range condition
  • With sessions in Redis, Redis becomes a store of login credentials: anyone who can read Redis gets every valid session. Keep Redis on the internal network, turn on ACLs and TLS, and protect it to the same standard as the database

When to use it, and when not to

  • Scale up first: for database primaries, early products, when single-machine sizes still have headroom, or when you need to stop the bleeding right away. One big machine plus one standby is often far simpler than ten small ones
  • Switch to horizontal scaling: when you need high availability (at least two instances), traffic has clear peaks that call for elastic scaling, a single machine is close to the largest size, or you need zero-downtime deploys
  • When to re-evaluate: the largest single machine runs above 60% utilization at peak; downtime caused by deploys is no longer acceptable; the shared Redis or MySQL starts to become the bottleneck, which is when you move on to scaling the data tier in Part 3 and Part 4

References

Comments