Scrivio Interview library
CodingFoundations6 min read · updated 13 November 2026

A Spring Boot service is described as stateless, but its code contains: an in-memory per-user rate limiter, a Caffeine cache of product data, a @Scheduled(fixedRate = 60000) job that sends digest emails, and a ConcurrentHashMap<String, UploadState> tracking chunked uploads.

Which of these keep working correctly when the service runs as 6 replicas behind a round-robin load balancer, which break, and how would you fix the ones that break?

Only the Caffeine cache keeps working, because it holds a disposable copy of data that each replica can reload. The in-memory rate limiter gives each user about six times the limit, the @Scheduled job sends six digests, and the upload map loses chunks that land on another replica. We fix them by moving the counters to Redis or the gateway, guarding the job with ShedLock or moving it to one scheduler, and keeping upload state in a shared store or uploading straight to object storage.

Why this question is asked

A service is often called stateless because it has no database of its own, but state hides in many places: a map, a counter, a timer. Everything works on one instance, and the bugs only appear when the service is scaled out, which usually means in production. Interviewers ask this to see whether we can spot those hidden pieces and fix each one correctly. In this answer, we will recap what statelessness means behind a load balancer, give a simple rule for sorting in-memory data, then go through the four pieces one by one with code, and finish with how to catch this class of bug before production.

1A Quick Recap: What Stateless Means Behind a Load Balancer

With six replicas behind a round-robin load balancer, each request goes to the next replica in turn. A user's first request may reach replica 1 and the next one replica 4. A service is stateless when any replica can handle any request correctly, because nothing the request needs lives only inside one replica's memory.

That does not mean replicas hold no data at all. They can hold copies of data as long as losing or duplicating that copy does not change the result. The question for every in-memory structure is: is this a disposable copy, or is it the only record of something, or something that must be counted across all replicas?

The four pieces with six replicas
PieceWith 6 replicasFix
Caffeine product cacheworks; 6 copies, lower hit rationone needed; bound staleness with a TTL
In-memory rate limiterbreaks: about 6x the limit per usercounters in Redis, or limit at the gateway
@Scheduled digest jobbreaks: 6 digests per userShedLock, a single scheduler, or a queue
Upload state mapbreaks: chunks reach other replicasshared store, or multipart upload to S3

2The Caffeine Cache: A Disposable Copy

The product cache holds data that lives in the database. If replica 3 has an older copy than replica 5, or loses its cache on restart, it just reloads from the source. The only costs of having six caches are memory, a lower hit ratio because each replica warms its own copy, and the chance that two replicas show slightly different product data for a while.

So the cache is fine as long as some staleness is acceptable. We bound it with expireAfterWrite, and if a product change must show immediately we can publish an invalidation message that each replica listens to.

Java
Cache<String, Product> products = Caffeine.newBuilder()
.maximumSize(50_000)
.expireAfterWrite(Duration.ofMinutes(5)) // a replica is at most 5 minutes stale
.build();
Product p = products.get(id, repo::load); // miss -> load from the database

3The Rate Limiter: Counted Six Times

A per-user limit of 100 requests per minute, counted in a local map, becomes about 600 per minute across six replicas, because round robin spreads the user's requests and each replica sees only a sixth of them. The limit must be counted in one place. The common fix is a counter in Redis with an expiry, which every replica increments atomically.

Java
// Fixed-window limiter shared by all replicas (Spring Data Redis)
boolean allow(String userId) {
String key = "rl:" + userId + ":" + (System.currentTimeMillis() / 60_000);
Long n = redis.opsForValue().increment(key); // 1, 2, 3 ... across all replicas
if (n != null && n == 1) redis.expire(key, Duration.ofSeconds(70));
return n != null && n <= 100; // the 101st call in the minute -> false
}

Notice that INCR is atomic in Redis, so two replicas incrementing at the same moment never lose a count. Alternatively, we can enforce limits at the API gateway, which sees all traffic before it is split. A library such as Bucket4j with a Redis backend gives a token bucket instead of fixed windows if bursts at window edges matter.

4The Scheduled Job: Six Digests

@Scheduled runs inside each application instance, so with six replicas the digest job fires six times a minute and every user gets six emails. We need exactly one replica to run it each time. ShedLock does that with a lock row in the database or a key in Redis: each replica tries to take the lock, and only the one that succeeds runs the job.

Java
@Scheduled(fixedRate = 60000)
@SchedulerLock(name = "digest", lockAtMostFor = "50s", lockAtLeastFor = "10s")
public void sendDigests() {
digestService.sendDue(); // runs on 1 of 6 replicas per tick
}

lockAtMostFor releases the lock if the replica dies mid-run, and lockAtLeastFor stops a fast replica from running it twice in one tick because of clock skew. The job should also be idempotent, for example by recording which digests were sent, so a rerun after a crash does not email twice. For heavier work, a single scheduler service that puts jobs on a queue is cleaner still.

5The Upload Map: Chunks on Different Replicas

A chunked upload sends chunk 1, chunk 2 and so on in separate requests. With round robin, chunk 2 probably reaches a replica whose map has never heard of this upload, so it fails or, worse, starts a new upload. The map is the only record of the upload's progress, so it cannot live in one replica.

The best fix is to take the bytes out of the service entirely: the service creates an S3 multipart upload and hands the client presigned URLs for each part, so the client uploads to object storage directly and the service only completes the upload at the end. If the service must receive the chunks, the upload state, meaning which parts arrived and where they are stored, goes in a shared store such as Redis or the database, and the chunks themselves go to object storage, never to local disk.

Step throughChunked upload with presigned URLs
ClientAny replicaS3
start upload
CreateMultipartUpload
uploadId and presigned part URLs
PUT part 1, part 2, part 3
complete(uploadId, part ETags)
CompleteMultipartUpload
file stored

7 messages in order. Play them, or step through them one at a time.

Any replica can start or finish the upload, because the state lives in S3, not in a replica's memory.

6The Rule of Thumb

In-memory data that is a disposable copy of something stored elsewhere is fine on every replica. Data that is the only record of something, like the upload progress, or that must be counted or done once globally, like the rate limit and the digest, needs a shared home: Redis, the database, a queue or object storage. Applying that one question to every field and timer in a service catches most scale-out bugs before they ship.

7Follow-up questions

How would you test for this class of bug before production?

Run the service as at least two replicas in every test environment, never one, behind a round-robin balancer, and write integration tests that make consecutive calls land on different instances, for example with Testcontainers and two application containers. Check that a user hits the rate limit at the real number, that a scheduled job runs once per tick, and that a chunked upload survives chunks going to different replicas. In code review, ask of every static map, counter or @Scheduled method what happens with N copies.

Could sticky sessions fix the upload and rate limiter problems?

They would hide the upload problem until a replica restarts or scales in, and they would only partly help the rate limiter, because a user with several clients or a changed cookie would still spread across replicas. They do nothing for the scheduled job. Moving the state to a shared home is the real fix.

Is a Redis rate limiter a new single point of failure?

It is a dependency, so we decide what happens when Redis is down. Usually we fail open with a local fallback limit, accepting looser limits for a short time rather than rejecting every request, and run Redis with a replica and automatic failover.

8Conclusion

In this answer, we saw that the Caffeine cache survives six replicas because it is a reloadable copy, while the rate limiter, the scheduled job and the upload map break because they count globally, must run once, or are the only record of an upload. We fixed them with Redis counters or gateway limits, ShedLock or a single scheduler with idempotent jobs, and shared upload state or direct multipart uploads to S3.

What to say in the interviewAbout 70 seconds aloud

Open with

I sort each piece by one question: is this in-memory data a disposable copy, or is it the only record of something or something that must be counted globally?

Then, if they want more

The Caffeine product cache is a copy, so it keeps working with six replicas; it just costs memory and some hit ratio, and I bound staleness with a TTL.

The rate limiter breaks, because each replica counts separately and round robin spreads a user's calls, so they get about six times the limit; I would move the counters to Redis with an atomic INCR or enforce the limit at the gateway.

The @Scheduled job runs on all six replicas, so users get six digests; I would use ShedLock so only one replica runs each tick, make the job idempotent, or move it to a single scheduler that feeds a queue.

The upload map breaks because chunk 2 can land on another replica; I would have clients upload parts straight to S3 with presigned multipart URLs, or keep upload state in a shared store. To catch this early, I would always test with at least two replicas.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Which of these keep working correctly when the service runs as 6 replicas behind a...": https://scrivio-interview-library.netlify.app/architecture/sd-fundamentals/84d9786eba/